text:
package cstruct

import (
	"encoding/binary"
	"io"
	"reflect"
	"unsafe"
)

type Buffer struct {
	buf   []byte
	index int
}

func NewBuffer(e []byte) *Buffer {
	return &Buffer{buf: e}
}

func (p *Buffer) Reset() {
	p.buf = p.buf[:0]
	p.index = 0
}

// Marshal

func (p *Buffer) Marshal(obj IStruct) error {
	t, base, err := getbase(obj)
	if structPointer_IsNil(base) {
		return ErrNil
	}
	if err == nil {
		props := GetProperties(t.Elem())
		s := p.size_struct(props, base)
		p.buf = make([]byte, s)
		err = p.enc_struct(props, base)
	}
	return err
}

func getbase(obj IStruct) (t reflect.Type, b structPointer, err error) {
	if obj == nil {
		err = ErrNil
		return
	}
	t = reflect.TypeOf(obj)
	value := reflect.ValueOf(obj)
	b = toStructPointer(value)
	return
}

func (o *Buffer) size_struct(prop *StructProperties, base structPointer) int {
	ret := prop.fixedSize
	for _, p := range prop.Prop {
		if p.siz != nil {
			ret += p.siz(o, p, base)
		}
	}
	return ret
}

func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
	for _, p := range prop.Prop {
		if p.enc != nil {
			if err := p.enc(o, p, base); err != nil {
				return err
			}
		}
	}
	return nil
}

// Unmarshal

func (p *Buffer) Unmarshal(obj IStruct) error {
	typ, base, err := getbase(obj)
	if err != nil {
		return err
	}

	return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), base)
}

func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, base structPointer) error {
	for _, p := range prop.Prop {
		if p.dec != nil {
			if err := p.dec(o, p, base); err != nil {
				return err
			}
		}
	}
	return nil
}

// bool
func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
	v := structPointer_BoolVal(base, p.field)
	x := 0
	if *v {
		x = 1
	}
	o.buf[o.index] = uint8(x)
	o.index++
	return nil
}

func (o *Buffer) dec_bool(p *Properties, base structPointer) error {
	i := o.index + 1
	if i < 0 || i > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	o.index = i
	u := uint8(o.buf[i-1])
	v := structPointer_BoolVal(base, p.field)
	*v = (u != 0)
	return nil
}

// uint8
func (o *Buffer) enc_uint8(p *Properties, base structPointer) error {
	v := (*uint8)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	o.buf[o.index] = *v
	o.index++
	return nil
}

func (o *Buffer) dec_uint8(p *Properties, base structPointer) error {
	i := o.index + 1
	if i < 0 || i > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	o.index = i
	u := uint8(o.buf[i-1])
	v := (*uint8)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	*v = u
	return nil
}

// uint16
func (o *Buffer) enc_uint16(p *Properties, base structPointer) error {
	v := (*uint16)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	binary.LittleEndian.PutUint16(o.buf[o.index:], *v)
	o.index += 2
	return nil
}

func (o *Buffer) dec_uint16(p *Properties, base structPointer) error {
	u, err := o.readUInt16()
	if err != nil {
		return err
	}
	v := (*uint16)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	*v = u
	return nil
}

// uint32
func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
	v := (*uint32)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	binary.LittleEndian.PutUint32(o.buf[o.index:], *v)
	o.index += 4
	return nil
}

func (o *Buffer) dec_uint32(p *Properties, base structPointer) error {
	v := (*uint32)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	i := o.index + 4
	if i < 0 || i > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	o.index = i
	*v = binary.LittleEndian.Uint32(o.buf[i-4:])
	return nil
}

// uint64
func (o *Buffer) enc_uint64(p *Properties, base structPointer) error {
	v := (*uint64)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	binary.LittleEndian.PutUint64(o.buf[o.index:], *v)
	o.index += 8
	return nil
}

func (o *Buffer) dec_uint64(p *Properties, base structPointer) error {
	v := (*uint64)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	i := o.index + 8
	if i < 0 || i > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	o.index = i
	*v = binary.LittleEndian.Uint64(o.buf[i-8:])
	return nil
}

// string
func (o *Buffer) enc_string(p *Properties, base structPointer) error {
	v := structPointer_StringVal(base, p.field)
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	if ln > 0 {
		copy(o.buf[o.index:], *v)
		o.index += ln
	}
	return nil
}

func (o *Buffer) dec_string(p *Properties, base structPointer) error {
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}

	end := o.index + int(nb)
	if end < o.index || end > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	buf := o.buf[o.index:end]
	o.index = end

	v := structPointer_StringVal(base, p.field)
	*v = string(buf)
	return nil
}

func (o *Buffer) size_string(p *Properties, base structPointer) int {
	v := structPointer_StringVal(base, p.field)
	return len(*v)
}

// []byte
func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
	v := structPointer_Bytes(base, p.field)
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	if ln > 0 {
		copy(o.buf[o.index:], *v)
		o.index += ln
	}
	return nil
}

func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error {
	v := structPointer_Bytes(base, p.field)
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}

	end := o.index + int(nb)
	if end < o.index || end > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	*v = append((*v)[:0], o.buf[o.index:end]...)
	o.index = end
	return nil
}

func (o *Buffer) size_slice_byte(p *Properties, base structPointer) int {
	v := structPointer_Bytes(base, p.field)
	return len(*v)
}

// struct ptr
func (o *Buffer) enc_substruct_ptr(p *Properties, base structPointer) error {
	v := structPointer_GetStructPointer(base, p.field)
	if v == nil {
		o.buf[o.index] = uint8(0)
		o.index++
		return nil
	} else {
		o.buf[o.index] = uint8(1)
		o.index++
		return o.enc_struct(p.sprop, v)
	}
}
func (o *Buffer) dec_substruct_ptr(p *Properties, base structPointer) error {
	bas := structPointer_GetStructPointer(base, p.field)
	i := o.index + 1
	if i < 0 || i > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	o.index = i
	flag := uint8(o.buf[i-1])
	if flag == 0 {
		return nil
	}
	if structPointer_IsNil(bas) {
		bas = toStructPointer(reflect.New(p.stype))
		structPointer_SetStructPointer(base, p.field, bas)
	}
	return o.unmarshalType(p.stype, p.sprop, bas)
}
func (o *Buffer) size_substruct_ptr(p *Properties, base structPointer) int {
	v := structPointer_GetStructPointer(base, p.field)
	if v == nil {
		return 1
	}
	return o.size_struct(p.sprop, v) + 1
}

// struct
func (o *Buffer) enc_substruct(p *Properties, base structPointer) error {
	return o.enc_struct(p.sprop, structPointer(unsafe.Pointer(uintptr(base)+uintptr(p.field))))
}
func (o *Buffer) dec_substruct(p *Properties, base structPointer) error {
	bas := structPointer(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	return o.unmarshalType(p.stype, p.sprop, bas)
}
func (o *Buffer) size_substruct(p *Properties, base structPointer) int {
	return o.size_struct(p.sprop, structPointer(unsafe.Pointer(uintptr(base)+uintptr(p.field))))
}

// []bool
func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
	v := structPointer_BoolSlice(base, p.field)
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	for i := 0; i < ln; i++ {
		x := 0
		if (*v)[i] {
			x = 1
		}
		o.buf[o.index] = uint8(x)
		o.index += 1
	}
	return nil
}

func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error {
	v := structPointer_BoolSlice(base, p.field)
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	end := o.index + int(nb)
	if end < o.index || end > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	*v = make([]bool, int(nb))
	for i := 0; i < int(nb); i++ {
		u := uint8(o.buf[o.index+i])
		(*v)[i] = (u != 0)
	}
	o.index = end
	return nil
}

func (o *Buffer) size_slice_bool(p *Properties, base structPointer) int {
	v := structPointer_BoolSlice(base, p.field)
	return len(*v)
}

// []uint16
func (o *Buffer) enc_slice_uint16(p *Properties, base structPointer) error {
	v := (*[]uint16)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	for i := 0; i < ln; i++ {
		binary.LittleEndian.PutUint16(o.buf[o.index:], (*v)[i])
		o.index += 2
	}
	return nil
}

func (o *Buffer) dec_slice_uint16(p *Properties, base structPointer) error {
	v := (*[]uint16)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	end := o.index + int(nb)*2
	if end < o.index || end > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	*v = make([]uint16, int(nb))
	for i := 0; i < int(nb); i++ {
		(*v)[i] = binary.LittleEndian.Uint16(o.buf[o.index+i*2:])
	}
	o.index = end
	return nil
}

func (o *Buffer) size_slice_uint16(p *Properties, base structPointer) int {
	v := (*[]uint16)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	return len(*v) * 2
}

// []uint32
func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
	v := (*[]uint32)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	for i := 0; i < ln; i++ {
		binary.LittleEndian.PutUint32(o.buf[o.index:], (*v)[i])
		o.index += 4
	}
	return nil
}

func (o *Buffer) dec_slice_uint32(p *Properties, base structPointer) error {
	v := (*[]uint32)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	end := o.index + int(nb)*4
	if end < o.index || end > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	*v = make([]uint32, int(nb))
	for i := 0; i < int(nb); i++ {
		(*v)[i] = binary.LittleEndian.Uint32(o.buf[o.index+i*4:])
	}
	o.index = end
	return nil
}

func (o *Buffer) size_slice_uint32(p *Properties, base structPointer) int {
	v := (*[]uint32)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	return len(*v) * 4
}

// []uint64
func (o *Buffer) enc_slice_uint64(p *Properties, base structPointer) error {
	v := (*[]uint64)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	for i := 0; i < ln; i++ {
		binary.LittleEndian.PutUint64(o.buf[o.index:], (*v)[i])
		o.index += 8
	}
	return nil
}

func (o *Buffer) dec_slice_uint64(p *Properties, base structPointer) error {
	v := (*[]uint64)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	end := o.index + int(nb)*8
	if end < o.index || end > len(o.buf) {
		return io.ErrUnexpectedEOF
	}
	*v = make([]uint64, int(nb))
	for i := 0; i < int(nb); i++ {
		(*v)[i] = binary.LittleEndian.Uint64(o.buf[o.index+i*8:])
	}
	o.index = end
	return nil
}

func (o *Buffer) size_slice_uint64(p *Properties, base structPointer) int {
	v := (*[]uint64)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	return len(*v) * 8
}

// []string
func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
	v := (*[]string)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	for i := 0; i < ln; i++ {
		ln2 := len((*v)[i])
		binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln2))
		o.index += 2
		if ln2 > 0 {
			copy(o.buf[o.index:], (*v)[i])
			o.index += ln2
		}
	}
	return nil
}

func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error {
	v := (*[]string)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	nb0, err0 := o.readUInt16()
	if err0 != nil {
		return err0
	}
	*v = make([]string, int(nb0))
	for i := 0; i < int(nb0); i++ {
		nb, err := o.readUInt16()
		if err != nil {
			return err
		}
		end := o.index + int(nb)
		if end < o.index || end > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		(*v)[i] = string(o.buf[o.index:end])
		o.index = end
	}
	return nil
}

func (o *Buffer) size_slice_string(p *Properties, base structPointer) int {
	v := (*[]string)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	ret := 0
	ln := len(*v)
	for i := 0; i < ln; i++ {
		ret += len((*v)[i]) + 2
	}
	return ret
}

// []struct
func (o *Buffer) enc_slice_substruct(p *Properties, base structPointer) error {
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	var ln = sliceHeader.Len
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	itemsize := int(p.stype.Size())
	for i := 0; i < ln; i++ {
		sv := (structPointer)(unsafe.Pointer(sliceHeader.Data + uintptr(i*itemsize)))
		o.enc_struct(p.sprop, sv)
	}
	return nil
}

func (o *Buffer) dec_slice_substruct(p *Properties, base structPointer) error {
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	if nb == 0 {
		return nil
	}
	itemsize := int(p.stype.Size())
	data := reflect.MakeSlice(p.t, int(nb), int(nb))
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	sliceHeader.Cap = int(nb)
	sliceHeader.Len = int(nb)
	sliceHeader.Data = data.Pointer()
	for i := 0; i < int(nb); i++ {
		data := (structPointer)(unsafe.Pointer(sliceHeader.Data + uintptr(i*itemsize)))
		o.unmarshalType(p.stype, p.sprop, data)
	}
	return nil
}

func (o *Buffer) size_slice_substruct(p *Properties, base structPointer) int {
	ret := 0
	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(uintptr(base) + uintptr(p.field)))
	var ln = sliceHeader.Len
	itemsize := int(p.stype.Size())
	for i := 0; i < ln; i++ {
		sv := (structPointer)(unsafe.Pointer(sliceHeader.Data + uintptr(i*itemsize)))
		ret += o.size_struct(p.sprop, sv)
	}
	return ret
}

// []struct_ptr
func (o *Buffer) enc_slice_substruct_ptr(p *Properties, base structPointer) error {
	v := structPointer_StructPointerSlice(base, p.field)
	ln := v.Len()
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	for i := 0; i < ln; i++ {
		sv := (*v)[i]
		if sv == nil {
			o.buf[o.index] = uint8(0)
			o.index++
		} else {
			o.buf[o.index] = uint8(1)
			o.index++
			o.enc_struct(p.sprop, sv)
		}
	}
	return nil
}

func (o *Buffer) dec_slice_substruct_ptr(p *Properties, base structPointer) error {
	v := structPointer_StructPointerSlice(base, p.field)
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	for j := 0; j < int(nb); j++ {
		i := o.index + 1
		if i < 0 || i > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		o.index = i
		flag := uint8(o.buf[i-1])
		if flag == 0 {
			v.Append(nil)
		} else {
			bas := toStructPointer(reflect.New(p.stype))
			o.unmarshalType(p.stype, p.sprop, bas)
			v.Append(bas)
		}
	}
	return nil
}

func (o *Buffer) size_slice_substruct_ptr(p *Properties, base structPointer) int {
	ret := 0
	v := structPointer_StructPointerSlice(base, p.field)
	ln := v.Len()
	for i := 0; i < ln; i++ {
		sv := (*v)[i]
		if sv == nil {
			ret += 1
		} else {
			ret += o.size_struct(p.sprop, sv) + 1
		}
	}
	return ret
}

// []struct_ptr ignore nil
func (o *Buffer) enc_slice_substruct_ptr_ignore_nil(p *Properties, base structPointer) error {
	v := structPointer_StructPointerSlice(base, p.field)
	ln := v.Len()
	len_index := o.index
	real_ln := 0
	o.index += 2
	for i := 0; i < ln; i++ {
		sv := (*v)[i]
		if sv != nil {
			real_ln++
			o.enc_struct(p.sprop, sv)
		}
	}
	binary.LittleEndian.PutUint16(o.buf[len_index:], uint16(real_ln))
	return nil
}

func (o *Buffer) dec_slice_substruct_ptr_ignore_nil(p *Properties, base structPointer) error {
	v := structPointer_StructPointerSlice(base, p.field)
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	for j := 0; j < int(nb); j++ {
		bas := toStructPointer(reflect.New(p.stype))
		v.Append(bas)
		o.unmarshalType(p.stype, p.sprop, bas)
	}
	return nil
}

func (o *Buffer) size_slice_substruct_ptr_ignore_nil(p *Properties, base structPointer) int {
	ret := 0
	v := structPointer_StructPointerSlice(base, p.field)
	ln := v.Len()
	for i := 0; i < ln; i++ {
		sv := (*v)[i]
		if sv != nil {
			ret += o.size_struct(p.sprop, sv)
		}
	}
	return ret
}

// [][]byte
func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
	v := structPointer_BytesSlice(base, p.field)
	ln := len(*v)
	binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln))
	o.index += 2
	for i := 0; i < ln; i++ {
		ln2 := len((*v)[i])
		binary.LittleEndian.PutUint16(o.buf[o.index:], uint16(ln2))
		o.index += 2
		if ln2 > 0 {
			copy(o.buf[o.index:], (*v)[i])
			o.index += ln2
		}
	}
	return nil
}

func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error {
	v := structPointer_BytesSlice(base, p.field)
	nb, err := o.readUInt16()
	if err != nil {
		return err
	}
	for i := 0; i < int(nb); i++ {
		nb2, err := o.readUInt16()
		if err != nil {
			return err
		}

		end := o.index + int(nb2)
		if end < o.index || end > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		buf := o.buf[o.index:end]
		o.index = end

		*v = append(*v, buf)
	}
	return nil
}

func (o *Buffer) size_slice_slice_byte(p *Properties, base structPointer) int {
	v := structPointer_BytesSlice(base, p.field)
	ret := 0
	ln := len(*v)
	for i := 0; i < ln; i++ {
		ret += len((*v)[i]) + 2
	}
	return ret
}

func (o *Buffer) readUInt16() (uint16, error) {
	i := o.index + 2
	if i < 0 || i > len(o.buf) {
		return 0, io.ErrUnexpectedEOF
	}
	o.index = i
	return binary.LittleEndian.Uint16(o.buf[i-2:]), nil
}

// [n]byte [n]uint8 [n]int8 [n]bool
func (o *Buffer) enc_array_byte(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		var data []byte
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		copy(o.buf[o.index:], data)
		o.index += ln
	}
	return nil
}

func (o *Buffer) dec_array_byte(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		end := o.index + ln
		if end < o.index || end > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		var data []byte
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		copy(data, o.buf[o.index:end])
		o.index = end
	}
	return nil
}

func (o *Buffer) size_array_byte(p *Properties, base structPointer) int {
	return p.t.Len()
}

// [n]uint16 [n]int16
func (o *Buffer) enc_array_uint16(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		var data []uint16
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		for i := 0; i < ln; i++ {
			binary.LittleEndian.PutUint16(o.buf[o.index:], data[i])
			o.index += 2
		}
	}
	return nil
}

func (o *Buffer) dec_array_uint16(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		end := o.index + ln*2
		if end < o.index || end > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		var data []uint16
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		for i := 0; i < ln; i++ {
			data[i] = binary.LittleEndian.Uint16(o.buf[o.index+i*2:])
		}
		o.index = end
	}
	return nil
}

func (o *Buffer) size_array_uint16(p *Properties, base structPointer) int {
	return p.t.Len() * 2
}

// [n]uint32 [n]int32 [n]float32
func (o *Buffer) enc_array_uint32(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		var data []uint32
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		for i := 0; i < ln; i++ {
			binary.LittleEndian.PutUint32(o.buf[o.index:], data[i])
			o.index += 4
		}
	}
	return nil
}

func (o *Buffer) dec_array_uint32(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		end := o.index + ln*4
		if end < o.index || end > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		var data []uint32
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		for i := 0; i < ln; i++ {
			data[i] = binary.LittleEndian.Uint32(o.buf[o.index+i*4:])
		}
		o.index = end
	}
	return nil
}

func (o *Buffer) size_array_uint32(p *Properties, base structPointer) int {
	return p.t.Len() * 4
}

// [n]uint64 [n]int64 [n]float64
func (o *Buffer) enc_array_uint64(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		var data []uint64
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		for i := 0; i < ln; i++ {
			binary.LittleEndian.PutUint64(o.buf[o.index:], data[i])
			o.index += 8
		}
	}
	return nil
}

func (o *Buffer) dec_array_uint64(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		end := o.index + ln*8
		if end < o.index || end > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		var data []uint64
		sliceHeader := (*reflect.SliceHeader)((unsafe.Pointer(&data)))
		sliceHeader.Cap = ln
		sliceHeader.Len = ln
		sliceHeader.Data = uintptr(base) + uintptr(p.field)
		for i := 0; i < ln; i++ {
			data[i] = binary.LittleEndian.Uint64(o.buf[o.index+i*8:])
		}
		o.index = end
	}
	return nil
}

func (o *Buffer) size_array_uint64(p *Properties, base structPointer) int {
	return p.t.Len() * 8
}

// [n]struct
func (o *Buffer) enc_array_substruct(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		itemsize := int(p.stype.Size())
		for i := 0; i < ln; i++ {
			data := (structPointer)(unsafe.Pointer(uintptr(base) + uintptr(p.field) + uintptr(i*itemsize)))
			o.enc_struct(p.sprop, data)
		}
	}
	return nil
}

func (o *Buffer) dec_array_substruct(p *Properties, base structPointer) error {
	ln := p.t.Len()
	if ln > 0 {
		itemsize := o.size_substruct(p, base)
		end := o.index + ln*itemsize
		if end < o.index || end > len(o.buf) {
			return io.ErrUnexpectedEOF
		}
		for i := 0; i < ln; i++ {
			data := (structPointer)(unsafe.Pointer(uintptr(base) + uintptr(p.field) + uintptr(i*int(p.stype.Size()))))
			o.unmarshalType(p.stype, p.sprop, data)
		}
		o.index = end
	}
	return nil
}

func (o *Buffer) size_array_substruct(p *Properties, base structPointer) int {
	return p.t.Len() * o.size_substruct(p, base)
}

repository: fananchong/cstruct-go

repo_name: fananchong/cstruct-go


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

// Copyright 2017-2020 Authors of Cilium
// SPDX-License-Identifier: Apache-2.0

package core_v1

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

import (
	"net/http"

	"github.com/go-openapi/runtime"

	"github.com/cilium/kube-apate/api/k8s/v1/models"
)

// ReadCoreV1NodeOKCode is the HTTP code returned for type ReadCoreV1NodeOK
const ReadCoreV1NodeOKCode int = 200

/*ReadCoreV1NodeOK OK

swagger:response readCoreV1NodeOK
*/
type ReadCoreV1NodeOK struct {

	/*
	  In: Body
	*/
	Payload *models.IoK8sAPICoreV1Node `json:"body,omitempty"`
}

// NewReadCoreV1NodeOK creates ReadCoreV1NodeOK with default headers values
func NewReadCoreV1NodeOK() *ReadCoreV1NodeOK {

	return &ReadCoreV1NodeOK{}
}

// WithPayload adds the payload to the read core v1 node o k response
func (o *ReadCoreV1NodeOK) WithPayload(payload *models.IoK8sAPICoreV1Node) *ReadCoreV1NodeOK {
	o.Payload = payload
	return o
}

// SetPayload sets the payload to the read core v1 node o k response
func (o *ReadCoreV1NodeOK) SetPayload(payload *models.IoK8sAPICoreV1Node) {
	o.Payload = payload
}

// WriteResponse to the client
func (o *ReadCoreV1NodeOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.WriteHeader(200)
	if o.Payload != nil {
		payload := o.Payload
		if err := producer.Produce(rw, payload); err != nil {
			panic(err) // let the recovery middleware deal with this
		}
	}
}

// ReadCoreV1NodeUnauthorizedCode is the HTTP code returned for type ReadCoreV1NodeUnauthorized
const ReadCoreV1NodeUnauthorizedCode int = 401

/*ReadCoreV1NodeUnauthorized Unauthorized

swagger:response readCoreV1NodeUnauthorized
*/
type ReadCoreV1NodeUnauthorized struct {
}

// NewReadCoreV1NodeUnauthorized creates ReadCoreV1NodeUnauthorized with default headers values
func NewReadCoreV1NodeUnauthorized() *ReadCoreV1NodeUnauthorized {

	return &ReadCoreV1NodeUnauthorized{}
}

// WriteResponse to the client
func (o *ReadCoreV1NodeUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {

	rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses

	rw.WriteHeader(401)
}

repository: cilium/kube-apate

license_type: permissive

repo_name: cilium/kube-apate

branch_name: refs/heads/main

extension: go


text:
@article{quadros2012,
  title={Tonic immobility in terrestrial isopods: intraspecific and interspecific variability},
  author={Quadros, Aline Ferreira and Bugs, Priscila Silva and Araujo, Paula Beatriz},
  journal={ZooKeys},
  number={176},
  pages={155},
  year={2012},
  publisher={Pensoft Publishers}
}

@article{hoagland1927,
  title={Quantitative aspects of tonic immobility in vertebrates},
  author={Hoagland, Hudson},
  journal={Proceedings of the National Academy of Sciences of the United States of America},
  volume={13},
  number={12},
  pages={838},
  year={1927},
  publisher={National Academy of Sciences}
}

license: MIT

branch_name: refs/heads/master

extension: bib


text:
package test

import (
	"context"

	"github.com/tidepool-org/platform/blob"
	blobStoreStructured "github.com/tidepool-org/platform/blob/store/structured"
	"github.com/tidepool-org/platform/page"
	"github.com/tidepool-org/platform/test"
)

type ListInput struct {
	Context    context.Context
	UserID     string
	Filter     *blob.Filter
	Pagination *page.Pagination
}

type ListOutput struct {
	Blobs blob.Blobs
	Error error
}

type CreateInput struct {
	Context context.Context
	UserID  string
	Create  *blobStoreStructured.Create
}

type CreateOutput struct {
	Blob  *blob.Blob
	Error error
}

type GetInput struct {
	Context context.Context
	ID      string
}

type GetOutput struct {
	Blob  *blob.Blob
	Error error
}

type UpdateInput struct {
	Context context.Context
	ID      string
	Update  *blobStoreStructured.Update
}

type UpdateOutput struct {
	Blob  *blob.Blob
	Error error
}

type DeleteInput struct {
	Context context.Context
	ID      string
}

type DeleteOutput struct {
	Deleted bool
	Error   error
}

type Session struct {
	*test.Closer
	ListInvocations   int
	ListInputs        []ListInput
	ListStub          func(ctx context.Context, userID string, filter *blob.Filter, pagination *page.Pagination) (blob.Blobs, error)
	ListOutputs       []ListOutput
	ListOutput        *ListOutput
	CreateInvocations int
	CreateInputs      []CreateInput
	CreateStub        func(ctx context.Context, userID string, create *blobStoreStructured.Create) (*blob.Blob, error)
	CreateOutputs     []CreateOutput
	CreateOutput      *CreateOutput
	GetInvocations    int
	GetInputs         []GetInput
	GetStub           func(ctx context.Context, id string) (*blob.Blob, error)
	GetOutputs        []GetOutput
	GetOutput         *GetOutput
	UpdateInvocations int
	UpdateInputs      []UpdateInput
	UpdateStub        func(ctx context.Context, id string, create *blobStoreStructured.Update) (*blob.Blob, error)
	UpdateOutputs     []UpdateOutput
	UpdateOutput      *UpdateOutput
	DeleteInvocations int
	DeleteInputs      []DeleteInput
	DeleteStub        func(ctx context.Context, id string) (bool, error)
	DeleteOutputs     []DeleteOutput
	DeleteOutput      *DeleteOutput
}

func NewSession() *Session {
	return &Session{
		Closer: test.NewCloser(),
	}
}

func (s *Session) List(ctx context.Context, userID string, filter *blob.Filter, pagination *page.Pagination) (blob.Blobs, error) {
	s.ListInvocations++
	s.ListInputs = append(s.ListInputs, ListInput{Context: ctx, UserID: userID, Filter: filter, Pagination: pagination})
	if s.ListStub != nil {
		return s.ListStub(ctx, userID, filter, pagination)
	}
	if len(s.ListOutputs) > 0 {
		output := s.ListOutputs[0]
		s.ListOutputs = s.ListOutputs[1:]
		return output.Blobs, output.Error
	}
	if s.ListOutput != nil {
		return s.ListOutput.Blobs, s.ListOutput.Error
	}
	panic("List has no output")
}

func (s *Session) Create(ctx context.Context, userID string, create *blobStoreStructured.Create) (*blob.Blob, error) {
	s.CreateInvocations++
	s.CreateInputs = append(s.CreateInputs, CreateInput{Context: ctx, UserID: userID, Create: create})
	if s.CreateStub != nil {
		return s.CreateStub(ctx, userID, create)
	}
	if len(s.CreateOutputs) > 0 {
		output := s.CreateOutputs[0]
		s.CreateOutputs = s.CreateOutputs[1:]
		return output.Blob, output.Error
	}
	if s.CreateOutput != nil {
		return s.CreateOutput.Blob, s.CreateOutput.Error
	}
	panic("Create has no output")
}

func (s *Session) Get(ctx context.Context, id string) (*blob.Blob, error) {
	s.GetInvocations++
	s.GetInputs = append(s.GetInputs, GetInput{Context: ctx, ID: id})
	if s.GetStub != nil {
		return s.GetStub(ctx, id)
	}
	if len(s.GetOutputs) > 0 {
		output := s.GetOutputs[0]
		s.GetOutputs = s.GetOutputs[1:]
		return output.Blob, output.Error
	}
	if s.GetOutput != nil {
		return s.GetOutput.Blob, s.GetOutput.Error
	}
	panic("Get has no output")
}

func (s *Session) Update(ctx context.Context, id string, update *blobStoreStructured.Update) (*blob.Blob, error) {
	s.UpdateInvocations++
	s.UpdateInputs = append(s.UpdateInputs, UpdateInput{Context: ctx, ID: id, Update: update})
	if s.UpdateStub != nil {
		return s.UpdateStub(ctx, id, update)
	}
	if len(s.UpdateOutputs) > 0 {
		output := s.UpdateOutputs[0]
		s.UpdateOutputs = s.UpdateOutputs[1:]
		return output.Blob, output.Error
	}
	if s.UpdateOutput != nil {
		return s.UpdateOutput.Blob, s.UpdateOutput.Error
	}
	panic("Update has no output")
}

func (s *Session) Delete(ctx context.Context, id string) (bool, error) {
	s.DeleteInvocations++
	s.DeleteInputs = append(s.DeleteInputs, DeleteInput{Context: ctx, ID: id})
	if s.DeleteStub != nil {
		return s.DeleteStub(ctx, id)
	}
	if len(s.DeleteOutputs) > 0 {
		output := s.DeleteOutputs[0]
		s.DeleteOutputs = s.DeleteOutputs[1:]
		return output.Deleted, output.Error
	}
	if s.DeleteOutput != nil {
		return s.DeleteOutput.Deleted, s.DeleteOutput.Error
	}
	panic("Delete has no output")
}

func (s *Session) AssertOutputsEmpty() {
	s.Closer.AssertOutputsEmpty()
	if len(s.ListOutputs) > 0 {
		panic("ListOutputs is not empty")
	}
	if len(s.CreateOutputs) > 0 {
		panic("CreateOutputs is not empty")
	}
	if len(s.GetOutputs) > 0 {
		panic("GetOutputs is not empty")
	}
	if len(s.UpdateOutputs) > 0 {
		panic("UpdateOutputs is not empty")
	}
	if len(s.DeleteOutputs) > 0 {
		panic("DeleteOutputs is not empty")
	}
}

repository: franck-fourel/platform

repo_name: franck-fourel/platform


text:
package api_server

import (
	"context"

	"github.com/emicklei/go-restful/v3"

	kuma_cp "github.com/kumahq/kuma/pkg/config/app/kuma-cp"
	"github.com/kumahq/kuma/pkg/config/core"
	core_mesh "github.com/kumahq/kuma/pkg/core/resources/apis/mesh"
	"github.com/kumahq/kuma/pkg/core/resources/manager"
	core_model "github.com/kumahq/kuma/pkg/core/resources/model"
	"github.com/kumahq/kuma/pkg/core/resources/store"
	rest_errors "github.com/kumahq/kuma/pkg/core/rest/errors"
	"github.com/kumahq/kuma/pkg/core/user"
	"github.com/kumahq/kuma/pkg/core/validators"
	"github.com/kumahq/kuma/pkg/envoy/admin"
	"github.com/kumahq/kuma/pkg/envoy/admin/access"
)

const (
	contentTypeText = "text/plain"
)

func addInspectEnvoyAdminEndpoints(
	ws *restful.WebService,
	cfg *kuma_cp.Config,
	rm manager.ResourceManager,
	adminAccess access.EnvoyAdminAccess,
	envoyAdminClient admin.EnvoyAdminClient,
) {
	ws.Route(
		ws.GET("/meshes/{mesh}/dataplanes/{dataplane}/xds").
			To(inspectDataplaneAdmin(envoyAdminClient.ConfigDump, adminAccess.ValidateViewConfigDump, rm, restful.MIME_JSON)).
			Doc("inspect dataplane XDS configuration").
			Param(ws.PathParameter("mesh", "mesh name").DataType("string")).
			Param(ws.PathParameter("dataplane", "dataplane name").DataType("string")),
	)
	ws.Route(
		ws.GET("/zoneingresses/{zoneingress}/xds").
			To(inspectZoneIngressAdmin(cfg.Mode, cfg.Multizone.Zone.Name, envoyAdminClient.ConfigDump, adminAccess.ValidateViewConfigDump, rm, restful.MIME_JSON)).
			Doc("inspect zone ingresses XDS configuration").
			Produces("application/json").
			Param(ws.PathParameter("zoneingress", "zoneingress name").DataType("string")),
	)
	ws.Route(
		ws.GET("/zoneegresses/{zoneegress}/xds").
			To(inspectZoneEgressAdmin(envoyAdminClient.ConfigDump, adminAccess.ValidateViewConfigDump, rm, restful.MIME_JSON)).
			Doc("inspect zone egresses XDS configuration").
			Produces("application/json").
			Param(ws.PathParameter("zoneegress", "zoneegress name").DataType("string")),
	)

	ws.Route(
		ws.GET("/meshes/{mesh}/dataplanes/{dataplane}/stats").
			To(inspectDataplaneAdmin(envoyAdminClient.Stats, adminAccess.ValidateViewStats, rm, contentTypeText)).
			Doc("inspect dataplane stats").
			Param(ws.PathParameter("mesh", "mesh name").DataType("string")).
			Param(ws.PathParameter("dataplane", "dataplane name").DataType("string")),
	)
	ws.Route(
		ws.GET("/zoneingresses/{zoneingress}/stats").
			To(inspectZoneIngressAdmin(cfg.Mode, cfg.Multizone.Zone.Name, envoyAdminClient.Stats, adminAccess.ValidateViewStats, rm, contentTypeText)).
			Doc("inspect zone ingresses stats").
			Param(ws.PathParameter("zoneingress", "zoneingress name").DataType("string")),
	)
	ws.Route(
		ws.GET("/zoneegresses/{zoneegress}/stats").
			To(inspectZoneEgressAdmin(envoyAdminClient.Stats, adminAccess.ValidateViewStats, rm, contentTypeText)).
			Doc("inspect zone egresses stats").
			Param(ws.PathParameter("zoneegress", "zoneegress name").DataType("string")),
	)

	ws.Route(
		ws.GET("/meshes/{mesh}/dataplanes/{dataplane}/clusters").
			To(inspectDataplaneAdmin(envoyAdminClient.Clusters, adminAccess.ValidateViewClusters, rm, contentTypeText)).
			Doc("inspect dataplane clusters").
			Param(ws.PathParameter("mesh", "mesh name").DataType("string")).
			Param(ws.PathParameter("dataplane", "dataplane name").DataType("string")),
	)
	ws.Route(
		ws.GET("/zoneingresses/{zoneingress}/clusters").
			To(inspectZoneIngressAdmin(cfg.Mode, cfg.Multizone.Zone.Name, envoyAdminClient.Clusters, adminAccess.ValidateViewClusters, rm, contentTypeText)).
			Doc("inspect zone ingresses clusters").
			Param(ws.PathParameter("zoneingress", "zoneingress name").DataType("string")),
	)
	ws.Route(
		ws.GET("/zoneegresses/{zoneegress}/clusters").
			To(inspectZoneEgressAdmin(envoyAdminClient.Clusters, adminAccess.ValidateViewClusters, rm, contentTypeText)).
			Doc("inspect zone egresses clusters").
			Param(ws.PathParameter("zoneegress", "zoneegress name").DataType("string")),
	)
}

func inspectDataplaneAdmin(
	adminFn func(context.Context, core_model.ResourceWithAddress) ([]byte, error),
	access func(context.Context, user.User) error,
	rm manager.ResourceManager,
	contentType string,
) restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		ctx := request.Request.Context()
		meshName := request.PathParameter("mesh")
		dataplaneName := request.PathParameter("dataplane")

		if err := access(ctx, user.FromCtx(ctx)); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not execute admin operation")
			return
		}

		dp := core_mesh.NewDataplaneResource()
		if err := rm.Get(ctx, dp, store.GetByKey(dataplaneName, meshName)); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not get dataplane resource")
			return
		}

		stats, err := adminFn(ctx, dp)
		if err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not execute admin operation")
			return
		}

		response.AddHeader(restful.HEADER_ContentType, contentType)
		if _, err := response.Write(stats); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not write response")
			return
		}
	}
}

func inspectZoneIngressAdmin(
	mode core.CpMode,
	localZone string,
	adminFn func(context.Context, core_model.ResourceWithAddress) ([]byte, error),
	access func(context.Context, user.User) error,
	rm manager.ResourceManager,
	contentType string,
) restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		ctx := request.Request.Context()
		zoneIngressName := request.PathParameter("zoneingress")

		if err := access(ctx, user.FromCtx(ctx)); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not execute admin operation")
			return
		}

		zi := core_mesh.NewZoneIngressResource()
		if err := rm.Get(ctx, zi, store.GetByKey(zoneIngressName, core_model.NoMesh)); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not get zone ingress resource")
			return
		}

		if mode == core.Zone && zi.IsRemoteIngress(localZone) {
			rest_errors.HandleError(request.Request.Context(), response, &validators.ValidationError{}, "Could not connect to zone ingress that resides in another zone")
			return
		}

		stats, err := adminFn(ctx, zi)
		if err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not execute admin operation")
			return
		}

		response.AddHeader(restful.HEADER_ContentType, contentType)
		if _, err := response.Write(stats); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not write response")
			return
		}
	}
}

func inspectZoneEgressAdmin(
	adminFn func(context.Context, core_model.ResourceWithAddress) ([]byte, error),
	access func(context.Context, user.User) error,
	rm manager.ResourceManager,
	contentType string,
) restful.RouteFunction {
	return func(request *restful.Request, response *restful.Response) {
		ctx := request.Request.Context()
		name := request.PathParameter("zoneegress")

		if err := access(ctx, user.FromCtx(ctx)); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not execute admin operation")
			return
		}

		ze := core_mesh.NewZoneEgressResource()
		if err := rm.Get(ctx, ze, store.GetByKey(name, core_model.NoMesh)); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not get zone egress resource")
			return
		}

		stats, err := adminFn(ctx, ze)
		if err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not execute admin operation")
			return
		}

		response.AddHeader(restful.HEADER_ContentType, contentType)
		if _, err := response.Write(stats); err != nil {
			rest_errors.HandleError(request.Request.Context(), response, err, "Could not write response")
			return
		}
	}
}

repository: kumahq/kuma

repo_name: kumahq/kuma

gha_language: Go


text:
@article{2012ApJ...744L..17B,
 abstract = {While a white dwarf (WD) is, from a theoretical perspective, the most
plausible primary star of a Type Ia supernova (SN Ia), many
other candidates have not been formally ruled out. Shock energy
deposited in the envelope of any exploding primary contributes
to the early SN brightness and, since this radiation energy is
degraded by expansion after the explosion, the diffusive
luminosity depends on the initial primary radius. We present a
new non-detection limit of the nearby SN Ia 2011fe, obtained at
a time that appears to be just 4 hr after explosion, allowing us
to directly constrain the initial primary radius (R$_p$ ).
Coupled with the non-detection of a quiescent X-ray counterpart
and the inferred synthesized $^56$Ni mass, we show that
R$_p$ <åisebox-0.5ex~ 0.02 R $_☉$ (a
factor of five smaller than previously inferred), that the
average density of the primary must be \ensuremath\o̊$_ p
$ > 10$^4$ g cm$^-3$, and that the effective
temperature must be less than a few × 10$^5$ K.
This rules out hydrogen-burning main-sequence stars and giants.
Constructing the helium-burning and carbon-burning main
sequences, we find that such objects are also excluded. By
process of elimination, we find that only degeneracy-supported
compact objects—WDs and neutron
stars—are viable as the primary star of SN 2011fe.
With few caveats, we also restrict the companion (secondary)
star radius to R $_c$ <\rs̊ebox-0.5ex~
0.1 R $_☉$, excluding Roche-lobe overflowing red giant and
main-sequence companions to high significance.},
 adsnote = {Provided by the SAO/NASA Astrophysics Data System},
 adsurl = {https://ui.adsabs.harvard.edu/abs/2012ApJ...744L..17B},
 archiveprefix = {arXiv},
 author = {Bloom, Joshua S. and Kasen, Daniel and Shen, Ken J. and
Nugent, Peter E. and Butler, Nathaniel R. and Graham, Melissa L. and
Howell, D. Andrew and Kolb, Ulrich and Holmes, Stefan and
Haswell, Carole A. and Burwitz, Vadim and Rodriguez, Juan and
Sullivan, Mark},
 doi = {10.1088/2041-8205/744/2/L17},
 eid = {L17},
 eprint = {1111.0966},
 journal = {\apjl},
 keywords = {supernovae: individual: 2011fe white dwarfs, supernovae: general, Astrophysics - High Energy Astrophysical Phenomena, Astrophysics - Cosmology and Extragalactic Astrophysics},
 month = {Jan},
 number = {2},
 pages = {L17},
 primaryclass = {astro-ph.HE},
 title = {A Compact Degenerate Primary-star Progenitor of SN 2011fe},
 volume = {744},
 year = {2012}
}

repository: profjsb/my-content

repo_name: profjsb/my-content

gha_license_id: MIT

gha_language: TeX


text:
@patent{johnson_mishra_khalilia_ouyang_nair_2022,
  author       = {Johnson, Gregory and Mishra, Pragyana and Khalilia, Mohammed and Ouyang, Wenbin and Nair, Naveen},
  title        = {Video Frame Replacement Based on Auxiliary Data},
  number       = 11368652,
  date         = {2022-06-21},
  holder       = {{Amazon Technologies Inc., Seattle, WA (US)}},
  type         = {patentus},
}


text:
@book{Rawls2009,
  abstract = {Since it appeared in 1971, John Rawls's "A Theory of Justice" has become a classic. The author has now revised the original edition to clear up a number of difficulties he and others have found in the original book.  Rawls aims to express an essential part of the common core of the democratic tradition--justice as fairness--and to provide an alternative to utilitarianism, which had dominated the Anglo-Saxon tradition of political thought since the nineteenth century. Rawls substitutes the ideal of the social contract as a more satisfactory account of the basic rights and liberties of citizens as free and equal persons. "Each person," writes Rawls, "possesses an inviolability founded on justice that even the welfare of society as a whole cannot override." Advancing the ideas of Rousseau, Kant, Emerson, and Lincoln, Rawls's theory is as powerful today as it was when first published.},
  author = {Rawls, John},
  date = {2009-07-01},
  isbn = {978-0-674-04258-2},
  keywords = {Law / General},
  langid = {english},
  pagetotal = {564},
  publisher = {Harvard University Press},
  timestamp = {2015-02-24 12:14:36 +0100},
  title = {A Theory of Justice},
  url = {\url{http://www.google.com}}
}

@book{Stowe2009,
  abstract = {With its gripping plot and pungent dialogue, Uncle Tom's Cabin offers readers today a passionate portrait of a nation on the verge of disunion and a surprisingly subtle examination of the relationship between race and nationalism that has always been at the heart of the American experience. This Broadview edition is based upon the first American edition of the novel and reprints its original illustrations and preface. In addition, it reprints all of the prefaces that Stowe wrote for authorized European editions of Uncle Tom's Cabin, offers a wide array of appendices that clarify the novel's participation in antebellum debates about domesticity, colonization, abolitionism, and the law, and includes sections on dramatic adaptations of the novel.},
  author = {Stowe, Harriet Beecher},
  date = {2009-04-27},
  isbn = {978-1-77048-257-9},
  keywords = {Fiction / Literary},
  langid = {english},
  pagetotal = {629},
  publisher = {Broadview Press},
  timestamp = {2015-02-24 12:14:36 +0100},
  title = {Uncle Tom's Cabin}
}

license: Unlicense

url: https://raw.githubusercontent.com/egh/zotero-better-bibtex/e0997174f683fdb4ac9a244d38ec017e8ffec26e/test/fixtures/export/Hang on non-file attachment export #112 - URL export broken #114.bib

repository: egh/zotero-better-bibtex

repo_name: egh/zotero-better-bibtex


text:
/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package dns

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"github.com/golang/glog"

	"github.com/kubernetes-incubator/federated-ingress-controller/pkg/controller/util"
	"k8s.io/kubernetes/federation/pkg/dnsprovider"

	"k8s.io/api/core/v1"
	extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	pkgruntime "k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/watch"
	restclient "k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/util/workqueue"
	federationclientset "k8s.io/kubernetes/federation/client/clientset_generated/federation_clientset"
	futil "k8s.io/kubernetes/federation/pkg/federation-controller/util"
	corelisters "k8s.io/kubernetes/pkg/client/listers/extensions/internalversion"

	opt "github.com/kubernetes-incubator/federated-ingress-controller/pkg/controller/ingress/options"
)

const (
	// ControllerName name of the controller
	ControllerName          = "ingress-dns"
	defaultIngressSeperator = "ing"
	globalIngressLBStatus   = "kubernetes.io/ingress.global-ingress-lb-status"
	// UserAgentName name of the user agent
	UserAgentName = "federation-ingress-dns-controller"

	ingressSyncPeriod = 30 * time.Second
)

// IngressDNSController DNS controller used for routing federated ingress endpoints
type IngressDNSController struct {
	*util.AbstractDNSController
	dns dnsprovider.Interface
	// domain to put dns records
	domain string
	// Client to federation api server
	federationClient federationclientset.Interface
	federationName   string
	// ingressDNSSuffix is the DNS suffix we use when publishing ingress DNS names
	ingressDNSSuffix string
	// each federation should be configured with a single zone (e.g. "mycompany.com")
	dnsZone  dnsprovider.Zone
	dnsZones dnsprovider.Zones
	// Informer Store for federated ingresses
	ingressStore corelisters.IngressLister
	// Informer controller for federated ingresses
	ingressInformerController cache.Controller
	workQueue                 workqueue.Interface
}

// StartFederatedIngressController starts a new federated ingress controller
func StartFederatedIngressController(config *restclient.Config, options *opt.FederatedIngressControllerOptions, stopChan <-chan struct{}) {
	restclient.AddUserAgent(config, "federatedingress-controller")
	client := federationclientset.NewForConfigOrDie(config)
	controller, err := NewIngressDNSController(client,
		options.DnsProvider,
		options.DnsProviderConfig,
		options.FkubeName,
		options.IngressDnsSuffix,
		options.Domain,
	)

	if err != nil {
		glog.Fatalf("error: %v", err)
	}
	controller.dnsControllerRun(1, stopChan)
}

// NewIngressDNSController returns a new ingress dns controller to manage DNS records for federated ingresses
func NewIngressDNSController(client federationclientset.Interface,
	dnsProvider string,
	dnsProviderConfig string,
	federationName string,
	ingressDNSSuffix string,
	domain string) (*IngressDNSController, error) {

	dns, err := dnsprovider.InitDnsProvider(dnsProvider, dnsProviderConfig)
	if err != nil {
		runtime.HandleError(fmt.Errorf("DNS provider could not be initialized: %v", err))
		return nil, err
	}
	return newIngressDNSController(client, dns, dnsProviderConfig, federationName, ingressDNSSuffix, domain)
}

func newIngressDNSController(client federationclientset.Interface,
	dns dnsprovider.Interface,
	dnsProviderConfig string,
	federationName string,
	ingressDNSSuffix string,
	domain string) (*IngressDNSController, error) {

	if ingressDNSSuffix == "" {
		ingressDNSSuffix = defaultIngressSeperator
	}

	a := &util.AbstractDNSController{}
	d := &IngressDNSController{
		AbstractDNSController: a,
		federationClient:      client,
		dns:                   dns,
		federationName:        federationName,
		ingressDNSSuffix:      ingressDNSSuffix,
		domain:                domain,
		workQueue:             workqueue.New(),
	}
	if err := d.validateConfig(); err != nil {
		runtime.HandleError(fmt.Errorf("Invalid configuration passed to DNS provider: %v", err))
		return nil, err
	}
	if err := d.retrieveOrCreateDNSZone(); err != nil {
		runtime.HandleError(fmt.Errorf("Failed to retrieve DNS zone: %v", err))
		return nil, err
	}

	// Start informer in federated API servers on federated ingresses
	var ingressIndexer cache.Indexer
	ingressIndexer, d.ingressInformerController = cache.NewIndexerInformer(
		&cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (pkgruntime.Object, error) {
				return client.ExtensionsV1beta1().Ingresses(metav1.NamespaceAll).List(options)
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				return client.ExtensionsV1beta1().Ingresses(metav1.NamespaceAll).Watch(options)
			},
		},
		&extensionsv1beta1.Ingress{},
		ingressSyncPeriod,
		futil.NewTriggerOnAllChanges(func(obj pkgruntime.Object) { d.workQueue.Add(obj) }),
		cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc},
	)
	d.ingressStore = corelisters.NewIngressLister(ingressIndexer)
	return d, nil
}

func (idc *IngressDNSController) dnsControllerRun(workers int, stopCh <-chan struct{}) {
	defer runtime.HandleCrash()
	defer idc.workQueue.ShutDown()

	glog.Infof("Starting federation ingress dns controller")
	defer glog.Infof("Stopping federation ingress dns controller")

	go idc.ingressInformerController.Run(stopCh)

	for i := 0; i < workers; i++ {
		go wait.Until(idc.worker, time.Second, stopCh)
	}

	<-stopCh
}

func wantsDNSRecords(ingress *extensionsv1beta1.Ingress) bool {
	return len(ingress.Status.LoadBalancer.Ingress) > 0
}

func (idc *IngressDNSController) workerFunction() bool {
	item, quit := idc.workQueue.Get()
	if quit {
		return true
	}
	defer idc.workQueue.Done(item)

	ingress := item.(*extensionsv1beta1.Ingress)

	if !wantsDNSRecords(ingress) {
		glog.V(4).Infof("Got Ingess event %s in cluster %s but Status.LoadBalancer.Ingress is empty ", ingress, ingress.ClusterName)
		return false
	}
	glog.V(4).Infof("Got Ingess event %s in cluster %s", ingress, ingress.ClusterName)

	globalIngLbStatuses, err := idc.parseGlobalLbStatusAnnotation(ingress)
	if err != nil {
		runtime.HandleError(fmt.Errorf("Error in parsing Global Ingress LB Status for  %s/%s: %v", ingress.Namespace, ingress.Name, err))
		return false
	}
	if globalIngLbStatuses != nil {
		for clusterName := range *globalIngLbStatuses {
			idc.ensureDNSRecords(clusterName, ingress)
		}
	}
	return false
}

func (idc *IngressDNSController) worker() {
	for {
		if quit := idc.workerFunction(); quit {
			glog.Infof("ingress dns controller worker queue shutting down")
			return
		}
	}
}

func (idc *IngressDNSController) validateConfig() error {
	if idc.federationName == "" {
		return fmt.Errorf("DNSController should not be run without federationName")
	}
	if idc.domain == "" {
		return fmt.Errorf("DNSController must be run with a domain")
	}
	if idc.dns == nil {
		return fmt.Errorf("DNSController should not be run without a dnsprovider")
	}
	zones, ok := idc.dns.Zones()
	if !ok {
		return fmt.Errorf("the dns provider does not support zone enumeration, which is required for creating dns records")
	}
	idc.dnsZones = zones
	return nil
}

func (idc *IngressDNSController) retrieveOrCreateDNSZone() error {
	zone, err := idc.GetDNSZone(idc.domain, idc.dnsZones)
	if err != nil {
		return fmt.Errorf("error querying for DNS zones: %v", err)
	}
	if zone == nil {
		if idc.domain == "" {
			return fmt.Errorf("DNSController must be run with domain to create zone automatically")
		}
		glog.Infof("DNS zone %q not found.  Creating DNS zone %q.", idc.domain, idc.domain)
		newZone, err := idc.dnsZones.New(idc.domain)
		if err != nil {
			return err
		}
		idc.dnsZone = newZone
		glog.Infof("DNS zone %q successfully created.  Note that DNS resolution will not work until you have registered this name with "+
			"a DNS registrar and they have changed the authoritative name servers for your domain to point to your DNS provider", newZone.Name())
	} else {
		idc.dnsZone = zone
	}

	return nil
}

// getHealthyEndpoints returns the hostnames and/or IP addresses of healthy endpoints for the ingress, at a zone, region and global level (or an error)
func (idc *IngressDNSController) getHealthyEndpoints(clusterName string, ingress *extensionsv1beta1.Ingress) (zoneEndpoints, regionEndpoints, globalEndpoints []string, err error) {

	var (
		zoneNames  []string
		regionName string
	)

	if zoneNames, regionName, err = idc.getClusterZoneNames(clusterName); err != nil {
		return nil, nil, nil, err
	}

	// If federated ingress is deleted, return empty endpoints, so that DNS records are removed
	if ingress.DeletionTimestamp != nil {
		return zoneEndpoints, regionEndpoints, globalEndpoints, nil
	}

	globalIngLbStatuses, err := idc.parseGlobalLbStatusAnnotation(ingress)
	if err != nil {
		return nil, nil, nil, err
	}

	for lbClusterName, lbStatuses := range *globalIngLbStatuses {
		lbZoneNames, lbRegionName, err := idc.getClusterZoneNames(lbClusterName)
		if err != nil {
			return nil, nil, nil, err
		}
		for _, lbStatus := range lbStatuses {
			for _, lbIngress := range lbStatus.Ingress {
				var address string
				// We should get either an IP address or a hostname - use whichever one we get
				if lbIngress.IP != "" {
					address = lbIngress.IP
				} else if lbIngress.Hostname != "" {
					address = lbIngress.Hostname
				}
				if len(address) <= 0 {
					return nil, nil, nil, fmt.Errorf("Ingress %s/%s in cluster %s has neither LoadBalancerStatus.ingress.ip nor LoadBalancerStatus.ingress.hostname. Cannot use it as endpoint for federated Ingress",
						ingress.Name, ingress.Namespace, clusterName)
				}
				for _, lbZoneName := range lbZoneNames {
					for _, zoneName := range zoneNames {
						if lbZoneName == zoneName {
							zoneEndpoints = append(zoneEndpoints, address)
						}
					}
				}
				if lbRegionName == regionName {
					regionEndpoints = append(regionEndpoints, address)
				}
				globalEndpoints = append(globalEndpoints, address)
			}
		}
	}

	return zoneEndpoints, regionEndpoints, globalEndpoints, nil
}

// getClusterZoneNames returns the name of the zones (and the region) where the specified cluster exists (e.g. zones "us-east1-c" on GCE, or "us-east-1b" on AWS)
func (idc *IngressDNSController) getClusterZoneNames(clusterName string) ([]string, string, error) {
	cluster, err := idc.federationClient.Federation().Clusters().Get(clusterName, metav1.GetOptions{})
	if err != nil {
		return nil, "", err
	}
	return cluster.Status.Zones, cluster.Status.Region, nil
}

/* ensureDNSRecords ensures (idempotently, and with minimum mutations) that all of the DNS records for a ingress in a given cluster are correct,
given the current state of that ingress in that cluster.  This should be called every time the state of a ingress might have changed
(either w.r.t. its loadbalancer address, or if the number of healthy backend endpoints for that ingress transitioned from zero to non-zero
(or vice versa).  Only shards of the ingress which have both a loadbalancer ingress IP address or hostname AND at least one healthy backend endpoint
are included in DNS records for that ingress (at all of zone, region and global levels). All other addresses are removed.  Also, if no shards exist
in the zone or region of the cluster, a CNAME reference to the next higher level is ensured to exist. */
func (idc *IngressDNSController) ensureDNSRecords(clusterName string, ingress *extensionsv1beta1.Ingress) error {
	// Quinton: Pseudocode....
	// See https://github.com/kubernetes/kubernetes/pull/25107#issuecomment-218026648
	// For each ingress we need the following DNS names:
	// mying.myns.myfed.ing.z1.r1.mydomain.com  (for zone z1 in region r1)
	//         - an A record to IP address of specific shard in that zone (if that shard exists and has healthy endpoints)
	//         - OR a CNAME record to the next level up, i.e. mying.myns.myfed.ing.r1.mydomain.com  (if a healthy shard does not exist in zone z1)
	// mying.myns.myfed.ing.r1.mydomain.com
	//         - a set of A records to IP addresses of all healthy shards in region r1, if one or more of these exist
	//         - OR a CNAME record to the next level up, i.e. mying.myns.myfed.svc.mydomain.com (if no healthy shards exist in region r1)
	// mysvc.myns.myfed.svc.mydomain.com
	//         - a set of A records to IP addresses of all healthy shards in all regions, if one or more of these exist.
	//         - no record (NXRECORD response) if no healthy shards exist in any regions
	//
	// Each ingress has the current known state of loadbalancer ingress for the federated cluster stored in annotations.
	// So generate the DNS records based on the current state and ensure those desired DNS records match the
	// actual DNS records (add new records, remove deleted records, and update changed records).
	//
	ingressName := ingress.Name
	namespaceName := ingress.Namespace

	zoneNames, regionName, err := idc.getClusterZoneNames(clusterName)
	if err != nil {
		return err
	}
	if zoneNames == nil {
		return fmt.Errorf("failed to get cluster zone names")
	}
	zoneEndpoints, regionEndpoints, globalEndpoints, err := idc.getHealthyEndpoints(clusterName, ingress)
	if err != nil {
		return err
	}

	commonPrefix := ingressName + "." + namespaceName + "." + idc.federationName + "." + idc.ingressDNSSuffix
	// dnsNames is the path up the DNS search tree, starting at the leaf
	dnsNames := []string{
		strings.Join([]string{commonPrefix, zoneNames[0], regionName, idc.domain}, "."), // zone level - TODO might need other zone names for multi-zone clusters
		strings.Join([]string{commonPrefix, regionName, idc.domain}, "."),               // region level, one up from zone level
		strings.Join([]string{commonPrefix, idc.domain}, "."),                           // global level, one up from region level
		"", // nowhere to go up from global level
	}

	glog.V(4).Infof("Going to create a set of dns names for Ingres %s -> %v", ingress.Name, dnsNames)

	endpoints := [][]string{zoneEndpoints, regionEndpoints, globalEndpoints}

	glog.V(4).Infof("Got Ingres %s endpoints %v", ingress.Name, endpoints)

	for i, endpoint := range endpoints {
		if err = idc.EnsureDNSRrsets(idc.dnsZone, dnsNames[i], endpoint, dnsNames[i+1]); err != nil {
			return err
		}
	}
	return nil
}

func (idc *IngressDNSController) parseGlobalLbStatusAnnotation(ingress *extensionsv1beta1.Ingress) (*map[string][]v1.LoadBalancerStatus, error) {

	globalLbStat := make(map[string][]v1.LoadBalancerStatus)
	if ingress.Annotations == nil {
		return nil, nil
	}
	globalLbStatString, found := ingress.Annotations[globalIngressLBStatus]
	if !found {
		return nil, nil
	}
	if err := json.Unmarshal([]byte(globalLbStatString), &globalLbStat); err != nil {
		return &globalLbStat, err
	}
	return &globalLbStat, nil
}

repository: ddrechse/federated-ingress-controller

repo_name: ddrechse/federated-ingress-controller


text:
DESCRIPTION = "Resin Configuration file"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://${RESIN_COREBASE}/COPYING.Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10"

PR = "r0"

SRC_URI = "file://resin.conf"
S = "${WORKDIR}"

FILES_${PN} = "${sysconfdir}"

do_patch[noexec] = "1"
do_configure[noexec] = "1"
do_compile[noexec] = "1"
do_build[noexec] = "1"

# MIXPANEL Staging/Production TOKEN
MIXPANEL_TOKEN_PRODUCTION = "99eec53325d4f45dd0633abd719e3ff1"
MIXPANEL_TOKEN_STAGING = "cb974f32bab01ecc1171937026774b18"

do_install() {
    install -d ${D}${sysconfdir}
    install -m 0755 ${WORKDIR}/resin.conf ${D}${sysconfdir}/

    if ${@bb.utils.contains('DISTRO_FEATURES','resin-staging','true','false',d)}; then
        # Staging Resin build
        sed -i -e 's:api.resin.io:api.resinstaging.io:g' ${D}${sysconfdir}/resin.conf
        sed -i -e 's:registry.resin.io:registry.resinstaging.io:g' ${D}${sysconfdir}/resin.conf
        sed -i -e 's:^MIXPANEL_TOKEN=.*:MIXPANEL_TOKEN=${MIXPANEL_TOKEN_STAGING}:g' ${D}${sysconfdir}/resin.conf
    else
        # Production Resin build
        sed -i -e 's:^MIXPANEL_TOKEN=.*:MIXPANEL_TOKEN=${MIXPANEL_TOKEN_PRODUCTION}:g' ${D}${sysconfdir}/resin.conf
    fi
}
do_install[vardeps] += "DISTRO_FEATURES"

repository: gmacario/meta-resin

repo_name: gmacario/meta-resin

extension: bb


text:
@inproceedings{jornadas17,
 address = {Málaga, Spain},
 author = {Coronado, Estefania and Riggio, Roberto and Villalón, Jose  and Garrido, Antonio},
 booktitle = {Proc. of Jornadas de Paralelismo},
 title = {Gestión de la movilidad de usuarios basada en SDN para aplicaciones multicast en WLANs},
 year = {2017}
}


text:
// Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
//     http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.

package store

import (
	"context"

	"github.com/blox/blox/daemon-scheduler/pkg/clients"
	etcd "github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
	"github.com/pkg/errors"
)

type etcdDataStore struct {
	etcdInterface clients.EtcdInterface
}

func NewDataStore(etcdInterface clients.EtcdInterface) (DataStore, error) {
	if etcdInterface == nil {
		return nil, errors.Errorf("Invalid etcd input")
	}
	return &etcdDataStore{
		etcdInterface: etcdInterface,
	}, nil
}

// Put puts the provided key-value pair into the datastore
func (datastore etcdDataStore) Put(ctx context.Context, key string, value string) error {
	if len(key) == 0 {
		return errors.Errorf("Key cannot be empty")
	}

	if len(value) == 0 {
		return errors.Errorf("Value cannot be empty")
	}

	_, err := datastore.etcdInterface.Put(ctx, key, value)

	if err != nil {
		return handleEtcdError(err)
	}

	return nil
}

// Get returns a map with one key-value pair where the key matches the provided key
func (datastore etcdDataStore) Get(ctx context.Context, key string) (map[string]string, error) {
	if len(key) == 0 {
		return nil, errors.New("Key cannot be empty")
	}

	resp, err := datastore.etcdInterface.Get(ctx, key)

	if err != nil {
		return nil, handleEtcdError(err)
	}

	kv, err := handleGetResponse(resp)
	return kv, err
}

// GetWithPrefix returns a map of key-value pairs where the key starts with keyPrefix
func (datastore etcdDataStore) GetWithPrefix(ctx context.Context, keyPrefix string) (map[string]string, error) {
	if len(keyPrefix) == 0 {
		return nil, errors.New("Key prefix cannot be empty while getting data from datastore by prefix")
	}

	resp, err := datastore.etcdInterface.Get(ctx, keyPrefix, etcd.WithPrefix())

	if err != nil {
		return nil, handleEtcdError(err)
	}

	kv, err := handleGetResponse(resp)
	return kv, err
}

func handleGetResponse(resp *etcd.GetResponse) (map[string]string, error) {
	kv := make(map[string]string)

	if resp == nil || resp.Kvs == nil {
		return kv, nil
	}

	for _, response := range resp.Kvs {
		kv[string(response.Key)] = string(response.Value)
	}

	return kv, nil
}

// Delete deletes the record with the matching key from the database
func (datastore etcdDataStore) Delete(ctx context.Context, key string) error {
	if len(key) == 0 {
		return errors.New("Key cannot be empty")
	}

	_, err := datastore.etcdInterface.Delete(ctx, key)

	if err != nil {
		return handleEtcdError(err)
	}

	return nil
}

func handleEtcdError(err error) error {
	switch err {
	case context.Canceled:
		return errors.Wrapf(err, "Context is canceled by another routine")
	case context.DeadlineExceeded:
		return errors.Wrapf(err, "Context deadline is exceeded")
	case rpctypes.ErrEmptyKey:
		return errors.Wrapf(err, "Client-side error")
	default:
		return errors.Wrapf(err, "Bad cluster endpoints, which are not etcd servers")
	}
}

branch_name: refs/heads/dev


text:
SUMMARY = "A Qt tool for creating business and scientific charts"
LICENSE = "BSD-3-Clause & MIT"
LIC_FILES_CHKSUM = " \
    file://LICENSES/BSD-3-Clause.txt;md5=f225922a2c12dfa5218fb70c49db3ea6 \
    file://LICENSES/MIT.txt;md5=7dda4e90ded66ab88b86f76169f28663 \
"

inherit cmake_qt5_extra

DEPENDS += " \
    qtbase \
    qtsvg \
"

do_install:append() {
    # these have gone wild / qmake was always pain
    rm -r ${D}/usr/mkspecs
}

SRC_URI = "git://github.com/KDAB/KDChart.git;branch=master;protocol=https"
SRCREV = "aa9de13376a5e9f4c8802091776584614db8677e"
S = "${WORKDIR}/git"
PV = "3.0.0"

FILES:${PN}-dev += "${datadir}/mkspecs"


text:
vcpkg_check_linkage(ONLY_STATIC_LIBRARY)

vcpkg_from_github(
    OUT_SOURCE_PATH SOURCE_PATH
    REPO ariya/FastLZ
    REF c3bdfad9e0094d0fb15c12cd300e647c13dc85f9 #2021-5-10
    SHA512 cb1c7e365e955f4cabfcb0bebf9cb57e88e81183fc0bec0713a88acee6bc3aeb31cdf8fa0b56b4b7c63f220ab7b50c299b13df15912a3b4a01ec70dd2a9513f7
    HEAD_REF master
)

file(COPY ${CMAKE_CURRENT_LIST_DIR}/CMakeLists.txt DESTINATION ${SOURCE_PATH})

vcpkg_configure_cmake(
    SOURCE_PATH ${SOURCE_PATH}
    PREFER_NINJA
)

vcpkg_install_cmake()

file(REMOVE_RECURSE ${CURRENT_PACKAGES_DIR}/debug/include)

# Handle copyright
file(INSTALL ${SOURCE_PATH}/LICENSE.MIT DESTINATION ${CURRENT_PACKAGES_DIR}/share/${PORT} RENAME copyright)

gha_license_id: NOASSERTION

extension: cmake


text:
// Copyright 2023 Matrix Origin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tree

// SelectLockType is the lock type for SelectStmt.
type SelectLockType int

// Select lock types.
const (
	SelectLockNone SelectLockType = iota
	SelectLockForUpdate
	SelectLockForShare
	SelectLockForUpdateNoWait
	SelectLockForUpdateWaitN
	SelectLockForShareNoWait
	SelectLockForUpdateSkipLocked
	SelectLockForShareSkipLocked
)

// String implements fmt.Stringer.
func (n SelectLockType) String() string {
	switch n {
	case SelectLockNone:
		return "none"
	case SelectLockForUpdate:
		return "for update"
	case SelectLockForShare:
		return "for share"
	case SelectLockForUpdateNoWait:
		return "for update nowait"
	case SelectLockForUpdateWaitN:
		return "for update wait"
	case SelectLockForShareNoWait:
		return "for share nowait"
	case SelectLockForUpdateSkipLocked:
		return "for update skip locked"
	case SelectLockForShareSkipLocked:
		return "for share skip locked"
	}
	return "unsupported select lock type"
}

type SelectLockInfo struct {
	LockType SelectLockType
	WaitSec  uint64
	Tables   []*TableName
}

func (node *SelectLockInfo) Format(ctx *FmtCtx) {
	ctx.WriteString(node.LockType.String())
}

repository: matrixorigin/matrixone

repo_name: matrixorigin/matrixone


text:
package model

import (
	"path/filepath"

	"github.com/gobwas/glob"
	"github.com/pkg/errors"
	"github.com/windmilleng/tilt/internal/ospath"
)

type PathMatcher interface {
	Matches(f string, isDir bool) (bool, error)
}

// A Matcher that matches nothing.
type emptyMatcher struct{}

func (m emptyMatcher) Matches(f string, isDir bool) (bool, error) {
	return false, nil
}

var EmptyMatcher PathMatcher = emptyMatcher{}

// A matcher that matches exactly against a set of files.
type fileMatcher struct {
	paths map[string]bool
}

func (m fileMatcher) Matches(f string, isDir bool) (bool, error) {
	return m.paths[f], nil
}

// NewSimpleFileMatcher returns a matcher for the given paths; any relative paths
// are converted to absolute (relative to cwd).
func NewSimpleFileMatcher(paths ...string) (fileMatcher, error) {
	pathMap := make(map[string]bool, len(paths))
	for _, path := range paths {
		// Get the absolute path of the path, because PathMatchers expect to always
		// work with absolute paths.
		path, err := filepath.Abs(path)
		if err != nil {
			return fileMatcher{}, errors.Wrap(err, "NewSimplePathMatcher")
		}
		pathMap[path] = true
	}
	return fileMatcher{paths: pathMap}, nil
}

// This matcher will match a path if it is:
// A. an exact match for one of matcher.paths, or
// B. the child of a path in matcher.paths
// e.g. if paths = {"foo.bar", "baz/"}, will match both
// A. "foo.bar" (exact match), and
// B. "baz/qux" (child of one of the paths)
type fileOrChildMatcher struct {
	paths map[string]bool
}

func (m fileOrChildMatcher) Matches(f string, isDir bool) (bool, error) {
	// (A) Exact match
	if m.paths[f] {
		return true, nil
	}

	// (B) f is child of any of m.paths
	for path := range m.paths {
		if ospath.IsChild(path, f) {
			return true, nil
		}
	}

	return false, nil

}

// NewRelativeFileOrChildMatcher returns a matcher for the given paths (with any
// relative paths converted to absolute, relative to the given baseDir).
func NewRelativeFileOrChildMatcher(baseDir string, paths ...string) fileOrChildMatcher {
	pathMap := make(map[string]bool, len(paths))
	for _, path := range paths {
		if !filepath.IsAbs(path) {
			path = filepath.Join(baseDir, path)
		}
		pathMap[path] = true
	}
	return fileOrChildMatcher{paths: pathMap}
}

// A PathSet stores one or more filepaths, along with the directory that any
// relative paths are relative to
// NOTE(maia): in its current usage (for LiveUpdate.Run.Triggers, LiveUpdate.FallBackOnFiles())
// this isn't strictly necessary, could just as easily convert paths to Abs when specified in
// the Tiltfile--but leaving this code in place for now because it was already written and
// may help with complicated future cases (glob support, etc.)
type PathSet struct {
	Paths         []string
	BaseDirectory string
}

func NewPathSet(paths []string, baseDir string) PathSet {
	return PathSet{
		Paths:         paths,
		BaseDirectory: baseDir,
	}
}

func (ps PathSet) Empty() bool { return len(ps.Paths) == 0 }

// AnyMatch returns true if any of the given filepaths match any paths contained in the pathset
// (along with the first path that matched).
func (ps PathSet) AnyMatch(paths []string) (bool, string, error) {
	matcher := NewRelativeFileOrChildMatcher(ps.BaseDirectory, ps.Paths...)

	for _, path := range paths {
		match, err := matcher.Matches(path, false)
		if err != nil {
			return false, "", err
		}
		if match {
			return true, path, nil
		}
	}
	return false, "", nil
}

type globMatcher struct {
	globs []glob.Glob
}

func (gm globMatcher) Matches(f string, isDir bool) (bool, error) {
	for _, g := range gm.globs {
		if g.Match(f) {
			return true, nil
		}
	}

	return false, nil
}

func NewGlobMatcher(globs ...string) PathMatcher {
	ret := globMatcher{}
	for _, g := range globs {
		ret.globs = append(ret.globs, glob.MustCompile(g))
	}

	return ret
}

type PatternMatcher interface {
	PathMatcher

	// Express this PathMatcher as a sequence of filepath.Match
	// patterns. These patterns are widely useful in Docker-land because
	// they're suitable in .dockerignore or Dockerfile ADD statements
	// https://docs.docker.com/engine/reference/builder/#add
	AsMatchPatterns() []string
}

type CompositePathMatcher struct {
	Matchers []PathMatcher
}

func NewCompositeMatcher(matchers []PathMatcher) PathMatcher {
	if len(matchers) == 0 {
		return EmptyMatcher
	}
	cMatcher := CompositePathMatcher{Matchers: matchers}
	pMatchers := make([]PatternMatcher, len(matchers))
	for i, m := range matchers {
		pm, ok := m.(CompositePatternMatcher)
		if !ok {
			return cMatcher
		}
		pMatchers[i] = pm
	}
	return CompositePatternMatcher{
		CompositePathMatcher: cMatcher,
		Matchers:             pMatchers,
	}
}

func (c CompositePathMatcher) Matches(f string, isDir bool) (bool, error) {
	for _, t := range c.Matchers {
		ret, err := t.Matches(f, isDir)
		if err != nil {
			return false, err
		}
		if ret {
			return true, nil
		}
	}
	return false, nil
}

type CompositePatternMatcher struct {
	CompositePathMatcher
	Matchers []PatternMatcher
}

func (c CompositePatternMatcher) AsMatchPatterns() []string {
	result := []string{}
	for _, m := range c.Matchers {
		result = append(result, m.AsMatchPatterns()...)
	}
	return result
}

var _ PathMatcher = CompositePathMatcher{}
var _ PatternMatcher = CompositePatternMatcher{}

repository: lyft/tilt

repo_name: lyft/tilt


text:
// +build e2e

/*
Copyright 2019 The Tekton Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package test

import (
	"context"
	"testing"

	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func withRegistry(ctx context.Context, t *testing.T, c *clients, namespace string) {
	deployment := getRegistryDeployment(namespace)
	if _, err := c.KubeClient.AppsV1().Deployments(namespace).Create(ctx, deployment, metav1.CreateOptions{}); err != nil {
		t.Fatalf("Failed to create the local registry deployment: %v", err)
	}
	if err := WaitForDeploymentState(ctx, c, deployment.Name, namespace, func(d *appsv1.Deployment) (bool, error) {
		var replicas int32 = 1
		if d.Spec.Replicas != nil {
			replicas = *d.Spec.Replicas
		}
		return d.Status.ReadyReplicas == replicas, nil
	}, "DeploymentPodRunning"); err != nil {
		t.Fatalf("Error waiting for Deployment %q to be ready: %v", deployment.Name, err)
	}

	service := getRegistryService(namespace)
	if _, err := c.KubeClient.CoreV1().Services(namespace).Create(ctx, service, metav1.CreateOptions{}); err != nil {
		t.Fatalf("Failed to create the local registry service: %v", err)
	}
}

func getRegistryDeployment(namespace string) *appsv1.Deployment {
	return &appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Namespace: namespace,
			Name:      "registry",
		},
		Spec: appsv1.DeploymentSpec{
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"app": "registry",
				},
			},
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"app": "registry",
					},
				},
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{{
						Name:  "registry",
						Image: getTestImage(registryImage),
					}},
				},
			},
		},
	}
}

func getRegistryService(namespace string) *corev1.Service {
	return &corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Namespace: namespace,
			Name:      "registry",
		},
		Spec: corev1.ServiceSpec{
			Ports: []corev1.ServicePort{{
				Port: 5000,
			}},
			Selector: map[string]string{
				"app": "registry",
			},
		},
	}
}

// getRegistryServiceIP fetches the registry service's current IP.
func getRegistryServiceIP(ctx context.Context, t *testing.T, c *clients, namespace string) string {
	t.Helper()
	svc, err := c.KubeClient.CoreV1().Services(namespace).Get(ctx, "registry", metav1.GetOptions{})
	if err != nil {
		t.Fatalf("failed to lookup registry service: %q", err)
	}
	return svc.Spec.ClusterIP
}

repository: jstrachan/pipeline

repo_name: jstrachan/pipeline


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type flags struct {
	env              string
	configFile       string
	configPath       string
	configDir        string
	marathonHost     string
	marathonCurlOpts string
	marathonForce    bool
	skipPrompt       bool
	verbose          bool
}

func (f *flags) parse() (err error) {

	// Parse flags
	flag.StringVar(&f.env, "e", "", "Environment (e.g. \"prod\")")
	flag.StringVar(&f.configFile, "f", "deploy.yaml", "Config File")
	flag.StringVar(&f.marathonHost, "marathon.host", "", "Marathon Host (e.g. \"www.example.com\"")
	flag.StringVar(&f.marathonCurlOpts, "marathon.curlopts", "", "Marathon cURL options (e.g. '-H \"OauthEmail: no-reply@cloudflare.com\"'). Note: only -H is currently supported.")
	flag.BoolVar(&f.marathonForce, "marathon.force", false, "Add the ?force=true to the Marathon request")
	flag.BoolVar(&f.skipPrompt, "y", false, "Skip confirmation prompt")
	flag.BoolVar(&f.verbose, "v", false, "Verbose mode e.g. dump Marathon config")
	flag.Parse()

	// Validate flags
	if f.env == "" || f.configFile == "" {
		flag.Usage()
		os.Exit(1)
	}
	f.configPath, err = filepath.Abs(f.configFile)
	if err != nil {
		return fmt.Errorf("Error parsing config file path: %s", err)
	}
	_, err = os.Stat(f.configPath)
	if err != nil {
		return fmt.Errorf("Invalid config file path '%s': %s", f.configFile, err)
	}
	f.configDir = filepath.Dir(f.configPath)
	if f.marathonHost != "" && strings.Contains(f.marathonHost, "/") {
		return fmt.Errorf(
			"Marathon hostname cannot contain forward slash. Found: %s",
			f.marathonHost,
		)
	}

	return

}

repository: larcher/cfdeploy

repo_name: larcher/cfdeploy


text:
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <experimental/filesystem>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "spawn.hpp"

namespace fs = std::experimental::filesystem;
using item = std::pair<int, std::string>;

std::vector<std::string> paths() {
    std::vector<std::string> paths;
    char* t = getenv("PATH");
    if(!t) throw std::runtime_error("Can not get PATH env var");

    char env_path[strlen(t) + 1];
    strcpy(env_path, t);

    for(auto p = strtok(env_path, ":"); p; p = strtok(NULL, ":"))
        paths.emplace_back(p);

    return paths;
}

bool is_executable(const auto& p) {
    return (fs::status(p).permissions() & (fs::perms::others_exec | fs::perms::group_exec |
                                           fs::perms::owner_exec)) != fs::perms::none;
}

std::vector<std::string> commands() {
    static std::vector<std::string> commands;
    if(commands.size() > 0) return commands;

    for(auto& path : paths()) try {
            for(auto& e : fs::directory_iterator(path)) {
                if(is_executable(e))
                    commands.emplace_back(e.path().filename().string());
            }
        } catch(...) {
            // Ignore errors for now
        }

    std::sort(commands.begin(), commands.end());
    commands.erase(std::unique(commands.begin(), commands.end()), commands.end());

    return commands;
}

std::vector<item> get_items(const auto& cache_file) {
    static std::vector<item> items_list;
    if(items_list.size() > 0) return items_list;

    if(std::ifstream cache(cache_file); cache.is_open()) {
        do {
            int n;
            cache >> n;

            std::string cmd;
            cache >> cmd;
            if(cmd == "") break;

            items_list.emplace_back(std::make_pair(n, cmd));
        } while(cache.good());

        std::sort(items_list.begin(), items_list.end(), [](const item& a, const item& b) {
            return a.first > b.first;
        });
    } else {
        for(auto& e : commands()) items_list.emplace_back(std::make_pair(0, e));
    }

    return items_list;
}

void update_items_cache(const auto& cache_file, const auto& cmd) {
    std::ofstream cache(cache_file, std::ios::trunc);
    if(!cache.is_open()) throw std::runtime_error("Can not open cache file");

    bool not_in_cache = true;
    for(auto& e : get_items(cache_file)) {
        if(e.second == cmd) {
            e.first++;
            not_in_cache = false;
        }

        cache << e.first << " " << e.second << "\n";
    }

    if(not_in_cache) cache << 1 << " " << cmd << "\n";
}

void execute_cmd(const auto& cmd, char* env[]) {
    auto pid = fork();
    if(pid < 0) throw std::runtime_error("Can not fork");
    if(pid > 0) std::exit(0);
    if(chdir("/") < 0) std::exit(1);
    if(!freopen("/dev/null", "r", stdin)) std::exit(1);
    if(!freopen("/dev/null", "w", stdout)) std::exit(1);
    if(!freopen("/dev/null", "w", stderr)) std::exit(1);
    const char* argv[] = {cmd.c_str(), (const char*)0};
    execvpe(argv[0], const_cast<char* const*>(argv), const_cast<char* const*>(env));
}

int main(int, char* argv[], char* env[]) try {
    auto home = getenv("HOME");
    if(!home) throw std::runtime_error("Can not get HOME env var");

    auto cache_file = std::string(home) + "/.cache/dmenu_sorted";

    argv[0] = const_cast<char*>("/usr/bin/dmenu");

    spawn dmenu(argv, false, env);

    for(auto& e : get_items(cache_file)) dmenu.stdin << e.second << "\n";
    dmenu.send_eof();
    dmenu.wait();

    std::string cmd;
    getline(dmenu.stdout, cmd);

    if(cmd == "") std::exit(1);

    update_items_cache(cache_file, cmd);
    execute_cmd(cmd, env);
} catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
    return 1;
}

extension: cpp


text:
@article{vanderplasComparisonThreeSimilarity2020,
 addendum = {Programming and analysis (20%), Writing (55%)},
 author = {Vanderplas, Susan and Nally, Melissa and Klep, Tylor and Cadevall, Cristina and Hofmann, Heike},
 author+an = {1=highlight},
 doi = {10.1016/j.forsciint.2020.110167},
 journal = {Forensic Science International},
 keywords = {3D microscopy, cross correlation, Forensic science, land engraved areas (LEAs), random forest, Toolmark},
 month = {January},
 title = {Comparison of three similarity scores for bullet LEA matching},
 year = {2020}
}

repository: srvanderplas/blogdown

repo_name: srvanderplas/blogdown


text:
// Copyright 2019, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package processor

import (
	"github.com/census-instrumentation/opencensus-service/consumer"
)

// TraceProcessor composes TraceConsumer with some additional processor-specific functions.
type TraceProcessor interface {
	consumer.TraceConsumer

	// TODO: Add processor specific functions.
}

// MetricsProcessor composes MetricsConsumer with some additional processor-specific functions.
type MetricsProcessor interface {
	consumer.MetricsConsumer

	// TODO: Add processor specific functions.
}

// Processor is a data consumer.
type Processor interface {
	consumer.DataConsumer
}

repository: Azure/azure-linux-extensions

repo_name: Azure/azure-linux-extensions

gha_language: Python


text:
/*
Copyright 2022 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package v2

import (
	"bytes"
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/require"
)

// Shows generic throws error when attempting to `Render“ an invalid output name
// And if it is then added as a template, no error is thrown upon `Render`
func TestGeneratorMissingOutput(t *testing.T) {
	var buf bytes.Buffer
	var doc map[string]interface{}

	err := json.Unmarshal([]byte(apiDiscoveryJSON), &doc)
	require.NoError(t, err)

	gen := NewGenerator()
	badTemplateName := "bad-template"
	err = gen.Render(badTemplateName, doc, apiGroupsGVR, nil, false, &buf)

	require.ErrorContains(t, err, "unrecognized format: "+badTemplateName)
	require.Zero(t, buf.Len())

	err = gen.AddTemplate(badTemplateName, "ok")
	require.NoError(t, err)

	err = gen.Render(badTemplateName, doc, apiGroupsGVR, nil, false, &buf)
	require.NoError(t, err)
	require.Equal(t, "ok", buf.String())
}

// Shows that correct context with the passed object is passed to the template
func TestGeneratorContext(t *testing.T) {
	var buf bytes.Buffer
	var doc map[string]interface{}

	err := json.Unmarshal([]byte(apiDiscoveryJSON), &doc)
	require.NoError(t, err)

	gen := NewGenerator()
	err = gen.AddTemplate("Context", "{{ toJson . }}")
	require.NoError(t, err)

	expectedContext := TemplateContext{
		Document:  doc,
		GVR:       apiGroupsGVR,
		Recursive: false,
		FieldPath: nil,
	}

	err = gen.Render("Context",
		expectedContext.Document,
		expectedContext.GVR,
		expectedContext.FieldPath,
		expectedContext.Recursive,
		&buf)
	require.NoError(t, err)

	var actualContext TemplateContext
	err = json.Unmarshal(buf.Bytes(), &actualContext)
	require.NoError(t, err)
	require.Equal(t, expectedContext, actualContext)
}

repository: thockin/kubernetes

repo_name: thockin/kubernetes


text:
// Code generated from grammars/rfc5424/RFC5424.g4 by ANTLR 4.7.1. DO NOT EDIT.

package rfc5424 // RFC5424
import "github.com/antlr/antlr4/runtime/Go/antlr"

// RFC5424Listener is a complete listener for a parse tree produced by RFC5424Parser.
type RFC5424Listener interface {
	antlr.ParseTreeListener

	// EnterFull is called when entering the full production.
	EnterFull(c *FullContext)

	// EnterHeadr is called when entering the headr production.
	EnterHeadr(c *HeadrContext)

	// EnterMsg is called when entering the msg production.
	EnterMsg(c *MsgContext)

	// EnterAllchars is called when entering the allchars production.
	EnterAllchars(c *AllcharsContext)

	// EnterTimestamp is called when entering the timestamp production.
	EnterTimestamp(c *TimestampContext)

	// EnterDate is called when entering the date production.
	EnterDate(c *DateContext)

	// EnterYear is called when entering the year production.
	EnterYear(c *YearContext)

	// EnterMonth is called when entering the month production.
	EnterMonth(c *MonthContext)

	// EnterDay is called when entering the day production.
	EnterDay(c *DayContext)

	// EnterTime is called when entering the time production.
	EnterTime(c *TimeContext)

	// EnterHour is called when entering the hour production.
	EnterHour(c *HourContext)

	// EnterMinute is called when entering the minute production.
	EnterMinute(c *MinuteContext)

	// EnterSecond is called when entering the second production.
	EnterSecond(c *SecondContext)

	// EnterNano is called when entering the nano production.
	EnterNano(c *NanoContext)

	// EnterTimezone is called when entering the timezone production.
	EnterTimezone(c *TimezoneContext)

	// EnterTimezonenum is called when entering the timezonenum production.
	EnterTimezonenum(c *TimezonenumContext)

	// EnterPri is called when entering the pri production.
	EnterPri(c *PriContext)

	// EnterVersion is called when entering the version production.
	EnterVersion(c *VersionContext)

	// EnterHostname is called when entering the hostname production.
	EnterHostname(c *HostnameContext)

	// EnterAppname is called when entering the appname production.
	EnterAppname(c *AppnameContext)

	// EnterMsgid is called when entering the msgid production.
	EnterMsgid(c *MsgidContext)

	// EnterProcid is called when entering the procid production.
	EnterProcid(c *ProcidContext)

	// EnterAllascii is called when entering the allascii production.
	EnterAllascii(c *AllasciiContext)

	// EnterStructured is called when entering the structured production.
	EnterStructured(c *StructuredContext)

	// EnterElement is called when entering the element production.
	EnterElement(c *ElementContext)

	// EnterSid is called when entering the sid production.
	EnterSid(c *SidContext)

	// EnterParam is called when entering the param production.
	EnterParam(c *ParamContext)

	// EnterName is called when entering the name production.
	EnterName(c *NameContext)

	// EnterSpecialname is called when entering the specialname production.
	EnterSpecialname(c *SpecialnameContext)

	// EnterValue is called when entering the value production.
	EnterValue(c *ValueContext)

	// EnterSpecialvalue is called when entering the specialvalue production.
	EnterSpecialvalue(c *SpecialvalueContext)

	// ExitFull is called when exiting the full production.
	ExitFull(c *FullContext)

	// ExitHeadr is called when exiting the headr production.
	ExitHeadr(c *HeadrContext)

	// ExitMsg is called when exiting the msg production.
	ExitMsg(c *MsgContext)

	// ExitAllchars is called when exiting the allchars production.
	ExitAllchars(c *AllcharsContext)

	// ExitTimestamp is called when exiting the timestamp production.
	ExitTimestamp(c *TimestampContext)

	// ExitDate is called when exiting the date production.
	ExitDate(c *DateContext)

	// ExitYear is called when exiting the year production.
	ExitYear(c *YearContext)

	// ExitMonth is called when exiting the month production.
	ExitMonth(c *MonthContext)

	// ExitDay is called when exiting the day production.
	ExitDay(c *DayContext)

	// ExitTime is called when exiting the time production.
	ExitTime(c *TimeContext)

	// ExitHour is called when exiting the hour production.
	ExitHour(c *HourContext)

	// ExitMinute is called when exiting the minute production.
	ExitMinute(c *MinuteContext)

	// ExitSecond is called when exiting the second production.
	ExitSecond(c *SecondContext)

	// ExitNano is called when exiting the nano production.
	ExitNano(c *NanoContext)

	// ExitTimezone is called when exiting the timezone production.
	ExitTimezone(c *TimezoneContext)

	// ExitTimezonenum is called when exiting the timezonenum production.
	ExitTimezonenum(c *TimezonenumContext)

	// ExitPri is called when exiting the pri production.
	ExitPri(c *PriContext)

	// ExitVersion is called when exiting the version production.
	ExitVersion(c *VersionContext)

	// ExitHostname is called when exiting the hostname production.
	ExitHostname(c *HostnameContext)

	// ExitAppname is called when exiting the appname production.
	ExitAppname(c *AppnameContext)

	// ExitMsgid is called when exiting the msgid production.
	ExitMsgid(c *MsgidContext)

	// ExitProcid is called when exiting the procid production.
	ExitProcid(c *ProcidContext)

	// ExitAllascii is called when exiting the allascii production.
	ExitAllascii(c *AllasciiContext)

	// ExitStructured is called when exiting the structured production.
	ExitStructured(c *StructuredContext)

	// ExitElement is called when exiting the element production.
	ExitElement(c *ElementContext)

	// ExitSid is called when exiting the sid production.
	ExitSid(c *SidContext)

	// ExitParam is called when exiting the param production.
	ExitParam(c *ParamContext)

	// ExitName is called when exiting the name production.
	ExitName(c *NameContext)

	// ExitSpecialname is called when exiting the specialname production.
	ExitSpecialname(c *SpecialnameContext)

	// ExitValue is called when exiting the value production.
	ExitValue(c *ValueContext)

	// ExitSpecialvalue is called when exiting the specialvalue production.
	ExitSpecialvalue(c *SpecialvalueContext)
}

repository: fossabot/skewer

repo_name: fossabot/skewer


text:
package ui

import "github.com/jroimartin/gocui"

// NewButtonWidget creates a new button
func NewButtonWidget(name string, x, y int, label string, handler func(g *gocui.Gui, v *gocui.View) error) *ButtonWidget {
	return &ButtonWidget{name: name, x: x, y: y, w: len(label) + 1, label: label, handler: handler}
}

// ButtonWidget holds button information
type ButtonWidget struct {
	name    string
	x, y    int
	w       int
	label   string
	handler func(g *gocui.Gui, v *gocui.View) error
}


text:
SUMMARY = "VideoOutput plugin for the camera backend"
HOMEPAGE = "http://bazaar.launchpad.net/~phablet-team/qtvideo-node"
LICENSE = "LGPL-3.0"
LIC_FILES_CHKSUM = "file://COPYING;md5=e6a600fd5e1d9cbde2d983680233ad02"

inherit qmake5

DEPENDS = "libhybris qtbase libqtubuntu-media-signals exiv2 qtmultimedia qtdeclarative"

RDEPENDS_${PN} += "qtmultimedia-plugins"

SRCREV = "d47a9b1eba42c0e5ba6f2e236f28bb779c9ba1cf"
SRC_URI = "git://github.com/webOS-ports/luneos-qtvideo-node.git"
PV = "0.2.1+git${SRCREV}"

S = "${WORKDIR}/git"

EXTRA_OEMAKE += "INSTALL_ROOT=${D}"

EXTRA_QMAKEVARS_PRE = "\
    PREFIX=${prefix} \
"

FILES_${PN} += "\
    ${OE_QMAKE_PATH_PLUGINS} \
"

repository: Tofee/meta-webos-ports

repo_name: Tofee/meta-webos-ports

gha_language: BitBake


text:
@book{miller_simultaneous_1981,
	edition = {2nd},
	title = {Simultaneous Statistical Inference},
	isbn = {0387905480},
	abstract = {Description: Rupert Miller wrote the classic text on multiple comparisons adjustments back in 1981. The book does not include some recent methods, but does provide a good overview. Dr. Miller also outlines several different philosophical perspectives on multiple comparison adjustments. This book is a gentle introduction to a specialized topic.},
	publisher = {Springer},
	author = {Miller, Rupert G. Jr.},
	date = {1981-03-18}
}

repository: pmean/build-website

repo_name: pmean/build-website


text:
package main

//go:generate rice embed-go

import (
	"context"
	"database/sql"

	rice "github.com/GeertJohan/go.rice"
	"github.com/andrewstucki/web-app-tools/go/oauth/verifier"
	"github.com/andrewstucki/web-app-tools/go/security"
	"github.com/andrewstucki/web-app-tools/go/server"
	uuid "github.com/satori/go.uuid"
	"github.com/volatiletech/sqlboiler/boil"
	"github.com/volatiletech/sqlboiler/queries/qm"

	"example/models"
	"example/roles"
	"example/routes"
)

// This gets a user based off of a JWT identity token
func userFromClaims(ctx context.Context, claims *verifier.StandardClaims) (*models.User, error) {
	user, err := models.Users(models.UserWhere.GoogleID.EQ(claims.Subject)).One(ctx, server.Tx(ctx))
	if err != nil && err == sql.ErrNoRows {
		return nil, nil
	}
	return user, err
}

// This gets a user based off of an API token
func userFromToken(ctx context.Context, token string) (*models.User, error) {
	if apiToken, err := uuid.FromString(token); err == nil {
		user, err := models.Users(qm.InnerJoin("user_tokens on user_tokens.user_id = users.id"), models.UserTokenWhere.ID.EQ(apiToken)).One(ctx, server.Tx(ctx))
		if err != nil && err == sql.ErrNoRows {
			return nil, nil
		}
		return user, err
	}
	// we don't have a valid uuid
	return nil, nil
}

var config = server.Config{
	// This contains the path to the migrations
	Migrations: rice.MustFindBox("./migrations"),
	// This contains the path to the frontend assets
	Assets: rice.MustFindBox("./frontend/build"),
	// This method is invoked after the database is initialized and migrated and various
	// internal auth handlers are set up, it's where the main route initialization code
	// should be
	Setup: func(config *server.SetupConfig) {
		roles.Register()
		config.Router.Route("/v1", routes.NewV1Handler(config.Logger, config.Render).Register)
	},
	// This callback is used to actually return the currently logged in user and allows
	// us to invoked the server.CurrentUser(ctx) method to get the user
	GetCurrentUser: func(ctx context.Context, claimsOrToken *server.ClaimsOrToken) (interface{}, error) {
		if claimsOrToken.Claims != nil {
			return userFromClaims(ctx, claimsOrToken.Claims)
		}
		return userFromToken(ctx, claimsOrToken.Token)
	},
	// This gets invoked the first time anyone ever logs into the system
	// it's useful for setting up an admin user
	OnFirstUser: func(ctx context.Context, claims *verifier.StandardClaims) error {
		user := models.User{Email: claims.Email, GoogleID: claims.Subject}
		if err := user.Upsert(ctx, server.Tx(ctx), false, nil, boil.Infer(), boil.Infer()); err != nil {
			return err
		}
		return security.SetRole(ctx, roles.SuperAdminRole, user.ID)
	},
	// This gets called every subsequent log in, it's useful for inserting
	// a user if they don't already exist
	OnLogin: func(ctx context.Context, claims *verifier.StandardClaims) error {
		user := models.User{Email: claims.Email, GoogleID: claims.Subject}
		return user.Upsert(ctx, server.Tx(ctx), false, nil, boil.Infer(), boil.Infer())
	},
}

func main() {
	server.RunServer(config)
}

repository: andrewstucki/web-app-tools

repo_name: andrewstucki/web-app-tools


text:
package main

import (
	"fmt"
	"math"
)

// START OMIT
type Point struct {
	X, Y float64
}

func (point Point) Distance(q Point) float64 { // HL
	return math.Hypot(point.X-q.X, point.Y-q.Y)
}

func main() {
	var p = Point{3, 5}

	dist := p.Distance(Point{1, 0}) // HL

	fmt.Println(dist)
}

// END OMIT

repository: sergeleger/mug

repo_name: sergeleger/mug


text:
require tisdk-core-bundle.inc

DEPLOY_SPL_NAME_omapl138 = ""
DEPLOY_SPL_NAME_k2hk = ""
DEPLOY_SPL_NAME_k2l = ""
DEPLOY_SPL_NAME_k2e = ""
# Only unset it for HS device, as k2g GP does provide MLO/SPL
DEPLOY_SPL_NAME_k2g-hs-evm = ""
DEPLOY_SPL_NAME_k3 = "tispl.bin tiboot3.bin"

DEPLOY_IMAGES_NAME_k3 = "bl31.bin bl32.bin"
DEPLOY_IMAGES_NAME_append_am65xx = " sysfw.itb"
DEPLOY_IMAGES_NAME_append_j7-evm = " sysfw.itb"
DEPLOY_IMAGES_NAME_append_j7-hs-evm = " sysfw.itb"
DEPLOY_IMAGES_NAME_append_am65xx-evm = " ti-sci-firmware-am65x-gp.bin sysfw-am65x-evm.itb sysfw-am65x_sr2-evm.itb"
DEPLOY_IMAGES_NAME_append_j7-evm = " ti-fs-firmware-j721e-gp.bin"

ARAGO_TISDK_IMAGE ?= "tisdk-core-bundle"
export IMAGE_BASENAME = "${ARAGO_TISDK_IMAGE}"


text:
package views

import (
	"net/http"
	"time"

	"github.com/antihax/evedata/services/vanguard"
	"github.com/antihax/evedata/services/vanguard/models"
)

func init() {
	vanguard.AddRoute("GET", "/activeWars",
		func(w http.ResponseWriter, r *http.Request) {
			renderTemplate(w,
				"wars.html",
				time.Hour*24*31,
				newPage(r, "Active Wars"))
		})

	vanguard.AddRoute("GET", "/J/activeWars", activeWars)
}

func activeWars(w http.ResponseWriter, r *http.Request) {
	v, err := models.GetActiveWarList()
	if err != nil {
		httpErr(w, err)
		return
	}

	renderJSON(w, v, time.Hour)
}

repository: antihax/evedata

repo_name: antihax/evedata