code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
package parser import ( "fmt" "reflect" ) type Kind int const ( KindScalar Kind = iota KindCustomScalar KindObject KindInterface KindInterfaceDefinition KindUnion KindEnum KindList KindNullable KindInvalidType ) func (kind Kind) String() string { typeMap := map[Kind]string{ KindScalar: "Scalar", KindCustomScalar: "CustomScalar", KindObject: "Object", KindInterface: "Interface", KindInterfaceDefinition: "InterfaceDefinition", KindUnion: "Union", KindEnum: "Enum", KindList: "List", KindNullable: "Nullable", KindInvalidType: "InvalidType", } return typeMap[kind] } func validateTypeKind(t reflect.Type, expected ...Kind) error { kindString := "" if len(expected) == 0 { return nil } kind, err := getTypeKind(t) if err != nil { return err } for _, expectedKind := range expected { kindString += fmt.Sprintf("%s, ", expectedKind.String()) if kind == expectedKind { return nil } } kindString = kindString[:len(kindString)-2] return fmt.Errorf("reflect.Type of kind %s was expected, got %s", kindString, kind.String()) } func getOrCreateType(t reflect.Type) (Type, error) { parserType, ok := cache.get(t) if ok { return parserType, nil } kind, err := getTypeKind(t) if err != nil { return nil, err } switch kind { case KindScalar, KindCustomScalar: return NewScalar(t) case KindInterface: return NewInterface(t) case KindInterfaceDefinition: return NewInterfaceFromDefinition(t) case KindObject: return NewObject(t) case KindUnion: return NewUnion(t) case KindEnum: return NewEnum(t) case KindList: return NewArray(t, false) case KindNullable: return NewNullable(t, false) } panic("groot: unexpected error occurred") } func isTypeUnion(t reflect.Type) bool { for i := 0; i < t.NumField(); i++ { field := t.Field(i) if field.Anonymous && field.Type == reflect.TypeOf(UnionType{}) { return true } } return false } func isInterfaceDefinition(t reflect.Type) bool { interfaceType := reflect.TypeOf(InterfaceType{}) if t.Kind() != reflect.Struct { return false } for i := 0; i < t.NumField(); i++ { if field := t.Field(i); field.Anonymous && field.Type == interfaceType { return true } } return false } func getTypeKind(t reflect.Type) (Kind, error) { var ( enumType = reflect.TypeOf((*EnumType)(nil)).Elem() scalarType = reflect.TypeOf((*ScalarType)(nil)).Elem() ) if parserType, ok := t.(Type); ok { t = parserType.ReflectType() } if ptrT := reflect.PtrTo(t); ptrT.Implements(scalarType) { return KindCustomScalar, nil } switch t.Kind() { case reflect.Ptr: return KindNullable, nil case reflect.Slice: return KindList, nil case reflect.Interface: return KindInterface, nil case reflect.Struct: if isTypeUnion(t) { return KindUnion, nil } if isInterfaceDefinition(t) { return KindInterfaceDefinition, nil } return KindObject, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Float32, reflect.Float64, reflect.Bool: return KindScalar, nil case reflect.String: if t.Name() == "string" || !t.Implements(enumType) { return KindScalar, nil } return KindEnum, nil } return KindInvalidType, fmt.Errorf("couldn't parse type %s", t.Name()) }
parser/type.go
0.575349
0.479626
type.go
starcoder
package bytecode import ( "encoding/binary" "math" "strings" ) func Float32ToBinary(value float32) []byte { bytes := make([]byte, 4) bits := math.Float32bits(value) binary.BigEndian.PutUint32(bytes, bits) return bytes } func Float64ToBinary(value float64) []byte { bytes := make([]byte, 8) bits := math.Float64bits(value) binary.BigEndian.PutUint64(bytes, bits) return bytes } func Int16ToBinary(value uint16) []byte { return SInt16ToBinary(int16(value)) } func SInt16ToBinary(value int16) []byte { bytes := make([]byte, 2) bytes[0] = byte(value >> 8) bytes[1] = byte(value) return bytes } func Int32ToBinary(value uint32) []byte { return SInt32ToBinary(int(value)) } func SInt32ToBinary(value int) []byte { bytes := make([]byte, 4) bytes[0] = byte(value >> 24) bytes[1] = byte(value >> 16) bytes[2] = byte(value >> 8) bytes[3] = byte(value) return bytes } func Int64ToBinary(value uint64) []byte { return SInt64ToBinary(int64(value)) } func SInt64ToBinary(value int64) []byte { bytes := make([]byte, 8) bytes[0] = byte(value >> 56) bytes[1] = byte(value >> 48) bytes[2] = byte(value >> 40) bytes[3] = byte(value >> 32) bytes[4] = byte(value >> 24) bytes[5] = byte(value >> 16) bytes[6] = byte(value >> 8) bytes[7] = byte(value) return bytes } func DescriptorToStackSize(descriptor string) []uint16 { beginIndex := strings.LastIndex(descriptor, "(") endIndex := strings.LastIndex(descriptor, ")") sizes := make([]uint16, 2) for i := beginIndex; i < endIndex; i++ { char := []rune(descriptor)[i] if char == '[' { continue } if char == 'L' { sizes[0] += 1 end := strings.Index(descriptor, ";") i = end if i > endIndex { break } continue } sizes[0] += 1 } sizes[0] -= 1 sub := strings.Split(descriptor, ")")[1] if sub == "V" { return sizes } sizes[1] = 1 return sizes }
converters.go
0.788176
0.448064
converters.go
starcoder
package sandbox import ( "encoding/json" ) // SandboxBeamCounts struct for SandboxBeamCounts type SandboxBeamCounts struct { Count *int64 `json:"count,omitempty"` } // NewSandboxBeamCounts instantiates a new SandboxBeamCounts object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewSandboxBeamCounts() *SandboxBeamCounts { this := SandboxBeamCounts{} return &this } // NewSandboxBeamCountsWithDefaults instantiates a new SandboxBeamCounts object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewSandboxBeamCountsWithDefaults() *SandboxBeamCounts { this := SandboxBeamCounts{} return &this } // GetCount returns the Count field value if set, zero value otherwise. func (o *SandboxBeamCounts) GetCount() int64 { if o == nil || o.Count == nil { var ret int64 return ret } return *o.Count } // GetCountOk returns a tuple with the Count field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SandboxBeamCounts) GetCountOk() (*int64, bool) { if o == nil || o.Count == nil { return nil, false } return o.Count, true } // HasCount returns a boolean if a field has been set. func (o *SandboxBeamCounts) HasCount() bool { if o != nil && o.Count != nil { return true } return false } // SetCount gets a reference to the given int64 and assigns it to the Count field. func (o *SandboxBeamCounts) SetCount(v int64) { o.Count = &v } func (o SandboxBeamCounts) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Count != nil { toSerialize["count"] = o.Count } return json.Marshal(toSerialize) } type NullableSandboxBeamCounts struct { value *SandboxBeamCounts isSet bool } func (v NullableSandboxBeamCounts) Get() *SandboxBeamCounts { return v.value } func (v *NullableSandboxBeamCounts) Set(val *SandboxBeamCounts) { v.value = val v.isSet = true } func (v NullableSandboxBeamCounts) IsSet() bool { return v.isSet } func (v *NullableSandboxBeamCounts) Unset() { v.value = nil v.isSet = false } func NewNullableSandboxBeamCounts(val *SandboxBeamCounts) *NullableSandboxBeamCounts { return &NullableSandboxBeamCounts{value: val, isSet: true} } func (v NullableSandboxBeamCounts) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableSandboxBeamCounts) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
openapi/sandbox/model_sandbox_beam_counts.go
0.757256
0.5425
model_sandbox_beam_counts.go
starcoder
package signals import ( "fmt" "strconv" "time" "github.com/google/edf" ) // GetSignals return the signals from an EDF dataset. func GetSignals(e *edf.Edf) ([]Signal, error) { signals := make([]Signal, e.Header.NumSignals) for i := range e.Header.Signals { signal, err := newEdfSignal(e, i) if err != nil { return nil, err } if e.Header.Signals[i].Label == "EDF Annotations" { signals[i], err = newAnnotationSignal(signal) if err != nil { return nil, err } } else { signals[i] = newDataSignal(signal) } } return signals, nil } type edfSignal struct { edf *edf.Edf startTime time.Time endTime time.Time signalIndex int // digital to physical conversion parameters a float64 b float64 } func newEdfSignal(e *edf.Edf, signalIndex int) (*edfSignal, error) { s := new(edfSignal) s.edf = e s.signalIndex = signalIndex start, err := getStartTime(e.Header) if err != nil { return nil, err } s.startTime = start end, err := getEndTime(e.Header) if err != nil { return nil, err } s.endTime = end def := &s.edf.Header.Signals[signalIndex] physMin, err := strconv.ParseFloat(def.PhysicalMinimum, 32) if err != nil { return nil, err } physMax, err := strconv.ParseFloat(def.PhysicalMaximum, 32) if err != nil { return nil, err } digiMin, err := strconv.ParseFloat(def.DigitalMinimum, 32) if err != nil { return nil, err } digiMax, err := strconv.ParseFloat(def.DigitalMaximum, 32) if err != nil { return nil, err } s.a = (physMax - physMin) / (digiMax - digiMin) s.b = physMin - s.a*digiMin return s, nil } func (s *edfSignal) Label() string { return s.Definition().Label } // Start date and time of the recording. func (s *edfSignal) StartTime() time.Time { return s.startTime } // End date and time of the recording. func (s *edfSignal) EndTime() time.Time { return s.endTime } // Signal definition. This may be nil for composite/generated signals. func (s *edfSignal) Definition() *edf.SignalDefinition { return &s.edf.Header.Signals[s.signalIndex] } // getStartTime returns the starting date and time of the recording func getStartTime(h *edf.Header) (time.Time, error) { return time.Parse("02.01.06 15.04.05", h.StartDate+" "+h.StartTime) } // getEndTime returns the end date and time of the recording func getEndTime(h *edf.Header) (time.Time, error) { start, err := getStartTime(h) if err != nil { return start, err } end := start.Add( time.Duration( float32(h.NumDataRecords)*h.DurationDataRecords) * time.Second) return end, nil } // getSignalData returns the signal samples between the specified times. func getSignalData(e *edf.Edf, signalIndex int, start, end time.Time) ([]int16, error) { recordingStart, err := getStartTime(e.Header) if err != nil { return nil, err } if recordingStart.After(start) { return nil, fmt.Errorf("Requesting data before the recording") } recordingEnd, err := getEndTime(e.Header) if err != nil { return nil, err } if recordingEnd.Before(end) { return nil, fmt.Errorf("Requesting data after the recording") } durationSample := float64(e.Header.DurationDataRecords) / float64(e.Header.Signals[signalIndex].SamplesRecord) skipStart := start.Sub(recordingStart) startRecord := uint32( skipStart.Seconds() / float64(e.Header.DurationDataRecords)) startSample := uint32( (skipStart.Seconds() - (float64(startRecord) * float64(e.Header.DurationDataRecords))) / (durationSample)) endRecord := uint32( end.Sub(recordingStart).Seconds() / float64(e.Header.DurationDataRecords)) endSample := uint32((end.Sub(recordingStart).Seconds() - (float64(endRecord) * float64(e.Header.DurationDataRecords))) / (durationSample)) numSamples := e.Header.Signals[signalIndex].SamplesRecord*(endRecord-startRecord-1) + endSample + (e.Header.Signals[signalIndex].SamplesRecord - startSample) result := make([]int16, numSamples) s := 0 for i := startRecord; i <= endRecord; i++ { for j := uint32(0); j < e.Header.Signals[signalIndex].SamplesRecord; j++ { if i == startRecord && j == 0 { j = startSample } if i == endRecord && j >= endSample { break } result[s] = e.Records[i].Signals[signalIndex].Samples[j] s++ } } return result, nil }
signals/parser.go
0.632616
0.414188
parser.go
starcoder
package kv import ( "bytes" "encoding" ) // KeyValue represents a recursive string key to arbitrary value container. type KeyValue interface { // Type returns the node's Type. Type() Type // SetType sets the node's Type and returns the receiver. SetType(Type) KeyValue // Key returns the node's Key. Key() string // SetKey sets the node's Key and returns the receiver. SetKey(key string) KeyValue // Value returns the node's Value. Value() string // SetValue sets the node's Value and returns the receiver. SetValue(value string) KeyValue // Parent returns the parent node. Parent() KeyValue // SetParent sets the node's parent node and returns the receiver. SetParent(KeyValue) KeyValue // Children returns all child nodes Children() []KeyValue // SetChildren sets the node's children and returns the receiver. SetChildren(...KeyValue) KeyValue // Child finds a child node with the given key. Child(key string) KeyValue // AddChild adds a child node and returns the receiver. AddChild(KeyValue) KeyValue // AddObject adds an Object child node and returns the receiver. AddObject(key string) KeyValue // AddString adds a String child node and returns the receiver. AddString(key, value string) KeyValue // AddInt32 adds an Int32 child node and returns the receiver. AddInt32(key, value string) KeyValue // AddInt64 adds an Int64 child node and returns the receiver. AddInt64(key, value string) KeyValue // AddUint64 adds an Uint64 child node and returns the receiver. AddUint64(key, value string) KeyValue // AddFloat32 adds a Float32 child node and returns the receiver. AddFloat32(key, value string) KeyValue // AddColor adds a Color child node and returns the receiver. AddColor(key, value string) KeyValue // AddPointer adds a Pointer child node and returns the receiver. AddPointer(key, value string) KeyValue encoding.BinaryMarshaler encoding.BinaryUnmarshaler } type keyValue struct { typ Type key string value string parent KeyValue children []KeyValue } func NewKeyValue(t Type, key, value string, parent KeyValue) KeyValue { return &keyValue{ typ: t, key: key, value: value, parent: parent, } } func NewKeyValueEmpty() KeyValue { return NewKeyValue(TypeInvalid, "", "", nil) } func NewKeyValueRoot(key string) KeyValue { return NewKeyValueObject(key, nil) } func NewKeyValueObject(key string, parent KeyValue) KeyValue { return NewKeyValue(TypeObject, key, "", parent) } func NewKeyValueString(key, value string, parent KeyValue) KeyValue { return NewKeyValue(TypeString, key, value, parent) } func NewKeyValueInt32(key, value string, parent KeyValue) KeyValue { return NewKeyValue(TypeInt32, key, value, parent) } func NewKeyValueInt64(key, value string, parent KeyValue) KeyValue { return NewKeyValue(TypeInt64, key, value, parent) } func NewKeyValueUint64(key, value string, parent KeyValue) KeyValue { return NewKeyValue(TypeUint64, key, value, parent) } func NewKeyValueFloat32(key, value string, parent KeyValue) KeyValue { return NewKeyValue(TypeFloat32, key, value, parent) } func NewKeyValueColor(key, value string, parent KeyValue) KeyValue { return NewKeyValue(TypeColor, key, value, parent) } func NewKeyValuePointer(key, value string, parent KeyValue) KeyValue { return NewKeyValue(TypePointer, key, value, parent) } func (kv *keyValue) Type() Type { return kv.typ } func (kv *keyValue) SetType(t Type) KeyValue { kv.typ = t return kv } func (kv *keyValue) Key() string { return kv.key } func (kv *keyValue) SetKey(k string) KeyValue { kv.key = k return kv } func (kv *keyValue) Value() string { return kv.value } func (kv *keyValue) SetValue(v string) KeyValue { kv.value = v return kv } func (kv *keyValue) Parent() KeyValue { return kv.parent } func (kv *keyValue) SetParent(p KeyValue) KeyValue { kv.parent = p return kv } func (kv *keyValue) Children() []KeyValue { return kv.children } func (kv *keyValue) SetChildren(children ...KeyValue) KeyValue { for _, c := range children { c.SetParent(kv) } kv.children = children return kv } func (kv *keyValue) Child(key string) KeyValue { for _, c := range kv.children { if c.Key() == key { return c } } return nil } func (kv *keyValue) AddChild(c KeyValue) KeyValue { c.SetParent(kv) kv.children = append(kv.children, c) return kv } func (kv *keyValue) AddObject(key string) KeyValue { return kv.AddChild(NewKeyValueObject(key, kv)) } func (kv *keyValue) AddString(key, value string) KeyValue { return kv.AddChild(NewKeyValueString(key, value, kv)) } func (kv *keyValue) AddInt32(key, value string) KeyValue { return kv.AddChild(NewKeyValueInt32(key, value, kv)) } func (kv *keyValue) AddInt64(key, value string) KeyValue { return kv.AddChild(NewKeyValueInt64(key, value, kv)) } func (kv *keyValue) AddUint64(key, value string) KeyValue { return kv.AddChild(NewKeyValueUint64(key, value, kv)) } func (kv *keyValue) AddFloat32(key, value string) KeyValue { return kv.AddChild(NewKeyValueFloat32(key, value, kv)) } func (kv *keyValue) AddColor(key, value string) KeyValue { return kv.AddChild(NewKeyValueColor(key, value, kv)) } func (kv *keyValue) AddPointer(key, value string) KeyValue { return kv.AddChild(NewKeyValuePointer(key, value, kv)) } func (kv *keyValue) MarshalText() ([]byte, error) { b := &bytes.Buffer{} if err := NewTextEncoder(b).Encode(kv); err != nil { return nil, err } return b.Bytes(), nil } func (kv *keyValue) MarshalBinary() ([]byte, error) { b := &bytes.Buffer{} if err := NewBinaryEncoder(b).Encode(kv); err != nil { return nil, err } return b.Bytes(), nil } func (kv *keyValue) UnmarshalBinary(data []byte) error { return NewBinaryDecoder(bytes.NewReader(data)).Decode(kv) }
kv/kv.go
0.821474
0.434701
kv.go
starcoder
package bloomfilter import ( "fmt" "strconv" "strings" ) // Encode handles encoding the bloom filter. // An example string before encoding: "AAAABBCCCDZZZRTTT" // An example string after encoding "A4B2C3D1Z3R1T3". // Please note: This could essentially return an inoptimal compression, as if // we have a string with alternating single values (i.e., "01010101010101") // this RLE encoding will result in a string twice as long. // There is an optimization where we only count runs and not single characters, // but for the time being, I don't think it's necessary. func Encode(inputString string) string { if len(inputString) == 0 { return "" } var currentChar byte var count int = 0 var output string // Iterate through each character in the string. Keep the current // character that we're tracking and the current count. If we reach a // character which is not the currently tracked character, we reset // the currently tracked character and the count. Runs in O(n). for i := range inputString { if i == 0 { currentChar = inputString[i] count++ continue } if inputString[i] == currentChar { count++ } else { output = writeOutput( output, currentChar, count, ) currentChar = inputString[i] count = 1 } } // Write it one more time because we hit bounds on ranging inputString. output = writeOutput( output, currentChar, count, ) return output } // Decode essentially works opposite of Encode and turns and encoded string // into a normal, usable string. func Decode(encodedString string) string { if len(encodedString) == 0 { return "" } encodedString = strings.TrimSpace(encodedString) var output string var accumulatedInt string var trackedChar byte for i := 0; i <= len(encodedString); i++ { if i == len(encodedString) { count, _ := strconv.Atoi(accumulatedInt) output = writeRepeat(output, trackedChar, count) continue } if _, err := strconv.Atoi(string(encodedString[i])); err == nil { if accumulatedInt == "0" { accumulatedInt = string(encodedString[i]) } else { accumulatedInt = fmt.Sprintf("%s%s", accumulatedInt, string(encodedString[i])) } } else { if accumulatedInt != "" { count, _ := strconv.Atoi(accumulatedInt) output = writeRepeat(output, trackedChar, count) } else if accumulatedInt == "0" { output = writeRepeat(output, trackedChar, 1) } trackedChar = encodedString[i] accumulatedInt = "0" } } return output } // writeOutput is just a simple helper method for Encode which sprintfs the // output string func writeOutput(outputString string, char byte, count int) string { var retVal string if count == 1 { return fmt.Sprintf( "%s%s", outputString, string(char), ) } else { retVal = fmt.Sprintf( "%s%s%d", outputString, string(char), count, ) } return retVal } // writeRepeat handles writing repeating characters intelligently func writeRepeat(output string, char byte, repeat int) string { var retVal string // If the next character is an integer, we can encode it. if repeat > 1 { retVal = fmt.Sprintf( "%s%s", output, strings.Repeat( string(char), repeat, ), ) } else { retVal = fmt.Sprintf( "%s%s", output, string(char), ) } return retVal }
bloomfilter/rle.go
0.688154
0.414069
rle.go
starcoder
package zarray import ( "errors" "fmt" ) // Array Array insert, delete, random access according to the subscript operation, the data is interface type type Array struct { data []interface{} size int } // ERR_ILLEGAL_INDEX illegal index var ERR_ILLEGAL_INDEX = errors.New("illegal index") // New array initialization memory func New(capacity ...int) (array *Array) { if len(capacity) >= 1 && capacity[0] != 0 { array = &Array{ data: make([]interface{}, capacity[0]), size: 0, } } else { array = &Array{ data: make([]interface{}, 10), size: 0, } } return } // Copy copy an array func Copy(arr interface{}) (array *Array, err error) { data, ok := arr.([]interface{}) if ok { l := len(data) array = New(l) for i := 0; i < l; i++ { array.Push(data[i]) } } else { err = errors.New("type of error") } return } // determine whether the index is out of bounds func (array *Array) checkIndex(index int) (bool, int) { size := array.size if index < 0 || index >= size { return true, size } return false, size } // array expansion func (array *Array) resize(capacity int) { newArray := make([]interface{}, capacity) for i := 0; i < array.size; i++ { newArray[i] = array.data[i] } array.data = newArray } // CapLength get array capacity func (array *Array) CapLength() int { return cap(array.data) } // Length get array length func (array *Array) Length() int { return array.size } // IsEmpty determine whether the array is empty func (array *Array) IsEmpty() bool { return array.size == 0 } // Unshift insert element into array header func (array *Array) Unshift(value interface{}) error { return array.Add(0, value) } // Push insert element to end of array func (array *Array) Push(values ...interface{}) { for i := 0; i < len(values); i++ { _ = array.Add(array.size, values[i]) } } // Set in the index position insert the element func (array *Array) Add(index int, value interface{}) (err error) { if index < 0 || index > array.size { err = errors.New("sdd failed. Require index >= 0 and index <= size") return } // If the current number of elements is equal to the array capacity, // the array will be expanded to twice the original size capLen := array.CapLength() if array.size == capLen { array.resize(capLen * 2) } for i := array.size - 1; i >= index; i-- { array.data[i+1] = array.data[i] } array.data[index] = value array.size++ return } // ForEcho traversing generates a new array func (array *Array) Map(fn func(interface{}) interface{}) *Array { values, _ := Copy(array.data) for i := 0; i < values.Length(); i++ { value, _ := values.Get(i) _ = values.Set(i, fn(value)) } return values } // Get Gets the element corresponding to the index position func (array *Array) Get(index int, def ...interface{}) (value interface{}, err error) { if r, _ := array.checkIndex(index); r { err = ERR_ILLEGAL_INDEX if dValue, dErr := GetInterface(def, 0, nil); dErr == nil { value = dValue } return } value = array.data[index] return } // Set modify the element at the index position func (array *Array) Set(index int, value interface{}) (err error) { if r, _ := array.checkIndex(index); r { return ERR_ILLEGAL_INDEX } array.data[index] = value return } // Contains find if there are elements in the array func (array *Array) Contains(value interface{}) bool { for i := 0; i < array.size; i++ { if array.data[i] == value { return true } } return false } // Index Find array by index, index range [0, n-1] (not found, return - 1) func (array *Array) Index(value interface{}) int { for i := 0; i < array.size; i++ { if array.data[i] == value { return i } } return -1 } // Remove delete the element at index position and return func (array *Array) Remove(index int, l ...int) (value []interface{}, err error) { r, size := array.checkIndex(index) if r { err = ERR_ILLEGAL_INDEX return } removeL := 1 if len(l) > 0 && l[0] > 1 { removeL = l[0] } value = make([]interface{}, removeL) copy(value, array.data[index:index+removeL]) for i := index + removeL; i < array.size; i++ { array.data[i-removeL] = array.data[i] array.data[i] = nil } array.size = size - removeL capLen := array.CapLength() if array.size == capLen/4 && capLen/2 != 0 { array.resize(capLen / 2) } return } // Shift delete the first element of the array func (array *Array) Shift() (interface{}, error) { return array.Remove(0) } // Pop delete end element func (array *Array) Pop() (interface{}, error) { return array.Remove(array.size - 1) } // RemoveValue removes the specified element from the array func (array *Array) RemoveValue(value interface{}) (e interface{}, err error) { index := array.Index(value) if index != -1 { e, err = array.Remove(index) } return } // Clear clear array func (array *Array) Clear() { array.data = make([]interface{}, array.size) array.size = 0 } // Raw original array func (array *Array) Raw() []interface{} { return array.data[:array.size] } // Format output sequence func (array *Array) Format() (format string) { format = fmt.Sprintf("Array: size = %d , capacity = %d\n", array.size, cap(array.data)) format += "[" for i := 0; i < array.Length(); i++ { format += fmt.Sprintf("%+v", array.data[i]) if i != array.size-1 { format += ", " } } format += "]" return } // GetInterface Get the element corresponding to the index position of [] interface {} func GetInterface(arr []interface{}, index int, def ...interface{}) (value interface{}, err error) { arrLen := len(arr) if arrLen > 0 && index < arrLen { value = arr[index] } else { err = ERR_ILLEGAL_INDEX var dValue interface{} if len(def) > 0 { dValue = def[0] } value = dValue } return }
zarray/array.go
0.542621
0.447762
array.go
starcoder
package oopmix import ( "errors" ) // ThousandOp holds the data necessary to call ten HunredOps. type ThousandOp struct { InPort func(int) op1 *HundredOp op2 *HundredOp op3 *HundredOp op4 *HundredOp op5 *HundredOp op6 *HundredOp op7 *HundredOp op8 *HundredOp op9 *HundredOp op10 *HundredOp } // NewThousandOp returns a new ThousandOp. func NewThousandOp() *ThousandOp { o := &ThousandOp{ op1: NewHundredOp(), op2: NewHundredOp(), op3: NewHundredOp(), op4: NewHundredOp(), op5: NewHundredOp(), op6: NewHundredOp(), op7: NewHundredOp(), op8: NewHundredOp(), op9: NewHundredOp(), op10: NewHundredOp(), } o.InPort = o.op1.InPort o.op1.SetOutPort(o.op2.InPort) o.op2.SetOutPort(o.op3.InPort) o.op3.SetOutPort(o.op4.InPort) o.op4.SetOutPort(o.op5.InPort) o.op5.SetOutPort(o.op6.InPort) o.op6.SetOutPort(o.op7.InPort) o.op7.SetOutPort(o.op8.InPort) o.op8.SetOutPort(o.op9.InPort) o.op9.SetOutPort(o.op10.InPort) return o } // SetOutPort sets the output port of the ThousandOp. func (op *ThousandOp) SetOutPort(port func(int)) { op.op10.SetOutPort(port) } // SetErrorPort sets the error port of the ThousandOp. func (op *ThousandOp) SetErrorPort(port func(error)) { op.op1.SetErrorPort(port) op.op2.SetErrorPort(port) op.op3.SetErrorPort(port) op.op4.SetErrorPort(port) op.op5.SetErrorPort(port) op.op6.SetErrorPort(port) op.op7.SetErrorPort(port) op.op8.SetErrorPort(port) op.op9.SetErrorPort(port) op.op10.SetErrorPort(port) } // HundredOp holds the data necessary to call ten tenOps. type HundredOp struct { InPort func(int) op1 *tenOp op2 *tenOp op3 *tenOp op4 *tenOp op5 *tenOp op6 *tenOp op7 *tenOp op8 *tenOp op9 *tenOp op10 *tenOp } // NewHundredOp returns a new HundredOp. func NewHundredOp() *HundredOp { o := &HundredOp{ op1: newTenOp(), op2: newTenOp(), op3: newTenOp(), op4: newTenOp(), op5: newTenOp(), op6: newTenOp(), op7: newTenOp(), op8: newTenOp(), op9: newTenOp(), op10: newTenOp(), } o.InPort = o.op1.InPort o.op1.SetOutPort(o.op2.InPort) o.op2.SetOutPort(o.op3.InPort) o.op3.SetOutPort(o.op4.InPort) o.op4.SetOutPort(o.op5.InPort) o.op5.SetOutPort(o.op6.InPort) o.op6.SetOutPort(o.op7.InPort) o.op7.SetOutPort(o.op8.InPort) o.op8.SetOutPort(o.op9.InPort) o.op9.SetOutPort(o.op10.InPort) return o } // SetOutPort sets the output port of the HundredOp. func (op *HundredOp) SetOutPort(port func(int)) { op.op10.SetOutPort(port) } // SetErrorPort sets the error port of the HundredOp. func (op *HundredOp) SetErrorPort(port func(error)) { op.op1.SetErrorPort(port) op.op2.SetErrorPort(port) op.op3.SetErrorPort(port) op.op4.SetErrorPort(port) op.op5.SetErrorPort(port) op.op6.SetErrorPort(port) op.op7.SetErrorPort(port) op.op8.SetErrorPort(port) op.op9.SetErrorPort(port) op.op10.SetErrorPort(port) } type tenOp struct { InPort func(int) op1 *singleOp op2 *singleOp op3 *singleOp op4 *singleOp op5 *singleOp op6 *singleOp op7 *singleOp op8 *singleOp op9 *singleOp op10 *singleOp } func newTenOp() *tenOp { o := &tenOp{ op1: &singleOp{}, op2: &singleOp{}, op3: &singleOp{}, op4: &singleOp{}, op5: &singleOp{}, op6: &singleOp{}, op7: &singleOp{}, op8: &singleOp{}, op9: &singleOp{}, op10: &singleOp{}, } o.InPort = o.op1.InPort o.op1.SetOutPort(o.op2.InPort) o.op2.SetOutPort(o.op3.InPort) o.op3.SetOutPort(o.op4.InPort) o.op4.SetOutPort(o.op5.InPort) o.op5.SetOutPort(o.op6.InPort) o.op6.SetOutPort(o.op7.InPort) o.op7.SetOutPort(o.op8.InPort) o.op8.SetOutPort(o.op9.InPort) o.op9.SetOutPort(o.op10.InPort) return o } func (op *tenOp) SetOutPort(port func(int)) { op.op10.SetOutPort(port) } func (op *tenOp) SetErrorPort(port func(error)) { op.op1.SetErrorPort(port) op.op2.SetErrorPort(port) op.op3.SetErrorPort(port) op.op4.SetErrorPort(port) op.op5.SetErrorPort(port) op.op6.SetErrorPort(port) op.op7.SetErrorPort(port) op.op8.SetErrorPort(port) op.op9.SetErrorPort(port) op.op10.SetErrorPort(port) } type singleOp struct { outPort func(int) errorPort func(error) } func (op *singleOp) InPort(i int) { if i < 0 || i > 1000000 { op.errorPort(errors.New("should not happen")) return } op.outPort(i + 1) } func (op *singleOp) SetOutPort(port func(int)) { op.outPort = port } func (op *singleOp) SetErrorPort(port func(error)) { op.errorPort = port }
oopmix/oopmix.go
0.528533
0.611498
oopmix.go
starcoder
package sql import ( "fmt" "io" "strings" "github.com/dolthub/vitess/go/vt/proto/query" "github.com/dolthub/go-mysql-server/sql/values" ) // Row is a tuple of values. type Row []interface{} // NewRow creates a row from the given values. func NewRow(values ...interface{}) Row { row := make([]interface{}, len(values)) copy(row, values) return row } // Copy creates a new row with the same values as the current one. func (r Row) Copy() Row { return NewRow(r...) } // Append appends all the values in r2 to this row and returns the result func (r Row) Append(r2 Row) Row { row := make(Row, len(r)+len(r2)) for i := range r { row[i] = r[i] } for i := range r2 { row[i+len(r)] = r2[i] } return row } // Equals checks whether two rows are equal given a schema. func (r Row) Equals(row Row, schema Schema) (bool, error) { if len(row) != len(r) || len(row) != len(schema) { return false, nil } for i, colLeft := range r { colRight := row[i] cmp, err := schema[i].Type.Compare(colLeft, colRight) if err != nil { return false, err } if cmp != 0 { return false, nil } } return true, nil } // FormatRow returns a formatted string representing this row's values func FormatRow(row Row) string { var sb strings.Builder sb.WriteRune('[') for i, v := range row { if i > 0 { sb.WriteRune(',') } sb.WriteString(fmt.Sprintf("%v", v)) } sb.WriteRune(']') return sb.String() } // RowIter is an iterator that produces rows. type RowIter interface { // Next retrieves the next row. It will return io.EOF if it's the last row. // After retrieving the last row, Close will be automatically closed. Next(ctx *Context) (Row, error) Closer } // RowIter2 is an iterator that fills a row frame buffer with rows from its source type RowIter2 interface { RowIter // Next2 produces the next row, and stores it in the RowFrame provided. // It will return io.EOF if it's the last row. After retrieving the // last row, Close will be automatically called. Next2(ctx *Context, frame *RowFrame) error } // RowIterToRows converts a row iterator to a slice of rows. func RowIterToRows(ctx *Context, sch Schema, i RowIter) ([]Row, error) { if ri2, ok := i.(RowIterTypeSelector); ok && ri2.IsNode2() && sch != nil { return RowIter2ToRows(ctx, sch, ri2.(RowIter2)) } var rows []Row for { row, err := i.Next(ctx) if err == io.EOF { break } if err != nil { i.Close(ctx) return nil, err } rows = append(rows, row) } return rows, i.Close(ctx) } func RowIter2ToRows(ctx *Context, sch Schema, i RowIter2) ([]Row, error) { var rows []Row for { f := NewRowFrame() err := i.Next2(ctx, f) if err == io.EOF { break } if err != nil { _ = i.Close(ctx) return nil, err } rows = append(rows, rowFromRow2(sch, f.Row2())) } return rows, i.Close(ctx) } func rowFromRow2(sch Schema, r Row2) Row { row := make(Row, len(sch)) for i, col := range sch { switch col.Type.Type() { case query.Type_INT8: row[i] = values.ReadInt8(r.GetField(i).Val) case query.Type_UINT8: row[i] = values.ReadUint8(r.GetField(i).Val) case query.Type_INT16: row[i] = values.ReadInt16(r.GetField(i).Val) case query.Type_UINT16: row[i] = values.ReadUint16(r.GetField(i).Val) case query.Type_INT32: row[i] = values.ReadInt32(r.GetField(i).Val) case query.Type_UINT32: row[i] = values.ReadUint32(r.GetField(i).Val) case query.Type_INT64: row[i] = values.ReadInt64(r.GetField(i).Val) case query.Type_UINT64: row[i] = values.ReadUint64(r.GetField(i).Val) case query.Type_FLOAT32: row[i] = values.ReadFloat32(r.GetField(i).Val) case query.Type_FLOAT64: row[i] = values.ReadFloat64(r.GetField(i).Val) case query.Type_TEXT, query.Type_VARCHAR, query.Type_CHAR: row[i] = values.ReadString(r.GetField(i).Val, values.ByteOrderCollation) case query.Type_BLOB, query.Type_VARBINARY, query.Type_BINARY: row[i] = values.ReadBytes(r.GetField(i).Val, values.ByteOrderCollation) case query.Type_BIT: fallthrough case query.Type_ENUM: fallthrough case query.Type_SET: fallthrough case query.Type_TUPLE: fallthrough case query.Type_GEOMETRY: fallthrough case query.Type_JSON: fallthrough case query.Type_EXPRESSION: fallthrough case query.Type_INT24: fallthrough case query.Type_UINT24: fallthrough case query.Type_TIMESTAMP: fallthrough case query.Type_DATE: fallthrough case query.Type_TIME: fallthrough case query.Type_DATETIME: fallthrough case query.Type_YEAR: fallthrough case query.Type_DECIMAL: panic(fmt.Sprintf("Unimplemented type conversion: %T", col.Type)) default: panic(fmt.Sprintf("unknown type %T", col.Type)) } } return row } // NodeToRows converts a node to a slice of rows. func NodeToRows(ctx *Context, n Node) ([]Row, error) { i, err := n.RowIter(ctx, nil) if err != nil { return nil, err } return RowIterToRows(ctx, nil, i) } // RowsToRowIter creates a RowIter that iterates over the given rows. func RowsToRowIter(rows ...Row) RowIter { return &sliceRowIter{rows: rows} } type sliceRowIter struct { rows []Row idx int } func (i *sliceRowIter) Next(*Context) (Row, error) { if i.idx >= len(i.rows) { return nil, io.EOF } r := i.rows[i.idx] i.idx++ return r.Copy(), nil } func (i *sliceRowIter) Close(*Context) error { i.rows = nil return nil }
sql/row.go
0.697197
0.552902
row.go
starcoder
package qesygo import ( "math/rand" "strconv" "time" ) /* people := []Person{ {"Bob", 31}, {"John", 42}, {"Michael", 17}, {"Jenny", 26}, } fmt.Println(people) // There are two ways to sort a slice. First, one can define // a set of methods for the slice type, as with ByAge, and // call sort.Sort. In this first example we use that technique. sort.Sort(ByAge(people)) fmt.Println(people) */ type Person struct { Name string Age int } // ByAge implements sort.Interface for []Person based on // the Age field. type ByAge []Person func (a ByAge) Len() int { return len(a) } func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age } func Array_merge(arr ...[]string) []string { var retArr []string for _, n := range arr { for _, v := range n { retArr = append(retArr, v) } } return retArr } func Array_merge_int(arr ...[]int) []int { var retArr []int for _, n := range arr { for _, v := range n { retArr = append(retArr, v) } } return retArr } func InArray(Arr interface{}, str string) bool { if strArr, ok := Arr.([]string); ok { for _, v := range strArr { if v == str { return true } } return false } if mapArr, ok := Arr.(map[string]string); ok { for _, v := range mapArr { if v == str { return true } } return false } if intArr, ok := Arr.([]int); ok { strInt := StrToInt(str) for _, v := range intArr { if v == strInt { return true } } return false } if intArr, ok := Arr.([]int32); ok { strInt32 := StrToInt32(str) for _, v := range intArr { if v == strInt32 { return true } } return false } return false } func Array_Rand(num int) []int { rand.Seed(time.Now().UnixNano()) return rand.Perm(num) } func Array_Diff(Arr1 []int, Arr2 []int) []int { BigArr, SmallArr := Arr1, Arr2 if len(Arr2) > len(Arr1) { BigArr = Arr2 SmallArr = Arr1 } TempArr := []int{} for _, v := range BigArr { if !InArray(SmallArr, strconv.Itoa(v)) { TempArr = append(TempArr, v) } } return TempArr } func Array_Diff_String(Arr1 []string, Arr2 []string) []string { BigArr, SmallArr := Arr1, Arr2 if len(Arr2) > len(Arr1) { BigArr = Arr2 SmallArr = Arr1 } TempArr := []string{} for _, v := range BigArr { if !InArray(SmallArr, v) { TempArr = append(TempArr, v) } } return TempArr } func Array_Mixed(Arr1 []int, Arr2 []int) []int { BigArr, SmallArr := Arr1, Arr2 if len(Arr2) > len(Arr1) { BigArr = Arr2 SmallArr = Arr1 } TempArr := []int{} for _, v := range BigArr { if InArray(SmallArr, strconv.Itoa(v)) { TempArr = append(TempArr, v) } } return TempArr } func Array_column(Arr []map[string]string, Str string) []string { NewArr := []string{} for _, v := range Arr { NewArr = append(NewArr, v[Str]) } return NewArr } func Array_column_index(Arr []map[string]string, Str string, Index string) map[string]string { NewArr := map[string]string{} for _, v := range Arr { NewArr[v[Index]] = v[Str] } return NewArr } func Keys(Arr map[string]string) []string { Keys := []string{} for k, _ := range Arr { Keys = append(Keys, k) } return Keys }
array.go
0.611846
0.407392
array.go
starcoder
package main import ( "aoc/utils" "container/ring" "fmt" "io/ioutil" "path/filepath" "strconv" ) type position struct { x, y int dir string } func createCardinalRing(start string) *ring.Ring { entries := []string{"N", "E", "S", "W"} ring := ring.New(len(entries)) for _, entry := range entries { ring.Value = entry ring = ring.Next() } // Rotate ourselves to our wanted starting direction for ring.Value != start { ring = ring.Next() } return ring } func executeCardinalDirection(pos position, dir string, value int) position { switch dir { case "N": pos.y += value case "E": pos.x += value case "S": pos.y -= value case "W": pos.x -= value } return pos } // Rotating the position is done by rotating through a circular list (ring) {N,E,S,W} func rotatePosition(pos position, dir string, value int) position { compass := createCardinalRing(pos.dir) switch dir { case "L": pos.dir = compass.Move(-value / 90).Value.(string) case "R": pos.dir = compass.Move(value / 90).Value.(string) } return pos } // Rotating the waypoint is treated as a series of 90deg vector rotations func rotateWaypoint(waypoint position, dir string, value int) position { updated := waypoint for v := value; v > 0; v -= 90 { switch dir { case "L": updated.x, updated.y = -waypoint.y, waypoint.x case "R": updated.x, updated.y = waypoint.y, -waypoint.x } waypoint = updated } return waypoint } func chaseWaypoint(pos position, waypoint position, times int) position { for i := 0; i < times; i++ { pos = executeCardinalDirection(pos, "E", waypoint.x) pos = executeCardinalDirection(pos, "N", waypoint.y) } return pos } func partOne(instructions []string) int { pos := position{0, 0, "E"} for _, instruction := range instructions { action := string(instruction[0]) value, _ := strconv.Atoi(instruction[1:]) switch action { case "L", "R": pos = rotatePosition(pos, action, value) case "N", "E", "S", "W": pos = executeCardinalDirection(pos, action, value) case "F": pos = executeCardinalDirection(pos, pos.dir, value) } } return utils.AbsI(pos.x) + utils.AbsI(pos.y) } func partTwo(instructions []string) int { pos := position{0, 0, "E"} waypoint := position{10, 1, ""} for _, instruction := range instructions { action := string(instruction[0]) value, _ := strconv.Atoi(instruction[1:]) switch action { case "L", "R": waypoint = rotateWaypoint(waypoint, action, value) case "N", "E", "S", "W": waypoint = executeCardinalDirection(waypoint, action, value) case "F": pos = chaseWaypoint(pos, waypoint, value) } } return utils.AbsI(pos.x) + utils.AbsI(pos.y) } func main() { p := filepath.Join("12", "input.txt") input, err := ioutil.ReadFile(p) if err != nil { panic(err) } lines := utils.GetLines(input) fmt.Println("Part one", partOne(lines)) fmt.Println("Part two", partTwo(lines)) }
12/main.go
0.695648
0.410461
main.go
starcoder
package runtime import ( "log" "github.com/dcaiafa/go-expr/expr/types" ) // Builder builds a Program using low level primitives. type Builder struct { labels []*Label strings []string stringMap map[string]int values []interface{} instr []Instruction exprs []Expr consts []Value inputs []types.Type } // NewBuilder creates a new Builder. func NewBuilder() *Builder { b := &Builder{ stringMap: make(map[string]int), } return b } // NewInput creates a new input that can be referenced in a LoadInput // instruction. func (b *Builder) NewInput(t types.Type) int { b.inputs = append(b.inputs, t) return len(b.inputs) - 1 } // NewConst creates a new constant that can be referenced in a LoadConst // instruction. func (b *Builder) NewConst(v Value) int { constIndex := len(b.consts) b.consts = append(b.consts, v) return constIndex } // NewLabel creates a new label that can be used in EmitJump. The label is // immediately ready to be used, but it must be assigned using AssignLabel // before Build is called. func (b *Builder) NewLabel() *Label { label := &Label{ index: len(b.labels), addr: -1, } b.labels = append(b.labels, label) return label } // AssignLabel assigns the label to the current address of the program being // built. func (b *Builder) AssignLabel(label *Label) { label.addr = len(b.instr) } // EmitOp emits an instruction with a simple operation. func (b *Builder) EmitOp(op Operation) { b.addInstr(Instruction{op: op}) } // EmitLoadConst emits a LoadConst instruction. func (b *Builder) EmitLoadConst(constIndex int) { b.addInstr(Instruction{op: LoadConst, extra: constIndex}) } // EmitLoadInput emits a LoadInput instruction. func (b *Builder) EmitLoadInput(inputIndex int) { b.addInstr(Instruction{op: LoadInput, extra: inputIndex}) } // EmitPushNumber emits a PushNumber instruction. func (b *Builder) EmitPushNumber(num float64) { b.addInstr(Instruction{op: PushNumber, vnum: num}) } // EmitPushString emits a PushString instruction. func (b *Builder) EmitPushString(str string) { strIndex := b.newString(str) b.addInstr(Instruction{op: PushString, extra: strIndex}) } func (b *Builder) EmitPushBasicValue(v interface{}) { switch v := v.(type) { case float64: b.EmitPushNumber(v) case bool: b.EmitPushBool(v) case string: b.EmitPushString(v) default: log.Fatal("invalid basic type") } } // EmitPushBool emits a PushBool instruction. func (b *Builder) EmitPushBool(v bool) { extra := 0 if v { extra = 1 } b.addInstr(Instruction{op: PushBool, extra: extra}) } func (b *Builder) EmitPushArray(elemCount int) { b.addInstr(Instruction{op: PushArray, extra: elemCount}) } // EmitJump emits a Jump, JumpIfTrue or JumpIfFalse instruction. func (b *Builder) EmitJump(op Operation, label *Label) { b.addInstr(Instruction{op: op, extra: label.index}) } // EmitCall emits a Call instruction that consumes argCount arguments from the // stack. func (b *Builder) EmitCall(argCount int) { b.addInstr(Instruction{op: Call, extra: argCount}) } func (b *Builder) addInstr(i Instruction) { b.instr = append(b.instr, i) } // FinishExpr finishes the current expression. func (b *Builder) FinishExpr() { for i := 0; i < len(b.instr); i++ { if b.instr[i].op != Jump && b.instr[i].op != JumpIfTrue && b.instr[i].op != JumpIfFalse { continue } label := b.labels[b.instr[i].extra] if label.addr == -1 { panic("unassigned label") } b.instr[i].extra = label.addr } b.exprs = append(b.exprs, Expr(b.instr)) b.instr = nil } // Build returns the Program. func (b *Builder) Build() *Program { return &Program{ exprs: b.exprs, strings: b.strings, consts: b.consts, inputs: b.inputs, } } func (b *Builder) newString(str string) int { index, ok := b.stringMap[str] if !ok { index = len(b.strings) b.strings = append(b.strings, str) b.stringMap[str] = index } return index } func (b *Builder) newConstValue(v interface{}) int { b.values = append(b.values, v) return len(b.values) - 1 }
expr/runtime/builder.go
0.741487
0.422326
builder.go
starcoder
package qtable import ( "fmt" "math" "strconv" ) // ActionType are cache possible actions type ActionType int const ( // ActionStore indicates to store an element in cache ActionStore ActionType = iota // ActionNotStore indicates to not store an element in cache ActionNotStore ) // QTable implements the Q-learning type QTable struct { states map[uint64][]float64 learningRate float64 DecayRate float64 features [][]float64 featureNames []string actions []ActionType Epsilon float64 MaxEpsilon float64 MinEpsilon float64 } // Init initilizes the QTable struct func (table *QTable) Init(features [][]float64, featureNames []string, actions []ActionType) { table.actions = make([]ActionType, len(actions)) copy(table.actions, actions) table.featureNames = make([]string, len(featureNames)) copy(table.featureNames, featureNames) table.features = make([][]float64, len(features)) for idx, feature := range features { table.features[idx] = make([]float64, len(feature)) copy(table.features[idx], feature) } table.states = make(map[uint64][]float64, 0) for state := range table.genStates() { stateIdx := table.GetStateIdx(state) fmt.Println(state, stateIdx) _, inMap := table.states[stateIdx] if !inMap { table.states[stateIdx] = make([]float64, len(actions)) } else { fmt.Printf("State %v with idx %d already present...\n", state, stateIdx) panic("Insert state error!!!") } } table.PrintTable() table.learningRate = 0.9 table.DecayRate = 0.005 table.Epsilon = 1.0 table.MaxEpsilon = 1.0 table.MinEpsilon = 0.01 } func createOneHot(lenght int, targetIdx int) []float64 { res := make([]float64, lenght) if targetIdx >= lenght { res[lenght-1] = 1.0 } else { res[targetIdx] = 1.0 } return res } func (table QTable) genStates() chan []float64 { genChan := make(chan []float64) go func() { defer close(genChan) partials := make([][]float64, 0) for _, feature := range table.features { var newEntries [][]float64 for idx := range feature { oneHot := createOneHot(len(feature), idx) newEntries = append(newEntries, oneHot) } if len(partials) == 0 { for idx := 0; idx < len(newEntries); idx++ { partials = append(partials, make([]float64, len(newEntries[idx]))) copy(partials[idx], newEntries[idx]) } } else { curPartials := make([][]float64, len(partials)) copy(curPartials, partials) for idx0 := 0; idx0 < len(newEntries)-1; idx0++ { for idx1 := 0; idx1 < len(curPartials); idx1++ { partials = append(partials, make([]float64, len(curPartials[idx1]))) copy(partials[len(partials)-1], curPartials[idx1]) } } for idx0 := 0; idx0 < len(newEntries); idx0++ { startIdx := len(curPartials) * idx0 for idx1 := startIdx; idx1 < startIdx+len(curPartials); idx1++ { partials[idx1] = append(partials[idx1], newEntries[idx0]...) } if len(partials) > 12 { } } } } for _, partial := range partials { genChan <- partial } }() return genChan } // GetStateIdx returns the index of a given state func (table QTable) GetStateIdx(state []float64) uint64 { var resIdx uint64 for idx := 0; idx < len(state); idx++ { if state[idx] != 0.0 { resIdx += uint64(math.Pow(2.0, float64(len(state)-idx-1))) } } return resIdx } // PrintTable outputs the state values func (table QTable) PrintTable() { for state, actions := range table.states { fmt.Printf("[%s]\t[", strconv.FormatInt(int64(state), 2)) for idx, action := range actions { fmt.Printf("%09.2f", action) if idx != len(actions)-1 { fmt.Print(" ") } } fmt.Println("]") } } func getArgMax(array []float64) int { maxIdx := 0 maxElm := array[maxIdx] for idx := 0; idx < len(array); idx++ { if array[idx] > maxElm { maxElm = array[idx] maxIdx = idx } } return maxIdx } // GetAction returns the possible environment action from a state func (table QTable) GetAction(stateIdx uint64, action ActionType) float64 { values := table.states[stateIdx] outIdx := 0 for idx := 0; idx < len(table.actions); idx++ { if table.actions[idx] == action { outIdx = idx break } } return values[outIdx] } // GetBestAction returns the action of the best action for the given state func (table QTable) GetBestAction(state []float64) ActionType { stateIdx := table.GetStateIdx(state) values := table.states[stateIdx] return table.actions[getArgMax(values)] } func (table QTable) convertFeature(featureIdx int, value float64) int { for idx := 0; idx < len(table.features[featureIdx]); idx++ { if value <= table.features[featureIdx][idx] { return idx } } return len(table.features[featureIdx]) - 1 } // GenCurState return the current environment state func (table QTable) GenCurState(args []float64) []float64 { state := []float64{} for idx := 0; idx < len(table.featureNames); idx++ { curFeature := args[idx] resIdx := table.convertFeature(idx, curFeature) resArr := createOneHot(len(table.features[idx]), resIdx) state = append(state, resArr...) } return state } // Update change the Q-table values of the given action func (table *QTable) Update(state []float64, action ActionType, reward float64) { stateIdx := table.GetStateIdx(state) actionValue := table.GetAction(stateIdx, action) maxValue := getArgMax(table.states[stateIdx]) table.states[stateIdx][action] = actionValue + table.learningRate*(reward+table.DecayRate*table.states[stateIdx][maxValue]-actionValue) }
qLearning_smartCache/qtable/qtable.go
0.605333
0.474144
qtable.go
starcoder
package recurly import () type SubscriptionChangeCreate struct { // The timeframe parameter controls when the upgrade or downgrade takes place. The subscription change can occur now, when the subscription is next billed, or when the subscription term ends. Generally, if you're performing an upgrade, you will want the change to occur immediately (now). If you're performing a downgrade, you should set the timeframe to `term_end` or `bill_date` so the change takes effect at a scheduled billing date. The `renewal` timeframe option is accepted as an alias for `term_end`. Timeframe *string `json:"timeframe,omitempty"` // If you want to change to a new plan, you can provide the plan's code or id. If both are provided the `plan_id` will be used. PlanId *string `json:"plan_id,omitempty"` // If you want to change to a new plan, you can provide the plan's code or id. If both are provided the `plan_id` will be used. PlanCode *string `json:"plan_code,omitempty"` // Optionally, sets custom pricing for the subscription, overriding the plan's default unit amount. The subscription's current currency will be used. UnitAmount *float64 `json:"unit_amount,omitempty"` // Optionally override the default quantity of 1. Quantity *int `json:"quantity,omitempty"` // The shipping address can currently only be changed immediately, using SubscriptionUpdate. Shipping *SubscriptionChangeShippingCreate `json:"shipping,omitempty"` // A list of coupon_codes to be redeemed on the subscription during the change. Only allowed if timeframe is now and you change something about the subscription that creates an invoice. CouponCodes []string `json:"coupon_codes,omitempty"` // If you provide a value for this field it will replace any // existing add-ons. So, when adding or modifying an add-on, you need to // include the existing subscription add-ons. Unchanged add-ons can be included // just using the subscription add-on''s ID: `{"id": "abc123"}`. If this // value is omitted your existing add-ons will be unaffected. To remove all // existing add-ons, this value should be an empty array.' // If a subscription add-on's `code` is supplied without the `id`, // `{"code": "def456"}`, the subscription add-on attributes will be set to the // current values of the plan add-on unless provided in the request. // - If an `id` is passed, any attributes not passed in will pull from the // existing subscription add-on // - If a `code` is passed, any attributes not passed in will pull from the // current values of the plan add-on // - Attributes passed in as part of the request will override either of the // above scenarios AddOns []SubscriptionAddOnUpdate `json:"add_ons,omitempty"` // Collection method CollectionMethod *string `json:"collection_method,omitempty"` // Revenue schedule type RevenueScheduleType *string `json:"revenue_schedule_type,omitempty"` // The custom fields will only be altered when they are included in a request. Sending an empty array will not remove any existing values. To remove a field send the name with a null or empty value. CustomFields []CustomFieldCreate `json:"custom_fields,omitempty"` // For manual invoicing, this identifies the PO number associated with the subscription. PoNumber *string `json:"po_number,omitempty"` // Integer representing the number of days after an invoice's creation that the invoice will become past due. If an invoice's net terms are set to '0', it is due 'On Receipt' and will become past due 24 hours after it’s created. If an invoice is due net 30, it will become past due at 31 days exactly. NetTerms *int `json:"net_terms,omitempty"` // An optional type designation for the payment gateway transaction created by this request. Supports 'moto' value, which is the acronym for mail order and telephone transactions. TransactionType *string `json:"transaction_type,omitempty"` }
subscription_change_create.go
0.747339
0.400222
subscription_change_create.go
starcoder
package tree import "sort" // Tree uniformly defines the data structure of the menu tree, you can also customize other fields to add type Tree struct { Title string `json:"title"` Data interface{} `json:"data"` Leaf bool `json:"leaf"` Selected bool `json:"checked"` PartialSelected bool `json:"partiallySelected"` Children []Tree `json:"children"` } // INode Other structures of want to generate a menu tree and directly implement this interface type INode interface { GetTitle() string GetId() int GetPid() int GetData() interface{} IsRoot() bool } type INodes []INode func (nodes INodes) Len() int { return len(nodes) } func (nodes INodes) Swap(i, j int) { nodes[i], nodes[j] = nodes[j], nodes[i] } func (nodes INodes) Less(i, j int) bool { return nodes[i].GetId() < nodes[j].GetId() } // GenerateTree After the custom structure implements the INode interface, call this method to generate the tree structure // nodes need to generate tree nodes // selectedNode selected node after spanning tree // The tree structure object after menuTrees is successfully generated func (Tree) GenerateTree(nodes, selectedNodes []INode) (trees []Tree) { trees = []Tree{} // Define the top-level root and child nodes var roots, childs []INode for _, v := range nodes { if v.IsRoot() { // Determine the top-level root node roots = append(roots, v) } childs = append(childs, v) } for _, v := range roots { childTree := &Tree{ Title: v.GetTitle(), Data: v.GetData(), } // Before recursion, confirm the selected state of childTree according to the parent node childTree.Selected = nodeSelected(v, selectedNodes, childTree.Children) // recursive recursiveTree(childTree, childs, selectedNodes) // After recursion, confirm the selected state of childTree according to the child node if !childTree.Selected { childTree.Selected = nodeSelected(v, selectedNodes, childTree.Children) } // After recursion, confirm the half-selected state of childTree according to the child nodes childTree.PartialSelected = nodePartialSelected(childTree.Children) // After recursion, confirm whether it is a leaf node according to the subsection childTree.Leaf = len(childTree.Children) == 0 trees = append(trees, *childTree) } return } // recursiveTree recursively spanning tree structure // tree recursive tree object // nodes recursive nodes // selectedNodes selected nodes func recursiveTree(tree *Tree, nodes, selectedNodes []INode) { data := tree.Data.(INode) for _, v := range nodes { if v.IsRoot() { // If the current node is the top-level root node, skip continue } if data.GetId() == v.GetPid() { childTree := &Tree{ Title: v.GetTitle(), Data: v.GetData(), } childTree.Selected = nodeSelected(v, selectedNodes, childTree.Children) || tree.Selected recursiveTree(childTree, nodes, selectedNodes) if !childTree.Selected { childTree.Selected = nodeSelected(v, selectedNodes, childTree.Children) } childTree.PartialSelected = nodePartialSelected(childTree.Children) childTree.Leaf = len(childTree.Children) == 0 tree.Children = append(tree.Children, *childTree) } } } // FindRelationNode queries all parent nodes of nodes in nodes in allTree // nodes to query the child node array of the parent node // allTree all nodes array func (Tree) FindRelationNode(nodes, allNodes []INode) (respNodes []INode) { nodeMap := make(map[int]INode) for _, v := range nodes { recursiveFindRelationNode(nodeMap, allNodes, v, 0) } for _, v := range nodeMap { respNodes = append(respNodes, v) } sort.Sort(INodes(respNodes)) return } // recursiveFindRelationNode recursively query related parent and child nodes // nodeMap query results are collected in the map // allNodes all nodes // node recursive node // t Recursive search type: 0 finds parent and child nodes; 1 only finds parent nodes; 2 only finds child nodes func recursiveFindRelationNode(nodeMap map[int]INode, allNodes []INode, node INode, t int) { nodeMap[node.GetId()] = node for _, v := range allNodes { if _, ok := nodeMap[v.GetId()]; ok { continue } // Find the parent node if t == 0 || t == 1 { if node.GetPid() == v.GetId() { nodeMap[v.GetId()] = v if v.IsRoot() { // When it is the top-level root node, no recursion continue } recursiveFindRelationNode(nodeMap, allNodes, v, 1) } } // Find child nodes if t == 0 || t == 2 { if node.GetId() == v.GetId() { nodeMap[v.GetId()] = v recursiveFindRelationNode(nodeMap, allNodes, v, 2) } } } } // nodeSelected determines the selected state of the node // node judges the node func nodeSelected(node INode, selectedNodes []INode, children []Tree) bool { for _, v := range selectedNodes { if node.GetId() == v.GetId() { // 1. If the current node exists in the selected node array return true } } if len(children) == 0 { // 2. Precondition 1 is not met, and there are no child nodes return false } selectedNum := 0 for _, v := range children { if v.Selected { selectedNum++ } } if selectedNum == len(children) { // The preconditions 1, 2 are not met, and all the child nodes are selected return true } return false } // nodePartialSelected judges the half-selected state of the node func nodePartialSelected(trees []Tree) bool { selectedNum := 0 for _, v := range trees { if v.Selected { selectedNum++ } } if selectedNum == len(trees) || selectedNum == 0 { // All child nodes are selected, or none of them are selected return false } return true }
tree/index.go
0.743541
0.426979
index.go
starcoder
package climbing import ( "strconv" "github.com/metalnem/parsing-algorithms/ast" "github.com/metalnem/parsing-algorithms/parse" "github.com/metalnem/parsing-algorithms/scan" "github.com/pkg/errors" ) type assoc int const ( left assoc = iota right ) type opInfo struct { prec int assoc assoc } var binOps = map[string]opInfo{ "+": {1, left}, "-": {1, left}, "*": {2, left}, "/": {2, left}, "^": {4, right}, } var unOps = map[string]opInfo{ "+": {3, right}, "-": {3, right}, } type parser struct { } type state struct { s *scan.Scanner t scan.Token } // New creates a new precedence climbing parser. func New() parse.Parser { return parser{} } func (parser) Parse(input string) (ast.Expr, error) { s := scan.NewScanner(input) t := s.Next() state := &state{s: s, t: t} expr, err := state.parseExpr(1) if err != nil { return nil, err } if state.t.Type != scan.EOF { return nil, errors.Errorf("Expected EOF, got %s", state.t.Value) } return expr, nil } func (s *state) parseExpr(prec int) (ast.Expr, error) { lhs, err := s.parsePrimary() if err != nil { return nil, err } for { if s.t.Type == scan.EOF || s.t.Type != scan.Operator { break } val := s.t.Value op, ok := binOps[val] if !ok { return nil, errors.Errorf("Expected operator, got %s", s.t.Value) } if binOps[s.t.Value].prec < prec { break } nextPrec := op.prec if op.assoc == left { nextPrec++ } s.t = s.s.Next() rhs, err := s.parseExpr(nextPrec) if err != nil { return nil, err } lhs = &ast.BinaryExpr{Op: val, X: lhs, Y: rhs} } return lhs, nil } func (s *state) parsePrimary() (ast.Expr, error) { if s.t.Type == scan.LeftParen { s.t = s.s.Next() expr, err := s.parseExpr(1) if err != nil { return nil, err } if s.t.Type != scan.RightParen { return nil, errors.Errorf("Expected right paren, got %s", s.t.Value) } s.t = s.s.Next() return expr, nil } if op, ok := unOps[s.t.Value]; ok { val := s.t.Value s.t = s.s.Next() expr, err := s.parseExpr(op.prec) if err != nil { return nil, err } return &ast.UnaryExpr{Op: val, X: expr}, nil } val, err := strconv.ParseFloat(s.t.Value, 64) if err != nil { return nil, errors.Errorf("Expected number, got %s", s.t.Value) } s.t = s.s.Next() return &ast.Number{Value: val}, nil }
parse/climbing/climbing.go
0.650023
0.432363
climbing.go
starcoder
package cryptopals import ( "crypto/rand" "errors" "fmt" "math/big" ) var minPkscs15Len = 11 var errInvalidPadding = errors.New("invalid padding") type rsaPkcs15PaddingOracle struct { key *privateKey } func gt(x, y *big.Int) bool { return x.Cmp(y) == 1 } func gte(x, y *big.Int) bool { return x.Cmp(y) >= 0 } func lt(x, y *big.Int) bool { return x.Cmp(y) == -1 } func pkcs15Pad(m []byte, size int) []byte { var paddingLen = size - len(m) if paddingLen < minPkscs15Len { panic(fmt.Errorf("pkcs 1.5 requres at least %v bytes", minPkscs15Len)) } var padded = make([]byte, size) padded[1] = 2 _, err := rand.Reader.Read(padded[2 : paddingLen-2]) if err != nil { panic(err) } for i := 2; i < paddingLen-1; { if padded[i] == 0 { _, err = rand.Reader.Read(padded[i : i+1]) if err != nil { panic(err) } } else { i++ } } copy(padded[paddingLen:], m) return padded } func pkcs15Unpad(padded []byte) ([]byte, error) { if len(padded) <= minPkscs15Len { return nil, errInvalidPadding } if padded[0] != 0 || padded[1] != 2 { return nil, errInvalidPadding } var i = 2 for ; i < minPkscs15Len; i++ { if padded[i] == 0 { return nil, errInvalidPadding } } for ; i < len(padded); i++ { if padded[i] == 0 { var unpadded = make([]byte, len(padded)-i-1) copy(unpadded, padded[i+1:]) return unpadded, nil } } return nil, errInvalidPadding } func (o rsaPkcs15PaddingOracle) isValidPadding(encrypted []byte) bool { var decrypted = pad(decryptRsa(encrypted, o.key), o.key.Size()) /* the probability that the message would be completly pkcs 1.5-conforming i.e. 00 02 [at least 11 not null bytes] 00 .. seems to be pretty low so we only check the pkcs 1.5 signature bytes here */ if decrypted[0] == 0 && decrypted[1] == 2 { return true } return false } type interval struct { a, b *big.Int } func (i1 *interval) eq(i2 *interval) bool { return eq(i1.a, i2.a) && eq(i1.b, i2.b) } type intervals []*interval func (itrvls intervals) contains(x *interval) bool { /* the Set data structure is a good fit here but it would be hard to use it here since we opereate with pointers. Anyway this is not done often and there would not be a lot of intervals so this O(n) could actually be faster then map's O(1) */ for _, y := range itrvls { if x.eq(y) { return true } } return false } func pad(b []byte, width int) []byte { var diff = width - len(b) if diff == 0 { return b } var j = make([]byte, width) copy(j[diff:], b) return j } func pkcs15PaddingOracleAttack(encrypted []byte, p *publicKey, o *rsaPkcs15PaddingOracle) []byte { var B = big.NewInt(1) B.Lsh(B, uint(8*(p.Size()-2))) var B2 = new(big.Int).Mul(B, big.NewInt(2)) var B3 = new(big.Int).Mul(B, big.NewInt(3)) var c = new(big.Int).SetBytes(encrypted) var cc = new(big.Int) var isValidS = func(s *big.Int) bool { // cc = c * s^e mod N cc.Exp(s, p.E, p.N) cc.Mul(cc, c) cc.Mod(cc, p.N) return o.isValidPadding(cc.Bytes()) } var s, sMax = new(big.Int), new(big.Int) var r = new(big.Int) var M = intervals([]*interval{&interval{ a: new(big.Int).Set(B2), b: new(big.Int).Set(B3), }}) M[0].b.Sub(M[0].b, one) /* step 2. a --------- We know s0 = 1 because m is already PKCS 1.5 conforming, but we can't use that value for s to get a new message approximation the same way we use s1, s2, ... because whth s = 1, r_max = (B-1)/n < 1 => r_max=0 and the only s that is possible with that r is again s = 1 For that reason we have to use a bruteforce approach to fine s1. But we can start from s = n / 3B: since 2B <= m < 3B, multiplying m with a smallest possible s=2 will make m * s > 3B, so the next time it can become PKCS 1.5-conforming is after it will "wrap" n. m * s >= n => s >= n/m, s is min when m is max, which is 3B-1, so s >= n / 3B */ for s.Div(p.N, B3); ; s.Add(s, one) { if isValidS(s) { break } } M = calculateNewIntervals(s, M, p) for { if len(M) == 0 { panic("no intervals to search m in left") } if len(M) == 1 { fmt.Printf("max(m)=%v\n", M[0].b) // check if we zeroed in on m if eq(M[0].a, M[0].b) { return pad(M[0].a.Bytes(), p.Size()) } /* step 2.c ________ mi = m0 * si - rn => si = (mi + rn) / m0 a <= m0 <= b; 2B <= mi <= 3B-1 => (2B + rn) / b <= si <= ((3B - 1) + rn) / a We want to half the interval we're searching s in each iteration. The width of the interval is approximately (3B - 2b) / s = B / s So doubling s would half the interval. this means that every iteration s is doubled From the whitepaper: r >= 2 * (s_{i-1} b - 2 B) / n Sticking it into s >= (2B + rn) / m0 results in si that is roughly 2 * s{i-1} we choose r, calculate si boundaries fot that r using (2B + rn) / b <= si <= ((3B - 1) + rn) / a and then search for si. After it is found we can calculate a new set of boundaries for m0: (2B + ri * n) / si <= m0 <= ((3B-1) + ri * n) / si for explanation what is ri see the note below */ // r >= 2 * (s_{i-1} b - 2 B) / n r.Mul(s, M[0].b) r.Sub(r, B2) r.Mul(r, two) r.Div(r, p.N) var sFound = false for ; ; r.Add(r, one) { // (2B + rn) / b <= si <= ((3B - 1) + rn) / a sMax.Mul(r, p.N) sMax.Add(sMax, B3) sMax.Sub(sMax, one) sMax.Div(sMax, M[0].a) s.Mul(r, p.N) s.Add(s, B2) s.Div(s, M[0].b) for ; gte(sMax, s); s.Add(s, one) { if isValidS(s) { sFound = true break } } if sFound { break } } /* no we found s but we we don't know can't know the exact r exactly (otherwise we could calculate m0 directly). The r we used before is of no use anymore - we used it to narrow the interval we search si for. Now that we know si, we can fund all r that could give as a valida padding knowing the boundaries for m0: so that r we used in the loop above is not the exact r that gives us 2B <= m*s - r*m < 3B: (m si - (3B - 1)) / n <= r <= (m si - 2B)/n m is in [a, b] => (a si - (3B - 1)) / n <= r <= (b si - 2B) / n for every we get a new possible interval, m0 would be in one of them. calculateNewIntervals(...) is basically step 3. */ M = calculateNewIntervals(s, M, p) continue } /* len(M) > 1 step 2.b ________ mi = m0 * si mod n = m0 * si - r * n we don't know r but can estimate it's boundaries: r = (m0 * si - mi) / n a <= m0 <= b, 2B <= mi <= 3B-1 r_min = (a * si - 2B) / n r_max = (b * si - (3B - 1)) / n now we can estimate new boundaries for m0 for each r in [r_min..r_max]: m0 = (mi + r * n)/si, 2B <= mi <= 3B-1 (2B + r * n) / si <= m0 <= ((3B-1) + r * n) / si because we're don't know actual r, just guessing, not all of these boundaries will contain m0, but since we try all possible r, one of them will. But we don't know which one so have to use a bruteforce again which will give us a new s and with that s some intervals would be filtered out */ // search for s_i beginning with s_{i-1} + 1 for s.Add(s, one); ; s.Add(s, one) { if isValidS(s) { break } } M = calculateNewIntervals(s, M, p) continue } } func calculateNewIntervals(s *big.Int, M intervals, p *publicKey) intervals { var B = big.NewInt(1) B.Lsh(B, uint(8*(p.Size()-2))) var B2 = new(big.Int).Mul(B, big.NewInt(2)) var B3 = new(big.Int).Mul(B, big.NewInt(3)) // step 3 var Mi = intervals([]*interval{}) var r, rMax = new(big.Int), new(big.Int) var a, b = new(big.Int), new(big.Int) var tmp = new(big.Int) for _, itrvl := range M { r.Mul(itrvl.a, s) r.Sub(r, B3) r.Add(r, one) r.Div(r, p.N) rMax.Mul(itrvl.b, s) rMax.Sub(rMax, B2) rMax.Div(rMax, p.N) for ; gte(rMax, r); r.Add(r, one) { // (2B + r * n) / si <= m0 <= ((3B-1) + r * n) / si a.Mul(r, p.N) a.Add(a, B2) a.QuoRem(a, s, tmp) if !isZero(tmp) { a.Add(a, one) } b.Mul(r, p.N) b.Add(b, B3) b.Sub(b, one) b.Div(b, s) if gt(itrvl.a, a) { a.Set(itrvl.a) } if lt(itrvl.b, b) { b.Set(itrvl.b) } if gte(b, a) { var newInterval = &interval{ new(big.Int).Set(a), new(big.Int).Set(b), } if Mi.contains(newInterval) { continue } Mi = append(Mi, newInterval) } } } return Mi }
cryptopals/6_47_rsa_pkcs1_padding_oracle.go
0.588416
0.42913
6_47_rsa_pkcs1_padding_oracle.go
starcoder
package accounting import ( "encoding/json" ) // Tax Representation of a tax defined in the external accounting system. type Tax struct { // The code/ID of the tax in the external accounting system. Code string `json:"code"` // The tax percentage. For example, 8.05 represents a 8.05% tax rate. Percentage float32 `json:"percentage"` // The display name of the tax. Name string `json:"name"` } // NewTax instantiates a new Tax object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewTax(code string, percentage float32, name string) *Tax { this := Tax{} this.Code = code this.Percentage = percentage this.Name = name return &this } // NewTaxWithDefaults instantiates a new Tax object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewTaxWithDefaults() *Tax { this := Tax{} return &this } // GetCode returns the Code field value func (o *Tax) GetCode() string { if o == nil { var ret string return ret } return o.Code } // GetCodeOk returns a tuple with the Code field value // and a boolean to check if the value has been set. func (o *Tax) GetCodeOk() (*string, bool) { if o == nil { return nil, false } return &o.Code, true } // SetCode sets field value func (o *Tax) SetCode(v string) { o.Code = v } // GetPercentage returns the Percentage field value func (o *Tax) GetPercentage() float32 { if o == nil { var ret float32 return ret } return o.Percentage } // GetPercentageOk returns a tuple with the Percentage field value // and a boolean to check if the value has been set. func (o *Tax) GetPercentageOk() (*float32, bool) { if o == nil { return nil, false } return &o.Percentage, true } // SetPercentage sets field value func (o *Tax) SetPercentage(v float32) { o.Percentage = v } // GetName returns the Name field value func (o *Tax) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *Tax) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *Tax) SetName(v string) { o.Name = v } func (o Tax) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["code"] = o.Code } if true { toSerialize["percentage"] = o.Percentage } if true { toSerialize["name"] = o.Name } return json.Marshal(toSerialize) } type NullableTax struct { value *Tax isSet bool } func (v NullableTax) Get() *Tax { return v.value } func (v *NullableTax) Set(val *Tax) { v.value = val v.isSet = true } func (v NullableTax) IsSet() bool { return v.isSet } func (v *NullableTax) Unset() { v.value = nil v.isSet = false } func NewNullableTax(val *Tax) *NullableTax { return &NullableTax{value: val, isSet: true} } func (v NullableTax) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTax) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
generated/accounting/model_tax.go
0.827898
0.454775
model_tax.go
starcoder
package schwordler import ( "fmt" "github.com/brensch/battleword" ) func (s *Store) GuessWord(prevGuessResults []battleword.GuessResult, defaultFirst string) (string, error) { if len(prevGuessResults) == 0 { return defaultFirst, nil } possibleAnswers, err := s.GetPossibleWords(prevGuessResults) if err != nil { return "", err } if len(possibleAnswers) == 1 { return possibleAnswers[0], nil } expectedRemainingWords := make([]float64, len(possibleAnswers)) distributions := make([][][]string, len(possibleAnswers)) for i, guess := range possibleAnswers { distribution := s.GetWordDistribution(guess, possibleAnswers) expectedRemainingWords[i] = s.GetDistributionExpectedRemainingAnswers(len(possibleAnswers), distribution) distributions[i] = distribution } var bestWord string bestWordExpectedRemaining := float64(len(possibleAnswers)) for i, expectedRemainingWord := range expectedRemainingWords { if expectedRemainingWord <= bestWordExpectedRemaining { bestWord = possibleAnswers[i] bestWordExpectedRemaining = expectedRemainingWord } } return bestWord, nil } func (s *Store) GetPossibleWords(prevGuessResults []battleword.GuessResult) ([]string, error) { possibleWords := CommonWords for _, prevGuessResult := range prevGuessResults { var newPossibleWords []string for _, newGuess := range possibleWords { if WordPossible(newGuess, prevGuessResult) { newPossibleWords = append(newPossibleWords, newGuess) } } possibleWords = newPossibleWords } return possibleWords, nil } func ResultToCode(result []int) int { answer := 0 for i, j := range result { base := IntPow(3, i) answer += base * j } return answer } func CodeToResult(code int) []int { var result []int i := 1 for { base := IntPow(3, i) rem := code % base result = append(result, rem/IntPow(3, i-1)) // fmt.Println(code, base, rem, rem/IntPow(3, i-1), result) code -= rem if code == 0 { return result } i++ if i > 10 { fmt.Println(i) panic("too many iterations") } } } // 83 // IntPower return x^y but as ints for speed func IntPow(x, y int) int { result := 1 for i := 0; i < y; i++ { result = result * x } return result } type ResultOdds struct { Result []int Words []string } func (s *Store) GetWordDistribution(word string, possibleAnswers []string) [][]string { distribution := make([][]string, IntPow(3, len(word))) for _, possibleAnswer := range possibleAnswers { result := battleword.GetResult(word, possibleAnswer) resultCode := ResultToCode(result) distribution[resultCode] = append(distribution[resultCode], possibleAnswer) } return distribution } func (s *Store) GetWordDistributionCount(word string, possibleAnswers []string) []int { distribution := make([]int, IntPow(3, len(word))) for _, possibleAnswer := range possibleAnswers { result := battleword.GetResult(word, possibleAnswer) resultCode := ResultToCode(result) distribution[resultCode]++ } return distribution } func (s *Store) GetDistributionExpectedRemainingAnswers(wordCount int, distribution [][]string) float64 { expectedRemainingAnswer := float64(0) for _, wordList := range distribution { expectedRemainingAnswer += float64(len(wordList)) / float64(wordCount) * float64(len(wordList)) } return expectedRemainingAnswer } func WordPossible(newGuess string, prevGuessResult battleword.GuessResult) bool { // i figured this out by looking at all the results. kinda cool. plz don't steal. newResult := battleword.GetResult(prevGuessResult.Guess, newGuess) // fmt.Println("---") // fmt.Println("new", newGuess, newResult) // fmt.Println("pre", prevGuessResult.Guess, prevGuessResult.Result) for i := 0; i < len(newGuess); i++ { if newResult[i] != prevGuessResult.Result[i] { return false } } return true }
logic.go
0.51562
0.44089
logic.go
starcoder
package main import ( "fmt" ) type depthSlice struct { depth int value int } func snailFishTreeToDepthSlice(node *snailfishNumber, depth int) (result []depthSlice) { if node == nil { return } result = append(result, snailFishTreeToDepthSlice(node.leftPair, depth+1)...) if node.isLeaf() { result = append(result, depthSlice{ depth: depth, value: node.value, }, ) } result = append(result, snailFishTreeToDepthSlice(node.rightPair, depth+1)...) return result } func sumSnailfishNumber(left, right []depthSlice) (result []depthSlice) { result = append(left, right...) for i := 0; i < len(result); i++ { result[i].depth++ } return result } func explode(number []depthSlice) (result []depthSlice, exploded bool) { var leftExploded int var rightExploded int var explodePosition int for i := range number { if number[i].depth > 4 { explodePosition = i leftExploded = number[i].value rightExploded = number[i+1].value exploded = true break } } if exploded { // Add the left explosion if explodePosition-1 >= 0 { number[explodePosition-1].value += leftExploded } // Add the right explosion if explodePosition+2 < len(number) { number[explodePosition+2].value += rightExploded } number[explodePosition+1].depth-- number[explodePosition+1].value = 0 number = append(number[:explodePosition], number[explodePosition+1:]...) } return number, exploded } func split(number []depthSlice) (result []depthSlice, splitted bool) { var splitPosition int for i := range number { if number[i].value > 9 { splitPosition = i splitted = true break } } if splitted { value := number[splitPosition].value number[splitPosition].value = value / 2 number[splitPosition].depth++ newNumber := depthSlice{ depth: number[splitPosition].depth, value: value/2 + value&0x1, } number = append(number[:splitPosition+1], append([]depthSlice{newNumber}, number[splitPosition+1:]...)...) } return number, splitted } func reduceSum(number []depthSlice) []depthSlice { isReduced := false var hasExploded bool var hasSplitted bool for !isReduced { isReduced = true number, hasExploded = explode(number) if hasExploded { isReduced = false } else { number, hasSplitted = split(number) if hasSplitted { isReduced = false } } } return number } func printDepthList(number []depthSlice) { depth := 0 printed := 0 for printed < len(number) { fmt.Print(depth, ": ") for _, depthSlice := range number { if depthSlice.depth == depth { fmt.Print(depthSlice.value) printed++ } else { fmt.Print(" ") } fmt.Print(" ") } depth++ fmt.Println() } } func magnetude(number []depthSlice) int { var magnetudeStack stack for _, element := range number { if magnetudeStack.Size() < 1 { magnetudeStack.Push(element) } else { magnetudeStack.Push(element) var partialResult depthSlice right := (magnetudeStack.Pop()).(depthSlice) left := (magnetudeStack.Pop()).(depthSlice) // Check if they are in the same level, if not, push them back to the stack if left.depth != right.depth { magnetudeStack.Push(left) magnetudeStack.Push(right) } else { partialResult.depth = left.depth - 1 partialResult.value = 3*left.value + 2*right.value magnetudeStack.Push(partialResult) } } // simplify stack isStackSimplified := false var partialResult depthSlice for !isStackSimplified { if magnetudeStack.Size() >= 2 { right := (magnetudeStack.Pop()).(depthSlice) left := (magnetudeStack.Pop()).(depthSlice) if left.depth != right.depth { magnetudeStack.Push(left) magnetudeStack.Push(right) isStackSimplified = true } else { partialResult.depth = left.depth - 1 partialResult.value = 3*left.value + 2*right.value magnetudeStack.Push(partialResult) } } else { isStackSimplified = true } } } return (magnetudeStack.Pop()).(depthSlice).value } func firstPart(homework []snailfishNumber) { fmt.Println("===================") fmt.Println("Starting first part") fmt.Println("===================") var homeworkButInAList [][]depthSlice for _, number := range homework { homeworkButInAList = append(homeworkButInAList, snailFishTreeToDepthSlice(&number, 0)) } partialResult := homeworkButInAList[0] for i := 1; i < len(homeworkButInAList); i++ { partialResult = sumSnailfishNumber(partialResult, homeworkButInAList[i]) partialResult = reduceSum(partialResult) } fmt.Println(magnetude(partialResult)) }
day-18/first.go
0.630344
0.499207
first.go
starcoder
package api import ( . "github.com/gocircuit/circuit/gocircuit.org/render" ) func RenderChannelPage() string { return RenderHtml("Using server", Render(channelBody, nil)) } const channelBody = ` <h2>Using channels</h2> <p>Channel elements are FIFO queues for binary messages. A channel physically lives on a particular host. It supports a ‘send’ operation which pushes a new binary message to the queue, and a ‘receive’ operation which removes the next binary message from the queue. <p>On creation, channels can be configured to buffer a fixed non-negative number of messages. When the buffer is full, send operations block until a message is received. Receive operations, on the other hand, block if there are no pending messages in the buffer, until the next send operation is performed. <p>Channels are created using the anchor's <code>MakeChan</code> method: <pre> MakeChan(n int) (Chan, error) </pre> <p>For instance, <pre> ch, err := anchor.MakeChan(0) if err != nil { … // this anchor is already busy } </pre> <p>An application error will be returned only if the anchor already has an element attached to it. The integer parameter specifies the number of messages the channel will buffer. This must be a non-negative integer. <p>Interacting with the channel is done using the channel element's interface: <pre> type Chan interface { Send() (io.WriteCloser, error) Recv() (io.ReadCloser, error) Close() error Stat() ChanStat Scrub() } </pre> <p>The <code>Scrub</code> method will forcefully abort and discard the channel element, even if messages are pending in the channel's buffer. <h3>Sending and receiving messages</h3> <p>The send/receive mechanism transports <code>io.ReadWriteCloser</code> pipes between the sender and the receiver. The sender gets the write end and the receiver gets the read end of the pipe. <p>To send a message, the user invokes <code>Send</code>. If the channel has been closed or aborted, a non-nil application error is returned. Otherwise, a new pipe is created. Send attempts to send the pipe itself through the channel. It will block until there is space in the channel buffer or there is a matching call to <code>Receive</code>. <p>When <code>Send</code> unblocks it returns an <code>io.WriteCloser</code> wherein the user writes the content of the message and closes the stream to indicate end of message. <pre> w, err := ch.Send() if err != nil { … // channel has been closed } w.Write(msg) w.Close() </pre> <p>To receive a message, the user invokes <code>Recv</code>. The operation blocks until there is a pipe in the channel buffer or a matching call to <code>Send</code>. Receive will return an application error if the channel has been closed. Otherwise it returns the reader end of the pipe received. <h3>Channel closure</h3> <p>Channels can be closed synchronously with the <code>Close</code> method. The closure event will be communicated to the receiver after all pending messages have been received. <code>Close</code> returns an application error only if the channel has already been clsoed. <p>An alternative method of closing the channel is to invoke <code>Scrub</code>. This will abort the channel and discard any pending messages. <h3>Retrieving channel state</h3> <p>The <code>Stat</code> method can be called asynchronously to retrieve the current state of the channel. The returned structure includes the channel capacity, whether the channel has been closed or aborted, the number of messages sent and received. (The difference of sent and received messages is the count of messages pending reception in the channel buffer.) <pre> type ChanStat struct { Cap int Closed bool Aborted bool NumSend int NumRecv int } </pre> `
gocircuit.org/api/channel.go
0.704872
0.561756
channel.go
starcoder
package templates import ( "math/rand" "time" "github.com/luisfcofv/indexter/models" ) func GetEventTemplates(world models.World) []models.Event { return []models.Event{ getFirstTemplate(world), getSecondTemplate(world), getThirdTemplate(world), getFourthTemplate(world), getFifthTemplate(world), } } func getFirstTemplate(world models.World) models.Event { time := time.Now().Unix() rand.Seed(time) location := world.Locations[rand.Intn(len(world.Locations))] agent := world.Agents[rand.Intn(len(world.Agents))] goal := world.Goals[rand.Intn(len(world.Goals))] causation := world.Goals[rand.Intn(len(world.Goals))] protagonist := false if rand.Intn(2) == 1 { protagonist = true } event := models.Event{ Name: "Something is happening", Description: "Nobody knows what is going on, be ready for an adventure", Protagonist: protagonist, Agents: []models.Agent{agent}, Location: location, Goal: goal, Propagation: rand.Intn(2) + 1, Cause: causation, } return event } func getSecondTemplate(world models.World) models.Event { event := models.Event{ Name: "The orcs are gathering", Description: "This unusal situation means they are looking for something valuable", Protagonist: false, Agents: []models.Agent{world.Agents[4]}, // Traveler Location: world.Locations[3], Goal: world.Goals[1], // Find the treasure Propagation: 1, Cause: world.Goals[2], // Collect coins } return event } func getThirdTemplate(world models.World) models.Event { event := models.Event{ Name: "The king has gathered important information", Description: "This information can solve an imporantant mistery", Protagonist: false, Agents: []models.Agent{world.Agents[0], world.Agents[1]}, // The king & Witness Location: world.Locations[1], // King Goal: world.Goals[0], // Talk to the king Propagation: 1, Cause: world.Goals[4], // Rescue the princess } return event } func getFourthTemplate(world models.World) models.Event { event := models.Event{ Name: "Kill the dragon", Description: "The most feared creature in this world, this dragon has a broad, elongated body with a very long tail", Protagonist: true, Agents: []models.Agent{world.Agents[3]}, // Wizard Location: world.Locations[4], Goal: world.Goals[3], // Fight the dragon Propagation: 1, } return event } func getFifthTemplate(world models.World) models.Event { time := time.Now().Unix() rand.Seed(time) possibleCities := []int{3, 4} cityID := rand.Intn(len(possibleCities)) event := models.Event{ Name: "The dragon has taken the princess", Description: "The princess disappeared at midnight, some people saw the dragon close to the city last night", Agents: []models.Agent{world.Agents[4]}, // Princess Location: world.Locations[possibleCities[cityID]], Goal: world.Goals[4], // Rescue the princess Propagation: 2, Cause: world.Goals[3], // Fight the dragon } return event }
templates/events.go
0.564819
0.406243
events.go
starcoder
package kate import ( "crypto/rand" "math/big" ) var _modulus big.Int func init() { bigNum((*Big)(&_modulus), "52435875175126190479447740508185965837690552500527637822603658699938581184513") initGlobals() } type Big big.Int // BigNumFrom32 mutates the big num. The value v is little-endian 32-bytes. func BigNumFrom32(dst *Big, v [32]byte) { // reverse endianness, big.Int takes big-endian bytes for i := 0; i < 16; i++ { v[i], v[31-i] = v[31-i], v[i] } (*big.Int)(dst).SetBytes(v[:]) } // BigNumTo32 serializes a big number to 32 bytes. Encoded little-endian. func BigNumTo32(src *Big) (v [32]byte) { b := (*big.Int)(src).Bytes() last := len(b) - 1 // reverse endianness, u256.Int outputs big-endian bytes for i := 0; i < 16; i++ { b[i], b[last-i] = b[last-i], b[i] } copy(v[:], b) return } func CopyBigNum(dst *Big, v *Big) { (*big.Int)(dst).Set((*big.Int)(v)) } func bigNum(dst *Big, v string) { if err := (*big.Int)(dst).UnmarshalText([]byte(v)); err != nil { panic(err) } } func asBig(dst *Big, i uint64) { (*big.Int)(dst).SetUint64(i) } func bigStr(b *Big) string { return (*big.Int)(b).String() } func equalOne(v *Big) bool { return (*big.Int)(v).Cmp((*big.Int)(&ONE)) == 0 } func equalZero(v *Big) bool { return (*big.Int)(v).Cmp((*big.Int)(&ZERO)) == 0 } func equalBig(a *Big, b *Big) bool { return (*big.Int)(a).Cmp((*big.Int)(b)) == 0 } func randomBig() *Big { v, err := rand.Int(rand.Reader, &_modulus) if err != nil { panic(err) } return (*Big)(v) } func subModBig(dst *Big, a, b *Big) { (*big.Int)(dst).Sub((*big.Int)(a), (*big.Int)(b)) (*big.Int)(dst).Mod((*big.Int)(dst), &_modulus) } func addModBig(dst *Big, a, b *Big) { (*big.Int)(dst).Add((*big.Int)(a), (*big.Int)(b)) (*big.Int)(dst).Mod((*big.Int)(dst), &_modulus) } func divModBig(dst *Big, a, b *Big) { (*big.Int)(dst).DivMod((*big.Int)(a), (*big.Int)(b)) } func mulModBig(dst *Big, a, b *Big) { (*big.Int)(dst).Mul((*big.Int)(a), (*big.Int)(b)) (*big.Int)(dst).Mod((*big.Int)(dst), &_modulus) } func powModBig(dst *Big, a, b *Big) { (*big.Int)(dst).Exp((*big.Int)(a), (*big.Int)(b), &_modulus) } func invModBig(dst *Big, v *Big) { (*big.Int)(dst).ModInverse((*big.Int)(v), &_modulus) } //func sqrModBig(dst *Big, v *Big) { // (*big.Int)(dst).ModSqrt((*big.Int)(v), &_modulus) //}
bignum_pure.go
0.627723
0.457621
bignum_pure.go
starcoder
package lzw import ( "errors" "fmt" "github.com/mjjs/gompressor/datastructure/dictionary" "github.com/mjjs/gompressor/datastructure/vector" ) // DictionarySize determines how large the dictionary used in compression can // grow before needing to be reset. Larger values result in more efficient // compression. type DictionarySize uint16 // Dictionary sizes const ( XS DictionarySize = 512 S = 1023 M = 4095 L = 32767 XL = 65535 ) const initialDictSize uint16 = 255 // ErrBadCompressedCode represents an error that occurs when the LZW decompression // algorithm finds a code that is not valid for the assumed compression algorithm. var ErrBadCompressedCode = errors.New("bad compression code") // ErrInvalidDictionarySize represents an error indicating usage of an invalid // dictionary size. This can happen when attempting to compress or decompress // data. var ErrInvalidDictionarySize = errors.New("invalid dictionary size") // CompressWithDictSize takes a slice of uncompressed bytes and a dictionary size // as input and returns a slice of LZW codes that represent the compressed data. // This is mostly a utility function for testing how the dictionary size changes // the compression level. func CompressWithDictSize(uncompressed *vector.Vector, size DictionarySize) (*vector.Vector, error) { if !isValidDictionarySize(size) { return nil, fmt.Errorf("%w: %d", ErrInvalidDictionarySize, int(size)) } if uncompressed.Size() == 0 { return uncompressed, nil } dict := createInitialCompressDictionary() compressed := vector.New(0, uint(uncompressed.Size())) compressed.Append(uint16(size)) word := vector.New() for i := 0; i < uncompressed.Size(); i++ { if dict.Size() == int(size) { dict = createInitialCompressDictionary() } byt := uncompressed.MustGet(i) newWord := word.AppendToCopy(byt) if _, ok := dict.Get(newWord.String()); ok { word = newWord } else { code, _ := dict.Get(word.String()) compressed.Append(code.(uint16)) dict.Set(newWord.String(), uint16(dict.Size())) word = vector.New().AppendToCopy(byt) } } if word.Size() > 0 { code, _ := dict.Get(word.String()) compressed.Append(code.(uint16)) } return compressed, nil } // Compress is a shortcut for compressing with the largest dictionary size. func Compress(uncompressed *vector.Vector) (*vector.Vector, error) { return CompressWithDictSize(uncompressed, XL) } // Decompress takes in a slice of LZW codes representing some compressed data // and outputs the decompressed data as a slice of bytes. // An error is returned if the decompression algorithm finds a bad LZW code. func Decompress(compressed *vector.Vector) (*vector.Vector, error) { if compressed.Size() == 0 { return compressed, nil } size := compressed.MustGet(0).(uint16) if !isValidDictionarySize(DictionarySize(size)) { return nil, fmt.Errorf("the data is compressed with an invalid dictionary size %d", size) } dict := createInitialDecompressDictionary() result := vector.New() word := vector.New() for i := 1; i < compressed.Size(); i++ { if dict.Size() == int(size) { dict = createInitialDecompressDictionary() } code := compressed.MustGet(i) entry := vector.New() if c, ok := dict.Get(code); ok { byteVector := c.(*vector.Vector) entry = vector.New(uint(byteVector.Size())) for i := 0; i < byteVector.Size(); i++ { entry.MustSet(i, byteVector.MustGet(i)) } } else if int(code.(uint16)) == dict.Size() && word.Size() > 0 { entry = word.AppendToCopy(word.MustGet(0)) } else { return nil, fmt.Errorf("%w: %d", ErrBadCompressedCode, code) } for i := 0; i < entry.Size(); i++ { result.Append(entry.MustGet(i)) } if word.Size() > 0 { word = word.AppendToCopy(entry.MustGet(0)) dict.Set(uint16(dict.Size()), word) } word = entry } return result, nil } func createInitialCompressDictionary() *dictionary.Dictionary { dict := dictionary.NewWithSize(uint(initialDictSize)) for i := uint16(0); i <= initialDictSize; i++ { dict.Set(string([]byte{byte(i)}), i) } return dict } func createInitialDecompressDictionary() *dictionary.Dictionary { dict := dictionary.NewWithSize(uint(initialDictSize)) for i := uint16(0); i <= initialDictSize; i++ { bv := vector.New(1) bv.MustSet(0, byte(i)) dict.Set(i, bv) } return dict } func isValidDictionarySize(size DictionarySize) bool { validSizes := []DictionarySize{ XS, S, M, L, XL, } for _, dictionarySize := range validSizes { if dictionarySize == size { return true } } return false }
algorithm/lzw/lzw.go
0.737064
0.484075
lzw.go
starcoder
package discovery import "fmt" type BinarySensor struct { // A list of MQTT topics subscribed to receive availability (online/offline) updates. Must not be used together with `availability_topic` // Default: <no value> Availability []Availability `json:"availability,omitempty"` // When `availability` is configured, this controls the conditions needed to set the entity to `available`. Valid entries are `all`, `any`, and `latest`. If set to `all`, `payload_available` must be received on all configured availability topics before the entity is marked as online. If set to `any`, `payload_available` must be received on at least one configured availability topic before the entity is marked as online. If set to `latest`, the last `payload_available` or `payload_not_available` received on any configured availability topic controls the availability // Default: latest AvailabilityMode string `json:"availability_mode,omitempty"` // Defines a [template](/docs/configuration/templating/#processing-incoming-data) to extract device's availability from the `availability_topic`. To determine the devices's availability result of this template will be compared to `payload_available` and `payload_not_available` // Default: <no value> AvailabilityTemplate string `json:"availability_template,omitempty"` // The MQTT topic subscribed to receive birth and LWT messages from the MQTT device. If `availability` is not defined, the binary sensor will always be considered `available` and its state will be `on`, `off` or `unknown`. If `availability` is defined, the binary sensor will be considered as `unavailable` by default and the sensor's initial state will be `unavailable`. Must not be used together with `availability` // Default: <no value> AvailabilityTopic string `json:"availability_topic,omitempty"` // Information about the device this binary sensor is a part of to tie it into the [device registry](https://developers.home-assistant.io/docs/en/device_registry_index.html). Only works through [MQTT discovery](/docs/mqtt/discovery/) and when [`unique_id`](#unique_id) is set. At least one of identifiers or connections must be present to identify the device // Default: <no value> Device *Device `json:"device,omitempty"` // Sets the [class of the device](/integrations/binary_sensor/#device-class), changing the device state and icon that is displayed on the frontend // Default: <no value> DeviceClass string `json:"device_class,omitempty"` // Flag which defines if the entity should be enabled when first added // Default: true EnabledByDefault bool `json:"enabled_by_default,omitempty"` // The encoding of the payload received at `state_topic` and availability topics `availability_topic` and `topic`. Set to `""` to disable decoding // Default: utf-8 Encoding string `json:"encoding,omitempty"` // The [category](https://developers.home-assistant.io/docs/core/entity#generic-properties) of the entity // Default: None EntityCategory string `json:"entity_category,omitempty"` // Defines the number of seconds after the sensor's state expires, if it's not updated. After expiry, the sensor's state becomes `unavailable` // Default: <no value> ExpireAfter int `json:"expire_after,omitempty"` // Sends update events (which results in update of [state object](/docs/configuration/state_object/)'s `last_changed`) even if the sensor's state hasn't changed. Useful if you want to have meaningful value graphs in history or want to create an automation that triggers on *every* incoming state message (not only when the sensor's new state is different to the current one) // Default: false ForceUpdate bool `json:"force_update,omitempty"` // [Icon](/docs/configuration/customizing-devices/#icon) for the entity // Default: <no value> Icon string `json:"icon,omitempty"` // Defines a [template](/docs/configuration/templating/#processing-incoming-data) to extract the JSON dictionary from messages received on the `json_attributes_topic`. Usage example can be found in [MQTT sensor](/integrations/sensor.mqtt/#json-attributes-template-configuration) documentation // Default: <no value> JsonAttributesTemplate string `json:"json_attributes_template,omitempty"` // The MQTT topic subscribed to receive a JSON dictionary payload and then set as sensor attributes. Usage example can be found in [MQTT sensor](/integrations/sensor.mqtt/#json-attributes-topic-configuration) documentation // Default: <no value> JsonAttributesTopic string `json:"json_attributes_topic,omitempty"` // The name of the binary sensor // Default: MQTT Binary Sensor Name string `json:"name,omitempty"` // Used instead of `name` for automatic generation of `entity_id // Default: <no value> ObjectId string `json:"object_id,omitempty"` // For sensors that only send `on` state updates (like PIRs), this variable sets a delay in seconds after which the sensor's state will be updated back to `off` // Default: <no value> OffDelay int `json:"off_delay,omitempty"` // The string that represents the `online` state // Default: online PayloadAvailable string `json:"payload_available,omitempty"` // The string that represents the `offline` state // Default: offline PayloadNotAvailable string `json:"payload_not_available,omitempty"` // The string that represents the `off` state. It will be compared to the message in the `state_topic` (see `value_template` for details // Default: OFF PayloadOff string `json:"payload_off,omitempty"` // The string that represents the `on` state. It will be compared to the message in the `state_topic` (see `value_template` for details // Default: ON PayloadOn string `json:"payload_on,omitempty"` // The maximum QoS level to be used when receiving messages // Default: 0 Qos int `json:"qos,omitempty"` // The MQTT topic subscribed to receive sensor's state // Default: <no value> StateTopic string `json:"state_topic"` // An ID that uniquely identifies this sensor. If two sensors have the same unique ID, Home Assistant will raise an exception // Default: <no value> UniqueId string `json:"unique_id,omitempty"` // Defines a [template](/docs/configuration/templating/#processing-incoming-data) that returns a string to be compared to `payload_on`/`payload_off` or an empty string, in which case the MQTT message will be removed. Available variables: `entity_id`. Remove this option when 'payload_on' and 'payload_off' are sufficient to match your payloads (i.e no pre-processing of original message is required) // Default: <no value> ValueTemplate string `json:"value_template,omitempty"` } // AnnounceTopic returns the topic to announce the discoverable BinarySensor // Topic has the format below: // <discovery_prefix>/<component>/<object_id>/config // 'object_id' is either the UniqueId, the Name, or a hash of the BinarySensor func (d *BinarySensor) AnnounceTopic(prefix string) string { topicFormat := "%s/binary_sensor/%s/config" objectID := "" switch { case d.UniqueId != "": objectID = d.UniqueId case d.Name != "": objectID = d.Name default: objectID = hash(d) } return fmt.Sprintf(topicFormat, prefix, objectID) }
binarysensor.go
0.846831
0.451508
binarysensor.go
starcoder
package game import ( "github.com/gitfyu/mable/biome" "github.com/gitfyu/mable/block" "math" ) const ( // chunkSectionBlocksSize is the number of bytes used for block data per chunkSection. chunkSectionBlocksSize = 16 * 16 * 16 * 2 // chunkSectionsPerChunk is the maximum number of chunkSection instances within a single Chunk. chunkSectionsPerChunk = 16 // lightDataSize is the number of bytes used for both block- and skylight data per chunkSection. lightDataSize = 16 * 16 * 16 / 2 * 2 // biomeDataSize is the number of bytes used for biome data in a single Chunk. biomeDataSize = 256 ) var ( // cachedLightAndBiomeData contains pre-generated light and biome data for a single full-sized chunk. cachedLightAndBiomeData [lightDataSize*chunkSectionsPerChunk + biomeDataSize]byte ) func init() { // I (currently) don't care about light or biome data for chunks, since it is not really relevant for Mable's // intended use case, which means that I can just pre-generate all this data and re-use it for every chunk, instead // of having to recompute it every time. const fullBright = 15 // light for i := 0; i < lightDataSize*chunkSectionsPerChunk; i++ { cachedLightAndBiomeData[i] = fullBright<<4 | fullBright } // biomes for i := lightDataSize * chunkSectionsPerChunk; i < lightDataSize*chunkSectionsPerChunk+biomeDataSize; i++ { cachedLightAndBiomeData[i] = uint8(biome.Plains) } } // ChunkPos contains a pair of chunk coordinates. type ChunkPos struct { X, Z int32 } // ChunkPosFromWorldCoords returns the ChunkPos for the given world coordinates. func ChunkPosFromWorldCoords(x, z float64) ChunkPos { return ChunkPos{ X: int32(math.Floor(x / 16)), Z: int32(math.Floor(z / 16)), } } // Dist returns the distance between two ChunkPos values, in chunks. Note that this is not the euclidean distance, // instead it is computed as max(abs(x1-x2), abs(z1-z2)). func (p ChunkPos) Dist(other ChunkPos) int32 { dx := p.X - other.X if dx < 0 { dx = -dx } dz := p.Z - other.Z if dz < 0 { dz = -dz } if dx > dz { return dx } else { return dz } } // chunkSection represents a 16-block tall section within a chunk. type chunkSection [chunkSectionBlocksSize]byte // Chunk represents a 16x16x256 area in a World. type Chunk struct { listeners map[uint32]chan<- interface{} // sectionMask is a bitmask where the nth bit indicates if sections[n] is set. sectionMask uint16 // sectionCount is the number of chunkSection instances stored in sections. sectionCount int // sections contains all chunkSection instances for this Chunk. It is possible that not all indices contain a // chunkSection, in which case they will be nil. sections [chunkSectionsPerChunk]*chunkSection } // NewChunk constructs a new Chunk. func NewChunk() *Chunk { return &Chunk{ listeners: make(map[uint32]chan<- interface{}), } } // SetBlock changes a block in the chunk. Note that the coordinates are relative to the chunk, not world coordinates. // Coordinates must all be within the range [0,15] or the function will panic. func (c *Chunk) SetBlock(x, y, z uint8, data block.Data) { sectionIdx := y >> 4 c.createSectionIfNotExists(sectionIdx) section := c.sections[sectionIdx] idx := int(y&15)<<9 | int(z)<<5 | int(x)<<1 v := data.ToUint16() section[idx] = uint8(v) section[idx+1] = uint8(v >> 8) } // createSectionIfNotExists creates and stores a new chunkSection at the specified index if it does not exist yet. func (c *Chunk) createSectionIfNotExists(index uint8) { if c.sectionMask&(1<<index) != 0 { return } c.sectionCount++ c.sectionMask |= 1 << index c.sections[index] = new(chunkSection) } // appendData will append the data for this chunk to the buffer, to be sent in a packet. The appended buffer will be // returned. func (c *Chunk) appendData(buf []byte) []byte { // blocks for i := 0; i < chunkSectionsPerChunk; i++ { if c.sectionMask&(1<<i) != 0 { buf = append(buf, c.sections[i][:]...) } } return append(buf, cachedLightAndBiomeData[(chunkSectionsPerChunk-c.sectionCount)*lightDataSize:]...) } // Subscribe registers the specified channel to receive updates for this Chunk. The specified ID must be unique to the // subscriber. func (c *Chunk) Subscribe(id uint32, ch chan<- interface{}) { ch <- "Subbed" c.listeners[id] = ch } // Unsubscribe cancels the subscription associated with the specified ID. func (c *Chunk) Unsubscribe(id uint32) { delete(c.listeners, id) } // Broadcast broadcasts a message to all subscribers of this Chunk. func (c *Chunk) Broadcast(msg interface{}) { for _, ch := range c.listeners { ch <- msg } }
game/chunk.go
0.642769
0.452596
chunk.go
starcoder
package main import "fmt" /** "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101" "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011" Given two binary strings, return their sum (also a binary string). The input strings are both non-empty and contains only characters 1 or 0. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" */ func addBinaryMy(a string, b string) string { i := len(a) - 1 j := len(b) - 1 var s string var c uint8 for { if i >= 0 || j >= 0 { c /= 2 if (i >= 0) { c += a[i] - '0'; i--; } if (j >= 0) { c += b[j] - '0'; j--; } if c%2 == 0 { s = "0" + s } else { s = "1" + s } } else { break } } if c > 1 { s = "1" + s } return s } func addBinary(a string, b string) string { IfAdd := 48 aToByte := []byte(a) bToByte := []byte(b) aLength := len(aToByte) bLength := len(bToByte) theSameLength := 0 var restPart []byte if aLength > bLength { restPart = aToByte[:aLength-bLength] aToByte = aToByte[aLength-bLength:] theSameLength = bLength } else if aLength < bLength { restPart = bToByte[:bLength-aLength] bToByte = bToByte[bLength-aLength:] theSameLength = aLength } else { theSameLength = aLength } for i := theSameLength - 1; i >= 0; i-- { switch { case aToByte[i] == 48 && bToByte[i] == 48 && IfAdd == 49: aToByte[i] = 49 IfAdd = 48 case aToByte[i] == 48 && bToByte[i] == 49 && IfAdd == 49: aToByte[i] = 48 IfAdd = 49 case aToByte[i] == 49 && bToByte[i] == 48 && IfAdd == 49: aToByte[i] = 48 IfAdd = 49 case aToByte[i] == 49 && bToByte[i] == 49 && IfAdd == 49: aToByte[i] = 49 IfAdd = 49 case aToByte[i] == 48 && bToByte[i] == 48 && IfAdd == 48: aToByte[i] = 48 IfAdd = 48 case aToByte[i] == 48 && bToByte[i] == 49 && IfAdd == 48: aToByte[i] = 49 IfAdd = 48 case aToByte[i] == 49 && bToByte[i] == 48 && IfAdd == 48: aToByte[i] = 49 IfAdd = 48 case aToByte[i] == 49 && bToByte[i] == 49 && IfAdd == 48: aToByte[i] = 48 IfAdd = 49 } } for i := len(restPart) - 1; i >= 0; i-- { switch { case restPart[i] == 48 && IfAdd == 48: restPart[i] = 48 IfAdd = 48 case restPart[i] == 48 && IfAdd == 49: restPart[i] = 49 IfAdd = 48 case restPart[i] == 49 && IfAdd == 48: restPart[i] = 49 IfAdd = 48 case restPart[i] == 49 && IfAdd == 49: restPart[i] = 48 IfAdd = 49 } } restPart = append(restPart, aToByte...) if IfAdd == 49 { restPart = append([]byte{49}, restPart...) return string(restPart) } return string(restPart) } func main() { fmt.Println(addBinary("0", "1")) }
main/addBinary.go
0.587233
0.507263
addBinary.go
starcoder
package matrigo import ( "fmt" "strings" ) // Mapper is the function type used for the Map function type Mapper func(val float64, x int, y int) float64 // Folder is the function type used for the Fold function type Folder func(accumulator, val float64, x int, y int) float64 // Matrix represents a matrix type Matrix struct { Rows int Columns int Data [][]float64 } // New returns a matrix func New(r, c int, data [][]float64) Matrix { if data == nil { data = make([][]float64, r) for i := range data { data[i] = make([]float64, c) } } if len(data) != r { panic("matrix: invalid shape of data") } for _, inputs := range data { if len(inputs) != c { panic("matrix: invalid shape of data") } } return Matrix{ Rows: r, Columns: c, Data: data, } } // NewFromArray creates a matrix that's basically a one dimensional vector going downwards // N amount of rows and 1 column func NewFromArray(d []float64) Matrix { return Map(New(len(d), 1, nil), func(val float64, x, y int) float64 { return d[x] }) } // Randomize randomizes the values in the matrix func (m *Matrix) Randomize(low, high float64) { for i := 0; i < m.Rows; i++ { for j := 0; j < m.Columns; j++ { m.Data[i][j] = randFloat(low, high) } } } // Zero sets all the values to 0 func (m *Matrix) Zero() { for i := 0; i < m.Rows; i++ { for j := 0; j < m.Columns; j++ { m.Data[i][j] = 0 } } } // Copy returns a copy of the matrix func (m *Matrix) Copy() Matrix { return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] }) } // Map applies f to every element of the matrix and returns the result func (m Matrix) Map(f Mapper) Matrix { return Map(m, f) } // Fold accumulates the values in a matrix according to a Folder function func (m Matrix) Fold(f Folder, accumulator float64) float64 { return Fold(m, f, accumulator) } // Transpose returns the transposed version of the matrix func (m Matrix) Transpose() Matrix { return Transpose(m) } // Multiply does scalar multiplication func (m Matrix) Multiply(a float64) Matrix { return Multiply(m, a) } // Divide does scalar multiplication func (m Matrix) Divide(a float64) Matrix { return Divide(m, a) } // Sum gives the sum of the elements in the matrix func (m Matrix) Sum() float64 { return Sum(m) } // AddMatrix adds 2 matrices together func (m Matrix) AddMatrix(n Matrix) Matrix { return AddMatrix(m, n) } // Add does scalar addition func (m Matrix) Add(a float64) Matrix { return Add(m, a) } // SubtractMatrix subtracts 2 matrices func (m Matrix) SubtractMatrix(n Matrix) Matrix { return SubtractMatrix(m, n) } // Subtract does scalar subtraction func (m Matrix) Subtract(a float64) Matrix { return Subtract(m, a) } // HadamardProduct does Hadamard product (entrywise) func (m Matrix) HadamardProduct(n Matrix) Matrix { return HadamardProduct(m, n) } // DotProduct does matrix product func (m Matrix) DotProduct(n Matrix) Matrix { return DotProduct(m, n) } // Flatten flattens the matrix func (m Matrix) Flatten() []float64 { r := make([]float64, m.Rows*m.Columns) i := 0 for _, line := range m.Data { for _, val := range line { r[i] = val i++ } } return r } // Det computes the determinant. func (m Matrix) Det() float64 { return Det(m) } // Unflatten chops the data in `c` slices `r` times // In other words it makes a new matrix from a 1D array func Unflatten(r, c int, data []float64) Matrix { if len(data) != r*c { panic("matrix: invalid shape of data") } return Map(New(r, c, nil), func(val float64, x, y int) float64 { return data[x*c+y] }) } func (m Matrix) String() string { b := &strings.Builder{} for _, line := range m.Data { for _, num := range line { fmt.Fprintf(b, " %f ", num) } b.WriteString("\n") } return b.String() }
matrix.go
0.844473
0.719938
matrix.go
starcoder
package imports import ( . "reflect" "image/color" ) // reflection: allow interpreted code to import "image/color" func init() { Packages["image/color"] = Package{ Binds: map[string]Value{ "Alpha16Model": ValueOf(&color.Alpha16Model).Elem(), "AlphaModel": ValueOf(&color.AlphaModel).Elem(), "Black": ValueOf(&color.Black).Elem(), "CMYKModel": ValueOf(&color.CMYKModel).Elem(), "CMYKToRGB": ValueOf(color.CMYKToRGB), "Gray16Model": ValueOf(&color.Gray16Model).Elem(), "GrayModel": ValueOf(&color.GrayModel).Elem(), "ModelFunc": ValueOf(color.ModelFunc), "NRGBA64Model": ValueOf(&color.NRGBA64Model).Elem(), "NRGBAModel": ValueOf(&color.NRGBAModel).Elem(), "NYCbCrAModel": ValueOf(&color.NYCbCrAModel).Elem(), "Opaque": ValueOf(&color.Opaque).Elem(), "RGBA64Model": ValueOf(&color.RGBA64Model).Elem(), "RGBAModel": ValueOf(&color.RGBAModel).Elem(), "RGBToCMYK": ValueOf(color.RGBToCMYK), "RGBToYCbCr": ValueOf(color.RGBToYCbCr), "Transparent": ValueOf(&color.Transparent).Elem(), "White": ValueOf(&color.White).Elem(), "YCbCrModel": ValueOf(&color.YCbCrModel).Elem(), "YCbCrToRGB": ValueOf(color.YCbCrToRGB), }, Types: map[string]Type{ "Alpha": TypeOf((*color.Alpha)(nil)).Elem(), "Alpha16": TypeOf((*color.Alpha16)(nil)).Elem(), "CMYK": TypeOf((*color.CMYK)(nil)).Elem(), "Color": TypeOf((*color.Color)(nil)).Elem(), "Gray": TypeOf((*color.Gray)(nil)).Elem(), "Gray16": TypeOf((*color.Gray16)(nil)).Elem(), "Model": TypeOf((*color.Model)(nil)).Elem(), "NRGBA": TypeOf((*color.NRGBA)(nil)).Elem(), "NRGBA64": TypeOf((*color.NRGBA64)(nil)).Elem(), "NYCbCrA": TypeOf((*color.NYCbCrA)(nil)).Elem(), "Palette": TypeOf((*color.Palette)(nil)).Elem(), "RGBA": TypeOf((*color.RGBA)(nil)).Elem(), "RGBA64": TypeOf((*color.RGBA64)(nil)).Elem(), "YCbCr": TypeOf((*color.YCbCr)(nil)).Elem(), }, Proxies: map[string]Type{ "Color": TypeOf((*P_image_color_Color)(nil)).Elem(), "Model": TypeOf((*P_image_color_Model)(nil)).Elem(), }, } } // --------------- proxy for image/color.Color --------------- type P_image_color_Color struct { Object interface{} RGBA_ func(interface{}) (r uint32, g uint32, b uint32, a uint32) } func (P *P_image_color_Color) RGBA() (r uint32, g uint32, b uint32, a uint32) { return P.RGBA_(P.Object) } // --------------- proxy for image/color.Model --------------- type P_image_color_Model struct { Object interface{} Convert_ func(_proxy_obj_ interface{}, c color.Color) color.Color } func (P *P_image_color_Model) Convert(c color.Color) color.Color { return P.Convert_(P.Object, c) }
vendor/github.com/cosmos72/gomacro/imports/image_color.go
0.619356
0.441553
image_color.go
starcoder
package prime import ( "math/rand" "github.com/TheAlgorithms/Go/math/modular" ) // formatNum accepts a number and returns the // odd number d such that num = 2^s * d + 1 func formatNum(num int64) (d int64, s int64) { d = num - 1 for num%2 == 0 { d /= 2 s++ } return } // isTrivial checks if num's primality is easy to determine. // If it is, it returns true and num's primality. Otherwise // it returns false and false. func isTrivial(num int64) (prime bool, trivial bool) { if num <= 4 { // 2 and 3 are primes prime = num == 2 || num == 3 trivial = true } else { prime = false // number is trivial prime if // it is divisible by 2 trivial = num%2 == 0 } return } // MillerTest tests whether num is a strong probable prime to a witness. // Formally: a^d ≡ 1 (mod n) or a^(2^r * d) ≡ -1 (mod n), 0 <= r <= s func MillerTest(num, witness int64) (bool, error) { d, _ := formatNum(num) res, err := modular.Exponentiation(witness, d, num) if err != nil { return false, err } // miller conditions checks if res == 1 || res == num-1 { return true, nil } for d != num-1 { res = (res * res) % num d *= 2 if res == 1 { return false, nil } if res == num-1 { return true, nil } } return false, nil } // MillerRandomTest This is the intermediate step that repeats within the // miller rabin primality test for better probabilitic chances of // receiving the correct result with random witnesses. func MillerRandomTest(num int64) (bool, error) { random := rand.Int63n(num-1) + 2 return MillerTest(num, random) } // MillerTestMultiple is like MillerTest but runs the test for multiple // witnesses. func MillerTestMultiple(num int64, witnesses ...int64) (bool, error) { for _, witness := range witnesses { prime, err := MillerTest(num, witness) if err != nil { return false, err } if !prime { return false, nil } } return true, nil } // MillerRabinProbabilistic is a probabilistic test for primality // of an integer based of the algorithm devised by Miller and Rabin. func MillerRabinProbabilistic(num, rounds int64) (bool, error) { if prime, trivial := isTrivial(num); trivial { // num is a trivial number return prime, nil } for i := int64(0); i < rounds; i++ { val, err := MillerRandomTest(num) if err != nil { return false, err } if !val { return false, nil } } return true, nil } // MillerRabinDeterministic is a Deterministic version of the Miller-Rabin // test, which returns correct results for all valid int64 numbers. func MillerRabinDeterministic(num int64) (bool, error) { if prime, trivial := isTrivial(num); trivial { // num is a trivial number return prime, nil } switch { case num < 2047: // witness 2 can determine the primality of any number less than 2047 return MillerTest(num, 2) case num < 1_373_653: // witnesses 2 and 3 can determine the primality // of any number less than 1,373,653 return MillerTestMultiple(num, 2, 3) case num < 9_080_191: // witnesses 31 and 73 can determine the primality // of any number less than 9,080,191 return MillerTestMultiple(num, 31, 73) case num < 25_326_001: // witnesses 2, 3, and 5 can determine the // primality of any number less than 25,326,001 return MillerTestMultiple(num, 2, 3, 5) case num < 1_122_004_669_633: // witnesses 2, 13, 23, and 1,662,803 can determine the // primality of any number less than 1,122,004,669,633 return MillerTestMultiple(num, 2, 13, 23, 1_662_803) case num < 2_152_302_898_747: // witnesses 2, 3, 5, 7, and 11 can determine the primality // of any number less than 2,152,302,898,747 return MillerTestMultiple(num, 2, 3, 5, 7, 11) case num < 341_550_071_728_321: // witnesses 2, 3, 5, 7, 11, 13, and 17 can determine the // primality of any number less than 341,550,071,728,321 return MillerTestMultiple(num, 2, 3, 5, 7, 11, 13, 17) default: // witnesses 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, and 37 can determine // the primality of any number less than 318,665,857,834,031,151,167,461 // which is well above the max int64 9,223,372,036,854,775,807 return MillerTestMultiple(num, 2, 3, 5, 7, 11, 13, 17, 19, 23, 31, 37) } }
math/prime/millerrabinprimalitytest.go
0.733261
0.633623
millerrabinprimalitytest.go
starcoder
package trie import ( "github.com/caravan/go-immutable-trie/key" "github.com/caravan/go-immutable-trie/nibble" ) type ( // Trie maps a set of Keys to another set of Values Trie[Key key.Keyable, Value any] interface { trie() // marker Read[Key, Value] Split[Key, Value] Write[Key, Value] } Read[Key key.Keyable, Value any] interface { Get(Key) (Value, bool) Count() int IsEmpty() bool Select() Direction[Key, Value] } Split[Key key.Keyable, Value any] interface { First() Pair[Key, Value] Rest() Trie[Key, Value] Split() (Pair[Key, Value], Trie[Key, Value], bool) } Write[Key key.Keyable, Value any] interface { Put(Key, Value) Trie[Key, Value] Remove(Key) (Value, Trie[Key, Value], bool) RemovePrefix(Key) (Trie[Key, Value], bool) } trie[Key key.Keyable, Value any] struct { pair[Key, Value] *buckets[Key, Value] } buckets[Key key.Keyable, Value any] [nibble.Size]*trie[Key, Value] bucketsMutator[Key key.Keyable, Value any] func(*buckets[Key, Value]) ) func (*trie[_, _]) trie() {} func (t *trie[Key, Value]) Get(k Key) (Value, bool) { n := nibble.Make(k) return t.get(k, n) } func (t *trie[Key, Value]) get(k Key, n nibble.Nibbles[Key]) (Value, bool) { if key.EqualTo[Key](t.pair.key, k) { return t.pair.value, true } if idx, n, ok := n.Consume(); ok && t.buckets != nil { bucket := t.buckets[idx] if bucket != nil { return bucket.get(k, n) } } var zero Value return zero, false } func (t *trie[Key, Value]) Put(k Key, v Value) Trie[Key, Value] { p := &pair[Key, Value]{k, v} n := nibble.Make[Key](p.key) return t.put(p, n) } func (t *trie[Key, Value]) put( p *pair[Key, Value], n nibble.Nibbles[Key], ) *trie[Key, Value] { switch key.Compare[Key](p.key, t.pair.key) { case key.Equal: return t.replacePair(p) case key.Less: return t.insertPair(p, n) default: return t.appendPair(p, n) } } func (t *trie[Key, Value]) replacePair(p *pair[Key, Value]) *trie[Key, Value] { res := *t res.pair = *p return &res } func (t *trie[Key, Value]) insertPair( p *pair[Key, Value], n nibble.Nibbles[Key], ) *trie[Key, Value] { if idx, next, ok := n.Branch(t.pair.key).Consume(); ok { res := t.mutateBuckets(func(buckets *buckets[Key, Value]) { if bucket := buckets[idx]; bucket != nil { buckets[idx] = bucket.put(&t.pair, next) return } buckets[idx] = &trie[Key, Value]{pair: t.pair} }) res.pair = *p return res } panic("programmer error: demoted a non-consumable key") } func (t *trie[Key, Value]) appendPair( p *pair[Key, Value], n nibble.Nibbles[Key], ) *trie[Key, Value] { if idx, n, ok := n.Consume(); ok { return t.mutateBuckets(func(buckets *buckets[Key, Value]) { if bucket := buckets[idx]; bucket != nil { buckets[idx] = bucket.put(p, n) return } buckets[idx] = &trie[Key, Value]{pair: *p} }) } panic("programmer error: appended a non-consumable key") } func (t *trie[Key, Value]) RemovePrefix(k Key) (Trie[Key, Value], bool) { n := nibble.Make(k) if res, ok := t.removePrefix(k, n); ok { return res, ok } return t, false } func (t *trie[Key, Value]) removePrefix( k Key, n nibble.Nibbles[Key], ) (*trie[Key, Value], bool) { if key.StartsWith(t.key, k) { if res := t.promote(); res != nil { res, _ = res.removePrefix(k, n) return res, true } return nil, true } if idx, n, ok := n.Consume(); ok && t.buckets != nil { if bucket := t.buckets[idx]; bucket != nil { if bucket, ok := bucket.removePrefix(k, n); ok { return t.mutateBuckets(func(buckets *buckets[Key, Value]) { buckets[idx] = bucket }), true } } } return t, false } func (t *trie[Key, Value]) Remove(k Key) (Value, Trie[Key, Value], bool) { n := nibble.Make(k) if val, rest, ok := t.remove(k, n); ok { if rest != nil { return val, rest, true } return val, empty[Key, Value]{}, true } var zero Value return zero, t, false } func (t *trie[Key, Value]) remove( k Key, n nibble.Nibbles[Key], ) (Value, *trie[Key, Value], bool) { if key.EqualTo[Key](t.pair.key, k) { return t.pair.value, t.promote(), true } if idx, n, ok := n.Consume(); ok && t.buckets != nil { if bucket := t.buckets[idx]; bucket != nil { if val, rest, ok := bucket.remove(k, n); ok { res := *t res.buckets[idx] = rest return val, &res, true } } } var zero Value return zero, nil, false } func (t *trie[Key, Value]) mutateBuckets( mutate bucketsMutator[Key, Value], ) *trie[Key, Value] { res := *t var storage buckets[Key, Value] if res.buckets != nil { storage = *res.buckets } res.buckets = &storage mutate(res.buckets) return &res } func (t *trie[Key, Value]) promote() *trie[Key, Value] { if bucket, idx := t.leastBucket(); bucket != nil { res := t.mutateBuckets(func(buckets *buckets[Key, Value]) { buckets[idx] = bucket.promote() }) res.pair = bucket.pair return res } return nil } func (t *trie[Key, Value]) leastBucket() (*trie[Key, Value], int) { var res *trie[Key, Value] var low Key idx := -1 first := true if t.buckets != nil { for i, bucket := range t.buckets { if bucket == nil { continue } if k := bucket.pair.Key(); first || key.LessThan[Key](k, low) { idx = i low = k res = bucket first = false } } } return res, idx } func (t *trie[Key, Value]) First() Pair[Key, Value] { f := t.pair return &f } func (t *trie[Key, Value]) Rest() Trie[Key, Value] { if rest := t.promote(); rest != nil { return rest } return empty[Key, Value]{} } func (t *trie[Key, Value]) Split() (Pair[Key, Value], Trie[Key, Value], bool) { first := t.pair if r := t.promote(); r != nil { return &first, r, true } return &first, empty[Key, Value]{}, true } func (t *trie[_, _]) Count() int { res := 1 if t.buckets != nil { for _, bucket := range t.buckets { if bucket != nil { res += bucket.Count() } } } return res } func (t *trie[_, _]) IsEmpty() bool { return false } func (t *trie[Key, Value]) Select() Direction[Key, Value] { return makeQuery[Key, Value](t) }
trie.go
0.663015
0.49884
trie.go
starcoder
package shape import ( "fmt" "github.com/veandco/go-sdl2/sdl" ) // Object describes default API of the scene object. type Object interface { Update() Paint(r *sdl.Renderer) error Restart() Destroy() } // Triangle represent a triangle shape. type Triangle struct { ps [3]*sdl.Point color *sdl.Color } // NewTriangle creates a new triangle from given slice of Points. func NewTriangle(points [3]*sdl.Point, color *sdl.Color) *Triangle { t := &Triangle{ps: points} return t } func (t *Triangle) String() string { return fmt.Sprintf("{[%d, %d], [%d, %d], [%d, %d]}", t.ps[0].X, t.ps[0].Y, t.ps[1].X, t.ps[1].Y, t.ps[2].X, t.ps[2].Y) } // ContainsPoint returns true of the given Point is inside the Triangle. func (t *Triangle) ContainsPoint(point *sdl.Point) bool { a := t.ps[0] b := t.ps[1] c := t.ps[2] asX := point.X - a.X asY := point.Y - a.Y sAB := (b.X-a.X)*asY-(b.Y-a.Y)*asX > 0 if (c.X-a.X)*asY-(c.Y-a.Y)*asX > 0 == sAB { return false } if (c.X-b.X)*(point.Y-b.Y)-(c.Y-b.Y)*(point.X-b.X) > 0 != sAB { return false } return true } // OverlapsRect returns true of the given Rect overlaps with the Triangle. func (t *Triangle) OverlapsRect(rect *sdl.Rect) bool { a := t.ps[0] b := t.ps[1] c := t.ps[2] rectX := rect.X rectY := rect.Y rectW := rect.W rectH := rect.H return rect.IntersectLine(&a.X, &a.Y, &b.X, &b.Y) || rect.IntersectLine(&b.X, &b.Y, &c.X, &c.Y) || rect.IntersectLine(&c.X, &c.Y, &a.X, &a.Y) || t.ContainsPoint(&sdl.Point{X: rectX, Y: rectY}) || t.ContainsPoint(&sdl.Point{X: rectX + rectW, Y: rectY}) || t.ContainsPoint(&sdl.Point{X: rectX + rectW, Y: rectY + rectH}) || t.ContainsPoint(&sdl.Point{X: rectX, Y: rectY + rectH}) } // Paint paints the Triangle to the window. func (t *Triangle) Paint(r *sdl.Renderer) error { // Set color of triangle if t.color != nil { r.SetDrawColor(t.color.R, t.color.G, t.color.B, t.color.A) } // rs := ToRectangles(t.ps[:]) //tr := t.triangle(rs) // r.FillRect(tr) // Reset colour r.SetDrawColor(0, 0, 0, 255) return nil }
types/shape/shape.go
0.825273
0.449332
shape.go
starcoder
package gota import ( "math" ) // KER - Kaufman's Efficiency Ratio (http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:kaufman_s_adaptive_moving_average#efficiency_ratio_er) type KER struct { points []kerPoint noise float64 count int idx int // index of newest point } type kerPoint struct { price float64 diff float64 } // NewKER constructs a new KER. func NewKER(inTimePeriod int) *KER { return &KER{ points: make([]kerPoint, inTimePeriod), } } // WarmCount returns the number of samples that must be provided for the algorithm to be fully "warmed". func (ker *KER) WarmCount() int { return len(ker.points) } // Add adds a new sample value to the algorithm and returns the computed value. func (ker *KER) Add(v float64) float64 { //TODO this does not return a sensible value if not warmed. n := len(ker.points) idxOldest := ker.idx + 1 if idxOldest >= n { idxOldest = 0 } signal := math.Abs(v - ker.points[idxOldest].price) kp := kerPoint{ price: v, diff: math.Abs(v - ker.points[ker.idx].price), } ker.noise -= ker.points[idxOldest].diff ker.noise += kp.diff noise := ker.noise ker.idx = idxOldest ker.points[ker.idx] = kp if !ker.Warmed() { ker.count++ } if signal == 0 || noise == 0 { return 0 } return signal / noise } // Warmed indicates whether the algorithm has enough data to generate accurate results. func (ker *KER) Warmed() bool { return ker.count == len(ker.points)+1 } // KAMA - Kaufman's Adaptive Moving Average (http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:kaufman_s_adaptive_moving_average) type KAMA struct { ker KER last float64 } // NewKAMA constructs a new KAMA. func NewKAMA(inTimePeriod int) *KAMA { ker := NewKER(inTimePeriod) return &KAMA{ ker: *ker, } } // WarmCount returns the number of samples that must be provided for the algorithm to be fully "warmed". func (kama *KAMA) WarmCount() int { return kama.ker.WarmCount() } // Add adds a new sample value to the algorithm and returns the computed value. func (kama *KAMA) Add(v float64) float64 { if !kama.Warmed() { /* // initialize with a simple moving average kama.last = 0 for _, v := range kama.ker.points[:kama.ker.count] { kama.last += v } kama.last /= float64(kama.ker.count + 1) */ // initialize with the last value kama.last = kama.ker.points[kama.ker.idx].price } er := kama.ker.Add(v) sc := math.Pow(er*(2.0/(2.0+1.0)-2.0/(30.0+1.0))+2.0/(30.0+1.0), 2) kama.last = kama.last + sc*(v-kama.last) return kama.last } // Warmed indicates whether the algorithm has enough data to generate accurate results. func (kama *KAMA) Warmed() bool { return kama.ker.Warmed() }
influxql/query/internal/gota/kama.go
0.675229
0.481698
kama.go
starcoder
package iso20022 // Details of the closing of the securities financing transaction. type SecuritiesFinancingTransactionDetails7 struct { // Unambiguous identification of the underlying securities financing trade as assigned by the instructing party. The identification is common to all collateral pieces (one or many). SecuritiesFinancingTradeIdentification *Max35Text `xml:"SctiesFincgTradId,omitempty"` // Unambiguous identification of the second leg of the transaction as known by the account owner (or the instructing party acting on its behalf). ClosingLegIdentification *Max35Text `xml:"ClsgLegId,omitempty"` // Closing date/time or maturity date/time of the transaction. TerminationDate *TerminationDate2Choice `xml:"TermntnDt,omitempty"` // Specifies whether the rate is fixed or variable. RateType *RateType5Choice `xml:"RateTp,omitempty"` // Legal framework of the transaction. LegalFramework *LegalFramework1Choice `xml:"LglFrmwk,omitempty"` // Specifies whether the maturity date of the securities financing transaction may be modified. MaturityDateModification *YesNoIndicator `xml:"MtrtyDtMod,omitempty"` // Specifies whether the interest is to be paid to the collateral taker. If set to no, the interest is paid to the collateral giver. InterestPayment *YesNoIndicator `xml:"IntrstPmt,omitempty"` // Index or support rate used together with the spread to calculate the // repurchase rate. VariableRateSupport *RateName1 `xml:"VarblRateSpprt,omitempty"` // Rate to be used to recalculate the repurchase amount. RepurchaseRate *Rate2 `xml:"RpRate,omitempty"` // Minimum number of days' notice a counterparty needs for terminating the transaction. TransactionCallDelay *Exact3NumericText `xml:"TxCallDely,omitempty"` // Interest amount that has accrued in between coupon payment periods. AccruedInterestAmount *AmountAndDirection4 `xml:"AcrdIntrstAmt,omitempty"` // Total amount of money to be settled to terminate the transaction. TerminationTransactionAmount *AmountAndDirection4 `xml:"TermntnTxAmt,omitempty"` // Provides additional information about the second leg in narrative form. SecondLegNarrative *Max140Text `xml:"ScndLegNrrtv,omitempty"` } func (s *SecuritiesFinancingTransactionDetails7) SetSecuritiesFinancingTradeIdentification(value string) { s.SecuritiesFinancingTradeIdentification = (*Max35Text)(&value) } func (s *SecuritiesFinancingTransactionDetails7) SetClosingLegIdentification(value string) { s.ClosingLegIdentification = (*Max35Text)(&value) } func (s *SecuritiesFinancingTransactionDetails7) AddTerminationDate() *TerminationDate2Choice { s.TerminationDate = new(TerminationDate2Choice) return s.TerminationDate } func (s *SecuritiesFinancingTransactionDetails7) AddRateType() *RateType5Choice { s.RateType = new(RateType5Choice) return s.RateType } func (s *SecuritiesFinancingTransactionDetails7) AddLegalFramework() *LegalFramework1Choice { s.LegalFramework = new(LegalFramework1Choice) return s.LegalFramework } func (s *SecuritiesFinancingTransactionDetails7) SetMaturityDateModification(value string) { s.MaturityDateModification = (*YesNoIndicator)(&value) } func (s *SecuritiesFinancingTransactionDetails7) SetInterestPayment(value string) { s.InterestPayment = (*YesNoIndicator)(&value) } func (s *SecuritiesFinancingTransactionDetails7) AddVariableRateSupport() *RateName1 { s.VariableRateSupport = new(RateName1) return s.VariableRateSupport } func (s *SecuritiesFinancingTransactionDetails7) AddRepurchaseRate() *Rate2 { s.RepurchaseRate = new(Rate2) return s.RepurchaseRate } func (s *SecuritiesFinancingTransactionDetails7) SetTransactionCallDelay(value string) { s.TransactionCallDelay = (*Exact3NumericText)(&value) } func (s *SecuritiesFinancingTransactionDetails7) AddAccruedInterestAmount() *AmountAndDirection4 { s.AccruedInterestAmount = new(AmountAndDirection4) return s.AccruedInterestAmount } func (s *SecuritiesFinancingTransactionDetails7) AddTerminationTransactionAmount() *AmountAndDirection4 { s.TerminationTransactionAmount = new(AmountAndDirection4) return s.TerminationTransactionAmount } func (s *SecuritiesFinancingTransactionDetails7) SetSecondLegNarrative(value string) { s.SecondLegNarrative = (*Max140Text)(&value) }
SecuritiesFinancingTransactionDetails7.go
0.82559
0.414958
SecuritiesFinancingTransactionDetails7.go
starcoder
package mathgl import ( "math" ) type Quatf struct { W float32 V Vec3f } func QuatIdentf() Quatf { return Quatf{1., Vec3f{0, 0, 0}} } func QuatRotatef(angle float32, axis Vec3f) Quatf { angle = (float32(math.Pi) * angle) / 180.0 c, s := float32(math.Cos(float64(angle/2))), float32(math.Sin(float64(angle/2))) return Quatf{c, axis.Mul(s)} } func EulerToQuatf(xAngle, yAngle, zAngle float32) Quatf { sinz, cosz := math.Sincos(float64(zAngle)) sz, cz := float32(sinz), float32(cosz) siny, cosy := math.Sincos(float64(yAngle)) sy, cy := float32(siny), float32(cosy) sinx, cosx := math.Sincos(float64(xAngle)) sx, cx := float32(sinx), float32(cosx) return Quatf{ W: cx*cy*cz + sx*sy*sz, V: Vec3f{ sx*cy*cz - cx*sy*sz, cx*sy*cz + sx*cy*sz, cx*cy*sz - sx*sy*cz, }, } } func (q Quatf) X() float32 { return q.V[0] } func (q Quatf) Y() float32 { return q.V[1] } func (q Quatf) Z() float32 { return q.V[2] } func (q1 Quatf) Add(q2 Quatf) Quatf { return Quatf{q1.W + q2.W, q1.V.Add(q2.V)} } func (q1 Quatf) Sub(q2 Quatf) Quatf { return Quatf{q1.W - q2.W, q1.V.Sub(q2.V)} } func (q1 Quatf) Mul(q2 Quatf) Quatf { return Quatf{q1.W*q2.W - q1.V.Dot(q2.V), q1.V.Cross(q2.V).Add(q2.V.Mul(q1.W)).Add(q1.V.Mul(q2.W))} } func (q1 Quatf) Scale(c float32) Quatf { return Quatf{q1.W * c, Vec3f{q1.V[0] * c, q1.V[1] * c, q1.V[2] * c}} } func (q1 Quatf) Conjugate() Quatf { return Quatf{q1.W, q1.V.Mul(-1)} } func (q1 Quatf) Len() float32 { return float32(math.Sqrt(float64(q1.W*q1.W + q1.V[0]*q1.V[0] + q1.V[1]*q1.V[1] + q1.V[2]*q1.V[2]))) } func (q1 Quatf) Normalize() Quatf { length := q1.Len() if FloatEqual(1, float64(length)) { return q1 } return Quatf{q1.W * 1 / length, q1.V.Mul(1 / length)} } func (q1 Quatf) Inverse() Quatf { leng := q1.Len() return Quatf{q1.W, q1.V.Mul(-1)}.Scale(1 / (leng * leng)) } func (q1 Quatf) Rotate(v Vec3f) Vec3f { return q1.Mul(Quatf{0, v}).Mul(q1.Conjugate()).V } func (q1 Quatf) Mat4() Mat4f { w, x, y, z := q1.W, q1.V[0], q1.V[1], q1.V[2] return Mat4f{1 - 2*y*y - 2*z*z, 2*x*y + 2*w*z, 2*x*z - 2*w*y, 0, 2*x*y - 2*w*z, 1 - 2*x*x - 2*z*z, 2*y*z + 2*w*x, 0, 2*x*z + 2*w*y, 2*y*z - 2*w*x, 1 - 2*x*x - 2*y*y, 0, 0, 0, 0, 1} } func (q1 Quatf) Dot(q2 Quatf) float32 { return q1.W*q1.W + q1.V[0]*q1.V[0] + q1.V[1]*q1.V[1] + q1.V[2]*q1.V[2] } func QuatSlerpf(q1, q2 Quatf, amount float32) Quatf { q1, q2 = q1.Normalize(), q2.Normalize() dot := q1.Dot(q2) // This is here for precision errors, I'm perfectly aware the *technically* the dot is bound [-1,1], but since Acos will freak out if it's not (even if it's just a liiiiitle bit over due to normal error) we need to clamp it dot = Clampf(dot, -1, 1) theta := float32(math.Acos(float64(dot))) * amount c, s := float32(math.Cos(float64(theta))), float32(math.Sin(float64(theta))) rel := q2.Sub(q1.Scale(dot)).Normalize() return q2.Sub(q1.Scale(c)).Add(rel.Scale(s)) } func QuatLerpf(q1, q2 Quatf, amount float32) Quatf { return q1.Add(q2.Sub(q1).Scale(amount)) } func QuatNlerpf(q1, q2 Quatf, amount float32) Quatf { return QuatLerpf(q1, q2, amount).Normalize() }
quatf.go
0.831861
0.636833
quatf.go
starcoder
package tv import ( "github.com/mmcloughlin/random" "github.com/mmcloughlin/trunnel/ast" "github.com/mmcloughlin/trunnel/fault" "github.com/mmcloughlin/trunnel/inspect" ) // Vector is a test vector. type Vector struct { Data []byte Constraints Constraints } // NewVector builds a test vector with empty constraints. func NewVector(b []byte) Vector { return Vector{ Data: b, Constraints: NewConstraints(), } } func cross(a, b []Vector) ([]Vector, error) { p := []Vector{} for _, u := range a { for _, w := range b { m, err := u.Constraints.Merge(w.Constraints) if err != nil { return nil, err } v := Vector{ Data: append(u.Data, w.Data...), Constraints: m, } p = append(p, v) } } return p, nil } type generator struct { resolver *inspect.Resolver constraints Constraints strct *ast.Struct selector Selector rnd random.Interface } // Generate generates a set of test vectors for the types defined in f. func Generate(f *ast.File, opts ...Option) (*Corpus, error) { return GenerateFiles([]*ast.File{f}, opts...) } // GenerateFiles generates test vectors for the types in the given files. func GenerateFiles(fs []*ast.File, opts ...Option) (*Corpus, error) { g := &generator{ selector: Exhaustive, rnd: random.New(), } for _, opt := range opts { opt(g) } return g.files(fs) } // Option is an option to control test vector generation. type Option func(*generator) // WithSelector sets the method for cutting down the number of vectors we have. func WithSelector(s Selector) Option { return func(g *generator) { g.selector = s } } // WithRandom sets the random source for test vector generation. func WithRandom(r random.Interface) Option { return func(g *generator) { g.rnd = r } } func (g *generator) init(fs []*ast.File) (err error) { g.resolver, err = inspect.NewResolverFiles(fs) return } func (g *generator) files(fs []*ast.File) (*Corpus, error) { err := g.init(fs) if err != nil { return nil, err } c := &Corpus{} for _, f := range fs { for _, s := range f.Structs { if s.Extern() { continue } g.constraints = NewConstraints() vs, err := g.structure(s) if err != nil { return nil, err } c.Suites = append(c.Suites, Suite{ Type: s.Name, Vectors: vs, }) } } return c, nil } func (g *generator) structure(s *ast.Struct) ([]Vector, error) { restore := g.strct g.strct = s vs := []Vector{ { Data: []byte{}, Constraints: g.constraints.CloneGlobal(), }, } vs, err := g.members(vs, s.Members) if err != nil { return nil, err } g.constraints.ClearLocal() for _, v := range vs { v.Constraints.ClearLocal() } g.strct = restore return vs, nil } func (g *generator) members(vs []Vector, ms []ast.Member) ([]Vector, error) { n := len(ms) for i := n - 1; i >= 0; i-- { extended := []Vector{} for _, v := range vs { g.constraints = v.Constraints mvs, err := g.member(ms[i]) if err != nil { return nil, err } for _, mv := range mvs { mv.Data = append(mv.Data, v.Data...) extended = append(extended, mv) } } vs = g.selector.SelectVectors(extended) } return vs, nil } func (g *generator) member(m ast.Member) ([]Vector, error) { switch m := m.(type) { case *ast.Field: return g.field(m) case *ast.UnionMember: return g.union(m) case *ast.Ignore: return []Vector{ g.empty(), g.vector(g.randbytes(1, 7)), }, nil case *ast.Fail: return []Vector{}, nil case *ast.EOS: return []Vector{g.empty()}, nil default: return nil, fault.NewUnexpectedType(m) } } func (g *generator) field(f *ast.Field) ([]Vector, error) { switch t := f.Type.(type) { case *ast.IntType: return g.intType(f.Name, t) case *ast.CharType: return g.intType(f.Name, ast.U8) case *ast.Ptr: return []Vector{g.empty()}, nil case *ast.NulTermString: return []Vector{g.vector(g.randnulterm(2, 20))}, nil case *ast.StructRef: s, err := g.resolver.StructNonExtern(t.Name) if err != nil { return nil, err } return g.structure(s) case *ast.FixedArrayMember: return g.array(t.Base, t.Size) case *ast.VarArrayMember: return g.array(t.Base, t.Constraint) default: return nil, fault.NewUnexpectedType(t) } } func (g *generator) intType(name string, t *ast.IntType) ([]Vector, error) { var b []byte switch x, ok := g.constraints.LookupLocal(name); { case ok: b = intbytes(x, t.Size) case t.Constraint != nil: s, err := g.resolver.Intervals(t.Constraint) if err != nil { return nil, err } r := s.RandomWithGenerator(g.rnd) b = intbytes(int64(r), t.Size) // XXX cast default: b = g.randint(t.Size) } return []Vector{g.vector(b)}, nil } func (g *generator) array(base ast.Type, s ast.LengthConstraint) ([]Vector, error) { iv := g.empty() v := []Vector{iv} var n int64 switch s := s.(type) { case *ast.IntegerConstRef, *ast.IntegerLiteral: i, err := g.resolver.Integer(s) if err != nil { return nil, err } n = i case *ast.IDRef: n = iv.Constraints.LookupOrCreateRef(s, int64(g.randbtw(1, 20))) case nil: n = int64(g.randbtw(1, 20)) case *ast.Leftover: return nil, fault.ErrNotImplemented default: return nil, fault.NewUnexpectedType(s) } for i := int64(0); i < n; i++ { w, err := g.field(&ast.Field{Type: base}) if err != nil { return nil, err } v, err = cross(w, v) if err != nil { return nil, err } v = g.selector.SelectVectors(v) } return v, nil } func (g *generator) union(u *ast.UnionMember) ([]Vector, error) { branches, err := inspect.NewBranches(g.resolver, g.strct, u) if err != nil { return nil, err } // has the tag already been set? options := branches.All() t, ok := g.constraints.LookupRef(u.Tag) if ok { branch, ok := branches.Lookup(t) if !ok { return []Vector{}, nil } options = []inspect.Branch{branch} } base := g.constraints.Clone() results := []Vector{} for _, b := range options { g.constraints = base.Clone() g.constraints.LookupOrCreateRef(u.Tag, int64(b.Set.RandomWithGenerator(g.rnd))) // XXX cast vs, err := g.members([]Vector{g.empty()}, b.Case.Members) if err != nil { return nil, err } results = append(results, vs...) } // set length constraint if u.Length != nil { return g.lenconstrain(u.Length, results) } return results, nil } func (g *generator) lenconstrain(c ast.LengthConstraint, vs []Vector) ([]Vector, error) { r, ok := c.(*ast.IDRef) if !ok { return nil, fault.ErrNotImplemented } results := []Vector{} for _, v := range vs { n := int64(len(v.Data)) cst := v.Constraints.Clone() m := cst.LookupOrCreateRef(r, n) if m != n { continue } results = append(results, Vector{ Data: v.Data, Constraints: cst, }) } return results, nil } // empty returns an empty Vector with current constraints. func (g *generator) empty() Vector { return g.vector([]byte{}) } // vector builds vector with the current constraints. func (g *generator) vector(b []byte) Vector { return Vector{ Data: b, Constraints: g.constraints, } } func (g *generator) randint(bits uint) []byte { b := make([]byte, bits/8) g.randread(b) return b } // randbtw generates an integer between a and b, inclusive. func (g *generator) randbtw(a, b int) int { return a + g.rnd.Intn(b-a+1) } // randbytes returns a random byre array of length between a and b. func (g *generator) randbytes(a, b int) []byte { d := make([]byte, g.randbtw(a, b)) g.randread(d) return d } // randread reads random bytes into b from the configured random source. func (g *generator) randread(b []byte) { if _, err := g.rnd.Read(b); err != nil { panic(err) // should never happen } } // randnulterm generates a random nul-terminated string of length in [a,b] // inclusive of a and b, not including the nul byte. func (g *generator) randnulterm(a, b int) []byte { const alpha = "abcdefghijklmnopqrstuvwxyz" n := g.randbtw(a, b) s := make([]byte, n+1) for i := 0; i < n; i++ { s[i] = alpha[g.rnd.Intn(len(alpha))] } return s } func intbytes(x int64, bits uint) []byte { n := bits / 8 b := make([]byte, n) for i := uint(0); i < n; i++ { b[n-1-i] = byte(x) x >>= 8 } return b }
tv/generator.go
0.656438
0.412767
generator.go
starcoder
// Package codec provides support for interpreting byte slices as slices of // other basic types such as runes, int64's or strings. package codec // Decoder represents the ability to decode a byte slice into a slice of // some other data type. type Decoder[T any] interface { Decode(input []byte) []T } type options struct { resizePrecent int sizePercent int } // Option represents an option accepted by NewDecoder. type Option func(*options) // ResizePercent requests that the returned slice be reallocated if the // ratio of unused to used capacity exceeds the specified percentage. // That is, if cap(slice) - len(slice)) / len(slice) exceeds the percentage // new underlying storage is allocated and contents copied. The default // value for ResizePercent is 100. func ResizePercent(percent int) Option { return func(o *options) { o.resizePrecent = percent } } // SizePercent requests that the initially allocated slice be 'percent' as // large as the original input slice's size in bytes. A percent of 25 will // divide the original size by 4 for example. func SizePercent(percent int) Option { return func(o *options) { o.sizePercent = percent } } // NewDecode returns an instance of Decoder appropriate for the supplied // function. func NewDecoder[T any](fn func([]byte) (T, int), opts ...Option) Decoder[T] { dec := &decoder[T]{fn: fn} dec.resizePrecent = 100 for _, fn := range opts { fn(&dec.options) } if dec.sizePercent == 0 { dec.sizePercent = 100 } return dec } type decoder[T any] struct { options fn func([]byte) (T, int) } // Decode implements Decoder. func (d *decoder[T]) Decode(input []byte) []T { if len(input) == 0 { return []T{} } out := make([]T, 0, len(input)/(100/d.sizePercent)) cursor, i := 0, 0 for { item, n := d.fn(input[cursor:]) if n == 0 { break } out = append(out, item) i++ cursor += n if cursor >= len(input) { break } } return resize(out[:i], d.resizePrecent) } func resizedNeeded(used, available int, percent int) bool { wasted := available - used if used == 0 { used = 1 } return ((wasted * 100) / used) > percent } // resize will allocate new underlying storage and copy the contents of // slice to it if the ratio of wasted to used, ie: // (cap(slice) - len(slice)) / len(slice)) // exceeds the specified percentage. func resize[T any](slice []T, percent int) []T { if resizedNeeded(len(slice), cap(slice), percent) { r := make([]T, len(slice)) copy(r, slice) return r } return slice }
algo/codec/codec.go
0.808181
0.425068
codec.go
starcoder
package graph import ( "math" "github.com/cpmech/gosl/chk" "github.com/cpmech/gosl/io" "github.com/cpmech/gosl/plt" "github.com/cpmech/gosl/utl" ) // Plotter draws graphs type Plotter struct { G *Graph // the graph Parts []int32 // [nverts] partitions VertsLabels map[int]string // [nverts] labels of vertices. may be nil EdgesLabels map[int]string // [nedges] labels of edges. may be nil FcParts []string // [nverts] face colors of circles indicating partitions. may be nil Radius float64 // radius of circles. can be 0 Width float64 // distance between two edges. can be 0 Gap float64 // gap between text and edges; e.g. width/2. can be 0 ArgsVertsTxt *plt.A // arguments for vertex ids. may be nil ArgsEdgesTxt *plt.A // arguments for edge ids. may be nil ArgsVerts *plt.A // arguments for vertices. may be nil ArgsEdges *plt.A // arguments for edges. may be nil } // Draw draws graph func (o *Plotter) Draw() { // check nverts := len(o.G.Verts) if nverts < 1 { chk.Panic("vertices are required to draw graph\n") } // plot arguments if o.ArgsVertsTxt == nil { o.ArgsVertsTxt = &plt.A{C: "#d70d0d", Fsz: 8, Va: "center", Ha: "center"} } if o.ArgsEdgesTxt == nil { o.ArgsEdgesTxt = &plt.A{C: "#2732c6", Fsz: 7, Va: "center", Ha: "center"} } if o.ArgsVerts == nil { o.ArgsVerts = &plt.A{Fc: "none", Ec: "k", Lw: 0.8, NoClip: true} } if o.ArgsEdges == nil { o.ArgsEdges = &plt.A{Style: "->", Scale: 12} } if len(o.Parts) == nverts { nparts := 0 for i := 0; i < nverts; i++ { nparts = utl.Imax(nparts, int(o.Parts[i])) } nparts++ if len(o.FcParts) != nparts { o.FcParts = make([]string, nparts) for i := 0; i < nparts; i++ { o.FcParts[i] = plt.C(i, 9) } } } // constants if o.Radius < 1e-10 { o.Radius = 0.25 } if o.Width < 1e-10 { o.Width = 0.15 } if o.Gap < 1e-10 { o.Gap = 0.12 } // draw vertex data and find limits xmin, ymin := o.G.Verts[0][0], o.G.Verts[0][1] xmax, ymax := xmin, ymin var lbl string for i, v := range o.G.Verts { if o.VertsLabels == nil { lbl = io.Sf("%d", i) } else { lbl = o.VertsLabels[i] } plt.Text(v[0], v[1], lbl, o.ArgsVertsTxt) fcOrig := o.ArgsVerts.Fc if len(o.Parts) == nverts { o.ArgsVerts.Fc = o.FcParts[o.Parts[i]] } plt.Circle(v[0], v[1], o.Radius, o.ArgsVerts) o.ArgsVerts.Fc = fcOrig xmin, ymin = utl.Min(xmin, v[0]), utl.Min(ymin, v[1]) xmax, ymax = utl.Max(xmax, v[0]), utl.Max(ymax, v[1]) } // distance between edges if o.Width > 2*o.Radius { o.Width = 1.8 * o.Radius } w := o.Width / 2.0 l := math.Sqrt(o.Radius*o.Radius - w*w) // draw edges xa, xb := make([]float64, 2), make([]float64, 2) xc, dx := make([]float64, 2), make([]float64, 2) mu, nu := make([]float64, 2), make([]float64, 2) xi, xj := make([]float64, 2), make([]float64, 2) var L float64 for k, e := range o.G.Edges { L = 0.0 for i := 0; i < 2; i++ { xa[i] = o.G.Verts[e[0]][i] xb[i] = o.G.Verts[e[1]][i] xc[i] = (xa[i] + xb[i]) / 2.0 dx[i] = xb[i] - xa[i] L += dx[i] * dx[i] } L = math.Sqrt(L) mu[0], mu[1] = dx[0]/L, dx[1]/L nu[0], nu[1] = -dx[1]/L, dx[0]/L for i := 0; i < 2; i++ { xi[i] = xa[i] + l*mu[i] - w*nu[i] xj[i] = xb[i] - l*mu[i] - w*nu[i] xc[i] = (xi[i]+xj[i])/2.0 - o.Gap*nu[i] } plt.Arrow(xi[0], xi[1], xj[0], xj[1], o.ArgsEdges) if o.EdgesLabels == nil { lbl = io.Sf("%d", k) } else { lbl = o.EdgesLabels[k] } plt.Text(xc[0], xc[1], lbl, o.ArgsEdgesTxt) } xmin -= o.Radius xmax += o.Radius ymin -= o.Radius ymax += o.Radius plt.AxisRange(xmin, xmax, ymin, ymax) }
graph/plotting.go
0.603815
0.466238
plotting.go
starcoder
package aggregaterange import ( "errors" "math" "math/big" "sync" "github.com/incognitochain/incognito-chain/common" "github.com/incognitochain/incognito-chain/privacy" ) // pad returns number has format 2^k that it is the nearest number to num func pad(num int) int { if num == 1 || num == 2 { return num } tmp := 2 for i := 2; ; i++ { tmp *= 2 if tmp >= num { num = tmp break } } return num } /*-----------------------------Vector Functions-----------------------------*/ // The length here always has to be a power of two //vectorAdd adds two vector and returns result vector func vectorAdd(a []*big.Int, b []*big.Int) ([]*big.Int, error) { if len(a) != len(b) { return nil, errors.New("VectorAdd: Arrays not of the same length") } res := make([]*big.Int, len(a)) var wg sync.WaitGroup wg.Add(len(a)) for i := range a { go func(i int, wg *sync.WaitGroup) { defer wg.Done() res[i] = new(big.Int).Add(a[i], b[i]) res[i] = res[i].Mod(res[i], privacy.Curve.Params().N) }(i, &wg) } wg.Wait() return res, nil } // innerProduct calculates inner product between two vectors a and b func innerProduct(a []*big.Int, b []*big.Int) (*big.Int, error) { if len(a) != len(b) { return nil, errors.New("InnerProduct: Arrays not of the same length") } res := big.NewInt(0) tmp := new(big.Int) for i := range a { res.Add(res, tmp.Mul(a[i], b[i])) res.Mod(res, privacy.Curve.Params().N) } return res, nil } // hadamardProduct calculates hadamard product between two vectors a and b func hadamardProduct(a []*big.Int, b []*big.Int) ([]*big.Int, error) { if len(a) != len(b) { return nil, errors.New("InnerProduct: Arrays not of the same length") } res := make([]*big.Int, len(a)) var wg sync.WaitGroup wg.Add(len(a)) for i := 0; i < len(res); i++ { go func(i int, wg *sync.WaitGroup) { defer wg.Done() res[i] = new(big.Int).Mul(a[i], b[i]) res[i].Mod(res[i], privacy.Curve.Params().N) }(i, &wg) } wg.Wait() return res, nil } // powerVector calculates base^n func powerVector(base *big.Int, n int) []*big.Int { res := make([]*big.Int, n) res[0] = big.NewInt(1) var wg sync.WaitGroup wg.Add(n - 1) for i := 1; i < n; i++ { go func(i int, wg *sync.WaitGroup) { defer wg.Done() res[i] = new(big.Int).Exp(base, new(big.Int).SetInt64(int64(i)), privacy.Curve.Params().N) }(i, &wg) } wg.Wait() return res } // vectorAddScalar adds a vector to a big int, returns big int array func vectorAddScalar(v []*big.Int, s *big.Int) []*big.Int { res := make([]*big.Int, len(v)) var wg sync.WaitGroup wg.Add(len(v)) for i := range v { go func(i int, wg *sync.WaitGroup) { defer wg.Done() res[i] = new(big.Int).Add(v[i], s) res[i].Mod(res[i], privacy.Curve.Params().N) }(i, &wg) } wg.Wait() return res } // vectorMulScalar mul a vector to a big int, returns a vector func vectorMulScalar(v []*big.Int, s *big.Int) []*big.Int { res := make([]*big.Int, len(v)) var wg sync.WaitGroup wg.Add(len(v)) for i := range v { go func(i int, wg *sync.WaitGroup) { defer wg.Done() res[i] = new(big.Int).Mul(v[i], s) res[i].Mod(res[i], privacy.Curve.Params().N) }(i, &wg) } wg.Wait() return res } // estimateMultiRangeProofSize estimate multi range proof size func EstimateMultiRangeProofSize(nOutput int) uint64 { return uint64((nOutput+2*int(math.Log2(float64(maxExp*pad(nOutput))))+5)*privacy.CompressedEllipticPointSize + 5*common.BigIntSize + 2) } // CommitAll commits a list of PCM_CAPACITY value(s) func encodeVectors(l []*big.Int, r []*big.Int, g []*privacy.EllipticPoint, h []*privacy.EllipticPoint) (*privacy.EllipticPoint, error) { if len(l) != len(r) || len(g) != len(h) || len(l) != len(g) { return nil, errors.New("invalid input") } res := new(privacy.EllipticPoint) res.Zero() var wg sync.WaitGroup var tmp1, tmp2 *privacy.EllipticPoint for i := 0; i < len(l); i++ { wg.Add(2) go func(i int, wg *sync.WaitGroup) { defer wg.Done() tmp1 = g[i].ScalarMult(l[i]) }(i, &wg) go func(i int, wg *sync.WaitGroup) { defer wg.Done() tmp2 = h[i].ScalarMult(r[i]) }(i, &wg) wg.Wait() res = res.Add(tmp1).Add(tmp2) } return res, nil }
privacy/zeroknowledge/aggregaterange/aggregaterangeutils.go
0.531209
0.511107
aggregaterangeutils.go
starcoder
package coops const ( // ResponseFormatJSON represents the JSON format. ResponseFormatJSON ResponseFormat = iota // ResponseFormatXML represents the XML format. ResponseFormatXML // ResponseFormatCSV represents the CSV format. ResponseFormatCSV ) // ResponseFormatStrings contains all the allowed string values in the order of the // enumeration above. var ResponseFormatStrings = [...]string{"json", "xml", "csv"} // String returns the response format to a string. func (s ResponseFormat) String() string { return ResponseFormatStrings[s] } // StringToResponseFormat converts a string to a ResponseFormat. func StringToResponseFormat(s string) (ResponseFormat, bool) { if i, ok := indexOf(ResponseFormatStrings[:], s); ok { return ResponseFormat(i), true } return -1, false } const ( // TimeZoneFormatGMT is for GMT time. TimeZoneFormatGMT TimeZoneFormat = iota // TimeZoneFormatLST is for the local standard time of the target station. TimeZoneFormatLST // TimeZoneFormatLSTLDT is for the local standard or daylight time of the target station. TimeZoneFormatLSTLDT ) // TimeZoneFormatStrings contains all the allowed string values in the order of the // enumeration above. var TimeZoneFormatStrings = [...]string{"gmt", "lst", "lst_ldt"} // String returns the timezone format to a string. func (s TimeZoneFormat) String() string { return TimeZoneFormatStrings[s] } // StringToTimeZoneFormat converts a string to a TimeZoneFormat. func StringToTimeZoneFormat(s string) (TimeZoneFormat, bool) { if i, ok := indexOf(TimeZoneFormatStrings[:], s); ok { return TimeZoneFormat(i), true } return -1, false } const ( // UnitsEnglish represents imperial units. UnitsEnglish Units = iota // UnitsMetric represents metric units. UnitsMetric ) // UnitsStrings contains all the allowed string values in the order of the // enumeration above. var UnitsStrings = [...]string{"english", "metric"} // String returns the timezone format to a string. func (s Units) String() string { return UnitsStrings[s] } // StringToUnits converts a string to a Units. func StringToUnits(s string) (Units, bool) { if i, ok := indexOf(UnitsStrings[:], s); ok { return Units(i), true } return -1, false } // Datums! https://tidesandcurrents.noaa.gov/datum_options.html const ( // DatumCRD is for the Columbia River Datum. DatumCRD Datum = iota // DatumIGLD is for the International Great Lakes Datum. DatumIGLD // DatumLWD is for the Great Lakes Low Water Datum (Chart Datum). DatumLWD // DatumMHHW is for the Mean Higher High Water datum. DatumMHHW // DatumMHW is for the Mean High Water datum. DatumMHW // DatumMTL is for the Mean Tide Level datum. DatumMTL // DatumMSL is for the Mean Sea Level datum. DatumMSL // DatumMLW is for the Mean Low Water datum. DatumMLW // DatumMLLW is for the Mean Lower Low Water datum. DatumMLLW // DatumNAVD is for the North American Vertical Datum. DatumNAVD // DatumSTND is the Station Datum. DatumSTND ) // DatumStrings contains all the allowed string values in the order of the // enumeration above. var DatumStrings = [...]string{ "CRD", "IGLD", "LWD", "MHHW", "MHW", "MTL", "MSL", "MLW", "MLLW", "NAVD", "STND", } // String returns the datum's string value. func (s Datum) String() string { return DatumStrings[s] } // StringToDatum converts a string to a Datum. func StringToDatum(s string) (Datum, bool) { if i, ok := indexOf(DatumStrings[:], s); ok { return Datum(i), true } return -1, false } const ( // ProductAirGap is for the air Gap (distance between a bridge and the water's surface) at the station. ProductAirGap Product = iota // ProductAirPressure is for the barometric pressure as measured at the station. ProductAirPressure // ProductAirTemperature is for the air temperature as measured at the station. ProductAirTemperature // ProductConductivity is for the water's conductivity as measured at the station. ProductConductivity // ProductCurrents is for the currents data for currents stations. ProductCurrents // ProductCurrentsPredictions is for the currents predictions data for currents predictions stations. ProductCurrentsPredictions // ProductDailyMean is for the verified daily mean water level data for the station. ProductDailyMean // ProductDatums is for the datums data for the stations. ProductDatums // ProductHighLow is for the verified high/low water level data for the station. ProductHighLow // ProductHourlyHeight is for the verified hourly height water level data for the station. ProductHourlyHeight // ProductHumidity is for the relative humidity as measured at the station. ProductHumidity // ProductMonthlyMean is for the verified monthly mean water level data for the station. ProductMonthlyMean // ProductOneMinuteWaterLevel is for one minute water level data for the station. ProductOneMinuteWaterLevel // ProductPredictions is for 6 minute predictions water level data for the station. ProductPredictions // ProductSalinity is for salinity and specific gravity data for the station. ProductSalinity // ProductVisibility is for visibility from the station's visibility sensor. A measure of atmospheric clarity. ProductVisibility // ProductWaterLevel is for preliminary or verified water levels, depending on availability. ProductWaterLevel // ProductWaterTemperature is for water temperature as measured at the station. ProductWaterTemperature // ProductWind is for wind speed, direction, and gusts as measured at the station. ProductWind ) // ProductStrings contains all the allowed string values in the order of the // enumeration above. var ProductStrings = [...]string{ "air_gap", "air_pressure", "air_temperature", "conductivity", "currents", "currents_predictions", "daily_mean", "datums", "high_low", "hourly_height", "humidity", "monthly_mean", "one_minute_waterlevel", "predictions", "salinity", "visibility", "water_level", "water_temperature", "wind", } // String returns the product's string value. func (s Product) String() string { return ProductStrings[s] } // StringToProduct converts a string to a Product. func StringToProduct(s string) (Product, bool) { if i, ok := indexOf(ProductStrings[:], s); ok { return Product(i), true } return -1, false } func indexOf(haystack []string, needle string) (int, bool) { for i, v := range haystack { if v == needle { return i, true } } return -1, false }
src/coops/constants.go
0.825449
0.411525
constants.go
starcoder
package challenge import "strconv" /* Problem: Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1. */ func FirstDuplicate(a []int) int { m := make(map[int]int) for _, v := range a { if _, ok := m[v]; !ok { m[v]++ } else { return v } } return -1 } /* Problem: Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'. */ func FirstNotRepeatingCharacter(s string) string { m := make(map[string]int) for _, v := range s { m[string(v)]++ } for _, v := range s { if m[string(v)] == 1 { return string(v) } } return "_" } /* Problem: You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise). */ func RotateImage(a [][]int) [][]int { b := make([][]int, len(a)) for r := 0; r < (len(a)); r++ { b[r] = make([]int, len(a[r])) for c := 0; c < len(a); c++ { b[r][c] = a[(len(a)-1)-c][r] } } return b } /* Problem: Sudoku is a number-placement puzzle. The objective is to fill a 9 × 9 grid with numbers in such a way that each column, each row, and each of the nine 3 × 3 sub-grids that compose the grid all contain all of the numbers from 1 to 9 one time. Implement an algorithm that will check whether the given grid of numbers represents a valid Sudoku puzzle according to the layout rules described above. Note that the puzzle represented by grid does not have to be solvable. */ func Sudoku(grid [][]string) bool { for row := 0; row < len(grid); row++ { for col := 0; col < len(grid[row]); col++ { current := grid[row][col] sR := row + 3 sC := col + 3 if sR%3 == 0 && sC%3 == 0 { m := make(map[string]int) for iR := row; iR < sR; iR++ { for iC := col; iC < sC; iC++ { v := grid[iR][iC] if v == "." { continue } if _, ok := m[v]; !ok { m[v]++ } else { return false } } } } if current == "." { continue } for r := row + 1; r < len(grid); r++ { m := make(map[string]int) cc := grid[r][col] if cc == "." { continue } if cc == current { return false } if _, ok := m[cc]; !ok { m[cc]++ } else { return false } } for c := col + 1; c < len(grid); c++ { m := make(map[string]int) cc := grid[row][c] if cc == "." { continue } if cc == current { return false } if _, ok := m[cc]; !ok { m[cc]++ } else { return false } } } } return false } /* Problem: A cryptarithm is a mathematical puzzle for which the goal is to find the correspondence between letters and digits, such that the given arithmetic equation consisting of letters holds true when the letters are converted to digits. You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], which should be interpreted as the word1 + word2 = word3 cryptarithm. If crypt, when it is decoded by replacing all of the letters in the cryptarithm with digits using the mapping in solution, becomes a valid arithmetic equation containing no numbers with leading zeroes, the answer is true. If it does not become a valid arithmetic solution, the answer is false. Note that number 0 doesn't contain leading zeroes (while for example 00 or 0123 do). */ func IsCryptSolution(crypt []string, solution [][]string) bool { m := make(map[string]string) for i, v := range solution { m[v[0]] = solution[i][1] } list := [3]int{} for i, v := range crypt { var s string if i == 0 && m[string(v[0])] == "0" && len(v) > 1 { return false } for c, l := range v { if c == 0 && m[string(l)] == "0" && len(v) > 1 { return false } s += m[string(l)] } tmp, err := strconv.Atoi(s) if err != nil { return false } list[i] = tmp } return list[0]+list[1] == list[2] }
arrays/arrays.go
0.760651
0.6508
arrays.go
starcoder
package rawv2 import ( "bytes" "encoding/binary" "encoding/hex" "encoding/json" "errors" "fmt" ) // DataRAWv2 is a concrete implementation of AdvertisementData interface // Data format is described here: https://docs.ruuvi.com/communication/bluetooth-advertisements/data-format-5-rawv2 type DataRAWv2 struct { rawBytes []byte } // InvalidValue is error returned when raw data contains data specified as invalid, // i.e. 0xFFFF for unsigned values or 0x8000 for signed values type InvalidValue struct { whatMeasurement string } func newInvalidValue(whatMeasurement string) *InvalidValue { return &InvalidValue{whatMeasurement: whatMeasurement} } func (iv *InvalidValue) Error() string { return fmt.Sprintf("Data for %s is invalid", iv.whatMeasurement) } // Is makes it possible to use errors.Is() on this error type func (iv *InvalidValue) Is(target error) bool { switch target.(type) { case *InvalidValue: return true default: return false } } // NewDataRAWv2 returns pointer to DataRAWv2 wrapping func NewDataRAWv2(d []byte) (*DataRAWv2, error) { if determineDataVersion(d) != 5 { return nil, errors.New("Data is not RAWv2 (5)") } if len(d) < 24 { return nil, errors.New("Data is too short to be valid, expected 14 bytes") } return &DataRAWv2{rawBytes: d}, nil } func determineDataVersion(d []byte) int8 { return int8(d[0]) } func dataNotAvailable(whatData string) error { return fmt.Errorf("%s is not available with data format RAWv2 (5)", whatData) } // Copy copies the raw bytes internally so the AdvertisementData object is safe to use for a longer time. // Without Copy(), incoming BLE packets can overwrite the bytes func (d *DataRAWv2) Copy() { c := make([]byte, len(d.rawBytes)) copy(c[:], d.rawBytes[:]) d.rawBytes = c } // DataFormat returns format of underlying data func (d *DataRAWv2) DataFormat() int8 { return 5 } // Temperature returns measured temperature in degrees Celsius func (d *DataRAWv2) Temperature() (float64, error) { b := d.rawBytes[1:3] u := binary.BigEndian.Uint16(b) if u == 0x8000 { return 0.0, newInvalidValue("temperature") } temp := float64(int16(u)) * 0.005 return temp, nil } // Humidity returns measured humidity as percentage func (d *DataRAWv2) Humidity() (float64, error) { b := d.rawBytes[3:5] v := binary.BigEndian.Uint16(b) if v == 0xFFFF { return 0.0, newInvalidValue("humidity") } humidity := float64(v) * 0.0025 return humidity, nil } // Pressure returns measured atmospheric pressure with unit Pa (pascal) func (d *DataRAWv2) Pressure() (int, error) { pb := d.rawBytes[5:7] pres := binary.BigEndian.Uint16(pb) if pres == 0xFFFF { return 0, newInvalidValue("pressure") } return int(pres) + 50000, nil } // AccelerationX returns the acceleration in X axis with unit G, if supported by data format func (d *DataRAWv2) AccelerationX() (float64, error) { b := d.rawBytes[7:9] u := binary.BigEndian.Uint16(b) if u == 0x8000 { return 0.0, newInvalidValue("acceleration-x") } acc := int16(u) gs := float64(acc) / 1000.0 return gs, nil } // AccelerationY returns the acceleration in Y axis with unit G, if supported by data format func (d *DataRAWv2) AccelerationY() (float64, error) { b := d.rawBytes[9:11] u := binary.BigEndian.Uint16(b) if u == 0x8000 { return 0.0, newInvalidValue("acceleration-y") } acc := int16(u) gs := float64(acc) / 1000.0 return gs, nil } // AccelerationZ returns the acceleration in Z axis with unit G, if supported by data format func (d *DataRAWv2) AccelerationZ() (float64, error) { b := d.rawBytes[11:13] u := binary.BigEndian.Uint16(b) if u == 0x8000 { return 0.0, newInvalidValue("acceleration-z") } acc := int16(u) gs := float64(acc) / 1000.0 return gs, nil } // BatteryVoltage returns battery voltage with unit V (volt), if supported by data format func (d *DataRAWv2) BatteryVoltage() (float64, error) { b := d.rawBytes[13:15] v := binary.BigEndian.Uint16(b) if v == 0xFFFF { return 0.0, newInvalidValue("battery voltage") } v = (v & 0b1111111111100000) >> 5 return (float64(v) / 1000) + 1.6, nil } // TransmissionPower returns transmission power with unit dBm, if supported by data format func (d *DataRAWv2) TransmissionPower() (float64, error) { b := d.rawBytes[13:15] v := binary.BigEndian.Uint16(b) if v == 0xFFFF { return 0.0, newInvalidValue("tx power") } v = v & 0b0000000000011111 return (float64(v) * 2) - 40.0, nil } // MovementCounter returns number of movements detected by accelerometer, if supported by data format func (d *DataRAWv2) MovementCounter() (int, error) { b := d.rawBytes[15] if b == 0xFF { return 0, newInvalidValue("movement counter") } return int(b), nil } // MeasurementSequenceNumber returns measurement sequence number, if supported by data format func (d *DataRAWv2) MeasurementSequenceNumber() (int, error) { b := d.rawBytes[16:18] v := binary.BigEndian.Uint16(b) if v == 0xFFFF { return 0, newInvalidValue("measurement sequence number") } return int(v), nil } // MACAddress returns MAC address (48 bits / 6 bytes) of broadcasting ruuvitag, if supported by data format func (d *DataRAWv2) MACAddress() ([]byte, error) { b := d.rawBytes[18:24] if bytes.Equal(b, []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}) { return nil, newInvalidValue("MAC address") } return b, nil } // RawData returns the raw bytes. Make sure to copy the data, or it may be overwritten by the next broadcast. func (d *DataRAWv2) RawData() []byte { return d.rawBytes } // MarshalJSON outputs available data as JSON func (d *DataRAWv2) MarshalJSON() ([]byte, error) { m := make(map[string]interface{}, 13) m["raw"] = hex.EncodeToString(d.rawBytes) m["format"] = d.DataFormat() if t, err := d.Temperature(); err == nil { m["temperature"] = t } if h, err := d.Humidity(); err == nil { m["humidity"] = h } if p, err := d.Pressure(); err == nil { m["pressure"] = p } if a, err := d.AccelerationX(); err == nil { m["accel-x"] = a } if a, err := d.AccelerationY(); err == nil { m["accel-y"] = a } if a, err := d.AccelerationZ(); err == nil { m["accel-z"] = a } if v, err := d.BatteryVoltage(); err == nil { m["voltage"] = v } if p, err := d.TransmissionPower(); err == nil { m["tx-power"] = p } if s, err := d.MeasurementSequenceNumber(); err == nil { m["meas-seq"] = s } if c, err := d.MovementCounter(); err == nil { m["movement-count"] = c } if mac, err := d.MACAddress(); err == nil && len(mac) == 6 { m["mac"] = fmt.Sprintf("%x:%x:%x:%x:%x:%x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]) } return json.Marshal(&m) }
internal/pkg/rawv2/dataformat.go
0.818954
0.409545
dataformat.go
starcoder
package satellite import ( "math" "strconv" "strings" ) // Constants const TWOPI float64 = math.Pi * 2.0 const DEG2RAD float64 = math.Pi / 180.0 const RAD2DEG float64 = 180.0 / math.Pi const XPDOTP float64 = 1440.0 / (2.0 * math.Pi) // LatLong holds latitude and Longitude in either degrees or radians type LatLong struct { Latitude, Longitude float64 } // Vector3 holds X, Y, Z position type Vector3 struct { X, Y, Z float64 } // LookAngles holds an azimuth, elevation and range type LookAngles struct { Az, El, Rg float64 } // ParseTLE parses a two line element dataset into a Satellite struct func ParseTLE(line1, line2, gravconst string) (Satellite, error) { var err error sat := Satellite{} sat.Line1 = line1 sat.Line2 = line2 sat.whichconst, err = getGravConst(gravconst) if err != nil { return Satellite{}, err } // LINE 1 BEGIN if sat.satnum, err = parseInt(strings.TrimSpace(line1[2:7])); err != nil { return sat, err } if sat.epochyr, err = parseInt(line1[18:20]); err != nil { return sat, err } if sat.epochdays, err = parseFloat(line1[20:32]); err != nil { return sat, err } // These three can be negative / positive if sat.ndot, err = parseFloat(strings.Replace(line1[33:43], " ", "", 2)); err != nil { return sat, err } if sat.nddot, err = parseFloat(strings.Replace(line1[44:45]+"."+line1[45:50]+"e"+line1[50:52], " ", "", 2)); err != nil { return sat, err } if sat.bstar, err = parseFloat(strings.Replace(line1[53:54]+"."+line1[54:59]+"e"+line1[59:61], " ", "", 2)); err != nil { return sat, err } // LINE 1 END // LINE 2 BEGIN if sat.inclo, err = parseFloat(strings.Replace(line2[8:16], " ", "", 2)); err != nil { return sat, err } if sat.nodeo, err = parseFloat(strings.Replace(line2[17:25], " ", "", 2)); err != nil { return sat, err } if sat.ecco, err = parseFloat("." + line2[26:33]); err != nil { return sat, err } if sat.argpo, err = parseFloat(strings.Replace(line2[34:42], " ", "", 2)); err != nil { return sat, err } if sat.mo, err = parseFloat(strings.Replace(line2[43:51], " ", "", 2)); err != nil { return sat, err } if sat.no, err = parseFloat(strings.Replace(line2[52:63], " ", "", 2)); err != nil { return sat, err } // LINE 2 END return sat, nil } // TLEToSat converts a two line element data set into a Satellite struct and runs sgp4init func TLEToSat(line1, line2 string, gravconst string) (Satellite, error) { sat, err := ParseTLE(line1, line2, gravconst) if err != nil { return Satellite{}, err } opsmode := "i" sat.no = sat.no / XPDOTP sat.ndot = sat.ndot / (XPDOTP * 1440.0) sat.nddot = sat.nddot / (XPDOTP * 1440.0 * 1440) sat.inclo = sat.inclo * DEG2RAD sat.nodeo = sat.nodeo * DEG2RAD sat.argpo = sat.argpo * DEG2RAD sat.mo = sat.mo * DEG2RAD var year int64 = 0 if sat.epochyr < 57 { year = sat.epochyr + 2000 } else { year = sat.epochyr + 1900 } mon, day, hr, min, sec := days2mdhms(year, sat.epochdays) sat.jdsatepoch = JDay(int(year), int(mon), int(day), int(hr), int(min), int(sec)) sgp4init(&opsmode, sat.jdsatepoch-2433281.5, &sat) return sat, nil } // parseFloat parses a string into a float64 value. func parseFloat(strIn string) (float64, error) { return strconv.ParseFloat(strIn, 64) } // parseInt parses a string into a int64 value. func parseInt(strIn string) (int64, error) { return strconv.ParseInt(strIn, 10, 0) }
helpers.go
0.717309
0.531453
helpers.go
starcoder
package main import ( "fmt" "strings" "github.com/fernomac/advent2019/lib" ) type state int func parse(in string) state { lines := strings.Split(strings.TrimSpace(in), "\n") if len(lines) != 5 { panic(fmt.Sprint("too many lines of input:", lines)) } ret := state(0) for y, line := range lines { if len(line) != 5 { panic(fmt.Sprint("line too long:", line)) } for x, char := range line { switch char { case '#': ret = ret.set(x, y) case '.': // Nothing happens. default: panic(fmt.Sprint("line malformed:", line)) } } } return ret } func (s state) get(x, y int) bool { if x < 0 || x >= 5 || y < 0 || y >= 5 { return false } return (s & bit(x, y)) != 0 } func (s state) set(x, y int) state { if x < 0 || x >= 5 || y < 0 || y >= 5 { panic(fmt.Sprintf("invalid coordinates (%v, %v)", x, y)) } return s | bit(x, y) } func bit(x, y int) state { return 1 << ((y * 5) + x) } func (s state) step() state { next := state(0) for y := 0; y < 5; y++ { for x := 0; x < 5; x++ { if stepone(s.get(x, y), s.neighbors(x, y)) { next = next.set(x, y) } } } return next } func stepone(cur bool, neighbors int) bool { if cur { // A bug dies (becoming an empty space) unless there is exactly one bug adjacent to it. return neighbors == 1 } // An empty space becomes infested with a bug if exactly one or two bugs are adjacent to it. return neighbors == 1 || neighbors == 2 } func (s state) neighbors(x, y int) int { count := 0 if s.get(x, y-1) { count++ } if s.get(x, y+1) { count++ } if s.get(x-1, y) { count++ } if s.get(x+1, y) { count++ } return count } func (s state) biodiversity() int { return int(s) } func (s state) print() { for y := 0; y < 5; y++ { for x := 0; x < 5; x++ { if s.get(x, y) { fmt.Print("#") } else { fmt.Print(".") } } fmt.Println() } } func (s state) count() int { sum := 0 for y := 0; y < 5; y++ { for x := 0; x < 5; x++ { if s.get(x, y) { sum++ } } } return sum } func findRepeat(init state) state { visited := map[state]bool{ init: true, } s := init.step() for { if visited[s] { return s } visited[s] = true s = s.step() } } type multiverse struct { levels map[int]state min, max int } func multiversify(s state) multiverse { return multiverse{ levels: map[int]state{0: s}, } } func (m multiverse) get(x, y, z int) bool { return m.levels[z].get(x, y) } func (m multiverse) getint(x, y, z int) int { if m.get(x, y, z) { return 1 } return 0 } func (m multiverse) step() multiverse { next := multiverse{ levels: map[int]state{}, } for z := m.min - 1; z <= m.max+1; z++ { nz := m.steplevel(z) if nz == 0 { continue } next.levels[z] = nz if z < next.min { next.min = z } if z > next.max { next.max = z } } return next } func (m multiverse) steplevel(z int) state { next := state(0) for y := 0; y < 5; y++ { for x := 0; x < 5; x++ { if x == 2 && y == 2 { continue } if stepone(m.get(x, y, z), m.neighbors(x, y, z)) { next = next.set(x, y) } } } return next } func (m multiverse) neighbors(x, y, z int) int { return m.left(x, y, z) + m.right(x, y, z) + m.up(x, y, z) + m.down(x, y, z) } func (m multiverse) left(x, y, z int) int { if x == 0 { // Off the outer-left edge; tile (1,2) of the enclosing. return m.getint(1, 2, z-1) } if x == 3 && y == 2 { // Off the inner-left edge; tiles (4,0-4) of the enclosed. sum := 0 for i := 0; i < 5; i++ { if m.get(4, i, z+1) { sum++ } } return sum } // A regular neighbor on this level. return m.getint(x-1, y, z) } func (m multiverse) right(x, y, z int) int { if x == 4 { // Off the outer-right edge; tile (3,2) of the enclosing. return m.getint(3, 2, z-1) } if x == 1 && y == 2 { // Off the inner-right edge; tiles (0,0-4) of the enclosed. sum := 0 for i := 0; i < 5; i++ { if m.get(0, i, z+1) { sum++ } } return sum } // A regular neighbor on this level. return m.getint(x+1, y, z) } func (m multiverse) up(x, y, z int) int { if y == 0 { // Off the outer-top edge; tile (2, 1) of the enclosing. return m.getint(2, 1, z-1) } if x == 2 && y == 3 { // Off the inner-top edge; tiles (0-4, 4) of the enclosed. sum := 0 for i := 0; i < 5; i++ { if m.get(i, 4, z+1) { sum++ } } return sum } // A regular neighbor on this level. return m.getint(x, y-1, z) } func (m multiverse) down(x, y, z int) int { if y == 4 { // Off the outer-bottom edge; tile (2,3) of the enclosing. return m.getint(2, 3, z-1) } if x == 2 && y == 1 { // Off the inner-bottom edge; tiles (0-4, 0) of the enclosed. sum := 0 for i := 0; i < 5; i++ { if m.get(i, 0, z+1) { sum++ } } return sum } // A regular neighbor on this level. return m.getint(x, y+1, z) } func (m multiverse) count() int { sum := 0 for i := m.min; i <= m.max; i++ { sum += m.levels[i].count() } return sum } func (m multiverse) print() { for i := m.min; i <= m.max; i++ { fmt.Println("Depth", i) m.levels[i].print() fmt.Println() } } func main() { init := parse(lib.Load("input.txt")) { repeat := findRepeat(init) fmt.Println(repeat.biodiversity()) } { m := multiversify(init) for i := 0; i < 200; i++ { m = m.step() } fmt.Println(m.count()) } }
week4/day24/day24.go
0.633183
0.504578
day24.go
starcoder
package curve import ( "math" "github.com/bradfitz/iter" "github.com/shopspring/decimal" ) var ( nCoins = decimal.NewFromInt(2) one = decimal.NewFromInt(1) two = decimal.NewFromInt(2) precision int32 = 8 ) type Swap struct { // Amplification coefficient A decimal.Decimal } func (m Swap) Swap(x, y decimal.Decimal, dx decimal.Decimal) decimal.Decimal { x = x.Shift(precision) y = y.Shift(precision) dx = dx.Shift(precision) dy := m.exchange(x, y, dx) if !dy.IsPositive() { return decimal.Zero } dy = dy.Shift(-precision) return dy } func (m Swap) Reverse(x, y decimal.Decimal, dy decimal.Decimal) decimal.Decimal { if y.LessThanOrEqual(dy) { return decimal.Zero } x = x.Shift(precision) y = y.Shift(precision) dy = dy.Shift(precision) dx := m.reverseExchange(x, y, dy) if !dx.IsPositive() { return decimal.Zero } dx = dx.Shift(-precision) return dx } func (m Swap) getD(xp []decimal.Decimal) decimal.Decimal { sum := decimal.Sum(decimal.Zero, xp[0:]...) if !sum.IsPositive() { return decimal.Zero } dp := decimal.Zero d := sum ann := m.A.Mul(nCoins) for range iter.N(255) { _dp := d for _, _x := range xp { _dp = _dp.Mul(d).Div(_x.Mul(nCoins)) } dp = d d1 := ann.Sub(one).Mul(d) d2 := nCoins.Add(one).Mul(_dp) d = ann.Mul(sum).Add(_dp.Mul(nCoins)).Mul(d).Div(d1.Add(d2)) if d.Sub(dp).Truncate(0).IsZero() { break } } return d.Truncate(0) } func (m Swap) getY(d decimal.Decimal, x decimal.Decimal) decimal.Decimal { ann := m.A.Mul(nCoins) c := d.Mul(d).Div(x.Mul(nCoins)) c = c.Mul(d).Div(ann.Mul(nCoins)) b := x.Add(d.Div(ann)) yp := decimal.Zero y := d for range iter.N(255) { yp = y y = y.Mul(y).Add(c).Div(y.Add(y).Add(b).Sub(d)) if y.Sub(yp).Truncate(0).IsZero() { break } } return y } // reverse getY func (m Swap) getX(d decimal.Decimal, y decimal.Decimal) decimal.Decimal { ann := m.A.Mul(nCoins) k := d.Mul(d).Mul(d).Div(ann).Div(nCoins).Div(nCoins) j := d.Div(ann).Sub(d).Add(y).Add(y) n := y.Sub(j).Div(two) x := sqrt(k.Div(y).Add(n.Mul(n))).Add(n) return x } func (m Swap) exchange(x, y, dx decimal.Decimal) decimal.Decimal { xp := []decimal.Decimal{x, y} _x := x.Add(dx) d := m.getD(xp) _y := m.getY(d, _x) dy := y.Sub(_y) return dy } func (m Swap) reverseExchange(x, y, dy decimal.Decimal) decimal.Decimal { xp := []decimal.Decimal{x, y} _y := y.Sub(dy) d := m.getD(xp) _x := m.getX(d, _y) dx := _x.Sub(x) return dx } func sqrt(d decimal.Decimal) decimal.Decimal { f, _ := d.Float64() f = math.Sqrt(f) return decimal.NewFromFloat(f) }
swap/curve/curve.go
0.795658
0.490053
curve.go
starcoder
package testdata const MultipleSitesResponse = `{ "data": [ { "id": 1, "url": "http://yoursite.tld", "sort_url": "yoursite.tld", "label": "your-site", "team_id": 1, "latest_run_date": "2019-09-16 07:29:02", "summarized_check_result": "succeeded", "created_at": "20171106 07:40:49", "updated_at": "20171106 07:40:49", "checks": [ { "id": 100, "type": "uptime", "label": "Uptime", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:02", "latest_run_result": "succeeded" }, { "id": 101, "type": "broken_links", "label": "Broken links", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:05", "latest_run_result": "succeeded" }, ] }, { "id": 2, "url": "https://yourothersite.tld", "sort_url": "yourothersite.tld", "label": "my-site", "team_id": 1, "latest_run_date": "2019-09-16 07:29:02", "summarized_check_result": "failed", "created_at": "20171108 07:40:16", "updated_at": "20171108 07:40:16", "checks": [ { "id": 1, "type": "uptime", "label": "Uptime", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:02", "latest_run_result": "succeeded" }, { "id": 2, "type": "broken_links", "label": "Broken links", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:05", "latest_run_result": "failed" }, { "id": 3, "type": "mixed_content", "label": "Mixed content", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:05", "latest_run_result": "succeeded" }, { "id": 4, "type": "certificate_health", "label": "Certificate health", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:02", "latest_run_result": "failed" }, { "id": 5, "type": "certificate_transparency", "label": "Certificate transparency", "enabled": true, "latest_run_ended_at": null, "latest_run_result": null } ] } ] }` const SingleSiteResponse = `{ "id": 1, "url": "http://yoursite.tld", "sort_url": "yoursite.tld", "label": "your-site", "team_id": 1, "latest_run_date": "2019-09-16 07:29:02", "summarized_check_result": "succeeded", "created_at": "2017-11-06 07:40:49", "updated_at": "2017-11-06 07:40:49", "checks": [ { "id": 100, "type": "uptime", "label": "Uptime", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:02", "latest_run_result": "succeeded" }, { "id": 101, "type": "broken_links", "label": "Broken links", "enabled": true, "latest_run_ended_at": "2019-09-16 07:29:05", "latest_run_result": "succeeded" } ] }` const UptimeResponse = `{ data [ { datetime: 2018-09-22 12:00:00, uptime_percentage: 99.98 }, { datetime: 2018-09-23 12:00:00, uptime_percentage: 98.00 } ] }`
testdata/sites.go
0.546496
0.428473
sites.go
starcoder
package radialcells func (rc *RadialCells) radiusQueryGridIntersection(centerX, centerY, radius float32) cellsheap { const radiusEps = 1e-06 radius -= radiusEps step := rc.step r2 := radius * radius visitadd := step / 2 rc.heapcache.reset() vertstart := rc.anchor(centerX-radius, 1) vertend := rc.anchor(centerX+radius, 0) if vertstart < 0 { vertstart = 0 // start with gridstep } if vertend > rc.width { vertend = rc.width // without last vert } for ; vertstart <= vertend; vertstart += step { ytop, ybot := intersectAxis(vertstart, centerX, centerY, r2) vm := rc.val2grid(vertstart - visitadd) vp := rc.val2grid(vertstart + visitadd) if ytop >= 0 && ytop < rc.height { r := rc.val2grid(ytop) rc.heapcache.push(cell{r, vp}) rc.heapcache.push(cell{r, vm}) } if ybot >= 0 && ybot < rc.height { r := rc.val2grid(ybot) rc.heapcache.push(cell{r, vp}) rc.heapcache.push(cell{r, vm}) } } horzstart := rc.anchor(centerY-radius, 1) horzend := rc.anchor(centerY+radius, 0) if horzstart < 0 { horzstart = 0 // start with gridstep } if horzend > rc.height { horzend = rc.height // without last horz } for ; horzstart <= horzend; horzstart += step { xleft, xright := intersectAxis(horzstart, centerY, centerX, r2) vp := rc.val2grid(horzstart + visitadd) vm := rc.val2grid(horzstart - visitadd) if xleft >= 0 && xleft < rc.width { c := rc.val2grid(xleft) rc.heapcache.push(cell{vp, c}) rc.heapcache.push(cell{vm, c}) } if xright >= 0 && xright < rc.width { c := rc.val2grid(xright) rc.heapcache.push(cell{vp, c}) rc.heapcache.push(cell{vm, c}) } } return rc.heapcache } func (rc *RadialCells) drawedge(centerX, centerY, radius float32) cellsheap { // reset cache rc.heapcache.reset() const radiusEps = 1e-06 radius -= radiusEps r2 := radius * radius gridstep := rc.step visitShift := gridstep / 2 // roll by axis var anchorX, anchorY, stoplineX, stoplineY float32 // left to top cell anchorY, anchorX = rc.anchor(centerY, 0), rc.anchor(centerX-radius, 1) stoplineX = rc.anchor(centerX, 1) + visitShift // next anchor (top) with shift for { if cmpsqd(anchorX-centerX, anchorY-centerY, r2) { anchorY -= gridstep } else { anchorX += gridstep } if anchorX > stoplineX { break } rc.heapcache.push(rc.pointAsCell(anchorY+visitShift, anchorX-visitShift)) } // top to right cell anchorY, anchorX = rc.anchor(centerY-radius, 1), rc.anchor(centerX, 1) stoplineY = rc.anchor(centerY, 1) + visitShift // next anchor (right) with shift for { if cmpsqd(anchorX-centerX, anchorY-centerY, r2) { anchorX += gridstep } else { anchorY += gridstep } if anchorY > stoplineY { break } rc.heapcache.push(rc.pointAsCell(anchorY-visitShift, anchorX-visitShift)) } // right to bot cell anchorY, anchorX = rc.anchor(centerY, 1), rc.anchor(centerX+radius, 0) stoplineX = rc.anchor(centerX, 0) - visitShift // next anchor (bot) with shift for { if cmpsqd(anchorX-centerX, anchorY-centerY, r2) { anchorY += gridstep } else { anchorX -= gridstep } if anchorX < stoplineX { break } rc.heapcache.push(rc.pointAsCell(anchorY-visitShift, anchorX+visitShift)) } // bot to left cell anchorY, anchorX = rc.anchor(centerY+radius, 0), rc.anchor(centerX, 0) stoplineY = rc.anchor(centerY, 0) - visitShift // next anchor (left) with shift for { if cmpsqd(anchorX-centerX, anchorY-centerY, r2) { anchorX -= gridstep } else { anchorY -= gridstep } if anchorY < stoplineY { break } rc.heapcache.push(rc.pointAsCell(anchorY+visitShift, anchorX+visitShift)) } return rc.heapcache } func (rc *RadialCells) RadiusQuery(centerX, centerY, radius float32) []DIndex { if radius < 0 { panic("radius < 0") } return rc.radiusQuery(centerX, centerY, radius) } func (rc *RadialCells) radiusQuery(centerX, centerY, radius float32) []DIndex { // reset cache rc.result = rc.result[:0] // get edge cells in a circle edgecells := rc.drawedge(centerX, centerY, radius) // at end override var for reuse slice defer func() { rc.heapcache = edgecells }() // draw four neighboring cells for small radius if radius < rc.step { edgecells.push(rc.pointAsCell(centerY, centerX-radius)) edgecells.push(rc.pointAsCell(centerY-radius, centerX)) edgecells.push(rc.pointAsCell(centerY, centerX+radius)) edgecells.push(rc.pointAsCell(centerY+radius, centerX)) } // sorting and deduplication cells in place edgecells.sortDeduplicateInplace() r2 := radius * radius for _, cell := range edgecells { if rc.grid.notInBounds(cell) { continue } start, end := rc.indCellAt(cell) for i, pt := range rc.points[start:end] { dy := pt.Row - centerY dx := pt.Col - centerX d2 := dy*dy + dx*dx if d2 < r2 { rc.result = append(rc.result, DIndex{i + start, fastSqrt0(d2)}) } } } // inline tool split := func(x cell) (int, int) { return x.r, x.c } prow, pcol := split(edgecells[0]) for i := 1; i < len(edgecells); i++ { row, col := split(edgecells[i]) if row < 0 { continue } else if row >= rc.rows { break } else if col-pcol > 1 && prow == row { // check if gap in one row startcol, beglim := clamp(pcol+1, 0, rc.cols-1) // start col endcol, endlim := clamp(col-1, 0, rc.cols-1) // end col if beglim && endlim && startcol == endcol { continue } start, end := rc.indCellRange(startcol, endcol, row) for i, pt := range rc.points[start:end] { dy := pt.Row - centerY dx := pt.Col - centerX rc.result = append(rc.result, DIndex{i + start, fastSqrt0(dy*dy + dx*dx)}) } } prow, pcol = row, col } return rc.result }
algo.go
0.686895
0.521106
algo.go
starcoder
package resolv import ( "github.com/ClessLi/2d-game-engin/core/render" "github.com/ClessLi/2d-game-engin/resource" "github.com/go-gl/mathgl/mgl32" ) // Rectangle represents a rectangle type Rectangle struct { MoveShape W, H int32 } // NewRectangle creates a new Rectangle and returns a pointer to it. func NewRectangle(x, y, w, h int32, friction, drawMulti float32, moveTextures, standTextures []*resource.Texture2D) *Rectangle { r := &Rectangle{ MoveShape: *NewMoveShape( x, y, 0, friction, drawMulti, moveTextures, standTextures), W: w, H: h, } return r } // IsColliding returns whether the Rectangle is colliding with the specified other Shape or not, including the other Shape // being wholly contained within the Rectangle. func (r *Rectangle) IsColliding(other Shape) bool { switch b := other.(type) { case *Rectangle: return r.X > b.X-r.W && r.Y > b.Y-r.H && r.X < b.X+b.W && r.Y < b.Y+b.H default: return b.IsColliding(r) } } // WouldBeColliding returns whether the Rectangle would be colliding with the other Shape if it were to move in the // specified direction. func (r *Rectangle) WouldBeColliding(other Shape, dx, dy int32) bool { r.X += dx r.Y += dy isColliding := r.IsColliding(other) r.X -= dx r.Y -= dy return isColliding } // Center returns the center point of the Rectangle. func (r *Rectangle) Center() (int32, int32) { x := r.X + r.W/2 y := r.Y + r.H/2 return x, y } // GetBoundingCircle returns a circle that wholly contains the Rectangle. func (r *Rectangle) GetBoundingCircle() *Circle { x, y := r.Center() c := NewCircle(x, y, Distance(x, y, r.X+r.W, r.Y), r.friction, r.multiple, r.moveTextures, r.standTextures) return c } // GetXY2, Rectangle 类获取第二点坐标的方法, Shape.GetXY2() (int32, int32) 方法的实现 // 返回值: // x, y: 坐标 func (r *Rectangle) GetXY2() (x, y int32) { return r.X + r.W, r.Y + r.H } // Draw, Rectangle 类图像渲染方法, Shape.Draw(*render.SpriteRenderer) 方法的实现 // 参数: // renderer: render.SpriteRenderer 类指针,指定渲染器 func (r *Rectangle) Draw(renderer *render.SpriteRenderer) { size := &mgl32.Vec2{ r.multiple * float32(r.W), r.multiple * float32(r.H), } position := &mgl32.Vec2{ float32(r.X) - float32(r.W)*(r.multiple-1)/2, float32(r.Y) - float32(r.H)*(r.multiple-1)/2, } renderer.DrawSprite(r.Texture, position, size, r.rotate, r.color, r.IsXReverse) }
core/resolv/rectangle.go
0.847495
0.505188
rectangle.go
starcoder
package numerology import ( "errors" "strings" ) // NameNumerology is used as a struct to store the name and configuration information that is required // to calculate the numerological values of names. type NameNumerology struct { Name string *NameOpts *NameSearchOpts mask *maskStruct counts *map[int32]int unknowns *unknownCharacters } // initMask builds the maskStruct as it is needed. func (n *NameNumerology) initMask() { if n.mask == nil { m := maskConstructor(n.Name) n.mask = &m } } // Full contains the numerological calculations done using all the letters of the given name. Sometimes referred to as // the Destiny or Expression number. func (n NameNumerology) Full() (result NumerologicalResult) { n.initMask() return calculateCoreNumber(n.Name, n.MasterNumbers, n.ReduceWords, n.NumberSystem, n.mask.Full()) } // Destiny is an alias for Full(). func (n NameNumerology) Destiny() (destiny NumerologicalResult) { return n.Full() } // Expression is an alias for Full(). func (n NameNumerology) Expression() (expression NumerologicalResult) { return n.Full() } // Vowels contains the numerological calculations done using just the vowel letters of the given name. Sometimes // referred to as Heart's Desire or Soul's Urge number. func (n NameNumerology) Vowels() (result NumerologicalResult) { n.initMask() return calculateCoreNumber(n.Name, n.MasterNumbers, n.ReduceWords, n.NumberSystem, n.mask.Vowels()) } // SoulsUrge is an alias for Vowels(). func (n NameNumerology) SoulsUrge() (soulsUrge NumerologicalResult) { return n.Vowels() } // HeartsDesire is an alias for Vowels(). func (n NameNumerology) HeartsDesire() (heartsDesire NumerologicalResult) { return n.Vowels() } // Consonants contains the numerological calculations done using just the consonant letters of the given name. // Sometimes referred to as Personality number. func (n NameNumerology) Consonants() (result NumerologicalResult) { n.initMask() return calculateCoreNumber(n.Name, n.MasterNumbers, n.ReduceWords, n.NumberSystem, n.mask.Consonants()) } // Personality is an alias for Consonants(). func (n NameNumerology) Personality() (personality NumerologicalResult) { return n.Consonants() } // HiddenPassions contains the calculation of the numerological number(s) that repeat the most in the given name. func (n NameNumerology) HiddenPassions() (result HiddenPassionResults) { return hiddenPassions(n.Counts()) } // KarmicLessons contains the calculation of the numerological number(s) that do not appear in the given name. func (n NameNumerology) KarmicLessons() (result KarmicLessonResults) { return karmicLessons(n.Counts()) } // Search searches the name database for names that satisfy given numerological criteria. func (n NameNumerology) Search(opts NameSearchOpts) (results []NameNumerology, offset int64, err error) { switch strings.Count(n.Name, "?") { case 0: return []NameNumerology{}, 0, errors.New("missing '?' in name") case 1: return nameSearch(n.Name, n.NumberSystem, n.MasterNumbers, n.ReduceWords, opts) default: return []NameNumerology{}, 0, errors.New("too many '?' (only able to search for one '?' at a time)") } } // Counts returns a map of each numerological value and how many times it appears in the name. func (n *NameNumerology) Counts() (counts map[int32]int) { if n.counts == nil { counts, _, unknowns := countNumerologicalNumbers(n.Name, n.NumberSystem) n.counts = &counts n.unknowns = &unknowns } return *n.counts } // UnknownCharacters is a set of characters that cannot be converted to numerological values. They are // ignored in calculations. func (n *NameNumerology) UnknownCharacters() (unknowns []string) { if n.unknowns == nil { counts, _, unknowns := countNumerologicalNumbers(n.Name, n.NumberSystem) n.counts = &counts n.unknowns = &unknowns } return n.unknowns.Unacceptable().ToStringSlice() } // Name calculates various numerological numbers from a given name. Argument numberSystem indicates what // calculation method is used (Pythagorean or Chaldean). Argument reduceWords determines whether each part of // a name is reduced independently before being merged in a final number. func Name(name string, numberSystem NumberSystem, masterNumbers []int, reduceWords bool) (result NameNumerology) { asciiName := ToAscii(name) result = NameNumerology{ Name: asciiName, NameOpts: &NameOpts{ NumberSystem: numberSystem, MasterNumbers: masterNumbers, ReduceWords: reduceWords, }, } return } // Names calculates various numerological numbers from a list of given names. Argument numberSystem indicates what // calculation method is used (Pythagorean or Chaldean). Argument reduceWords determines whether each part of // a name is reduced independently before being merged in a final number. func Names(names []string, numberSystem NumberSystem, masterNumbers []int, reduceWords bool) (results []NameNumerology) { opts := NameOpts{ NumberSystem: numberSystem, MasterNumbers: masterNumbers, ReduceWords: reduceWords, } for _, n := range names { name := ToAscii(n) results = append(results, NameNumerology{name, &opts, nil, nil, nil, nil}) } return }
numerology/calculateNames.go
0.822759
0.433862
calculateNames.go
starcoder
package main import ( RLBot "github.com/Trey2k/RLBotGo" vector "github.com/xonmello/BotKoba/vector3" // rotator "github.com/xonmello/BotKoba/rotator" math "github.com/chewxy/math32" ) type State int const ( ATBA State = iota Kickoff DefensiveCorner Air OffensiveCorner OnWall ) type StateInfo struct { current State start int64 allotted int64 } // (Mostly) Always Toward Ball Agent func stateATBA(koba *RLBot.PlayerInfo, opponent *RLBot.PlayerInfo, ball *RLBot.BallInfo, ballPrediction *RLBot.BallPrediction) *RLBot.ControllerState { PlayerInput := &RLBot.ControllerState{} kobaPos, kobaRot, _, opponentPos, _, _, ballPos, _ := initialSetup(koba, opponent, ball) // If in air, point wheels down if !koba.HasWheelContact { PlayerInput.Roll = -1.0 * kobaRot.Roll / math.Pi } // Go toward ball PlayerInput.Steer = steerToward(kobaPos, kobaRot, ballPos) // Drift if close to the ball and not very aligned if kobaPos.Distance(ballPos) < 500 && math.Abs(PlayerInput.Steer) > 0.3 { PlayerInput.Handbrake = true } // If on the wrong side of the ball, go back goal := vector.New(0, 3000, 0) if correctSide(kobaPos, ballPos, goal) { predictionPosition := ballPrediction.Slices[4].Physics.Location predictionPositionVector := vector.New(predictionPosition.X, predictionPosition.Y, predictionPosition.Z) if predictionPositionVector.Magnitude() == 0 { predictionPositionVector = ballPos } PlayerInput.Steer = steerToward(kobaPos, kobaRot, predictionPositionVector) PlayerInput.Boost = true } else if opponentPos.Distance(ballPos) > kobaPos.Distance(ballPos) { PlayerInput.Boost = true } // Flip if close to the ball if kobaPos.Distance(ballPos) < 400 && kobaPos.Y < ballPos.Y { PlayerInput.Steer = steerToward(kobaPos, kobaRot, ballPos) PlayerInput = flipToward(kobaPos, koba.Jumped, kobaRot, ballPos, PlayerInput) } // Go forward PlayerInput.Throttle = 1.0 return PlayerInput } // Kickoff with 2 flips func stateKickoff(koba *RLBot.PlayerInfo, opponent *RLBot.PlayerInfo, ball *RLBot.BallInfo) *RLBot.ControllerState { PlayerInput := &RLBot.ControllerState{} kobaPos, kobaRot, kobaVel, _, _, _, ballPos, _ := initialSetup(koba, opponent, ball) // Go toward ball PlayerInput.Steer = steerToward(kobaPos, kobaRot, ballPos) // Starting flip to gain speed if kobaVel.Magnitude() > 1300 { PlayerInput = flipToward(kobaPos, koba.Jumped, kobaRot, ballPos, PlayerInput) } // Flip when close to the ball if kobaPos.Distance(ballPos) < 500 && kobaPos.Y < ballPos.Y { PlayerInput = flipToward(kobaPos, koba.Jumped, kobaRot, ballPos, PlayerInput) } // Go forward and boost if koba.HasWheelContact { PlayerInput.Throttle = 1.0 PlayerInput.Boost = true } return PlayerInput } // Getting on the correct side of the ball when in the corner func stateDefensiveCorner(koba *RLBot.PlayerInfo, opponent *RLBot.PlayerInfo, ball *RLBot.BallInfo) *RLBot.ControllerState { PlayerInput := &RLBot.ControllerState{} kobaPos, kobaRot, _, _, _, _, ballPos, _ := initialSetup(koba, opponent, ball) // If in air, point wheels down if !koba.HasWheelContact { PlayerInput.Roll = -1.0 * kobaRot.Roll / math.Pi } // Check if on the correct side of the ball if math.Abs(kobaPos.X) < math.Abs(ballPos.X) && kobaPos.Y < ballPos.Y+500 { PlayerInput.Steer = steerToward(kobaPos, kobaRot, ballPos) // Flip when close to the ball if kobaPos.Distance(ballPos) < 500 && kobaPos.Y < ballPos.Y { PlayerInput = flipToward(kobaPos, koba.Jumped, kobaRot, ballPos, PlayerInput) } } else { PlayerInput.Steer = steerToward(kobaPos, kobaRot, vector.New(0, -4500, 0)) } // Drift if not very aligned if math.Abs(PlayerInput.Steer) > 0.5 { PlayerInput.Handbrake = true } // Go forward PlayerInput.Throttle = 1.0 return PlayerInput } // General state for when the ball is in the air func stateAir(koba *RLBot.PlayerInfo, opponent *RLBot.PlayerInfo, ball *RLBot.BallInfo, ballPrediction *RLBot.BallPrediction) *RLBot.ControllerState { PlayerInput := &RLBot.ControllerState{} kobaPos, kobaRot, _, _, _, _, ballPos, _ := initialSetup(koba, opponent, ball) // Target is in front of where the ball will land target := lowestPrediction(ballPrediction) target.Y = ballPos.Y - 500 // Go toward ball PlayerInput.Steer = steerToward(kobaPos, kobaRot, target) // Drift if not very aligned if math.Abs(PlayerInput.Steer) > 0.5 { PlayerInput.Handbrake = true } // Go forward PlayerInput.Throttle = 1.0 return PlayerInput } // Getting in position to hit it if it goes center // TODO Needs work func stateOffensiveCorner(koba *RLBot.PlayerInfo, opponent *RLBot.PlayerInfo, ball *RLBot.BallInfo) *RLBot.ControllerState { PlayerInput := &RLBot.ControllerState{} kobaPos, kobaRot, _, _, _, _, ballPos, _ := initialSetup(koba, opponent, ball) // Go to the side of the field the ball is in // Wait for the ball to go in front of goal or out of corner target := vector.New(0, 200, 0) if ballPos.X > 0 { target.X = 2000 } else { target.X = -2000 } PlayerInput.Steer = steerToward(kobaPos, kobaRot, target) // Slow down if close to target location PlayerInput.Throttle = 1 if kobaPos.Distance(target) < 1250 { PlayerInput.Throttle = 0.2 } // Drift if not very aligned if math.Abs(PlayerInput.Steer) > 0.5 { PlayerInput.Handbrake = true } return PlayerInput } // Jump off wall when on it func stateOnWall(koba *RLBot.PlayerInfo, opponent *RLBot.PlayerInfo, ball *RLBot.BallInfo) *RLBot.ControllerState { PlayerInput := &RLBot.ControllerState{} kobaPos, kobaRot, _, _, _, _, ballPos, _ := initialSetup(koba, opponent, ball) // Jump off wall PlayerInput.Jump = true // If in air, point wheels down and turn toward ball if !koba.HasWheelContact { PlayerInput.Roll = -1.0 * kobaRot.Roll / math.Pi PlayerInput.Yaw = steerToward(kobaPos, kobaRot, ballPos) } return PlayerInput }
states.go
0.595728
0.454472
states.go
starcoder
package deregexp // sequenceable parts are parts that are allowed in a sequence. type sequenceable interface { part isSequenceable() } func (word) isSequenceable() {} func (separator) isSequenceable() {} // sequence is a simplified concatenation in which all concatenations and orParts have been resolved. type sequence []sequenceable // flatSequences converts a part into all possible options described by that part. // concatenation{word("Hi"), separator{}, word(" there")} -> [][]string{[]string{"Hi", " there"}} // orPart{word("Hi"), word("Bye")} -> [][]string{[]string{"Hi"}, []string{"Bye"}} func flatSequences(p part) [][]string { seqs := toSequences(concatenation{p}) ret := make([][]string, len(seqs)) for i, s := range seqs { ret[i] = s.flatten() } return ret } // toSequence returns all possible combinations described by a concatenation. If there are no orParts in c, this will only return a single sequence. func toSequences(c concatenation) []sequence { ret := []sequence{sequence{}} var todo []part = c for len(todo) > 0 { p := todo[0] todo = todo[1:] switch tp := p.(type) { case sequenceable: // word, separator // Add this sequenceable to all possible results. for i, o := range ret { ret[i] = append(o, tp) } case orPart: // Multiply all possible combinations we had so far with the options from this orPart. newRet := make([]sequence, 0, len(ret)*len(tp)) for _, o1 := range ret { for _, o2 := range tp { o3 := toSequences(concatenation{o1.toConcatenation(), o2}) newRet = append(newRet, o3...) } } ret = newRet case concatenation: // "Recurse" into tp by prepending it to our remaining todo list. todo = append(append([]part{}, tp...), todo...) default: panic("wtf") } } return ret } func (s sequence) toConcatenation() concatenation { ret := make(concatenation, len(s)) for i, e := range s { ret[i] = e } return ret } // flatten reduces a sequences to a list of words. Consecutive words get merged together, separators are boundaries between words. func (s sequence) flatten() []string { var ret []string var w string for _, p := range s { switch t := p.(type) { case word: w += string(t) case separator: if w != "" { ret = append(ret, w) w = "" } default: panic("wtf") } } if w != "" { ret = append(ret, w) } return ret }
sequences.go
0.569613
0.433502
sequences.go
starcoder
package playbook import ( "fmt" ) // Inventory represents a set of variable to apply to the templates (see config). // Namespace is the namespace dedicated files where to apply the variables contains into Values // Values is map of string that contains whatever the user set in the default inventory from a playbook type Inventory struct { Namespace string `json:"namespace"` Values map[string]interface{} `json:"values"` } // InventoryService define the way inventories are managed. type InventoryService interface { Create(namespace string) (Inventory, error) Update(namespace string, inventory Inventory) error Get(namespace string) (Inventory, error) Exists(namespace string) bool List() ([]Inventory, error) Delete(namespace string) error Reset(namespace string) (Inventory, error) } // InventoryRepository define the way inventories are actually managed type InventoryRepository interface { Get(namespace string) (Inventory, error) Exists(namespace string) bool Create(Inventory) error Delete(namespace string) error Update(namespace string, inventory Inventory) error List() ([]Inventory, error) } type inventoryService struct { inventories InventoryRepository playbooks PlaybookService } // NewInventoryService create an InventoryService func NewInventoryService(inventories InventoryRepository, playbooks PlaybookService) InventoryService { return &inventoryService{ inventories, playbooks, } } // Create instantiate a new Inventory from the default inventory of a playbook and save it func (is *inventoryService) Create(namespace string) (Inventory, error) { if namespace == "" { return Inventory{}, fmt.Errorf("A namespace cannot be empty") } def, err := is.playbooks.GetDefault() if err != nil { return Inventory{}, err } inv := Inventory{ Namespace: namespace, Values: def.Values, } if err := is.inventories.Create(inv); err != nil { return Inventory{}, err } return inv, nil } // Get returns the Inventory for a given namespace func (is *inventoryService) Get(namespace string) (Inventory, error) { if namespace == "" { return Inventory{}, fmt.Errorf("A namespace cannot be empty") } return is.inventories.Get(namespace) } // Exists return true if an inventory for the given namespace already exists. // Else, it return false. func (is *inventoryService) Exists(namespace string) bool { return is.inventories.Exists(namespace) } // Delete deletes the inventory for the given namespace func (is *inventoryService) Delete(namespace string) error { return is.inventories.Delete(namespace) } // List returns the list of available inventories func (is *inventoryService) List() ([]Inventory, error) { return is.inventories.List() } // Update replace the inventory associated to the given namespace by the given inventory func (is *inventoryService) Update(namespace string, inv Inventory) error { return is.inventories.Update(namespace, inv) } // Reset override the inventory file for the given namespace base on the content of the default inventory. func (is *inventoryService) Reset(namespace string) (Inventory, error) { def, err := is.playbooks.GetDefault() if err != nil { return Inventory{}, err } var inv Inventory inv.Namespace = namespace inv.Values = def.Values if err := is.inventories.Update(namespace, inv); err != nil { return Inventory{}, err } return inv, nil } // ErrorReadingDefaultsFile represents an error due to unreadable default inventory type ErrorReadingDefaultsFile struct { msg string } // Error returns the error message func (err ErrorReadingDefaultsFile) Error() string { return err.msg } // NewErrorReadingDefaultsFile creates an ErrorReadingDefaultsFile error func NewErrorReadingDefaultsFile(err error) ErrorReadingDefaultsFile { return ErrorReadingDefaultsFile{fmt.Sprintf("Error when reading defaults file : %s", err.Error())} } // ErrorInventoryAlreadyExist represents an error due to an already existing inventory for a given namespace type ErrorInventoryAlreadyExist struct { msg string } // Error returns the error message func (err ErrorInventoryAlreadyExist) Error() string { return err.msg } // NewErrorInventoryAlreadyExist creates a new ErrorInventoryAlreadyExist error func NewErrorInventoryAlreadyExist(namespace string) ErrorInventoryAlreadyExist { return ErrorInventoryAlreadyExist{fmt.Sprintf("An inventory for the namespace %s already exist", namespace)} } // ErrorInventoryNotFound represents an error due to a missing inventory for the given namespace type ErrorInventoryNotFound struct { msg string } // Error returns the error message func (err ErrorInventoryNotFound) Error() string { return err.msg } // NewErrorInventoryNotFound creates a new ErrorInventoryNotFound error func NewErrorInventoryNotFound(namespace string) ErrorInventoryNotFound { return ErrorInventoryNotFound{fmt.Sprintf("The inventory for %s does not exist.", namespace)} }
pkg/playbook/inventory.go
0.801703
0.44746
inventory.go
starcoder
package nelson import ( "container/list" "fmt" "math" "github.com/gonum/stat" ) type Rule struct { Name string Description string f func(d *Data, v float64) bool } var Rule1 = Rule{ "Rule1", "One point is more than 3 standard deviations from the mean.", (*Data).rule1, } var Rule2 = Rule{ "Rule2", "Nine (or more) points in a row are on the same side of the mean.", (*Data).rule2, } var Rule3 = Rule{ "Rule3", "Six (or more) points in a row are continually increasing (or decreasing).", (*Data).rule3, } var Rule4 = Rule{ "Rule4", "Fourteen (or more) points in a row alternate in direction, increasing then decreasing.", (*Data).rule4, } var Rule5 = Rule{ "Rule5", "At least 2 of 3 points in a row are > 2 standard deviations from the mean in the same direction.", (*Data).rule5, } var Rule6 = Rule{ "Rule6", "At least 4 of 5 points in a row are > 1 standard deviation from the mean in the same direction.", (*Data).rule6, } var Rule7 = Rule{ "Rule7", "Fifteen points in a row are all within 1 standard deviation of the mean on either side of the mean.", (*Data).rule7, } var Rule8 = Rule{ "Rule8", "Eight points in a row exist, but none within 1 standard deviation of the mean and the points are in both directions from the mean.", (*Data).rule8, } func (r Rule) String() string { return r.Name } // CommonRules includes all rules other than: Rule7 var CommonRules = []Rule{Rule1, Rule2, Rule3, Rule4, Rule5, Rule6, Rule8} // AllRules is not recommended for metrics with little to no variance when well-behaved var AllRules = []Rule{Rule1, Rule2, Rule3, Rule4, Rule5, Rule6, Rule7, Rule8} // MaxSamples indicates the max number of Samples needed to evaluate any Rule. // Rule7 requires the most Samples, 15. const MaxSamples = 15 type Sample interface { Time() int64 // unix time in ms Val() float64 } type statistics struct { ready bool // number of samples required to determine mean and stddev sampleSize int numSamples int values []float64 mean float64 standardDeviation float64 twoDeviations float64 threeDeviations float64 } func (s statistics) String() string { if !s.ready { return fmt.Sprintf("Waiting on [%v] samples", s.sampleSize-s.numSamples) } return fmt.Sprintf("mean=%.2f, stddev=%.2f, twodev=%.2f, threedev=%.2f", s.mean, s.standardDeviation, s.twoDeviations, s.threeDeviations) } func newStatistics(sampleSize int) statistics { return statistics{ sampleSize: sampleSize, values: make([]float64, sampleSize), } } func (s *statistics) clear() { s.numSamples = 0 s.values = make([]float64, s.sampleSize) s.mean = 0 s.standardDeviation = 0 s.twoDeviations = 0 s.threeDeviations = 0 } // addSample returns true if stats are ready, false otherwise. Values // added after stats are ready are ignored. func (s *statistics) addSample(sample Sample) bool { if !s.ready { s.values[s.numSamples] = sample.Val() s.numSamples++ if s.numSamples == s.sampleSize { s.mean = stat.Mean(s.values, nil) s.standardDeviation = stat.StdDev(s.values, nil) s.twoDeviations = 2 * s.standardDeviation s.threeDeviations = 3 * s.standardDeviation s.ready = true } } return s.ready } // Data tracks nelson rule evaluations for a particular time series. Each Data // can be configured with its own sample size and rule set. The life-cycle of // Data should be tied to the TS. type Data struct { Metric interface{} Violations map[string]int // List of Sample Elements backing the current Rule evaluations ViolationsData *list.List Rules []Rule stats statistics // List of Rule Elements indicating currently violated Rules rule2Count int rule3Count int rule3PreviousSample *float64 rule4Count int rule4PreviousSample *float64 rule4PreviousDirection string // List of Sample.Value() Elements rule5LastThree *list.List // List of Sample.Value() Elements rule6LastFive *list.List rule7Count int rule8Count int } func NewData(m interface{}, sampleSize int, rules ...Rule) Data { if nil == rules { rules = AllRules } return Data{ Metric: m, Rules: rules, Violations: make(map[string]int), ViolationsData: list.New(), rule5LastThree: list.New(), rule6LastFive: list.New(), stats: newStatistics(sampleSize), } } func (d Data) String() string { if len(d.Violations) == 0 { return fmt.Sprintf("%v:\n\tNo Violations, stats:%+v", d.Metric, d.stats) } var vr, comma string for k, v := range d.Violations { vr += fmt.Sprintf("%s%s(%v)", comma, k, v) comma = "," } vd := "[" comma = "" for e := d.ViolationsData.Front(); e != nil; e = e.Next() { vd += fmt.Sprintf("%s%.2f", comma, e.Value.(Sample).Val()) comma = "," } vd += "]" return fmt.Sprintf("%v:\n\tviolations: %v\n\tstats: %v\n\tvalues: %v", d.Metric, vr, d.stats, vd) } func (d *Data) Clear() { d.stats.clear() d.Violations = make(map[string]int) d.ViolationsData = d.ViolationsData.Init() d.rule2Count = 0 d.rule3Count = 0 d.rule3PreviousSample = nil d.rule4Count = 0 d.rule4PreviousSample = nil d.rule4PreviousDirection = "" d.rule5LastThree.Init() d.rule6LastFive.Init() d.rule7Count = 0 d.rule8Count = 0 } func (d *Data) hasViolations() bool { return len(d.Violations) > 0 } func (d *Data) AddSample(s Sample) map[string]bool { if d.stats.ready { return d.evaluate(s) } d.stats.addSample(s) return nil } func (d *Data) evaluate(s Sample) (result map[string]bool) { d.ViolationsData.PushFront(s) if d.ViolationsData.Len() > MaxSamples { d.ViolationsData.Remove(d.ViolationsData.Back()) } result = make(map[string]bool) for _, r := range d.Rules { violation := r.f(d, s.Val()) result[r.Name] = violation if violation { fmt.Printf("Violation! %s %v\n", r.Name, d.Metric) d.Violations[r.Name] += 1 } } return result } // one point is more than 3 standard deviations from the mean func (d *Data) rule1(s float64) bool { if d.stats.standardDeviation == 0.0 { return false } return math.Abs(s-d.stats.mean) > d.stats.threeDeviations } // Nine (or more) points in a row are on the same side of the mean func (d *Data) rule2(s float64) bool { switch { case s > d.stats.mean: if d.rule2Count > 0 { d.rule2Count++ } else { d.rule2Count = 1 } case s < d.stats.mean: if d.rule2Count < 0 { d.rule2Count-- } else { d.rule2Count = -1 } default: d.rule2Count = 0 } return math.Abs(float64(d.rule2Count)) >= 9 } // Six (or more) points in a row are continually increasing (or decreasing) func (d *Data) rule3(s float64) bool { if nil == d.rule3PreviousSample { d.rule3PreviousSample = &s d.rule3Count = 0 return false } if s > *d.rule3PreviousSample { if d.rule3Count > 0 { d.rule3Count++ } else { d.rule3Count = 1 } } else if s < *d.rule3PreviousSample { if d.rule3Count < 0 { d.rule3Count-- } else { d.rule3Count = -1 } } else { d.rule3Count = 0 } *d.rule3PreviousSample = s return math.Abs(float64(d.rule3Count)) >= 6 } // Fourteen (or more) points in a row alternate in direction, increasing then decreasing func (d *Data) rule4(s float64) bool { if nil == d.rule4PreviousSample || s == *d.rule4PreviousSample { d.rule4PreviousSample = &s d.rule4PreviousDirection = "=" d.rule4Count = 0 return false } sampleDirection := ">" if s <= *d.rule4PreviousSample { sampleDirection = "<" } if sampleDirection == d.rule4PreviousDirection { d.rule4Count = 0 } else { d.rule4Count++ } *d.rule4PreviousSample = s d.rule4PreviousDirection = sampleDirection return math.Abs(float64(d.rule4Count)) >= 14 } // At least 2 of 3 points in a row are > 2 standard deviations from the mean in the same direction func (d *Data) rule5(s float64) bool { if d.stats.standardDeviation == 0.0 { return false } if math.Abs(s-d.stats.mean) > d.stats.twoDeviations { if s > d.stats.mean { d.rule5LastThree.PushFront(">") } else { d.rule5LastThree.PushFront("<") } } else { d.rule5LastThree.PushFront("") } if d.rule5LastThree.Len() > 3 { d.rule5LastThree.Remove(d.rule5LastThree.Back()) } var above, below int for e := d.rule5LastThree.Front(); e != nil; e = e.Next() { switch e.Value.(string) { case ">": above++ case "<": below++ } } return above >= 2 || below >= 2 } // At least 4 of 5 points in a row are > 1 standard deviation from the mean in the same direction func (d *Data) rule6(s float64) bool { if d.stats.standardDeviation == 0.0 { return false } if math.Abs(s-d.stats.mean) > d.stats.standardDeviation { if s > d.stats.mean { d.rule6LastFive.PushFront(">") } else { d.rule6LastFive.PushFront("<") } } else { d.rule6LastFive.PushFront("") } if d.rule6LastFive.Len() > 5 { d.rule6LastFive.Remove(d.rule6LastFive.Back()) } var above, below int for e := d.rule6LastFive.Front(); e != nil; e = e.Next() { switch e.Value.(string) { case ">": above++ case "<": below++ } } return above >= 4 || below >= 4 } // Fifteen points in a row are all within 1 standard deviation of the mean on either side of the mean // Note: I have my doubts about this one wrt monitored metrics, i think it may not be uncommon to have // a very steady metric. Minimally, I have taken away the flat-line case where all samples are the mean. func (d *Data) rule7(s float64) bool { if d.stats.standardDeviation == 0.0 { return false } if s == d.stats.mean { d.rule7Count = 0 return false } if math.Abs(s-d.stats.mean) <= d.stats.standardDeviation { d.rule7Count++ } else { d.rule7Count = 0 } return d.rule7Count >= 15 } // Eight points in a row exist, but none within 1 standard deviation of the mean // and the points are in both directions from the mean func (d *Data) rule8(s float64) bool { if d.stats.standardDeviation == 0.0 { return false } if math.Abs(s-d.stats.mean) > d.stats.standardDeviation { d.rule8Count++ } else { d.rule8Count = 0 } return d.rule8Count >= 8 }
nelson/nelson.go
0.757974
0.614452
nelson.go
starcoder
package greeso /* #include "matrix.h" */ import "C" import ( "errors" "fmt" "strconv" ) type ( vector []byte row []uint matrix []row ) var ( ErrDimensionMismatch = errors.New("dimension mismatch") ErrNonInvert = errors.New("matrix not invertible") ) // NewMatrix initializes a zero matrix of m rows and n columns. func NewMatrix(m, n int) matrix { A := make([]row, m) for i := range A { A[i] = make([]uint, n) } return A } // Copy the matrix. func (A matrix) Copy() matrix { m := NewMatrix(len(A), len(A[0])) for i, row := range A { copy(m[i], row) } return m } // Identity generates a (possibly truncated) identity matrix. func Identity(m, n int) matrix { I := NewMatrix(m, n) for diag := range I { if diag < len(I[diag]) { I[diag][diag] = uint(1) } } return I } func (A matrix) Mul(V vector, C vector) error { if len(A[0]) != len(V) { return ErrDimensionMismatch } for i := range C { C[i] = 0 } for i := range A { for j, a := range A[i] { C[i] ^= mul(byte(a), V[j]) } } return nil } func (A matrix) Inverse() matrix { w := A.Copy() result := Identity(len(A), len(A[0])) w.LowerGaussianElim(result) w.UpperInverse(result) return result } func (A matrix) PartialLowerGaussElim(row, col int, inverse matrix) (int, int) { lastRow := len(A) - 1 for row < lastRow { if col >= len(A[row]) { return row, col } if 0 == A[row][col] { return row, col } divisor := div(byte(1), byte(A[row][col])) for k := row + 1; k < len(A); k++ { nextTerm := A[k][col] if nextTerm == 0 { continue } multiple := mul(divisor, sub(byte(0), byte(nextTerm))) A.rowMulAdd(multiple, row, k) if inverse != nil { inverse.rowMulAdd(multiple, row, k) } } row = row + 1 col = col + 1 } return row, col } func (A matrix) LowerGaussianElim(inverse matrix) matrix { row, col := 0, 0 lastRow, lastCol := len(A)-1, len(A[0])-1 if lastRow > lastCol+1 { lastRow = lastCol + 1 } for row < lastRow && col < lastCol { leader := A.findRowLeader(row, col) if leader < 0 { col = col + 1 continue } if leader != row { A.rowAdd(leader, row) if inverse != nil { inverse.rowAdd(leader, row) } } row, col = A.PartialLowerGaussElim(row, col, inverse) } return A } func (A matrix) UpperInverse(inverse matrix) (matrix, error) { lastCol := len(A) if lastCol > len(A[0]) { lastCol = len(A[0]) } for col := 0; col < lastCol; col++ { if byte(0) == byte(A[col][col]) { return nil, ErrNonInvert } divisor := div(byte(1), byte(A[col][col])) if divisor != byte(1) { A.rowMul(col, divisor, 0) if inverse != nil { inverse.rowMul(col, divisor, 0) } } for elim := 0; elim < col; elim++ { multiple := sub(byte(0), byte(A[elim][col])) A.rowMulAdd(multiple, col, elim) if inverse != nil { inverse.rowMulAdd(multiple, col, elim) } } } return A, nil } func (A matrix) Transpose() matrix { old := A A = make([]row, len(old[0])) for row := range A { A[row] = make([]uint, len(old)) } for r := range A { for c := range old { A[r][c] = old[c][r] } } return A } func (A matrix) Logify() matrix { old := A A = make([]row, len(old)) for row := range A { A[row] = make([]uint, len(old[row])) } for i, row := range old { for j, v := range row { A[i][j] = log(byte(v)) } } return A } func (A matrix) AntiLogify() matrix { old := A A = make([]row, len(old)) for row := range A { A[row] = make([]uint, len(old[row])) } for i, row := range old { for j, v := range row { A[i][j] = uint(aLog(v)) } } return A } func (A matrix) LogMul(V vector, C vector) error { if len(A[0]) != len(V) { return ErrDimensionMismatch } for i := range C { C[i] = 0 } for i := range A { for j, a := range A[i] { C[i] ^= logMul(a, V[j]) } } return nil } func (A matrix) String() string { return A.GoString() } func (A matrix) GoString() string { m := 0 for _, row := range A { for _, c := range row { l := len(strconv.Itoa(int(c))) if l > m { m = l } } } s := "" f := "%" + strconv.Itoa(m+1) + "s" for _, r := range A { s = s + "\n" for _, c := range r { s = s + fmt.Sprintf(f, strconv.Itoa(int(c))) } } return s } func (A matrix) rowMul(row int, multiplier byte, start int) { for i := range A[row] { A[row][i] = uint(mul(byte(A[row][i]), multiplier)) } } func (A matrix) rowAdd(i, j int) { for k := range A[j] { A[j][k] = uint(add(byte(A[j][k]), byte(A[i][k]))) } } func (A matrix) rowMulAdd(multiplier byte, i, j int) { for k := range A[j] { A[j][k] = uint(add(byte(A[j][k]), mul(multiplier, byte(A[i][k])))) } } func (A matrix) findRowLeader(row, col int) int { for r := row; r < len(A); r++ { if uint(0) != A[r][col] { return r } } return -1 }
matrix.go
0.624064
0.45744
matrix.go
starcoder
// The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): // Any live cell with fewer than two live neighbors dies as if caused by under-population. // Any live cell with two or three live neighbors lives on to the next generation. // Any live cell with more than three live neighbors dies, as if by over-population. // Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. // The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state. // Example 1: // Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] // Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] // Example 2: // Input: board = [[1,1],[1,0]] // Output: [[1,1],[1,1]] // Constraints: // m == board.length // n == board[i].length // 1 <= m, n <= 25 // board[i][j] is 0 or 1. // Follow up: // Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. // In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems? func gameOfLife(board [][]int) { n := len(board) m := len(board[0]) for i := 0; i < n; i++ { for j := 0; j < m; j++ { c := count(board, i, j) if board[i][j] == 0 { board[i][j] = 10 + c } else { board[i][j] = 20 + c } } } for i := 0; i < n; i++ { for j := 0; j < m; j++ { v, c := getValAndCount(board[i][j]) if c < 2 { board[i][j] = 0 } else if v == 1 && (c == 2 || c == 3) { board[i][j] = v } else if c > 3 { board[i][j] = 0 } else if v == 0 && c == 3 { board[i][j] = 1 } else { board[i][j] = v } } } } func getValAndCount(a int) (value, count int) { if a < 10 { return a, 0 } else if a >= 10 && a < 20 { return 0, a - 10 } else { return 1, a - 20 } } func getVal(a int) (value int) { if a < 10 { return a } else if a >= 10 && a < 20 { return 0 } else { return 1 } } func count(board [][]int, i, j int) int { n := len(board) m := len(board[0]) c := 0 if i-1 >= 0 { c += getVal(board[i-1][j]) if j-1 >= 0 { c += getVal(board[i-1][j-1]) } if j+1 < m { c += getVal(board[i-1][j+1]) } } if i+1 < n { c += getVal(board[i+1][j]) if j-1 >= 0 { c += getVal(board[i+1][j-1]) } if j+1 < m { c += getVal(board[i+1][j+1]) } } if j-1 >= 0 { c += getVal(board[i][j-1]) } if j+1 < m { c += getVal(board[i][j+1]) } return c }
0289-game-of-life.go
0.747892
0.69581
0289-game-of-life.go
starcoder
package input import ( "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/lib/input/reader" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" "github.com/Jeffail/benthos/v3/lib/util/tls" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeAMQP09] = TypeSpec{ constructor: fromSimpleConstructor(NewAMQP09), Summary: ` Connects to an AMQP (0.91) queue. AMQP is a messaging protocol used by various message brokers, including RabbitMQ.`, Description: ` TLS is automatic when connecting to an ` + "`amqps`" + ` URL, but custom settings can be enabled in the ` + "`tls`" + ` section. ### Metadata This input adds the following metadata fields to each message: ` + "``` text" + ` - amqp_content_type - amqp_content_encoding - amqp_delivery_mode - amqp_priority - amqp_correlation_id - amqp_reply_to - amqp_expiration - amqp_message_id - amqp_timestamp - amqp_type - amqp_user_id - amqp_app_id - amqp_consumer_tag - amqp_delivery_tag - amqp_redelivered - amqp_exchange - amqp_routing_key - All existing message headers, including nested headers prefixed with the key of their respective parent. ` + "```" + ` You can access these metadata fields using [function interpolation](/docs/configuration/interpolation#metadata).`, sanitiseConfigFunc: func(conf Config) (interface{}, error) { return sanitiseWithBatch(conf.AMQP09, conf.AMQP09.Batching) }, Categories: []Category{ CategoryServices, }, FieldSpecs: docs.FieldSpecs{ docs.FieldCommon("url", "A URL to connect to.", "amqp://localhost:5672/", "amqps://guest:guest@localhost:5672/", ), docs.FieldCommon("queue", "An AMQP queue to consume from."), docs.FieldAdvanced("queue_declare", ` Allows you to passively declare the target queue. If the queue already exists then the declaration passively verifies that they match the target fields.`, map[string]interface{}{ "enabled": true, "durable": false, }, ), docs.FieldAdvanced("bindings_declare", "Allows you to passively declare bindings for the target queue.", []interface{}{ map[string]interface{}{ "exchange": "foo", "key": "bar", }, }, ), docs.FieldCommon("consumer_tag", "A consumer tag."), docs.FieldAdvanced("auto_ack", "Acknowledge messages automatically as they are consumed rather than waiting for acknowledgments from downstream. This can improve throughput and prevent the pipeline from blocking but at the cost of eliminating delivery guarantees."), docs.FieldCommon("prefetch_count", "The maximum number of pending messages to have consumed at a time."), docs.FieldAdvanced("prefetch_size", "The maximum amount of pending messages measured in bytes to have consumed at a time."), tls.FieldSpec(), docs.FieldDeprecated("batching"), }, } } //------------------------------------------------------------------------------ // NewAMQP09 creates a new AMQP09 input type. func NewAMQP09(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) { var a reader.Async var err error if a, err = reader.NewAMQP09(conf.AMQP09, log, stats); err != nil { return nil, err } if a, err = reader.NewAsyncBatcher(conf.AMQP09.Batching, a, mgr, log, stats); err != nil { return nil, err } a = reader.NewAsyncBundleUnacks(a) return NewAsyncReader(TypeAMQP09, true, a, log, stats) } //------------------------------------------------------------------------------
lib/input/amqp_0_9.go
0.727685
0.670797
amqp_0_9.go
starcoder
package fakedata import "strconv" //DummyDataFaker is used in tests type DummyDataFaker struct { Dummy string } func NewDummyDataFaker(dummyString string) DummyDataFaker { result := DummyDataFaker{Dummy: dummyString} return result } func (ddf DummyDataFaker) Brand() string { return ddf.Dummy } func (ddf DummyDataFaker) Character() string { return ddf.Dummy } func (ddf DummyDataFaker) Characters() string { return ddf.Dummy } func (ddf DummyDataFaker) CharactersN(n int) string { return ddf.Dummy + strconv.Itoa(n) } func (ddf DummyDataFaker) City() string { return ddf.Dummy } func (ddf DummyDataFaker) Color() string { return ddf.Dummy } func (ddf DummyDataFaker) Company() string { return ddf.Dummy } func (ddf DummyDataFaker) Continent() string { return ddf.Dummy } func (ddf DummyDataFaker) Country() string { return ddf.Dummy } func (ddf DummyDataFaker) CreditCardVisa() string { return ddf.Dummy } func (ddf DummyDataFaker) CreditCardMasterCard() string { return ddf.Dummy } func (ddf DummyDataFaker) CreditCardAmericanExpress() string { return ddf.Dummy } func (ddf DummyDataFaker) Currency() string { return ddf.Dummy } func (ddf DummyDataFaker) CurrencyCode() string { return ddf.Dummy } func (ddf DummyDataFaker) Day() string { return ddf.Dummy } func (ddf DummyDataFaker) Digits() string { return ddf.Dummy } func (ddf DummyDataFaker) DigitsN(n int) string { return ddf.Dummy + strconv.Itoa(n) } func (ddf DummyDataFaker) EmailAddress() string { return ddf.Dummy } func (ddf DummyDataFaker) FirstName() string { return ddf.Dummy } func (ddf DummyDataFaker) FullName() string { return ddf.Dummy } func (ddf DummyDataFaker) LastName() string { return ddf.Dummy } func (ddf DummyDataFaker) Gender() string { return ddf.Dummy } func (ddf DummyDataFaker) IPv4() string { return ddf.Dummy } func (ddf DummyDataFaker) Language() string { return ddf.Dummy } func (ddf DummyDataFaker) Model() string { return ddf.Dummy } func (ddf DummyDataFaker) Month() string { return ddf.Dummy } func (ddf DummyDataFaker) Year() string { return ddf.Dummy } func (ddf DummyDataFaker) MonthShort() string { return ddf.Dummy } func (ddf DummyDataFaker) Paragraph() string { return ddf.Dummy } func (ddf DummyDataFaker) Paragraphs() string { return ddf.Dummy } func (ddf DummyDataFaker) ParagraphsN(n int) string { return ddf.Dummy + strconv.Itoa(n) } func (ddf DummyDataFaker) Phone() string { return ddf.Dummy } func (ddf DummyDataFaker) Product() string { return ddf.Dummy } func (ddf DummyDataFaker) Sentence() string { return ddf.Dummy } func (ddf DummyDataFaker) Sentences() string { return ddf.Dummy } func (ddf DummyDataFaker) SentencesN(n int) string { return ddf.Dummy + strconv.Itoa(n) } func (ddf DummyDataFaker) SimplePassword() string { return ddf.Dummy } func (ddf DummyDataFaker) State() string { return ddf.Dummy } func (ddf DummyDataFaker) StateAbbrev() string { return ddf.Dummy } func (ddf DummyDataFaker) Street() string { return ddf.Dummy } func (ddf DummyDataFaker) StreetAddress() string { return ddf.Dummy } func (ddf DummyDataFaker) UserName() string { return ddf.Dummy } func (ddf DummyDataFaker) WeekDay() string { return ddf.Dummy } func (ddf DummyDataFaker) Word() string { return ddf.Dummy } func (ddf DummyDataFaker) Words() string { return ddf.Dummy } func (ddf DummyDataFaker) WordsN(n int) string { return ddf.Dummy + strconv.Itoa(n) } func (ddf DummyDataFaker) Zip() string { return ddf.Dummy } func (ddf DummyDataFaker) Int(n int) string { return ddf.Dummy + strconv.Itoa(n) } func (ddf DummyDataFaker) Float(n int) string { return ddf.Dummy + strconv.Itoa(n) } func (ddf DummyDataFaker) UUID() string { return "00000000-0000-0000-0000-000000000000" }
vars/fakedata/dummy_data_faker.go
0.647018
0.723688
dummy_data_faker.go
starcoder
package arn import ( "bytes" "image" "path" "time" "github.com/akyoto/imageserver" ) const ( // AnimeImageLargeWidth is the minimum width in pixels of a large anime image. AnimeImageLargeWidth = 250 // AnimeImageLargeHeight is the minimum height in pixels of a large anime image. AnimeImageLargeHeight = 350 // AnimeImageMediumWidth is the minimum width in pixels of a medium anime image. AnimeImageMediumWidth = 142 // AnimeImageMediumHeight is the minimum height in pixels of a medium anime image. AnimeImageMediumHeight = 200 // AnimeImageSmallWidth is the minimum width in pixels of a small anime image. AnimeImageSmallWidth = 55 // AnimeImageSmallHeight is the minimum height in pixels of a small anime image. AnimeImageSmallHeight = 78 // AnimeImageWebPQuality is the WebP quality of anime images. AnimeImageWebPQuality = 70 // AnimeImageJPEGQuality is the JPEG quality of anime images. AnimeImageJPEGQuality = 70 // AnimeImageQualityBonusLowDPI ... AnimeImageQualityBonusLowDPI = 10 // AnimeImageQualityBonusLarge ... AnimeImageQualityBonusLarge = 5 // AnimeImageQualityBonusMedium ... AnimeImageQualityBonusMedium = 10 // AnimeImageQualityBonusSmall ... AnimeImageQualityBonusSmall = 10 ) // Define the anime image outputs var animeImageOutputs = []imageserver.Output{ // Original at full size &imageserver.OriginalFile{ Directory: path.Join(Root, "images/anime/original/"), Width: 0, Height: 0, Quality: 0, }, // JPEG - Large &imageserver.JPEGFile{ Directory: path.Join(Root, "images/anime/large/"), Width: AnimeImageLargeWidth, Height: AnimeImageLargeHeight, Quality: AnimeImageJPEGQuality + AnimeImageQualityBonusLowDPI + AnimeImageQualityBonusLarge, }, // JPEG - Medium &imageserver.JPEGFile{ Directory: path.Join(Root, "images/anime/medium/"), Width: AnimeImageMediumWidth, Height: AnimeImageMediumHeight, Quality: AnimeImageJPEGQuality + AnimeImageQualityBonusLowDPI + AnimeImageQualityBonusMedium, }, // JPEG - Small &imageserver.JPEGFile{ Directory: path.Join(Root, "images/anime/small/"), Width: AnimeImageSmallWidth, Height: AnimeImageSmallHeight, Quality: AnimeImageJPEGQuality + AnimeImageQualityBonusLowDPI + AnimeImageQualityBonusSmall, }, // WebP - Large &imageserver.WebPFile{ Directory: path.Join(Root, "images/anime/large/"), Width: AnimeImageLargeWidth, Height: AnimeImageLargeHeight, Quality: AnimeImageWebPQuality + AnimeImageQualityBonusLowDPI + AnimeImageQualityBonusLarge, }, // WebP - Medium &imageserver.WebPFile{ Directory: path.Join(Root, "images/anime/medium/"), Width: AnimeImageMediumWidth, Height: AnimeImageMediumHeight, Quality: AnimeImageWebPQuality + AnimeImageQualityBonusLowDPI + AnimeImageQualityBonusMedium, }, // WebP - Small &imageserver.WebPFile{ Directory: path.Join(Root, "images/anime/small/"), Width: AnimeImageSmallWidth, Height: AnimeImageSmallHeight, Quality: AnimeImageWebPQuality + AnimeImageQualityBonusLowDPI + AnimeImageQualityBonusSmall, }, } // Define the high DPI anime image outputs var animeImageOutputsHighDPI = []imageserver.Output{ // JPEG - Large &imageserver.JPEGFile{ Directory: path.Join(Root, "images/anime/large/"), Width: AnimeImageLargeWidth * 2, Height: AnimeImageLargeHeight * 2, Quality: AnimeImageJPEGQuality + AnimeImageQualityBonusLarge, }, // JPEG - Medium &imageserver.JPEGFile{ Directory: path.Join(Root, "images/anime/medium/"), Width: AnimeImageMediumWidth * 2, Height: AnimeImageMediumHeight * 2, Quality: AnimeImageJPEGQuality + AnimeImageQualityBonusMedium, }, // JPEG - Small &imageserver.JPEGFile{ Directory: path.Join(Root, "images/anime/small/"), Width: AnimeImageSmallWidth * 2, Height: AnimeImageSmallHeight * 2, Quality: AnimeImageJPEGQuality + AnimeImageQualityBonusSmall, }, // WebP - Large &imageserver.WebPFile{ Directory: path.Join(Root, "images/anime/large/"), Width: AnimeImageLargeWidth * 2, Height: AnimeImageLargeHeight * 2, Quality: AnimeImageWebPQuality + AnimeImageQualityBonusLarge, }, // WebP - Medium &imageserver.WebPFile{ Directory: path.Join(Root, "images/anime/medium/"), Width: AnimeImageMediumWidth * 2, Height: AnimeImageMediumHeight * 2, Quality: AnimeImageWebPQuality + AnimeImageQualityBonusMedium, }, // WebP - Small &imageserver.WebPFile{ Directory: path.Join(Root, "images/anime/small/"), Width: AnimeImageSmallWidth * 2, Height: AnimeImageSmallHeight * 2, Quality: AnimeImageWebPQuality + AnimeImageQualityBonusSmall, }, } // SetImageBytes accepts a byte buffer that represents an image file and updates the anime image. func (anime *Anime) SetImageBytes(data []byte) error { // Decode img, format, err := image.Decode(bytes.NewReader(data)) if err != nil { return err } return anime.SetImage(&imageserver.MetaImage{ Image: img, Format: format, Data: data, }) } // SetImage sets the anime image to the given MetaImage. func (anime *Anime) SetImage(metaImage *imageserver.MetaImage) error { var lastError error // Save the different image formats and sizes in low DPI for _, output := range animeImageOutputs { err := output.Save(metaImage, anime.ID) if err != nil { lastError = err } } // Save the different image formats and sizes in high DPI for _, output := range animeImageOutputsHighDPI { err := output.Save(metaImage, anime.ID+"@2") if err != nil { lastError = err } } anime.Image.Extension = metaImage.Extension() anime.Image.Width = metaImage.Image.Bounds().Dx() anime.Image.Height = metaImage.Image.Bounds().Dy() anime.Image.AverageColor = GetAverageColor(metaImage.Image) anime.Image.LastModified = time.Now().Unix() return lastError }
arn/AnimeImage.go
0.556641
0.437523
AnimeImage.go
starcoder
--------------------------------------------------------------------------- Copyright (c) 2013-2015 AT&T Intellectual Property 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. --------------------------------------------------------------------------- */ /* Mnemonic: atoll Absrtract: a clike atoll that doesn't error when it encounters a non-digit; returning 0 if there are no digits. This supports 0x<hex> or 0<octal> values and should parse them stopping conversion at the first non-appropriate 'digit'. This also allows a lead +/-. There is an extension on the C functions... if the value is postfixed with M/K/G or m/k/g the return value will be 'expanded' accordingly with the capitalised values being powrs of 10 (e.g. MB) and the lower case indicating powers of 2 (e.g. MiB). This might cause unwanted side effects should the goal be to take a string 200grains and capture just the value; these functions will interpret the leading g incorrectly. Input can be either a string, pointer to string, or a byte array. If the string/array passed in does not begin with a valid digit or sign, or is a pointer that is nil, a value of 0 is returned rather than an error. */ package clike import ( "strconv" ) /* Convert a string or an array of bytes into a 64 bit integer. */ func Atoll( objx interface{} ) (v int64) { var ( i int buf []byte ) v = 0 // ensure all early returns have a value of 0 if objx == nil { return } switch objx.( type ) { // place into a container we can deal with case []byte: buf = objx.([]byte) case string: buf = []byte( objx.(string) ) case *string: bp := objx.( *string ) if bp == nil { return 0 } buf = []byte( *bp ); default: return // who knows, but it doesn't convert } if len( buf ) < 1 { return } i = 0 if buf[i] == '-' || buf[i] == '+' { i++ } if buf[i] == '0' { if len( buf ) > 1 && buf[i+1] == 'x' { i += 2 for ; i < len(buf) && ((buf[i] >= '0' && buf[i] <= '9') || (buf[i] >= 'a' && buf[i] <= 'f') ); i++ {} // find last digit } else { i++ for ; i < len(buf) && (buf[i] >= '0' && buf[i] <= '7'); i++ {} // find last octal digit } } else { for ; i < len(buf) && (buf[i] >= '0' && buf[i] <= '9'); i++ {} // find last digit } if i > 0 { v, _ = strconv.ParseInt( string( buf[0:i] ), 0, 64 ) } if i < len( buf ) { switch string( buf[i:] ) { case "M", "MB": v *= 1000000 case "G", "GB": v *= 1000000000 case "K", "KB": v *= 1000 case "m", "MiB": v *= 1048576 case "g", "GiB": v *= 1073741824 case "k", "KiB": v *= 1024 default: break; } } return } /* Convert to unsigned 64bit. */ func Atoull( objx interface{} ) (v uint64) { var ( i int buf []byte ) v = 0 // ensure all early returns have a value of 0 if objx == nil { return } switch objx.( type ) { // place into a container we can deal with case []byte: buf = objx.([]byte) case string: buf = []byte( objx.(string) ) case *string: bp := objx.( *string ) if bp == nil { return 0 } buf = []byte( *bp ); default: return // who knows, but it doesn't convert } if len( buf ) < 1 { return } i = 0 if buf[i] == '-' || buf[i] == '+' { i++ } if buf[i] == '0' { if len( buf ) > 1 && buf[i+1] == 'x' { i += 2 for ; i < len(buf) && ((buf[i] >= '0' && buf[i] <= '9') || (buf[i] >= 'a' && buf[i] <= 'f') ); i++ {} // find last digit } else { i++ for ; i < len(buf) && (buf[i] >= '0' && buf[i] <= '7'); i++ {} // find last octal digit } } else { for ; i < len(buf) && (buf[i] >= '0' && buf[i] <= '9'); i++ {} // find last digit } if i > 0 { v, _ = strconv.ParseUint( string( buf[0:i] ), 0, 64 ) } if i < len( buf ) { switch string( buf[i:] ) { case "M", "MB": v *= 1000000 case "G", "GB": v *= 1000000000 case "K", "KB": v *= 1000 case "m", "MiB": v *= 1048576 case "g", "GiB": v *= 1073741824 case "k", "KiB": v *= 1024 default: break; } } return }
clike/atoll.go
0.675444
0.439687
atoll.go
starcoder
package constraint import ( "github.com/g3n/engine/experimental/physics/equation" "github.com/g3n/engine/math32" ) // Hinge constraint. // Think of it as a door hinge. // It tries to keep the door in the correct place and with the correct orientation. type Hinge struct { PointToPoint axisA *math32.Vector3 // Rotation axis, defined locally in bodyA. axisB *math32.Vector3 // Rotation axis, defined locally in bodyB. rotEq1 *equation.Rotational rotEq2 *equation.Rotational motorEq *equation.RotationalMotor } // NewHinge creates and returns a pointer to a new Hinge constraint object. func NewHinge(bodyA, bodyB IBody, pivotA, pivotB, axisA, axisB *math32.Vector3, maxForce float32) *Hinge { hc := new(Hinge) hc.initialize(bodyA, bodyB, pivotA, pivotB, maxForce) hc.axisA = axisA hc.axisB = axisB hc.axisA.Normalize() hc.axisB.Normalize() hc.rotEq1 = equation.NewRotational(bodyA, bodyB, maxForce) hc.rotEq2 = equation.NewRotational(bodyA, bodyB, maxForce) hc.motorEq = equation.NewRotationalMotor(bodyA, bodyB, maxForce) hc.motorEq.SetEnabled(false) // Not enabled by default hc.AddEquation(hc.rotEq1) hc.AddEquation(hc.rotEq2) hc.AddEquation(hc.motorEq) return hc } func (hc *Hinge) SetMotorEnabled(state bool) { hc.motorEq.SetEnabled(state) } func (hc *Hinge) SetMotorSpeed(speed float32) { hc.motorEq.SetTargetSpeed(speed) } func (hc *Hinge) SetMotorMaxForce(maxForce float32) { hc.motorEq.SetMaxForce(maxForce) hc.motorEq.SetMinForce(-maxForce) } // Update updates the equations with data. func (hc *Hinge) Update() { hc.PointToPoint.Update() // Get world axes quatA := hc.bodyA.Quaternion() quatB := hc.bodyB.Quaternion() worldAxisA := hc.axisA.Clone().ApplyQuaternion(quatA) worldAxisB := hc.axisB.Clone().ApplyQuaternion(quatB) t1, t2 := worldAxisA.RandomTangents() hc.rotEq1.SetAxisA(t1) hc.rotEq2.SetAxisA(t2) hc.rotEq1.SetAxisB(worldAxisB) hc.rotEq2.SetAxisB(worldAxisB) if hc.motorEq.Enabled() { hc.motorEq.SetAxisA(hc.axisA.Clone().ApplyQuaternion(quatA)) hc.motorEq.SetAxisB(hc.axisB.Clone().ApplyQuaternion(quatB)) } }
experimental/physics/constraint/hinge.go
0.836755
0.5867
hinge.go
starcoder
package block import ( "github.com/df-mc/dragonfly/dragonfly/item" "github.com/df-mc/dragonfly/dragonfly/world" "github.com/go-gl/mathgl/mgl64" ) type ( // Quartz is a mineral block used only for decoration. Quartz struct { noNBT solid bassDrum // Smooth specifies if the quartz block is smooth or not. Smooth bool } // ChiseledQuartz is a mineral block used only for decoration. ChiseledQuartz struct { noNBT solid bassDrum } // QuartzPillar is a mineral block used only for decoration. QuartzPillar struct { noNBT solid bassDrum // Axis is the axis which the quartz pillar block faces. Axis world.Axis } ) // UseOnBlock handles the rotational placing of quartz pillar blocks. func (q QuartzPillar) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) { pos, face, used = firstReplaceable(w, pos, face, q) if !used { return } q.Axis = face.Axis() place(w, pos, q, user, ctx) return placed(ctx) } var quartzBreakInfo = BreakInfo{ Hardness: 0.8, Harvestable: pickaxeHarvestable, Effective: pickaxeEffective, Drops: simpleDrops(item.NewStack(Quartz{}, 1)), } // BreakInfo ... func (q Quartz) BreakInfo() BreakInfo { return quartzBreakInfo } // BreakInfo ... func (c ChiseledQuartz) BreakInfo() BreakInfo { i := quartzBreakInfo i.Drops = simpleDrops(item.NewStack(c, 1)) return i } // BreakInfo ... func (q QuartzPillar) BreakInfo() BreakInfo { i := quartzBreakInfo i.Drops = simpleDrops(item.NewStack(q, 1)) return i } // EncodeItem ... func (q Quartz) EncodeItem() (id int32, meta int16) { if q.Smooth { return 155, 3 } return 155, 0 } // EncodeItem ... func (c ChiseledQuartz) EncodeItem() (id int32, meta int16) { return 155, 1 } // EncodeItem ... func (q QuartzPillar) EncodeItem() (id int32, meta int16) { return 155, 2 } // EncodeBlock ... func (q Quartz) EncodeBlock() (name string, properties map[string]interface{}) { if q.Smooth { return "minecraft:quartz_block", map[string]interface{}{"chisel_type": "smooth", "pillar_axis": "x"} } return "minecraft:quartz_block", map[string]interface{}{"chisel_type": "default", "pillar_axis": "x"} } // Hash ... func (q Quartz) Hash() uint64 { return hashQuartz | (uint64(boolByte(q.Smooth)) << 32) } // EncodeBlock ... func (ChiseledQuartz) EncodeBlock() (name string, properties map[string]interface{}) { return "minecraft:quartz_block", map[string]interface{}{"chisel_type": "chiseled", "pillar_axis": "x"} } // Hash ... func (ChiseledQuartz) Hash() uint64 { return hashChiseledQuartz } // EncodeBlock ... func (q QuartzPillar) EncodeBlock() (name string, properties map[string]interface{}) { return "minecraft:quartz_block", map[string]interface{}{"pillar_axis": q.Axis.String(), "chisel_type": "lines"} } // Hash ... func (q QuartzPillar) Hash() uint64 { return hashQuartzPillar | (uint64(q.Axis << 32)) }
dragonfly/block/quartz_block.go
0.710126
0.415017
quartz_block.go
starcoder
package ga //The Populatio type type Population struct { Chromosomes []Chromosome TotalFitness float64 } //Create a new population of a given size func NewPopulation(size int) Population { var population Population //Loop through the new population for index := 0; index < size; index++ { //Generate a new chromosome and add to the population population.Chromosomes = append(population.Chromosomes, GenerateRandomChromosome()) } //Calculate the total fitness of the new population population.CalculateFitness() //Return the new population return population } //Calculate the total fitness of the population func (population *Population) CalculateFitness() { //Initialise the population total fitness population.TotalFitness = 0 //Loop through the population for index, chromosome := range population.Chromosomes { //Calculate the fitness of the chromosome chromosomeFitness := chromosome.CalculateFitness() //Set the chromosome fitness population.Chromosomes[index].Fitness = chromosomeFitness //Add the individual chromosome fitness to the population total fitness population.TotalFitness += chromosome.Fitness } } //Select a random chromosome from the population based on fitness func (population *Population) SelectRoulette() Chromosome { //Get a target rank in the population targetRank := Random().Float64() * population.TotalFitness //Set the currennt rank equal to the target rank currentRank := targetRank //Loop through the population of chromosomes for _, chromosome := range population.Chromosomes { //Get closer to the target rank currentRank -= chromosome.Fitness //If met the target rank if currentRank < 0 { return chromosome } } //If target rank cannot be met, return last chromosome in population return population.Chromosomes[len(population.Chromosomes)-1] } //Get the fittest chromosome func (population *Population) Fittest() Chromosome { //Initialise the fittest chromosome fittestChromosome := population.Chromosomes[0] //If the fitness of the population hasn't been calculated (should never happen) if fittestChromosome.Fitness == 0.0 { population.CalculateFitness() } //Loop through the population for _, chromosome := range population.Chromosomes { //If the chromosome is fitter than the current fittest if chromosome.Fitness > fittestChromosome.Fitness { //Set the fittest chromosome to be this chromosome fittestChromosome = chromosome } } //Retrun the fittest chromosome return fittestChromosome }
ga/population.go
0.778481
0.600305
population.go
starcoder
// Package internal is for internal use. package internal import ( "fmt" "reflect" "runtime" "testing" ) const ( compareNotEqual int = iota - 2 compareLess compareEqual compareGreater ) // Assert is a simple implementation of assertion, only for internal usage type Assert struct { T *testing.T CaseName string } // NewAssert return instance of Assert func NewAssert(t *testing.T, caseName string) *Assert { return &Assert{T: t, CaseName: caseName} } // Equal check if expected is equal with actual func (a *Assert) Equal(expected, actual interface{}) { if compare(expected, actual) != compareEqual { makeTestFailed(a.T, a.CaseName, expected, actual) } } // NotEqual check if expected is not equal with actual func (a *Assert) NotEqual(expected, actual interface{}) { if compare(expected, actual) == compareEqual { expectedInfo := fmt.Sprintf("not %v", expected) makeTestFailed(a.T, a.CaseName, expectedInfo, actual) } } // Greater check if expected is greate than actual func (a *Assert) Greater(expected, actual interface{}) { if compare(expected, actual) != compareGreater { expectedInfo := fmt.Sprintf("> %v", expected) makeTestFailed(a.T, a.CaseName, expectedInfo, actual) } } // GreaterOrEqual check if expected is greate than or equal with actual func (a *Assert) GreaterOrEqual(expected, actual interface{}) { isGreatOrEqual := compare(expected, actual) == compareGreater || compare(expected, actual) == compareEqual if !isGreatOrEqual { expectedInfo := fmt.Sprintf(">= %v", expected) makeTestFailed(a.T, a.CaseName, expectedInfo, actual) } } // Less check if expected is less than actual func (a *Assert) Less(expected, actual interface{}) { if compare(expected, actual) != compareLess { expectedInfo := fmt.Sprintf("< %v", expected) makeTestFailed(a.T, a.CaseName, expectedInfo, actual) } } // LessOrEqual check if expected is less than or equal with actual func (a *Assert) LessOrEqual(expected, actual interface{}) { isLessOrEqual := compare(expected, actual) == compareLess || compare(expected, actual) == compareEqual if !isLessOrEqual { expectedInfo := fmt.Sprintf("<= %v", expected) makeTestFailed(a.T, a.CaseName, expectedInfo, actual) } } // IsNil check if value is nil func (a *Assert) IsNil(value interface{}) { if value != nil { makeTestFailed(a.T, a.CaseName, nil, value) } } // IsNotNil check if value is not nil func (a *Assert) IsNotNil(value interface{}) { if value == nil { makeTestFailed(a.T, a.CaseName, "not nil", value) } } // compare x and y return : // x > y -> 1, x < y -> -1, x == y -> 0, x != y -> -2 func compare(x, y interface{}) int { vx := reflect.ValueOf(x) vy := reflect.ValueOf(y) if vx.Type() != vy.Type() { return compareNotEqual } switch vx.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: xInt := vx.Int() yInt := vy.Int() if xInt > yInt { return compareGreater } if xInt == yInt { return compareEqual } if xInt < yInt { return compareLess } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: xUint := vx.Uint() yUint := vy.Uint() if xUint > yUint { return compareGreater } if xUint == yUint { return compareEqual } if xUint < yUint { return compareLess } case reflect.Float32, reflect.Float64: xFloat := vx.Float() yFloat := vy.Float() if xFloat > yFloat { return compareGreater } if xFloat == yFloat { return compareEqual } if xFloat < yFloat { return compareLess } case reflect.String: xString := vx.String() yString := vy.String() if xString > yString { return compareGreater } if xString == yString { return compareEqual } if xString < yString { return compareLess } default: if reflect.DeepEqual(x, y) { return compareEqual } return compareNotEqual } return compareNotEqual } // logFailedInfo make test failed and log error info func makeTestFailed(t *testing.T, caseName string, expected, actual interface{}) { _, file, line, _ := runtime.Caller(2) errInfo := fmt.Sprintf("Case %v failed. file: %v, line: %v, expected: %v, actual: %v.", caseName, file, line, expected, actual) t.Error(errInfo) t.FailNow() }
internal/assert.go
0.70028
0.678507
assert.go
starcoder
package unit // Pressure represents a SI derived unit of pressure (in pascal, Pa) type Pressure Unit // ... const ( // SI derived Yoctopascal = Pascal * 1e-24 Zeptopascal = Pascal * 1e-21 Attopascal = Pascal * 1e-18 Femtopascal = Pascal * 1e-15 Picopascal = Pascal * 1e-12 Nanopascal = Pascal * 1e-9 Micropascal = Pascal * 1e-6 Millipascal = Pascal * 1e-3 Centipascal = Pascal * 1e-2 Decipascal = Pascal * 1e-1 Pascal Pressure = 1e0 Decapascal = Pascal * 1e1 Hectopascal = Pascal * 1e2 Kilopascal = Pascal * 1e3 Megapascal = Pascal * 1e6 Gigapascal = Pascal * 1e9 Terapascal = Pascal * 1e12 Petapascal = Pascal * 1e15 Exapascal = Pascal * 1e18 Zettapascal = Pascal * 1e21 Yottapascal = Pascal * 1e24 // non-SI Yoctobar = Bar * 1e-24 Zeptobar = Bar * 1e-21 Attobar = Bar * 1e-18 Femtobar = Bar * 1e-15 Picobar = Bar * 1e-12 Nanobar = Bar * 1e-9 Microbar = Bar * 1e-6 Millibar = Bar * 1e-3 Centibar = Bar * 1e-2 Decibar = Bar * 1e-1 Bar = Pascal * 1e5 Decabar = Bar * 1e1 Hectobar = Bar * 1e2 Kilobar = Bar * 1e3 Megabar = Bar * 1e6 Gigabar = Bar * 1e9 Terabar = Bar * 1e12 Petabar = Bar * 1e15 Exabar = Bar * 1e18 Zettabar = Bar * 1e21 Yottabar = Bar * 1e24 Atmosphere = Pascal * 1.01325 * 1e5 TechAtmosphere = Pascal * 9.80665 * 1e4 Torr = Pascal * 133.3224 PoundsPerSquareInch = Pascal * 6.8948 * 1e3 ) // Yoctopascals returns the pressure in yPa func (p Pressure) Yoctopascals() float64 { return float64(p / Yoctopascal) } // Zeptopascals returns the pressure in zPa func (p Pressure) Zeptopascals() float64 { return float64(p / Zeptopascal) } // Attopascals returns the pressure in aPa func (p Pressure) Attopascals() float64 { return float64(p / Attopascal) } // Femtopascals returns the pressure in fPa func (p Pressure) Femtopascals() float64 { return float64(p / Femtopascal) } // Picopascals returns the pressure in pPa func (p Pressure) Picopascals() float64 { return float64(p / Picopascal) } // Nanopascals returns the pressure in nPa func (p Pressure) Nanopascals() float64 { return float64(p / Nanopascal) } // Micropascals returns the pressure in µPa func (p Pressure) Micropascals() float64 { return float64(p / Micropascal) } // Millipascals returns the pressure in mPa func (p Pressure) Millipascals() float64 { return float64(p / Millipascal) } // Centipascals returns the pressure in cPa func (p Pressure) Centipascals() float64 { return float64(p / Centipascal) } // Decipascals returns the pressure in dPa func (p Pressure) Decipascals() float64 { return float64(p / Decipascal) } // Pascals returns the pressure in Pa func (p Pressure) Pascals() float64 { return float64(p) } // Decapascals returns the pressure in daPa func (p Pressure) Decapascals() float64 { return float64(p / Decapascal) } // Hectopascals returns the pressure in hPa func (p Pressure) Hectopascals() float64 { return float64(p / Hectopascal) } // Kilopascals returns the pressure in kPa func (p Pressure) Kilopascals() float64 { return float64(p / Kilopascal) } // Megapascals returns the pressure in MPa func (p Pressure) Megapascals() float64 { return float64(p / Megapascal) } // Gigapascals returns the pressure in GPa func (p Pressure) Gigapascals() float64 { return float64(p / Gigapascal) } // Terapascals returns the pressure in TPa func (p Pressure) Terapascals() float64 { return float64(p / Terapascal) } // Petapascals returns the pressure in PPa func (p Pressure) Petapascals() float64 { return float64(p / Petapascal) } // Exapascals returns the pressure in EPa func (p Pressure) Exapascals() float64 { return float64(p / Exapascal) } // Zettapascals returns the pressure in ZPa func (p Pressure) Zettapascals() float64 { return float64(p / Zettapascal) } // Yottapascals returns the pressure in YPa func (p Pressure) Yottapascals() float64 { return float64(p / Yottapascal) } // Yoctobars returns the pressure in ybar func (p Pressure) Yoctobars() float64 { return float64(p / Yoctobar) } // Zeptobars returns the pressure in zbar func (p Pressure) Zeptobars() float64 { return float64(p / Zeptobar) } // Attobars returns the pressure in abar func (p Pressure) Attobars() float64 { return float64(p / Attobar) } // Femtobars returns the pressure in fbar func (p Pressure) Femtobars() float64 { return float64(p / Femtobar) } // Picobars returns the pressure in pbar func (p Pressure) Picobars() float64 { return float64(p / Picobar) } // Nanobars returns the pressure in nbar func (p Pressure) Nanobars() float64 { return float64(p / Nanobar) } // Microbars returns the pressure in µbar func (p Pressure) Microbars() float64 { return float64(p / Microbar) } // Millibars returns the pressure in mbar func (p Pressure) Millibars() float64 { return float64(p / Millibar) } // Centibars returns the pressure in cbar func (p Pressure) Centibars() float64 { return float64(p / Centibar) } // Decibars returns the pressure in dbar func (p Pressure) Decibars() float64 { return float64(p / Decibar) } // Bars returns the pressure in bar func (p Pressure) Bars() float64 { return float64(p / Bar) } // Decabars returns the pressure in dabar func (p Pressure) Decabars() float64 { return float64(p / Decabar) } // Hectobars returns the pressure in hbar func (p Pressure) Hectobars() float64 { return float64(p / Hectobar) } // Kilobars returns the pressure in kbar func (p Pressure) Kilobars() float64 { return float64(p / Kilobar) } // Megabars returns the pressure in Mbar func (p Pressure) Megabars() float64 { return float64(p / Megabar) } // Gigabars returns the pressure in Gbar func (p Pressure) Gigabars() float64 { return float64(p / Gigabar) } // Terabars returns the pressure in Tbar func (p Pressure) Terabars() float64 { return float64(p / Terabar) } // Petabars returns the pressure in Pbar func (p Pressure) Petabars() float64 { return float64(p / Petabar) } // Exabars returns the pressure in Ebar func (p Pressure) Exabars() float64 { return float64(p / Exabar) } // Zettabars returns the pressure in Zbar func (p Pressure) Zettabars() float64 { return float64(p / Zettabar) } // Yottabars returns the pressure in Ybar func (p Pressure) Yottabars() float64 { return float64(p / Yottabar) } // Atmospheres returns the pressure in atm func (p Pressure) Atmospheres() float64 { return float64(p / Atmosphere) } // TechAtmospheres returns the pressure in at func (p Pressure) TechAtmospheres() float64 { return float64(p / TechAtmosphere) } // Torrs returns the pressure in Torr func (p Pressure) Torrs() float64 { return float64(p / Torr) } // PoundsPerSquareInch returns the pressure in psi func (p Pressure) PoundsPerSquareInch() float64 { return float64(p / PoundsPerSquareInch) }
pressure.go
0.762424
0.609321
pressure.go
starcoder
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // Int8RangeArrayFromIntArray2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]int. func Int8RangeArrayFromIntArray2Slice(val [][2]int) driver.Valuer { return int8RangeArrayFromIntArray2Slice{val: val} } // Int8RangeArrayToIntArray2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]int and sets it to val. func Int8RangeArrayToIntArray2Slice(val *[][2]int) sql.Scanner { return int8RangeArrayToIntArray2Slice{val: val} } // Int8RangeArrayFromInt8Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]int8. func Int8RangeArrayFromInt8Array2Slice(val [][2]int8) driver.Valuer { return int8RangeArrayFromInt8Array2Slice{val: val} } // Int8RangeArrayToInt8Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]int8 and sets it to val. func Int8RangeArrayToInt8Array2Slice(val *[][2]int8) sql.Scanner { return int8RangeArrayToInt8Array2Slice{val: val} } // Int8RangeArrayFromInt16Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]int16. func Int8RangeArrayFromInt16Array2Slice(val [][2]int16) driver.Valuer { return int8RangeArrayFromInt16Array2Slice{val: val} } // Int8RangeArrayToInt16Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]int16 and sets it to val. func Int8RangeArrayToInt16Array2Slice(val *[][2]int16) sql.Scanner { return int8RangeArrayToInt16Array2Slice{val: val} } // Int8RangeArrayFromInt32Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]int32. func Int8RangeArrayFromInt32Array2Slice(val [][2]int32) driver.Valuer { return int8RangeArrayFromInt32Array2Slice{val: val} } // Int8RangeArrayToInt32Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]int32 and sets it to val. func Int8RangeArrayToInt32Array2Slice(val *[][2]int32) sql.Scanner { return int8RangeArrayToInt32Array2Slice{val: val} } // Int8RangeArrayFromInt64Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]int64. func Int8RangeArrayFromInt64Array2Slice(val [][2]int64) driver.Valuer { return int8RangeArrayFromInt64Array2Slice{val: val} } // Int8RangeArrayToInt64Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]int64 and sets it to val. func Int8RangeArrayToInt64Array2Slice(val *[][2]int64) sql.Scanner { return int8RangeArrayToInt64Array2Slice{val: val} } // Int8RangeArrayFromUintArray2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]uint. func Int8RangeArrayFromUintArray2Slice(val [][2]uint) driver.Valuer { return int8RangeArrayFromUintArray2Slice{val: val} } // Int8RangeArrayToUintArray2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]uint and sets it to val. func Int8RangeArrayToUintArray2Slice(val *[][2]uint) sql.Scanner { return int8RangeArrayToUintArray2Slice{val: val} } // Int8RangeArrayFromUint8Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]uint8. func Int8RangeArrayFromUint8Array2Slice(val [][2]uint8) driver.Valuer { return int8RangeArrayFromUint8Array2Slice{val: val} } // Int8RangeArrayToUint8Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]uint8 and sets it to val. func Int8RangeArrayToUint8Array2Slice(val *[][2]uint8) sql.Scanner { return int8RangeArrayToUint8Array2Slice{val: val} } // Int8RangeArrayFromUint16Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]uint16. func Int8RangeArrayFromUint16Array2Slice(val [][2]uint16) driver.Valuer { return int8RangeArrayFromUint16Array2Slice{val: val} } // Int8RangeArrayToUint16Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]uint16 and sets it to val. func Int8RangeArrayToUint16Array2Slice(val *[][2]uint16) sql.Scanner { return int8RangeArrayToUint16Array2Slice{val: val} } // Int8RangeArrayFromUint32Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]uint32. func Int8RangeArrayFromUint32Array2Slice(val [][2]uint32) driver.Valuer { return int8RangeArrayFromUint32Array2Slice{val: val} } // Int8RangeArrayToUint32Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]uint32 and sets it to val. func Int8RangeArrayToUint32Array2Slice(val *[][2]uint32) sql.Scanner { return int8RangeArrayToUint32Array2Slice{val: val} } // Int8RangeArrayFromUint64Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]uint64. func Int8RangeArrayFromUint64Array2Slice(val [][2]uint64) driver.Valuer { return int8RangeArrayFromUint64Array2Slice{val: val} } // Int8RangeArrayToUint64Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]uint64 and sets it to val. func Int8RangeArrayToUint64Array2Slice(val *[][2]uint64) sql.Scanner { return int8RangeArrayToUint64Array2Slice{val: val} } // Int8RangeArrayFromFloat32Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]float32. func Int8RangeArrayFromFloat32Array2Slice(val [][2]float32) driver.Valuer { return int8RangeArrayFromFloat32Array2Slice{val: val} } // Int8RangeArrayToFloat32Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]float32 and sets it to val. func Int8RangeArrayToFloat32Array2Slice(val *[][2]float32) sql.Scanner { return int8RangeArrayToFloat32Array2Slice{val: val} } // Int8RangeArrayFromFloat64Array2Slice returns a driver.Valuer that produces a PostgreSQL int8range[] from the given Go [][2]float64. func Int8RangeArrayFromFloat64Array2Slice(val [][2]float64) driver.Valuer { return int8RangeArrayFromFloat64Array2Slice{val: val} } // Int8RangeArrayToFloat64Array2Slice returns an sql.Scanner that converts a PostgreSQL int8range[] into a Go [][2]float64 and sets it to val. func Int8RangeArrayToFloat64Array2Slice(val *[][2]float64) sql.Scanner { return int8RangeArrayToFloat64Array2Slice{val: val} } type int8RangeArrayFromIntArray2Slice struct { val [][2]int } func (v int8RangeArrayFromIntArray2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendInt(out, int64(a[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToIntArray2Slice struct { val *[][2]int } func (v int8RangeArrayToIntArray2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]int, len(elems)) for i, elem := range elems { var lo, hi int64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseInt(string(arr[0]), 10, 64); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseInt(string(arr[1]), 10, 64); err != nil { return err } } ranges[i][0] = int(lo) ranges[i][1] = int(hi) } *v.val = ranges return nil } type int8RangeArrayFromInt8Array2Slice struct { val [][2]int8 } func (v int8RangeArrayFromInt8Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendInt(out, int64(a[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToInt8Array2Slice struct { val *[][2]int8 } func (v int8RangeArrayToInt8Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]int8, len(elems)) for i, elem := range elems { var lo, hi int64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseInt(string(arr[0]), 10, 8); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseInt(string(arr[1]), 10, 8); err != nil { return err } } ranges[i][0] = int8(lo) ranges[i][1] = int8(hi) } *v.val = ranges return nil } type int8RangeArrayFromInt16Array2Slice struct { val [][2]int16 } func (v int8RangeArrayFromInt16Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendInt(out, int64(a[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToInt16Array2Slice struct { val *[][2]int16 } func (v int8RangeArrayToInt16Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]int16, len(elems)) for i, elem := range elems { var lo, hi int64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseInt(string(arr[0]), 10, 16); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseInt(string(arr[1]), 10, 16); err != nil { return err } } ranges[i][0] = int16(lo) ranges[i][1] = int16(hi) } *v.val = ranges return nil } type int8RangeArrayFromInt32Array2Slice struct { val [][2]int32 } func (v int8RangeArrayFromInt32Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendInt(out, int64(a[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToInt32Array2Slice struct { val *[][2]int32 } func (v int8RangeArrayToInt32Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]int32, len(elems)) for i, elem := range elems { var lo, hi int64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseInt(string(arr[0]), 10, 32); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseInt(string(arr[1]), 10, 32); err != nil { return err } } ranges[i][0] = int32(lo) ranges[i][1] = int32(hi) } *v.val = ranges return nil } type int8RangeArrayFromInt64Array2Slice struct { val [][2]int64 } func (v int8RangeArrayFromInt64Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendInt(out, int64(a[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToInt64Array2Slice struct { val *[][2]int64 } func (v int8RangeArrayToInt64Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]int64, len(elems)) for i, elem := range elems { var lo, hi int64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseInt(string(arr[0]), 10, 64); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseInt(string(arr[1]), 10, 64); err != nil { return err } } ranges[i][0] = lo ranges[i][1] = hi } *v.val = ranges return nil } type int8RangeArrayFromUintArray2Slice struct { val [][2]uint } func (v int8RangeArrayFromUintArray2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendUint(out, uint64(a[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToUintArray2Slice struct { val *[][2]uint } func (v int8RangeArrayToUintArray2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]uint, len(elems)) for i, elem := range elems { var lo, hi uint64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseUint(string(arr[0]), 10, 64); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseUint(string(arr[1]), 10, 64); err != nil { return err } } ranges[i][0] = uint(lo) ranges[i][1] = uint(hi) } *v.val = ranges return nil } type int8RangeArrayFromUint8Array2Slice struct { val [][2]uint8 } func (v int8RangeArrayFromUint8Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendUint(out, uint64(a[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToUint8Array2Slice struct { val *[][2]uint8 } func (v int8RangeArrayToUint8Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]uint8, len(elems)) for i, elem := range elems { var lo, hi uint64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseUint(string(arr[0]), 10, 8); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseUint(string(arr[1]), 10, 8); err != nil { return err } } ranges[i][0] = uint8(lo) ranges[i][1] = uint8(hi) } *v.val = ranges return nil } type int8RangeArrayFromUint16Array2Slice struct { val [][2]uint16 } func (v int8RangeArrayFromUint16Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendUint(out, uint64(a[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToUint16Array2Slice struct { val *[][2]uint16 } func (v int8RangeArrayToUint16Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]uint16, len(elems)) for i, elem := range elems { var lo, hi uint64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseUint(string(arr[0]), 10, 16); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseUint(string(arr[1]), 10, 16); err != nil { return err } } ranges[i][0] = uint16(lo) ranges[i][1] = uint16(hi) } *v.val = ranges return nil } type int8RangeArrayFromUint32Array2Slice struct { val [][2]uint32 } func (v int8RangeArrayFromUint32Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendUint(out, uint64(a[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToUint32Array2Slice struct { val *[][2]uint32 } func (v int8RangeArrayToUint32Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]uint32, len(elems)) for i, elem := range elems { var lo, hi uint64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseUint(string(arr[0]), 10, 32); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseUint(string(arr[1]), 10, 32); err != nil { return err } } ranges[i][0] = uint32(lo) ranges[i][1] = uint32(hi) } *v.val = ranges return nil } type int8RangeArrayFromUint64Array2Slice struct { val [][2]uint64 } func (v int8RangeArrayFromUint64Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendUint(out, uint64(a[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToUint64Array2Slice struct { val *[][2]uint64 } func (v int8RangeArrayToUint64Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]uint64, len(elems)) for i, elem := range elems { var lo, hi uint64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseUint(string(arr[0]), 10, 64); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseUint(string(arr[1]), 10, 64); err != nil { return err } } ranges[i][0] = lo ranges[i][1] = hi } *v.val = ranges return nil } type int8RangeArrayFromFloat32Array2Slice struct { val [][2]float32 } func (v int8RangeArrayFromFloat32Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendInt(out, int64(a[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToFloat32Array2Slice struct { val *[][2]float32 } func (v int8RangeArrayToFloat32Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]float32, len(elems)) for i, elem := range elems { var lo, hi int64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseInt(string(arr[0]), 10, 32); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseInt(string(arr[1]), 10, 32); err != nil { return err } } ranges[i][0] = float32(lo) ranges[i][1] = float32(hi) } *v.val = ranges return nil } type int8RangeArrayFromFloat64Array2Slice struct { val [][2]float64 } func (v int8RangeArrayFromFloat64Array2Slice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, a := range v.val { out = append(out, '"', '[') out = strconv.AppendInt(out, int64(a[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(a[1]), 10) out = append(out, ')', '"', ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int8RangeArrayToFloat64Array2Slice struct { val *[][2]float64 } func (v int8RangeArrayToFloat64Array2Slice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { v.val = nil return nil } elems := pgParseQuotedStringArray(data) ranges := make([][2]float64, len(elems)) for i, elem := range elems { var lo, hi int64 arr := pgParseRange(elem) if len(arr[0]) > 0 { if lo, err = strconv.ParseInt(string(arr[0]), 10, 64); err != nil { return err } } if len(arr[1]) > 0 { if hi, err = strconv.ParseInt(string(arr[1]), 10, 64); err != nil { return err } } ranges[i][0] = float64(lo) ranges[i][1] = float64(hi) } *v.val = ranges return nil }
pgsql/int8rangearr.go
0.819929
0.503113
int8rangearr.go
starcoder
package parser import ( "github.com/PuerkitoBio/goquery" "github.com/Rhymond/go-money" "github.com/ed-fx/go-soft4fx/internal/simulator" "github.com/pkg/errors" "strconv" ) func parseClosedTransactions(sim *simulator.Simulator, row *goquery.Selection) (*goquery.Selection, error) { if err := validateSectionHeader(row, "Closed Transactions:"); err != nil { return nil, err } row = row.Next().Next() // Skip Section and Grid Header // Parse InitialDeposit row, err := parseInitialDeposit(sim, row) if err != nil { return nil, err } var rowCount = 1 for { nextRow, err := parseClosedTransactionOrder(sim, rowCount, row) if err != nil { return nil, err } if nextRow == nil { break } rowCount++ row = nextRow } for { firstTd := row.ChildrenFiltered("td").First().Text() if firstTd == "Open Trades:" { return row, nil } row = row.Next() } } func parseInitialDeposit(sim *simulator.Simulator, row *goquery.Selection) (*goquery.Selection, error) { // 0 2020.01.06 00:00:00 balance Initial deposit 10 000.00 cells := rowToStringArray(row) id, err := strconv.Atoi(cells[0]) if err != nil { return nil, errors.New("Failed to parse initial deposit's id of [" + cells[0] + "]") } openTime, err := parseRowDateTime(cells[1]) if err != nil { return nil, errors.New("Failed to parse initial deposit's openTime of [" + cells[1] + "]") } orderType, err := simulator.NewOrderTypeFromString(cells[2]) if err != nil { return nil, errors.New("Failed to parse initial deposit's order type of [" + cells[2] + "]") } amount, err := parseMoney(sim.Currency, cells[4]) if err != nil { return nil, errors.New("Failed to parse initial deposit's amount of [" + cells[4] + "]") } currency := amount.Currency().Code zeroAmount := money.New(0, currency) order := &simulator.Order{ Id: id, OpenTime: openTime, Type: orderType, Commission: zeroAmount, Taxes: zeroAmount, Swap: zeroAmount, Profit: amount, Comment: cells[3], } order.PostConstruct() sim.ClosedOrders = append(sim.ClosedOrders, order) return row.Next(), nil } func parseClosedTransactionOrder(sim *simulator.Simulator, rowNumber int, row *goquery.Selection) (nextRow *goquery.Selection, err error) { rowNumStr := strconv.Itoa(rowNumber) // 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 // '1','2020.01.13 17:00:00','buy','0.67','gbpjpy','142.797','142.377','143.217','2020.01.13 23:00:00','142.846','0.00','0.00','0.00','22.98' cells := rowToStringArray(row) id, err := strconv.Atoi(cells[0]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s id of [" + cells[0] + "]") } openTime, err := parseRowDateTime(cells[1]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s openTime of [" + cells[1] + "]") } orderType, err := simulator.NewOrderTypeFromString(cells[2]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s order type of [" + cells[2] + "]") } lotSize, err := parseFloat(cells[3]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s lot size of [" + cells[3] + "]") } openPrice, err := parseFloat(cells[5]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s open price of [" + cells[5] + "]") } stopLoss, err := parseFloat(cells[6]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s stop loss of [" + cells[6] + "]") } takeProfit, err := parseFloat(cells[7]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s take profit of [" + cells[7] + "]") } closeTime, err := parseRowDateTime(cells[8]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s close time of [" + cells[8] + "]") } closePrice, err := parseFloat(cells[9]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s close price of [" + cells[9] + "]") } commission, err := parseMoney(sim.Currency, cells[10]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s commission of [" + cells[10] + "]") } taxes, err := parseMoney(sim.Currency, cells[11]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s taxes of [" + cells[11] + "]") } swap, err := parseMoney(sim.Currency, cells[12]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s swap of [" + cells[12] + "]") } profit, err := parseMoney(sim.Currency, cells[13]) if err != nil { return nil, errors.New("Failed to parse order row [" + rowNumStr + "]'s profit of [" + cells[13] + "]") } order := &simulator.Order{ Id: id, OpenTime: openTime, Type: orderType, Size: &lotSize, Symbol: cells[4], OpenPrice: &openPrice, StopLoss: &stopLoss, TakeProfit: &takeProfit, CloseTime: closeTime, ClosePrice: &closePrice, Commission: commission, Taxes: taxes, Swap: swap, Profit: profit, } order.PostConstruct() sim.ClosedOrders = append(sim.ClosedOrders, order) nextRow = closedTransactionNextRow(nextRow, row) return } func closedTransactionNextRow(nextRow *goquery.Selection, row *goquery.Selection) *goquery.Selection { nextRow = row.Next() { nodes := nextRow.ChildrenFiltered("td").Nodes childrenCount := len(nodes) if childrenCount == 3 { nextRow = nextRow.Next() } } { // Just in case if follow with summary childrenCount := len(nextRow.ChildrenFiltered("td").Nodes) if childrenCount == 5 { nextRow = nil } } return nextRow }
internal/simulator/parser/parser_closed_transactions.go
0.584864
0.471223
parser_closed_transactions.go
starcoder
package types import ( "encoding/json" "fmt" "strings" "github.com/AccumulateNetwork/accumulate/internal/encoding" ) // TransactionType is the type of a transaction. type TransactionType uint64 // TxType is an alias for TransactionType // Deprecated: use TransactionType type TxType = TransactionType const ( // TxTypeUnknown represents an unknown transaction type. TxTypeUnknown TransactionType = 0x00 // txMaxUser is the highest number reserved for user transactions. txMaxUser TransactionType = 0x2F // txMaxSynthetic is the highest number reserved for synthetic transactions. txMaxSynthetic TransactionType = 0x5F // txMaxInternal is the highest number reserved for internal transactions. txMaxInternal TransactionType = 0xFF ) // User transactions const ( // TxTypeCreateIdentity creates an ADI, which produces a synthetic chain // create transaction. TxTypeCreateIdentity TransactionType = 0x01 // TxTypeCreateTokenAccount creates an ADI token account, which produces a // synthetic chain create transaction. TxTypeCreateTokenAccount TransactionType = 0x02 // TxTypeSendTokens transfers tokens between token accounts, which produces // a synthetic deposit tokens transaction. TxTypeSendTokens TransactionType = 0x03 // TxTypeCreateDataAccount creates an ADI Data Account, which produces a // synthetic chain create transaction. TxTypeCreateDataAccount TransactionType = 0x04 // TxTypeWriteData writes data to an ADI Data Account, which *does not* // produce a synthetic transaction. TxTypeWriteData TransactionType = 0x05 // TxTypeWriteDataTo writes data to a Lite Data Account, which produces a // synthetic write data transaction. TxTypeWriteDataTo TransactionType = 0x06 // TxTypeAcmeFaucet produces a synthetic deposit tokens transaction that // deposits ACME tokens into a lite account. TxTypeAcmeFaucet TransactionType = 0x07 // TxTypeCreateToken creates a token issuer, which produces a synthetic // chain create transaction. TxTypeCreateToken TransactionType = 0x08 // TxTypeIssueTokens issues tokens to a token account, which produces a // synthetic token deposit transaction. TxTypeIssueTokens TransactionType = 0x09 // TxTypeBurnTokens burns tokens from a token account, which produces a // synthetic burn tokens transaction. TxTypeBurnTokens TransactionType = 0x0A // TxTypeCreateKeyPage creates a key page, which produces a synthetic chain // create transaction. TxTypeCreateKeyPage TransactionType = 0x0C // TxTypeCreateKeyBook creates a key book, which produces a synthetic chain // create transaction. TxTypeCreateKeyBook TransactionType = 0x0D // TxTypeAddCredits converts ACME tokens to credits, which produces a // synthetic deposit credits transaction. TxTypeAddCredits TransactionType = 0x0E // TxTypeUpdateKeyPage adds, removes, or updates keys in a key page, which // *does not* produce a synthetic transaction. TxTypeUpdateKeyPage TransactionType = 0x0F // TxTypeSignPending is used to sign a pending transaction. TxTypeSignPending TransactionType = 0x30 ) // Synthetic transactions const ( // TxTypeSyntheticCreateChain creates or updates chains. TxTypeSyntheticCreateChain TransactionType = 0x31 // TxTypeSyntheticWriteData writes data to a data account. TxTypeSyntheticWriteData TransactionType = 0x32 // TxTypeSyntheticDepositTokens deposits tokens into token accounts. TxTypeSyntheticDepositTokens TransactionType = 0x33 // TxTypeSyntheticAnchor anchors one network to another. TxTypeSyntheticAnchor TransactionType = 0x34 // TxTypeSyntheticDepositCredits deposits credits into a credit holder. TxTypeSyntheticDepositCredits TransactionType = 0x35 // TxTypeSyntheticBurnTokens returns tokens to a token issuer's pool of // issuable tokens. TxTypeSyntheticBurnTokens TransactionType = 0x36 // TxTypeSyntheticMirror mirrors records from one network to another. TxTypeSyntheticMirror TransactionType = 0x38 // TxTypeSegWitDataEntry is a surrogate transaction segregated witness for // a WriteData transaction TxTypeSegWitDataEntry TransactionType = 0x39 ) const ( // TxTypeInternalGenesis initializes system chains. TxTypeInternalGenesis TransactionType = 0x60 TxTypeInternalSendTransactions TransactionType = 0x61 // TxTypeInternalTransactionsSigned notifies the executor of synthetic // transactions that have been signed. TxTypeInternalTransactionsSigned TransactionType = 0x62 // TxTypeInternalTransactionsSent notifies the executor of synthetic // transactions that have been sent. TxTypeInternalTransactionsSent TransactionType = 0x63 ) // IsUser returns true if the transaction type is user. func (t TransactionType) IsUser() bool { return TxTypeUnknown < t && t <= txMaxUser } // IsSynthetic returns true if the transaction type is synthetic. func (t TransactionType) IsSynthetic() bool { return txMaxUser < t && t <= txMaxSynthetic } // IsInternal returns true if the transaction type is internal. func (t TransactionType) IsInternal() bool { return txMaxSynthetic < t && t <= txMaxInternal } // ID returns the transaction type ID func (t TransactionType) ID() uint64 { return uint64(t) } // String returns the name of the transaction type func (t TransactionType) String() string { switch t { case TxTypeUnknown: return "unknown" case TxTypeCreateIdentity: return "createIdentity" case TxTypeCreateTokenAccount: return "createTokenAccount" case TxTypeSendTokens: return "sendTokens" case TxTypeCreateDataAccount: return "createDataAccount" case TxTypeWriteData: return "writeData" case TxTypeWriteDataTo: return "writeDataTo" case TxTypeAcmeFaucet: return "acmeFaucet" case TxTypeCreateToken: return "createToken" case TxTypeIssueTokens: return "issueTokens" case TxTypeBurnTokens: return "burnTokens" case TxTypeCreateKeyPage: return "createKeyPage" case TxTypeCreateKeyBook: return "createKeyBook" case TxTypeAddCredits: return "addCredits" case TxTypeUpdateKeyPage: return "updateKeyPage" case TxTypeSignPending: return "signPending" case TxTypeSyntheticCreateChain: return "syntheticCreateChain" case TxTypeSyntheticWriteData: return "syntheticWriteData" case TxTypeSyntheticDepositTokens: return "syntheticDepositTokens" case TxTypeSyntheticAnchor: return "syntheticAnchor" case TxTypeSyntheticDepositCredits: return "syntheticDepositCredits" case TxTypeSyntheticBurnTokens: return "syntheticBurnTokens" case TxTypeSyntheticMirror: return "syntheticMirror" case TxTypeSegWitDataEntry: return "segWitDataEntry" case TxTypeInternalGenesis: return "genesis" case TxTypeInternalSendTransactions: return "sendTransactions" case TxTypeInternalTransactionsSigned: return "transactionsSigned" case TxTypeInternalTransactionsSent: return "transactionsSent" default: return fmt.Sprintf("TransactionType:%d", t) } } // Name is an alias for String // Deprecated: use String func (t TransactionType) Name() string { return t.String() } var txByName = map[string]TransactionType{} func init() { for t := TxTypeUnknown; t < txMaxInternal; t++ { txByName[t.String()] = t } } func (t *TransactionType) UnmarshalJSON(data []byte) error { var s string err := json.Unmarshal(data, &s) if err != nil { return err } var ok bool *t, ok = txByName[s] if !ok || strings.ContainsRune(t.String(), ':') { return fmt.Errorf("invalid transaction type %q", s) } return nil } func (t TransactionType) MarshalJSON() ([]byte, error) { return json.Marshal(t.String()) } func (t TransactionType) BinarySize() int { return encoding.UvarintBinarySize(t.ID()) } func (t TransactionType) MarshalBinary() ([]byte, error) { return encoding.UvarintMarshalBinary(t.ID()), nil } func (t *TransactionType) UnmarshalBinary(data []byte) error { v, err := encoding.UvarintUnmarshalBinary(data) if err != nil { return err } *t = TransactionType(v) return nil }
types/transaction_types.go
0.635109
0.441432
transaction_types.go
starcoder
package matrigo import "math" // Map applies f to every element of the matrix and returns the result. func Map(m Matrix, f Mapper) Matrix { n := New(m.Rows, m.Columns, nil) for i := 0; i < m.Rows; i++ { for j := 0; j < m.Columns; j++ { val := m.Data[i][j] n.Data[i][j] = f(val, i, j) } } return n } // Fold accumulates the values in a matrix according to a Folder function. func Fold(m Matrix, f Folder, accumulator float64) float64 { for i := 0; i < m.Rows; i++ { for j := 0; j < m.Columns; j++ { accumulator = f(accumulator, m.Data[i][j], i, j) } } return accumulator } // Transpose returns the transposed version of the matrix. func Transpose(m Matrix) Matrix { return Map(New(m.Columns, m.Rows, nil), func(val float64, x, y int) float64 { return m.Data[y][x] }) } // Multiply does scalar multiplication. func Multiply(m Matrix, a float64) Matrix { return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] * a }) } // Divide does scalar division. func Divide(m Matrix, a float64) Matrix { return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] / a }) } // Sum gives the sum of the elements in the matrix. func Sum(m Matrix) float64 { return m.Fold(func(accumulator, val float64, x, y int) float64 { return accumulator + val }, 0) } // Det computes the determinant. func Det(m Matrix) float64 { // Base case -> det([[x]]) = x if m.Rows == 1 && m.Columns == 1 { return m.Data[0][0] } // Remove 1st Row and n-th column f := func(m Matrix, n int) Matrix { data := [][]float64{} for i, row := range m.Data { // Skip first row if i == 0 { continue } current := []float64{} for j, col := range row { // Skip n-th column if j == n { continue } current = append(current, col) } data = append(data, current) } return New(m.Rows-1, m.Columns-1, data) } det := 0.0 for n, v := range m.Data[0] { det += math.Pow(-1, float64(n)) * v * Det(f(m, n)) } return det } // AddMatrix adds 2 matrices together. func AddMatrix(m, n Matrix) Matrix { if m.Rows != n.Rows || m.Columns != n.Columns { panic("matrix: can't add different sized matricies") } return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] + n.Data[x][y] }) } // Add does scalar addition. func Add(m Matrix, n float64) Matrix { return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] + n }) } // SubtractMatrix subtracts 2 matrices. func SubtractMatrix(m, n Matrix) Matrix { if m.Rows != n.Rows || m.Columns != n.Columns { panic("matrix: can't subtract different sized matricies") } return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] - n.Data[x][y] }) } // Subtract does scalar subtraction. func Subtract(m Matrix, n float64) Matrix { return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] - n }) } // HadamardProduct does Hadamard Product (entrywise). func HadamardProduct(m Matrix, n Matrix) Matrix { if m.Columns != n.Columns || m.Rows != n.Rows { panic("matrix: matricies must have the same shape") } return Map(New(m.Rows, m.Columns, nil), func(val float64, x, y int) float64 { return m.Data[x][y] * n.Data[x][y] }) } // DotProduct does matrix product. func DotProduct(m, n Matrix) Matrix { if m.Columns != n.Rows { panic("matrix: rows must match with columns of matricies") } return Map(New(m.Rows, n.Columns, nil), func(_ float64, x, y int) float64 { sum := 0.0 for i := 0; i < n.Rows; i++ { sum += m.Data[x][i] * n.Data[i][y] } return sum }) }
funcs.go
0.912843
0.679209
funcs.go
starcoder
package graphql // Errors is a linked list that contains Error values. type Errors struct { Data Error next *Errors pos int } // Add appends a Error to this linked list and returns this new head. func (es *Errors) Add(data Error) *Errors { var pos int if es != nil { pos = es.pos + 1 } return &Errors{ Data: data, next: es, pos: pos, } } // ForEach applies the given map function to each item in this linked list. func (es *Errors) ForEach(fn func(e Error, i int)) { if es == nil { return } iter := 0 current := es for { fn(current.Data, iter) if current.next == nil { break } iter++ current = current.next } } // ErrorsGenerator is a type used to iterate efficiently over Errors. // @wg:ignore type ErrorsGenerator struct { original *Errors current *Errors iter int length int } // Next returns the current value, and it's index in the list, and sets up the next value to be // returned. func (g *ErrorsGenerator) Next() (Error, int) { if g.current == nil { return Error{}, -1 } retv := g.current.Data reti := g.iter g.current = g.current.next g.iter++ return retv, reti } // Reset returns this generator to it's initial state, allowing it to be used again to iterate over // this linked list. func (g *ErrorsGenerator) Reset() { g.current = g.original g.iter = 0 } // Generator returns a "Generator" type for this list, allowing for much more efficient iteration // over items within this linked list than using ForEach, though ForEach may still be more // convenient, because ForEach is a high order function, it's slower. func (es *Errors) Generator() ErrorsGenerator { return ErrorsGenerator{ current: es, iter: 0, length: es.Len(), } } // Insert places the Error in the position given by pos. // The method will insert at top if pos is greater than or equal to list length. // The method will insert at bottom if the pos is less than 0. func (es *Errors) Insert(e Error, pos int) *Errors { if pos >= es.Len() || es == nil { return es.Add(e) } if pos < 0 { pos = 0 } mid := es for mid.pos != pos { mid = mid.next } bot := mid.next mid.next = nil es.pos -= mid.pos bot = bot.Add(e) es.Join(bot) return es } // Join attaches the tail of the receiver list "es" to the head of the otherList. func (es *Errors) Join(otherList *Errors) { if es == nil { return } pos := es.Len() + otherList.Len() - 1 last := es for es != nil { es.pos = pos pos-- last = es es = es.next } last.next = otherList } // Len returns the length of this linked list. func (es *Errors) Len() int { if es == nil { return 0 } return es.pos + 1 } // Reverse reverses this linked list of Error. Usually when the linked list is being // constructed the result will be last-to-first, so we'll want to reverse it to get it in the // "right" order. func (es *Errors) Reverse() *Errors { current := es var prev *Errors var pos int for current != nil { current.pos = pos pos++ next := current.next current.next = prev prev = current current = next } return prev } // ErrorsFromSlice returns a Errors list from a slice of Error. func ErrorsFromSlice(sl []Error) *Errors { var list *Errors for _, v := range sl { list = list.Add(v) } return list.Reverse() }
graphql/lists.go
0.7917
0.4133
lists.go
starcoder
package fractales import ( "math" "math/big" "math/cmplx" "github.com/Balise42/marzipango/params" ) // JuliaContinuousValueLow returns the fractional number of iterations corresponding to a complex in the Julia set in low precision func JuliaContinuousValueLow(z complex128, maxiter int) (float64, bool) { c := -0.4 + 0.6i for i := 0; i < maxiter; i++ { z = z*z + c if absz := cmplx.Abs(z); absz > r { return (float64(i) + 1 - math.Log2(math.Log2(absz))), true } } return math.MaxInt64, false } // JuliaContinuousValueComputerLow returns a ValueComputation for the julia set with low precision input func JuliaContinuousValueComputerLow(params params.ImageParams) ValueComputation { return func(x int, y int) (float64, bool) { return JuliaContinuousValueLow(scale(x, y, params), params.MaxIter) } } // JuliaContinuousValueHigh returns the fractional number of iterations corresponding to a complex in the Julia set in high precision func JuliaContinuousValueHigh(z LargeComplex, maxiter int) (float64, bool) { c := LargeComplex{big.NewFloat(-0.4), big.NewFloat(0.6)} for i := 0; i < maxiter; i++ { z = z.Square().Add(&c) if absz := z.Abs64(); absz > r { return (float64(i) + 1 - math.Log2(math.Log2(absz))), true } } return math.MaxInt64, false } // JuliaContinuousValueComputerHigh returns a ValueComputation for the julia set with high precision input func JuliaContinuousValueComputerHigh(params params.ImageParams) ValueComputation { return func(x int, y int) (float64, bool) { return JuliaContinuousValueHigh(scaleHigh(x, y, params), params.MaxIter) } } // JuliaOrbitValueLow returns the distance to the closest orbit hit by the computation of iterations corresponding to a complex in the Julia set in low precision func JuliaOrbitValueLow(z complex128, maxiter int, orbits []params.Orbit) (float64, bool) { dist := math.MaxFloat64 c := -0.4 + 0.6i i := 0 for i < maxiter && cmplx.Abs(z) < 4 { z = z*z + c for _, orbit := range orbits { dist = math.Min(dist, orbit.GetOrbitValue(orbit.GetOrbitFastValue(z))) } i++ } if i == maxiter { return math.MaxFloat64, false } return dist, true } // JuliaOrbitValueComputerLow returns a ValueComputation for the julia set with orbit trapping func JuliaOrbitValueComputerLow(params params.ImageParams, orbits []params.Orbit) ValueComputation { return func(x int, y int) (float64, bool) { return JuliaOrbitValueLow(scale(x, y, params), params.MaxIter, orbits) } }
fractales/julia.go
0.866472
0.509276
julia.go
starcoder
package edlib import "github.com/xybydy/go-edlib/internal/utils" // LevenshteinDistance calculate the distance between two string // This algorithm allow insertions, deletions and substitutions to change one string to the second // Compatible with non-ASCII characters func LevenshteinDistance(str1, str2 string) int { // Convert string parameters to rune arrays to be compatible with non-ASCII runeStr1 := []rune(str1) runeStr2 := []rune(str2) // Get and store length of these strings runeStr1len := len(runeStr1) runeStr2len := len(runeStr2) if runeStr1len == 0 { return runeStr2len } else if runeStr2len == 0 { return runeStr1len } else if utils.Equal(runeStr1, runeStr2) { return 0 } column := make([]int, runeStr1len+1) for y := 1; y <= runeStr1len; y++ { column[y] = y } for x := 1; x <= runeStr2len; x++ { column[0] = x lastkey := x - 1 for y := 1; y <= runeStr1len; y++ { oldkey := column[y] var i int if runeStr1[y-1] != runeStr2[x-1] { i = 1 } column[y] = utils.Min( utils.Min(column[y]+1, // insert column[y-1]+1), // delete lastkey+i) // substitution lastkey = oldkey } } return column[runeStr1len] } // OSADamerauLevenshteinDistance calculate the distance between two string // Optimal string alignment distance variant that use extension of the Wagner-Fisher dynamic programming algorithm // Doesn't allow multiple transformations on a same substring // Allowing insertions, deletions, substitutions and transpositions to change one string to the second // Compatible with non-ASCII characters func OSADamerauLevenshteinDistance(str1, str2 string) int { // Convert string parameters to rune arrays to be compatible with non-ASCII runeStr1 := []rune(str1) runeStr2 := []rune(str2) // Get and store length of these strings runeStr1len := len(runeStr1) runeStr2len := len(runeStr2) if runeStr1len == 0 { return runeStr2len } else if runeStr2len == 0 { return runeStr1len } else if utils.Equal(runeStr1, runeStr2) { return 0 } // 2D Array matrix := make([][]int, runeStr1len+1) for i := 0; i <= runeStr1len; i++ { matrix[i] = make([]int, runeStr2len+1) for j := 0; j <= runeStr2len; j++ { matrix[i][j] = 0 } } for i := 0; i <= runeStr1len; i++ { matrix[i][0] = i } for j := 0; j <= runeStr2len; j++ { matrix[0][j] = j } var count int for i := 1; i <= runeStr1len; i++ { for j := 1; j <= runeStr2len; j++ { if runeStr1[i-1] == runeStr2[j-1] { count = 0 } else { count = 1 } matrix[i][j] = utils.Min(utils.Min(matrix[i-1][j]+1, matrix[i][j-1]+1), matrix[i-1][j-1]+count) // insertion, deletion, substitution if i > 1 && j > 1 && runeStr1[i-1] == runeStr2[j-2] && runeStr1[i-2] == runeStr2[j-1] { matrix[i][j] = utils.Min(matrix[i][j], matrix[i-2][j-2]+1) // translation } } } return matrix[runeStr1len][runeStr2len] } // DamerauLevenshteinDistance calculate the distance between two string // This algorithm computes the true Damerau–Levenshtein distance with adjacent transpositions // Allowing insertions, deletions, substitutions and transpositions to change one string to the second // Compatible with non-ASCII characters func DamerauLevenshteinDistance(str1, str2 string) int { // Convert string parameters to rune arrays to be compatible with non-ASCII runeStr1 := []rune(str1) runeStr2 := []rune(str2) // Get and store length of these strings runeStr1len := len(runeStr1) runeStr2len := len(runeStr2) if runeStr1len == 0 { return runeStr2len } else if runeStr2len == 0 { return runeStr1len } else if utils.Equal(runeStr1, runeStr2) { return 0 } // Create alphabet based on input strings da := make(map[rune]int) for i := 0; i < runeStr1len; i++ { da[runeStr1[i]] = 0 } for i := 0; i < runeStr2len; i++ { da[runeStr2[i]] = 0 } // 2D Array for distance matrix : matrix[0..str1.length+2][0..s2.length+2] matrix := make([][]int, runeStr1len+2) for i := 0; i <= runeStr1len+1; i++ { matrix[i] = make([]int, runeStr2len+2) for j := 0; j <= runeStr2len+1; j++ { matrix[i][j] = 0 } } // Maximum possible distance maxDist := runeStr1len + runeStr2len // Initialize matrix matrix[0][0] = maxDist for i := 0; i <= runeStr1len; i++ { matrix[i+1][0] = maxDist matrix[i+1][1] = i } for i := 0; i <= runeStr2len; i++ { matrix[0][i+1] = maxDist matrix[1][i+1] = i } // Process edit distance var cost int for i := 1; i <= runeStr1len; i++ { db := 0 for j := 1; j <= runeStr2len; j++ { i1 := da[runeStr2[j-1]] j1 := db if runeStr1[i-1] == runeStr2[j-1] { cost = 0 db = j } else { cost = 1 } matrix[i+1][j+1] = utils.Min( utils.Min( matrix[i+1][j]+1, // Addition matrix[i][j+1]+1), // Deletion utils.Min( matrix[i][j]+cost, // Substitution matrix[i1][j1]+(i-i1-1)+1+(j-j1-1))) // Transposition } da[runeStr1[i-1]] = i } return matrix[runeStr1len+1][runeStr2len+1] }
levenshtein.go
0.564819
0.438244
levenshtein.go
starcoder
package storetest import ( "context" "fmt" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/store" ) func TestRoleStore(t *testing.T, ss store.Store, s SqlStore) { t.Run("Save", func(t *testing.T) { testRoleStoreSave(t, ss) }) t.Run("Get", func(t *testing.T) { testRoleStoreGet(t, ss) }) t.Run("GetAll", func(t *testing.T) { testRoleStoreGetAll(t, ss) }) t.Run("GetByName", func(t *testing.T) { testRoleStoreGetByName(t, ss) }) t.Run("GetNames", func(t *testing.T) { testRoleStoreGetByNames(t, ss) }) t.Run("Delete", func(t *testing.T) { testRoleStoreDelete(t, ss) }) t.Run("PermanentDeleteAll", func(t *testing.T) { testRoleStorePermanentDeleteAll(t, ss) }) t.Run("LowerScopedChannelSchemeRoles_AllChannelSchemeRoles", func(t *testing.T) { testRoleStoreLowerScopedChannelSchemeRoles(t, ss) }) t.Run("ChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest", func(t *testing.T) { testRoleStoreChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest(t, ss, s) }) } func testRoleStoreSave(t *testing.T, ss store.Store) { // Save a new role. r1 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } d1, err := ss.Role().Save(r1) assert.NoError(t, err) assert.Len(t, d1.Id, 26) assert.Equal(t, r1.Name, d1.Name) assert.Equal(t, r1.DisplayName, d1.DisplayName) assert.Equal(t, r1.Description, d1.Description) assert.Equal(t, r1.Permissions, d1.Permissions) assert.Equal(t, r1.SchemeManaged, d1.SchemeManaged) // Change the role permissions and update. d1.Permissions = []string{ "invite_user", "add_user_to_team", "delete_public_channel", } d2, err := ss.Role().Save(d1) assert.NoError(t, err) assert.Len(t, d2.Id, 26) assert.Equal(t, r1.Name, d2.Name) assert.Equal(t, r1.DisplayName, d2.DisplayName) assert.Equal(t, r1.Description, d2.Description) assert.Equal(t, d1.Permissions, d2.Permissions) assert.Equal(t, r1.SchemeManaged, d2.SchemeManaged) // Try saving one with an invalid ID set. r3 := &model.Role{ Id: model.NewId(), Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } _, err = ss.Role().Save(r3) assert.Error(t, err) // Try saving one with a duplicate "name" field. r4 := &model.Role{ Name: r1.Name, DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } _, err = ss.Role().Save(r4) assert.Error(t, err) } func testRoleStoreGetAll(t *testing.T, ss store.Store) { prev, err := ss.Role().GetAll() require.NoError(t, err) prevCount := len(prev) // Save a role to test with. r1 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } _, err = ss.Role().Save(r1) require.NoError(t, err) r2 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } _, err = ss.Role().Save(r2) require.NoError(t, err) data, err := ss.Role().GetAll() require.NoError(t, err) assert.Len(t, data, prevCount+2) } func testRoleStoreGet(t *testing.T, ss store.Store) { // Save a role to test with. r1 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } d1, err := ss.Role().Save(r1) assert.NoError(t, err) assert.Len(t, d1.Id, 26) // Get a valid role d2, err := ss.Role().Get(d1.Id) assert.NoError(t, err) assert.Equal(t, d1.Id, d2.Id) assert.Equal(t, r1.Name, d2.Name) assert.Equal(t, r1.DisplayName, d2.DisplayName) assert.Equal(t, r1.Description, d2.Description) assert.Equal(t, r1.Permissions, d2.Permissions) assert.Equal(t, r1.SchemeManaged, d2.SchemeManaged) // Get an invalid role _, err = ss.Role().Get(model.NewId()) assert.Error(t, err) } func testRoleStoreGetByName(t *testing.T, ss store.Store) { // Save a role to test with. r1 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } d1, err := ss.Role().Save(r1) assert.NoError(t, err) assert.Len(t, d1.Id, 26) // Get a valid role d2, err := ss.Role().GetByName(context.Background(), d1.Name) assert.NoError(t, err) assert.Equal(t, d1.Id, d2.Id) assert.Equal(t, r1.Name, d2.Name) assert.Equal(t, r1.DisplayName, d2.DisplayName) assert.Equal(t, r1.Description, d2.Description) assert.Equal(t, r1.Permissions, d2.Permissions) assert.Equal(t, r1.SchemeManaged, d2.SchemeManaged) // Get an invalid role _, err = ss.Role().GetByName(context.Background(), model.NewId()) assert.Error(t, err) } func testRoleStoreGetByNames(t *testing.T, ss store.Store) { // Save some roles to test with. r1 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } r2 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "read_channel", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } r3 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "delete_private_channel", "add_user_to_team", }, SchemeManaged: false, } d1, err := ss.Role().Save(r1) assert.NoError(t, err) assert.Len(t, d1.Id, 26) d2, err := ss.Role().Save(r2) assert.NoError(t, err) assert.Len(t, d2.Id, 26) d3, err := ss.Role().Save(r3) assert.NoError(t, err) assert.Len(t, d3.Id, 26) // Get two valid roles. n4 := []string{r1.Name, r2.Name} roles4, err := ss.Role().GetByNames(n4) assert.NoError(t, err) assert.Len(t, roles4, 2) assert.Contains(t, roles4, d1) assert.Contains(t, roles4, d2) assert.NotContains(t, roles4, d3) // Get two invalid roles. n5 := []string{model.NewId(), model.NewId()} roles5, err := ss.Role().GetByNames(n5) assert.NoError(t, err) assert.Empty(t, roles5) // Get one valid one and one invalid one. n6 := []string{r1.Name, model.NewId()} roles6, err := ss.Role().GetByNames(n6) assert.NoError(t, err) assert.Len(t, roles6, 1) assert.Contains(t, roles6, d1) assert.NotContains(t, roles6, d2) assert.NotContains(t, roles6, d3) } func testRoleStoreDelete(t *testing.T, ss store.Store) { // Save a role to test with. r1 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } d1, err := ss.Role().Save(r1) assert.NoError(t, err) assert.Len(t, d1.Id, 26) // Check the role is there. _, err = ss.Role().Get(d1.Id) assert.NoError(t, err) // Delete the role. _, err = ss.Role().Delete(d1.Id) assert.NoError(t, err) // Check the role is deleted there. d2, err := ss.Role().Get(d1.Id) assert.NoError(t, err) assert.NotZero(t, d2.DeleteAt) d3, err := ss.Role().GetByName(context.Background(), d1.Name) assert.NoError(t, err) assert.NotZero(t, d3.DeleteAt) // Try and delete a role that does not exist. _, err = ss.Role().Delete(model.NewId()) assert.Error(t, err) } func testRoleStorePermanentDeleteAll(t *testing.T, ss store.Store) { r1 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "invite_user", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } r2 := &model.Role{ Name: model.NewId(), DisplayName: model.NewId(), Description: model.NewId(), Permissions: []string{ "read_channel", "create_public_channel", "add_user_to_team", }, SchemeManaged: false, } _, err := ss.Role().Save(r1) require.NoError(t, err) _, err = ss.Role().Save(r2) require.NoError(t, err) roles, err := ss.Role().GetByNames([]string{r1.Name, r2.Name}) assert.NoError(t, err) assert.Len(t, roles, 2) err = ss.Role().PermanentDeleteAll() assert.NoError(t, err) roles, err = ss.Role().GetByNames([]string{r1.Name, r2.Name}) assert.NoError(t, err) assert.Empty(t, roles) } func testRoleStoreLowerScopedChannelSchemeRoles(t *testing.T, ss store.Store) { createDefaultRoles(ss) teamScheme1 := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), Scope: model.SchemeScopeTeam, } teamScheme1, err := ss.Scheme().Save(teamScheme1) require.NoError(t, err) defer ss.Scheme().Delete(teamScheme1.Id) teamScheme2 := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), Scope: model.SchemeScopeTeam, } teamScheme2, err = ss.Scheme().Save(teamScheme2) require.NoError(t, err) defer ss.Scheme().Delete(teamScheme2.Id) channelScheme1 := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), Scope: model.SchemeScopeChannel, } channelScheme1, err = ss.Scheme().Save(channelScheme1) require.NoError(t, err) defer ss.Scheme().Delete(channelScheme1.Id) channelScheme2 := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), Scope: model.SchemeScopeChannel, } channelScheme2, err = ss.Scheme().Save(channelScheme2) require.NoError(t, err) defer ss.Scheme().Delete(channelScheme1.Id) team1 := &model.Team{ DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), Type: model.TeamOpen, SchemeId: &teamScheme1.Id, } team1, err = ss.Team().Save(team1) require.NoError(t, err) defer ss.Team().PermanentDelete(team1.Id) team2 := &model.Team{ DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), Type: model.TeamOpen, SchemeId: &teamScheme2.Id, } team2, err = ss.Team().Save(team2) require.NoError(t, err) defer ss.Team().PermanentDelete(team2.Id) channel1 := &model.Channel{ TeamId: team1.Id, DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", Type: model.ChannelTypeOpen, SchemeId: &channelScheme1.Id, } channel1, nErr := ss.Channel().Save(channel1, -1) require.NoError(t, nErr) defer ss.Channel().Delete(channel1.Id, 0) channel2 := &model.Channel{ TeamId: team2.Id, DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", Type: model.ChannelTypeOpen, SchemeId: &channelScheme2.Id, } channel2, nErr = ss.Channel().Save(channel2, -1) require.NoError(t, nErr) defer ss.Channel().Delete(channel2.Id, 0) t.Run("ChannelRolesUnderTeamRole", func(t *testing.T) { t.Run("guest role for the right team's channels are returned", func(t *testing.T) { actualRoles, err := ss.Role().ChannelRolesUnderTeamRole(teamScheme1.DefaultChannelGuestRole) require.NoError(t, err) var actualRoleNames []string for _, role := range actualRoles { actualRoleNames = append(actualRoleNames, role.Name) } require.Contains(t, actualRoleNames, channelScheme1.DefaultChannelGuestRole) require.NotContains(t, actualRoleNames, channelScheme2.DefaultChannelGuestRole) }) t.Run("user role for the right team's channels are returned", func(t *testing.T) { actualRoles, err := ss.Role().ChannelRolesUnderTeamRole(teamScheme1.DefaultChannelUserRole) require.NoError(t, err) var actualRoleNames []string for _, role := range actualRoles { actualRoleNames = append(actualRoleNames, role.Name) } require.Contains(t, actualRoleNames, channelScheme1.DefaultChannelUserRole) require.NotContains(t, actualRoleNames, channelScheme2.DefaultChannelUserRole) }) t.Run("admin role for the right team's channels are returned", func(t *testing.T) { actualRoles, err := ss.Role().ChannelRolesUnderTeamRole(teamScheme1.DefaultChannelAdminRole) require.NoError(t, err) var actualRoleNames []string for _, role := range actualRoles { actualRoleNames = append(actualRoleNames, role.Name) } require.Contains(t, actualRoleNames, channelScheme1.DefaultChannelAdminRole) require.NotContains(t, actualRoleNames, channelScheme2.DefaultChannelAdminRole) }) }) t.Run("AllChannelSchemeRoles", func(t *testing.T) { t.Run("guest role for the right team's channels are returned", func(t *testing.T) { actualRoles, err := ss.Role().AllChannelSchemeRoles() require.NoError(t, err) var actualRoleNames []string for _, role := range actualRoles { actualRoleNames = append(actualRoleNames, role.Name) } allRoleNames := []string{ channelScheme1.DefaultChannelGuestRole, channelScheme2.DefaultChannelGuestRole, channelScheme1.DefaultChannelUserRole, channelScheme2.DefaultChannelUserRole, channelScheme1.DefaultChannelAdminRole, channelScheme2.DefaultChannelAdminRole, } for _, roleName := range allRoleNames { require.Contains(t, actualRoleNames, roleName) } }) }) } func testRoleStoreChannelHigherScopedPermissionsBlankTeamSchemeChannelGuest(t *testing.T, ss store.Store, s SqlStore) { teamScheme := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), Scope: model.SchemeScopeTeam, } teamScheme, err := ss.Scheme().Save(teamScheme) require.NoError(t, err) defer ss.Scheme().Delete(teamScheme.Id) channelScheme := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), Description: model.NewId(), Scope: model.SchemeScopeChannel, } channelScheme, err = ss.Scheme().Save(channelScheme) require.NoError(t, err) defer ss.Scheme().Delete(channelScheme.Id) team := &model.Team{ DisplayName: "Name", Name: "zz" + model.NewId(), Email: MakeEmail(), Type: model.TeamOpen, SchemeId: &teamScheme.Id, } team, err = ss.Team().Save(team) require.NoError(t, err) defer ss.Team().PermanentDelete(team.Id) channel := &model.Channel{ TeamId: team.Id, DisplayName: "Display " + model.NewId(), Name: "zz" + model.NewId() + "b", Type: model.ChannelTypeOpen, SchemeId: &channelScheme.Id, } channel, nErr := ss.Channel().Save(channel, -1) require.NoError(t, nErr) defer ss.Channel().Delete(channel.Id, 0) channelSchemeUserRole, err := ss.Role().GetByName(context.Background(), channelScheme.DefaultChannelUserRole) require.NoError(t, err) channelSchemeUserRole.Permissions = []string{} _, err = ss.Role().Save(channelSchemeUserRole) require.NoError(t, err) teamSchemeUserRole, err := ss.Role().GetByName(context.Background(), teamScheme.DefaultChannelUserRole) require.NoError(t, err) teamSchemeUserRole.Permissions = []string{model.PermissionUploadFile.Id} _, err = ss.Role().Save(teamSchemeUserRole) require.NoError(t, err) // get the channel scheme user role again and ensure that it has the permission inherited from the team // scheme user role roleMapBefore, err := ss.Role().ChannelHigherScopedPermissions([]string{channelSchemeUserRole.Name}) require.NoError(t, err) // blank-out the guest role to simulate an old team scheme, ensure it's blank result, sqlErr := s.GetMaster().Exec(fmt.Sprintf("UPDATE Schemes SET DefaultChannelGuestRole = '' WHERE Id = '%s'", teamScheme.Id)) require.NoError(t, sqlErr) rows, serr := result.RowsAffected() require.NoError(t, serr) require.Equal(t, int64(1), rows) teamScheme, err = ss.Scheme().Get(teamScheme.Id) require.NoError(t, err) require.Equal(t, "", teamScheme.DefaultChannelGuestRole) // trigger a cache clear _, err = ss.Role().Save(channelSchemeUserRole) require.NoError(t, err) roleMapAfter, err := ss.Role().ChannelHigherScopedPermissions([]string{channelSchemeUserRole.Name}) require.NoError(t, err) require.Equal(t, len(roleMapBefore), len(roleMapAfter)) }
store/storetest/role_store.go
0.581065
0.488588
role_store.go
starcoder
package language import ( "bytes" "fmt" "reflect" "strconv" ) // Eval runs the expression in the environment func Eval(n Node, env *Environment) Object { switch node := n.(type) { case *ConditionalExpression: return Eval(node.Expression, env) case *UpdateExpression: return Eval(node.Expression, env) case *PrefixExpression: return evalPrefixExpression(node, env) case *InfixExpression: return evalInfixParts(node, env) case *IndexExpression: return evalIndex(node, env) case *BetweenExpression: return evalBetween(node, env) case *CallExpression: return evalFunctionCall(node, env) case *Identifier: return evalIdentifier(node, env) } return newError("unsupported expression: %s", n.String()) } // EvalUpdate runs the update expression in the environment func EvalUpdate(n Node, env *Environment) Object { switch node := n.(type) { case *UpdateExpression: return EvalUpdate(node.Expression, env) case *SetExpression: return evalSetExpression(node, env) case *InfixExpression: return evalInfixUpdate(node, env) case *IndexExpression: return evalIndex(node, env) case *CallExpression: return evalUpdateFunctionCall(node, env) case *Identifier: return evalIdentifier(node, env) } return newError("unsupported expression: %s", n.String()) } func newError(format string, a ...interface{}) *Error { return &Error{Message: fmt.Sprintf(format, a...)} } func isError(obj Object) bool { if obj != nil { return obj.Type() == ObjectTypeError } return false } func isNumber(obj Object) bool { if obj != nil { return obj.Type() == ObjectTypeNumber } return false } func isString(obj Object) bool { if obj != nil { return obj.Type() == ObjectTypeString } return false } func isUndefined(obj Object) bool { return obj == nil || obj == NULL } func isComparable(obj Object) bool { return comparableTypes[obj.Type()] || isUndefined(obj) } func matchTypes(typ ObjectType, objs ...Object) bool { for _, o := range objs { if typ != o.Type() { return false } } return true } func evalPrefixExpression(node *PrefixExpression, env *Environment) Object { right := Eval(node.Right, env) if isError(right) { return right } if node.Operator == NOT { return evalBangOperatorExpression(right) } return newError("unknown operator: %s %s", node.Operator, right.Type()) } func evalBangOperatorExpression(right Object) Object { switch right { case TRUE: return FALSE case FALSE: return TRUE default: return newError("unknown operator: NOT %s", right.Type()) } } func evalInfixParts(node *InfixExpression, env *Environment) Object { left := Eval(node.Left, env) if isError(left) { return left } right := Eval(node.Right, env) if isError(right) { return right } return evalInfixExpression(node.Operator, left, right) } func evalInfixExpression(operator string, left, right Object) Object { switch { case isComparable(left) && isComparable(right): return evalComparableInfixExpression(operator, left, right) case matchTypes(ObjectTypeBoolean, left, right): return evalBooleanInfixExpression(operator, left, right) case matchTypes(ObjectTypeNull, left, right): return evalNullInfixExpression(operator, left, right) case operator == "=": return nativeBoolToBooleanObject(equalObject(left, right)) case operator == "<>": return nativeBoolToBooleanObject(!equalObject(left, right)) case !matchTypes(left.Type(), left, right): return newError("type mismatch: %s %s %s", left.Type(), operator, right.Type()) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalNullInfixExpression(operator string, left, right Object) Object { switch operator { case "=": if isUndefined(left) || isUndefined(right) { return FALSE } return TRUE case "<>": if isUndefined(left) || isUndefined(right) { return TRUE } return FALSE } return FALSE } func evalComparableInfixExpression(operator string, left, right Object) Object { if isUndefined(left) || isUndefined(right) { return FALSE } switch left.Type() { case ObjectTypeNumber: return evalNumberInfixExpression(operator, left, right) case ObjectTypeString: return evalStringInfixExpression(operator, left, right) case ObjectTypeBinary: return evalBinaryInfixExpression(operator, left, right) } return newError("comparing types are not supported: %s %s %s", left.Type(), operator, right.Type()) } func evalNumberInfixExpression(operator string, left, right Object) Object { leftVal := left.(*Number).Value rightVal := right.(*Number).Value switch operator { case "<": return nativeBoolToBooleanObject(leftVal < rightVal) case "<=": return nativeBoolToBooleanObject(leftVal <= rightVal) case ">": return nativeBoolToBooleanObject(leftVal > rightVal) case ">=": return nativeBoolToBooleanObject(leftVal >= rightVal) case "=": return nativeBoolToBooleanObject(leftVal == rightVal) case "<>": return nativeBoolToBooleanObject(leftVal != rightVal) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalStringInfixExpression(operator string, left, right Object) Object { leftVal := left.(*String).Value rightVal := right.(*String).Value switch operator { case "<": return nativeBoolToBooleanObject(leftVal < rightVal) case "<=": return nativeBoolToBooleanObject(leftVal <= rightVal) case ">": return nativeBoolToBooleanObject(leftVal > rightVal) case ">=": return nativeBoolToBooleanObject(leftVal >= rightVal) case "=": return nativeBoolToBooleanObject(leftVal == rightVal) case "<>": return nativeBoolToBooleanObject(leftVal != rightVal) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalBinaryInfixExpression(operator string, left, right Object) Object { leftVal := left.(*Binary).Value rightVal := right.(*Binary).Value switch operator { case "<": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) < 0) case "<=": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) <= 0) case ">": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) > 0) case ">=": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) >= 0) case "=": return nativeBoolToBooleanObject(bytes.Equal(leftVal, rightVal)) case "<>": return nativeBoolToBooleanObject(!bytes.Equal(leftVal, rightVal)) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalBooleanInfixExpression(operator string, left, right Object) Object { if isUndefined(left) || isUndefined(right) { return FALSE } leftVal := left.(*Boolean).Value rightVal := right.(*Boolean).Value switch operator { case "AND": return nativeBoolToBooleanObject(leftVal && rightVal) case "OR": return nativeBoolToBooleanObject(leftVal || rightVal) case "=": return nativeBoolToBooleanObject(left == right) case "<>": return nativeBoolToBooleanObject(left != right) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func equalObject(left, right Object) bool { if !matchTypes(left.Type(), left, right) { return false } return reflect.DeepEqual(left, right) } func evalIdentifier(node *Identifier, env *Environment) Object { val, ok := env.Get(node.Value) if !ok { return NULL } return val } func evalIndex(node *IndexExpression, env *Environment) Object { positions, o, errObj := evalIndexPositions(node, env) if isError(errObj) { return errObj } var obj Object = o for i := len(positions) - 1; i >= 0; i-- { pos := positions[i] obj = pos.Get(obj) if isError(obj) { return obj } } return obj } type indexAccessor struct { kind ObjectType val interface{} operator Token } func (i indexAccessor) Get(container Object) Object { switch c := container.(type) { case *List: pos, ok := i.val.(int64) if i.kind == ObjectTypeList && ok { return c.Value[pos] } case *Map: pos, ok := i.val.(string) if i.kind == ObjectTypeMap && ok { val := c.Value[pos] if val == nil { return NULL } return val } } return newError("index operator %s not supporter: %q", i.operator.Literal, container.Type()) } func (i indexAccessor) Set(container, val Object) Object { switch c := container.(type) { case *List: pos, ok := i.val.(int64) if i.kind == ObjectTypeList && ok { if int64(len(c.Value)) > pos { c.Value[pos] = val return NULL } c.Value = append(c.Value, val) } case *Map: pos, ok := i.val.(string) if i.kind == ObjectTypeMap && ok { c.Value[pos] = val } return NULL } return newError("index operator not supporter: %q", container.Type()) } func evalIndexPositions(n Expression, env *Environment) ([]indexAccessor, Object, Object) { positions := []indexAccessor{} for { switch node := n.(type) { case *Identifier: obj, errObj := evalIndexObj(n, env) if isError(errObj) { return nil, nil, errObj } return positions, obj, nil case *IndexExpression: identifier, ok := node.Index.(*Identifier) if !ok { return nil, nil, newError("identifier expected: got %q", identifier.String()) } pos, errObj := evalIndexValue(identifier, node, env) if isError(errObj) { return positions, nil, errObj } positions = append(positions, pos) n = node.Left default: return nil, nil, newError("index operator not supported: got %q", n.String()) } } } func evalIndexObj(identifierExpression Expression, env *Environment) (Object, Object) { identifier, ok := identifierExpression.(*Identifier) if !ok { return nil, newError("identifier expected: got %q", identifierExpression.String()) } obj := evalIdentifier(identifier, env) switch obj.(type) { case *List: return obj, nil case *Map: return obj, nil case *Error: return nil, obj } return nil, newError("index operator not supported for %q", obj.Type()) } func evalIndexValue(node *Identifier, indexNode *IndexExpression, env *Environment) (indexAccessor, Object) { switch indexNode.Type { case ObjectTypeList: pos, errObj := evalListIndexValue(node, env) if isError(errObj) { return indexAccessor{}, errObj } return indexAccessor{val: pos, kind: indexNode.Type, operator: indexNode.Token}, NULL case ObjectTypeMap: pos, errObj := evalMapIndexValue(node, env) if isError(errObj) { return indexAccessor{}, errObj } return indexAccessor{val: pos, kind: indexNode.Type, operator: indexNode.Token}, NULL } return indexAccessor{}, newError("index operator not supported: got %q", node.String()) } func evalListIndexValue(node *Identifier, env *Environment) (int64, Object) { if n, err := strconv.Atoi(node.Token.Literal); err == nil { return int64(n), nil } obj := evalIdentifier(node, env) if isError(obj) { return 0, obj } number, ok := obj.(*Number) if !ok { return 0, newError("access index with [] only support N as index : got %q", obj.Type()) } return int64(number.Value), nil } func evalMapIndexValue(node *Identifier, env *Environment) (string, Object) { obj := evalIdentifier(node, env) if isError(obj) { return "", obj } str, ok := obj.(*String) if !ok { return node.Token.Literal, nil } return str.Value, nil } func evalBetween(node *BetweenExpression, env *Environment) Object { val := evalBetweenOperand(node.Left, env) if isError(val) { return val } min := evalBetweenOperand(node.Range[0], env) if isError(min) { return min } max := evalBetweenOperand(node.Range[1], env) if isError(max) { return max } if isUndefined(val) || isUndefined(min) || isUndefined(max) { return FALSE } if !matchTypes(val.Type(), val, min, max) { return newError("mismatch type: BETWEEN operands must have the same type") } b := compareRange(val, min, max) return b } func compareRange(value, min, max Object) Object { switch val := value.(type) { case *Number: left := evalNumberInfixExpression("<=", min, val) right := evalNumberInfixExpression("<=", val, max) return evalBooleanInfixExpression("AND", left, right) case *String: left := evalStringInfixExpression("<=", min, val) right := evalStringInfixExpression("<=", val, max) return evalBooleanInfixExpression("AND", left, right) case *Binary: left := evalBinaryInfixExpression("<=", min, val) right := evalBinaryInfixExpression("<=", val, max) return evalBooleanInfixExpression("AND", left, right) } return newError("unsupported type: between do not support comparing %s", value.Type()) } func evalBetweenOperand(exp Expression, env *Environment) Object { identifier, ok := exp.(*Identifier) if !ok { return newError("identifier expected: got %q", exp.String()) } val := evalIdentifier(identifier, env) if !comparableTypes[val.Type()] && !isUndefined(val) { return newError("unexpected type: %q should be a comparable type(N,S,B) got %q", exp.String(), val.Type()) } return val } func evalFunctionCall(node *CallExpression, env *Environment) Object { fn := evalFunctionCallIdentifer(node, env) if isError(fn) { return fn } funcObj, ok := fn.(*Function) if !ok { return newError("invalid function call; expression: " + node.String()) } if funcObj.ForUpdate { return newError("the function is not allowed in an condition expression; function: " + funcObj.Name) } args := evalExpressions(node.Arguments, env) if len(args) == 1 && isError(args[0]) { return args[0] } return fn.(*Function).Value(args...) } func evalUpdateFunctionCall(node *CallExpression, env *Environment) Object { fn := evalFunctionCallIdentifer(node, env) if isError(fn) { return fn } funcObj, ok := fn.(*Function) if !ok { return newError("invalid function call; expression: " + node.String()) } if !funcObj.ForUpdate { return newError("the function is not allowed in an update expression; function: " + funcObj.Name) } args := evalExpressions(node.Arguments, env) if len(args) == 1 && isError(args[0]) { return args[0] } return fn.(*Function).Value(args...) } func evalFunctionCallIdentifer(node *CallExpression, env *Environment) Object { functionIdentifier, ok := node.Function.(*Identifier) if !ok { return newError("bad function syntax") } name := functionIdentifier.Value fn, ok := functions[name] if !ok { return newError("invalid function name; function: " + name) } return fn } func evalSetExpression(node *SetExpression, env *Environment) Object { if len(node.Expressions) == 0 { return newError("SET expression must have at least one action") } for _, act := range node.Expressions { infix, ok := act.(*InfixExpression) if !ok { return newError("invalid infix action") } result := EvalUpdate(infix, env) if isError(result) { return result } } return NULL } func evalInfixUpdate(node *InfixExpression, env *Environment) Object { switch node.Operator { case "=": val := EvalUpdate(node.Right, env) if isError(val) { return val } id, ok := node.Left.(*Identifier) if ok { env.Set(id.Value, val) return NULL } indexField, ok := node.Left.(*IndexExpression) if ok { errObj := evalAssignIndex(indexField, []int{}, val, env) if isError(errObj) { return errObj } return NULL } return newError("invalid assignation to: %s", node.String()) case "+": augend, addend, errObj := evalArithmeticTerms(node, env) if isError(errObj) { return errObj } return &Number{Value: augend.Value + addend.Value} case "-": minuend, subtrahend, errObj := evalArithmeticTerms(node, env) if isError(errObj) { return errObj } return &Number{Value: minuend.Value - subtrahend.Value} } return newError("unknown operator: %s", node.Operator) } func evalAssignIndex(n Expression, i []int, val Object, env *Environment) Object { positions, o, errObj := evalIndexPositions(n, env) if isError(errObj) { return errObj } var obj Object = o for i := len(positions) - 1; i >= 0; i-- { pos := positions[i] if i == 0 { pos.Set(obj, val) break } obj = pos.Get(obj) } return NULL } func evalArithmeticTerms(node *InfixExpression, env *Environment) (*Number, *Number, Object) { leftTerm := EvalUpdate(node.Left, env) if isError(leftTerm) { return nil, nil, leftTerm } rightTerm := EvalUpdate(node.Right, env) if isError(rightTerm) { return nil, nil, rightTerm } leftNumber, ok := leftTerm.(*Number) if !ok { return nil, nil, newError("invalid operation: %s %s %s", leftTerm.Type(), node.Operator, rightTerm.Type()) } rightNumber, ok := rightTerm.(*Number) if !ok { return nil, nil, newError("invalid operation: %s %s %s", leftTerm.Type(), node.Operator, rightTerm.Type()) } return leftNumber, rightNumber, NULL } func evalExpressions(exps []Expression, env *Environment) []Object { var result []Object for _, e := range exps { evaluated := Eval(e, env) if isError(evaluated) { return []Object{evaluated} } result = append(result, evaluated) } return result }
interpreter/language/evaluator.go
0.728169
0.441492
evaluator.go
starcoder
package main import ( "bytes" "fmt" "github.com/ecc1/crossword" ) const ( Across = crossword.Across Down = crossword.Down blackSquare = '.' emptySquare = ' ' wrongSquare = '?' ) var ( cells crossword.Grid homePos crossword.Position endPos crossword.Position cur crossword.Position curWord crossword.Word curDirection crossword.Direction ) func initGame() { cells = puz.MakeGrid() for y := 0; y < puz.Height; y++ { cells[y] = make([]byte, puz.Width) for x := 0; x < puz.Width; x++ { if puz.IsBlack(x, y) { cells[y][x] = blackSquare } else { cells[y][x] = emptySquare } } } curDirection = Across d := &puz.Dir[curDirection] homePos = d.Positions[1] cur = homePos lastNum := d.Numbers[len(d.Numbers)-1] endPos = d.Positions[lastNum] } func getContents() []byte { return cells.Contents() } func setContents(contents []byte) error { contents = bytes.ReplaceAll(contents, []byte{'\n'}, nil) if len(contents) != puz.Width*puz.Height { return fmt.Errorf("contents do not match this puzzle") } for y := 0; y < puz.Height; y++ { for x := 0; x < puz.Width; x++ { if !puz.IsBlack(x, y) { cells[y][x] = contents[0] redrawSquare(x, y) } contents = contents[1:] } } return nil } func puzzleIsSolved() bool { return bytes.Equal(getContents(), puz.SolutionBytes()) } func moveHome() { setActivePos(homePos) } func moveEnd() { setActivePos(endPos) } func moveLeft() { if curDirection == Down { changeDirection() return } moveBackward(false) } func moveRight() { if curDirection == Down { changeDirection() return } moveForward(false) } func moveUp() { if curDirection == Across { changeDirection() return } moveBackward(false) } func moveDown() { if curDirection == Across { changeDirection() return } moveForward(false) } func updateSquare(c uint) { cells[cur.Y][cur.X] = byte(c) redrawSquare(cur.X, cur.Y) if puzzleIsSolved() { winnerWinner() } } func eraseSquare() { updateSquare(emptySquare) } func backspaceSquare() { updateSquare(emptySquare) moveBackward(false) } func changeDirection() { curDirection = 1 - curDirection setActivePos(cur) } func setActivePos(pos crossword.Position) { cur = pos d := &puz.Dir[curDirection] oldWord := curWord num := int(d.Start[cur.Y][cur.X]) if num == 0 { // No word in this direction. return } curWord = d.Words[num] redrawWord(oldWord) redrawWord(curWord) highlightClues() } func setActive(x, y int) { setActivePos(crossword.NewPosition(x, y)) } func redrawWord(word crossword.Word) { for _, pos := range word { redrawSquare(pos.X, pos.Y) } } func isActive(x, y int) bool { return x == cur.X && y == cur.Y } func inActiveWord(x, y int) bool { return positionInWord(crossword.NewPosition(x, y), curWord) != -1 } func positionInWord(pos crossword.Position, word crossword.Word) int { for i, p := range word { if p == pos { return i } } return -1 } func moveForward(skip bool) { d := &puz.Dir[curDirection] num := int(d.Start[cur.Y][cur.X]) if num == 0 { // No word in this direction. return } word := d.Words[num] i := positionInWord(cur, word) if i == -1 { panic("moveForward") } for i < len(word)-1 { i++ pos := word[i] if !skip || cells[pos.Y][pos.X] == emptySquare { setActivePos(pos) return } } // Find the next empty square, if any. for k := d.Indexes[num] + 1; k < len(d.Numbers); k++ { num := d.Numbers[k] word := d.Words[num] for _, pos := range word { if cells[pos.Y][pos.X] == emptySquare { setActivePos(pos) return } } // This word is all filled in, try the next. } } func moveBackward(skip bool) { d := &puz.Dir[curDirection] num := int(d.Start[cur.Y][cur.X]) if num == 0 { // No word in this direction. return } word := d.Words[num] i := positionInWord(cur, word) if i == -1 { panic("moveBackward") } for i > 0 { i-- pos := word[i] if !skip || cells[pos.Y][pos.X] == emptySquare { setActivePos(pos) return } } k := d.Indexes[num] // If not on the first word, move to the end of the previous one. if k > 0 { prevNum := d.Numbers[k-1] prevWord := d.Words[prevNum] setActivePos(prevWord[len(prevWord)-1]) } } func activateFromClue(dir crossword.Direction, n int) { pos := puz.Dir[dir].Positions[n] curDirection = dir setActive(pos.X, pos.Y) } func highlightClues() { for dir, d := range puz.Dir { num := int(d.Start[cur.Y][cur.X]) if num == 0 { // No word in this direction. continue } i := d.Indexes[num] selectClue(crossword.Direction(dir), i) } } func checkSquare(x, y int) { c := cells[y][x] if c == emptySquare || c == puz.Answer(x, y) { return } cells[y][x] = wrongSquare redrawSquare(x, y) } func checkWord() { for _, pos := range curWord { checkSquare(pos.X, pos.Y) } } func checkPuzzle() { for y := 0; y < puz.Height; y++ { for x := 0; x < puz.Width; x++ { if puz.IsBlack(x, y) { continue } checkSquare(x, y) } } } func solveWord() { for _, pos := range curWord { x, y := pos.X, pos.Y cells[y][x] = puz.Answer(x, y) redrawSquare(x, y) } } func solvePuzzle() { setContents(puz.SolutionBytes()) }
cmd/playpuz/game.go
0.503906
0.414543
game.go
starcoder
package avl import ( "golang.org/x/exp/constraints" ) // Comparator is to compare keys type Comparator[Key any] func(a, b Key) int // Tree : AVL tree type Tree[Key any, Value any] struct { root *Node[Key, Value] comparator Comparator[Key] } // NewTree creates a new AVL tree func NewTree[Key any, Value any](comp Comparator[Key]) *Tree[Key, Value] { return &Tree[Key, Value]{nil, comp} } // NewTree creates a new AVL tree for comparable key types func NewTreeOrdered[Key constraints.Ordered, Value any]() *Tree[Key, Value] { return &Tree[Key, Value]{nil, func(a, b Key) int { if a < b { return 1 } else if a > b { return -1 } return 0 }} } func (t *Tree[Key, Value]) get(n *Node[Key, Value], key Key) (*Node[Key, Value], bool) { if n == nil { return nil, false } g := t.comparator(n.Key, key) if g == 0 { return n, true } else if g < 0 { return t.get(n.child[0], key) } else { return t.get(n.child[1], key) } } func (t *Tree[Key, Value]) index(n *Node[Key, Value], rank int) (*Node[Key, Value], bool) { if n == nil { return nil, false } m := nodeSizeOr(n.child[0]) if rank < m { return t.index(n.child[0], rank) } else if rank == m { return n, true } else { return t.index(n.child[1], rank-m-1) } } func (t *Tree[Key, Value]) rank(n *Node[Key, Value], key Key, prev int) int { if n == nil { return -1 } g := t.comparator(n.Key, key) if g == 0 { return prev + nodeSizeOr(n.child[0]) } else if g < 0 { return t.rank(n.child[0], key, prev) } else { return t.rank(n.child[1], key, prev+nodeSizeOr(n.child[0])+1) } } func (t *Tree[Key, Value]) set(n, p *Node[Key, Value], force bool) (*Node[Key, Value], bool) { if n == nil { return p, true } g := t.comparator(n.Key, p.Key) isChanged := false if g == 0 { if force { n.Val = p.Val } return n, false } else if g < 0 { n.child[0], isChanged = t.set(n.child[0], p, force) } else { n.child[1], isChanged = t.set(n.child[1], p, force) } if isChanged { n.size++ return balance(n), true } return n, false } func (t *Tree[Key, Value]) erase(n *Node[Key, Value], key Key) (*Node[Key, Value], bool) { if n == nil { return nil, false } g := t.comparator(n.Key, key) isChanged := false if g == 0 { return moveDown(n.child[0], n.child[1]), true } else if g < 0 { n.child[0], isChanged = t.erase(n.child[0], key) } else { n.child[1], isChanged = t.erase(n.child[1], key) } if isChanged { n.size-- return balance(n), true } return n, false } // Get returns the node whose key is 'key' and true. // If the key is not found, it returns nil and false. func (t *Tree[Key, Value]) Get(key Key) (*Node[Key, Value], bool) { return t.get(t.root, key) } // Index returns the node whose key is 'rank' th and true. // If the key is not found, it returns nil and false. func (t *Tree[Key, Value]) Index(rank int) (*Node[Key, Value], bool) { return t.index(t.root, rank) } // Rank returns the index of the node whose key is 'key'. // If the key is not found, it returns -1. func (t *Tree[Key, Value]) Rank(key Key) int { return t.rank(t.root, key, 0) } // Set adds a new node with 'key' and 'val' if a node with the key isn't found. // Set updates the node with 'key' and 'val' if a node with the key is found. func (t *Tree[Key, Value]) Set(key Key, val Value) { t.root, _ = t.set(t.root, newNode(key, val), true) } // Insert adds a new node with 'key' and 'val' if a node with the key isn't found. // Insert do nothing if a node with the key is found. func (t *Tree[Key, Value]) Insert(key Key, val Value) bool { var res bool t.root, res = t.set(t.root, newNode(key, val), false) return res } // Erase erases the node whose key is 'key' // If the key is not found, it returns false. func (t *Tree[Key, Value]) Erase(key Key) bool { var res bool t.root, res = t.erase(t.root, key) return res } // Size returns the size of the tree func (t *Tree[Key, Value]) Size() int { return nodeSizeOr(t.root) }
tree.go
0.74826
0.439988
tree.go
starcoder
package mocks import "github.com/control-center/serviced/dfs" import "github.com/stretchr/testify/mock" import "io" import "time" import "github.com/control-center/serviced/domain/service" type DFS struct { mock.Mock } // Lock provides a mock function with given fields: opName func (_m *DFS) Lock(opName string) { return } // LockWithTimeout provides a mock function with given fields: opName, timeout func (_m *DFS) LockWithTimeout(opName string, timeout time.Duration) error { return nil } // Unlock provides a mock function with given fields: func (_m *DFS) Unlock() { return } // Timeout provides a mock function with given fields: func (_m *DFS) Timeout() time.Duration { ret := _m.Called() var r0 time.Duration if rf, ok := ret.Get(0).(func() time.Duration); ok { r0 = rf() } else { r0 = ret.Get(0).(time.Duration) } return r0 } // Create provides a mock function with given fields: tenantID func (_m *DFS) Create(tenantID string) error { ret := _m.Called(tenantID) var r0 error if rf, ok := ret.Get(0).(func(string) error); ok { r0 = rf(tenantID) } else { r0 = ret.Error(0) } return r0 } // Destroy provides a mock function with given fields: tenantID func (_m *DFS) Destroy(tenantID string) error { ret := _m.Called(tenantID) var r0 error if rf, ok := ret.Get(0).(func(string) error); ok { r0 = rf(tenantID) } else { r0 = ret.Error(0) } return r0 } // Download provides a mock function with given fields: image, tenantID, upgrade func (_m *DFS) Download(image string, tenantID string, upgrade bool) (string, error) { ret := _m.Called(image, tenantID, upgrade) var r0 string if rf, ok := ret.Get(0).(func(string, string, bool) string); ok { r0 = rf(image, tenantID, upgrade) } else { r0 = ret.Get(0).(string) } var r1 error if rf, ok := ret.Get(1).(func(string, string, bool) error); ok { r1 = rf(image, tenantID, upgrade) } else { r1 = ret.Error(1) } return r0, r1 } // Commit provides a mock function with given fields: ctrID func (_m *DFS) Commit(ctrID string) (string, error) { ret := _m.Called(ctrID) var r0 string if rf, ok := ret.Get(0).(func(string) string); ok { r0 = rf(ctrID) } else { r0 = ret.Get(0).(string) } var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(ctrID) } else { r1 = ret.Error(1) } return r0, r1 } // Snapshot provides a mock function with given fields: info func (_m *DFS) Snapshot(info dfs.SnapshotInfo) (string, error) { ret := _m.Called(info) var r0 string if rf, ok := ret.Get(0).(func(dfs.SnapshotInfo) string); ok { r0 = rf(info) } else { r0 = ret.Get(0).(string) } var r1 error if rf, ok := ret.Get(1).(func(dfs.SnapshotInfo) error); ok { r1 = rf(info) } else { r1 = ret.Error(1) } return r0, r1 } // Rollback provides a mock function with given fields: snapshotID func (_m *DFS) Rollback(snapshotID string) error { ret := _m.Called(snapshotID) var r0 error if rf, ok := ret.Get(0).(func(string) error); ok { r0 = rf(snapshotID) } else { r0 = ret.Error(0) } return r0 } // Delete provides a mock function with given fields: snapshotID func (_m *DFS) Delete(snapshotID string) error { ret := _m.Called(snapshotID) var r0 error if rf, ok := ret.Get(0).(func(string) error); ok { r0 = rf(snapshotID) } else { r0 = ret.Error(0) } return r0 } // List provides a mock function with given fields: tenantID func (_m *DFS) List(tenantID string) ([]string, error) { ret := _m.Called(tenantID) var r0 []string if rf, ok := ret.Get(0).(func(string) []string); ok { r0 = rf(tenantID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]string) } } var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(tenantID) } else { r1 = ret.Error(1) } return r0, r1 } // Info provides a mock function with given fields: snapshotID func (_m *DFS) Info(snapshotID string) (*dfs.SnapshotInfo, error) { ret := _m.Called(snapshotID) var r0 *dfs.SnapshotInfo if rf, ok := ret.Get(0).(func(string) *dfs.SnapshotInfo); ok { r0 = rf(snapshotID) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dfs.SnapshotInfo) } } var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(snapshotID) } else { r1 = ret.Error(1) } return r0, r1 } // Backup provides a mock function with given fields: info, w func (_m *DFS) Backup(info dfs.BackupInfo, w io.Writer) error { ret := _m.Called(info, w) var r0 error if rf, ok := ret.Get(0).(func(dfs.BackupInfo, io.Writer) error); ok { r0 = rf(info, w) } else { r0 = ret.Error(0) } return r0 } // Restore provides a mock function with given fields: r, backupInfo func (_m *DFS) Restore(r io.Reader, backupInfo *dfs.BackupInfo) error { ret := _m.Called(r, backupInfo) var r0 error if rf, ok := ret.Get(0).(func(io.Reader, *dfs.BackupInfo) error); ok { r0 = rf(r, backupInfo) } else { r0 = ret.Error(0) } return r0 } // BackupInfo provides a mock function with given fields: r func (_m *DFS) BackupInfo(r io.Reader) (*dfs.BackupInfo, error) { ret := _m.Called(r) var r0 *dfs.BackupInfo if rf, ok := ret.Get(0).(func(io.Reader) *dfs.BackupInfo); ok { r0 = rf(r) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dfs.BackupInfo) } } var r1 error if rf, ok := ret.Get(1).(func(io.Reader) error); ok { r1 = rf(r) } else { r1 = ret.Error(1) } return r0, r1 } // Tag provides a mock function with given fields: snapshotID, tagName func (_m *DFS) Tag(snapshotID string, tagName string) error { ret := _m.Called(snapshotID, tagName) var r0 error if rf, ok := ret.Get(0).(func(string, string) error); ok { r0 = rf(snapshotID, tagName) } else { r0 = ret.Error(0) } return r0 } // Untag provides a mock function with given fields: tenantID, tagName func (_m *DFS) Untag(tenantID string, tagName string) (string, error) { ret := _m.Called(tenantID, tagName) var r0 string if rf, ok := ret.Get(0).(func(string, string) string); ok { r0 = rf(tenantID, tagName) } else { r0 = ret.Get(0).(string) } var r1 error if rf, ok := ret.Get(1).(func(string, string) error); ok { r1 = rf(tenantID, tagName) } else { r1 = ret.Error(1) } return r0, r1 } // TagInfo provides a mock function with given fields: tenantID, tagName func (_m *DFS) TagInfo(tenantID string, tagName string) (*dfs.SnapshotInfo, error) { ret := _m.Called(tenantID, tagName) var r0 *dfs.SnapshotInfo if rf, ok := ret.Get(0).(func(string, string) *dfs.SnapshotInfo); ok { r0 = rf(tenantID, tagName) } else { if ret.Get(0) != nil { r0 = ret.Get(0).(*dfs.SnapshotInfo) } } var r1 error if rf, ok := ret.Get(1).(func(string, string) error); ok { r1 = rf(tenantID, tagName) } else { r1 = ret.Error(1) } return r0, r1 } // UpgradeRegistry provides a mock function with given fields: svcs, tenantID, registryHost, override func (_m *DFS) UpgradeRegistry(svcs []service.Service, tenantID string, registryHost string, override bool) error { ret := _m.Called(svcs, tenantID, registryHost, override) var r0 error if rf, ok := ret.Get(0).(func([]service.Service, string, string, bool) error); ok { r0 = rf(svcs, tenantID, registryHost, override) } else { r0 = ret.Error(0) } return r0 } // Override provides a mock function with given fields: newImage, oldImage func (_m *DFS) Override(newImage string, oldImage string) error { ret := _m.Called(newImage, oldImage) var r0 error if rf, ok := ret.Get(0).(func(string, string) error); ok { r0 = rf(newImage, oldImage) } else { r0 = ret.Error(0) } return r0 }
dfs/mocks/DFS.go
0.679817
0.409811
DFS.go
starcoder
package block import ( "github.com/df-mc/dragonfly/server/block/cube" "github.com/df-mc/dragonfly/server/block/model" "github.com/df-mc/dragonfly/server/item" "github.com/df-mc/dragonfly/server/world" "github.com/go-gl/mathgl/mgl64" ) // WoodSlab is a half block that allows entities to walk up blocks without jumping. type WoodSlab struct { bass // Wood is the type of wood of the slabs. This field must have one of the values found in the material // package. Wood WoodType // Top specifies if the slab is in the top part of the block. Top bool // Double specifies if the slab is a double slab. These double slabs can be made by placing another slab // on an existing slab. Double bool } // FlammabilityInfo ... func (s WoodSlab) FlammabilityInfo() FlammabilityInfo { if !s.Wood.Flammable() { return newFlammabilityInfo(0, 0, false) } return newFlammabilityInfo(5, 20, true) } // Model ... func (s WoodSlab) Model() world.BlockModel { return model.Slab{Double: s.Double, Top: s.Top} } // UseOnBlock handles the placement of slabs with relation to them being upside down or not and handles slabs // being turned into double slabs. func (s WoodSlab) UseOnBlock(pos cube.Pos, face cube.Face, clickPos mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) { clickedBlock := w.Block(pos) if clickedSlab, ok := clickedBlock.(WoodSlab); ok && !s.Double { if (face == cube.FaceUp && !clickedSlab.Double && clickedSlab.Wood == s.Wood && !clickedSlab.Top) || (face == cube.FaceDown && !clickedSlab.Double && clickedSlab.Wood == s.Wood && clickedSlab.Top) { // A half slab of the same type was clicked at the top, so we can make it full. clickedSlab.Double = true place(w, pos, clickedSlab, user, ctx) return placed(ctx) } } if sideSlab, ok := w.Block(pos.Side(face)).(WoodSlab); ok && !replaceableWith(w, pos, s) && !s.Double { // The block on the side of the one clicked was a slab and the block clicked was not replaceableWith, so // the slab on the side must've been half and may now be filled if the wood types are the same. if !sideSlab.Double && sideSlab.Wood == s.Wood { sideSlab.Double = true place(w, pos.Side(face), sideSlab, user, ctx) return placed(ctx) } } pos, face, used = firstReplaceable(w, pos, face, s) if !used { return } if face == cube.FaceDown || (clickPos[1] > 0.5 && face != cube.FaceUp) { s.Top = true } place(w, pos, s, user, ctx) return placed(ctx) } // BreakInfo ... func (s WoodSlab) BreakInfo() BreakInfo { return newBreakInfo(2, alwaysHarvestable, axeEffective, func(item.Tool, []item.Enchantment) []item.Stack { if s.Double { s.Double = false // If the slab is double, it should drop two single slabs. return []item.Stack{item.NewStack(s, 2)} } return []item.Stack{item.NewStack(s, 1)} }) } // LightDiffusionLevel returns 0 if the slab is a half slab, or 15 if it is double. func (s WoodSlab) LightDiffusionLevel() uint8 { if s.Double { return 15 } return 0 } // EncodeItem ... func (s WoodSlab) EncodeItem() (name string, meta int16) { switch s.Wood { case OakWood(), SpruceWood(), BirchWood(), JungleWood(), AcaciaWood(), DarkOakWood(): if s.Double { return "minecraft:double_wooden_slab", int16(s.Wood.Uint8()) } return "minecraft:wooden_slab", int16(s.Wood.Uint8()) case CrimsonWood(): if s.Double { return "minecraft:crimson_double_slab", 0 } return "minecraft:crimson_slab", 0 case WarpedWood(): if s.Double { return "minecraft:warped_double_slab", 0 } return "minecraft:warped_slab", 0 } panic("invalid wood type") } // EncodeBlock ... func (s WoodSlab) EncodeBlock() (name string, properties map[string]interface{}) { if s.Double { if s.Wood == CrimsonWood() || s.Wood == WarpedWood() { return "minecraft:" + s.Wood.String() + "_double_slab", map[string]interface{}{"top_slot_bit": s.Top} } return "minecraft:double_wooden_slab", map[string]interface{}{"top_slot_bit": s.Top, "wood_type": s.Wood.String()} } if s.Wood == CrimsonWood() || s.Wood == WarpedWood() { return "minecraft:" + s.Wood.String() + "_slab", map[string]interface{}{"top_slot_bit": s.Top} } return "minecraft:wooden_slab", map[string]interface{}{"top_slot_bit": s.Top, "wood_type": s.Wood.String()} } // CanDisplace ... func (s WoodSlab) CanDisplace(b world.Liquid) bool { _, ok := b.(Water) return !s.Double && ok } // SideClosed ... func (s WoodSlab) SideClosed(pos, side cube.Pos, _ *world.World) bool { // Only returns true if the side is below the slab and if the slab is not upside down. return !s.Top && side[1] == pos[1]-1 } // allWoodSlabs returns all states of wood slabs. func allWoodSlabs() (slabs []world.Block) { f := func(double bool, upsideDown bool) { for _, w := range WoodTypes() { slabs = append(slabs, WoodSlab{Double: double, Top: upsideDown, Wood: w}) } } f(false, false) f(false, true) f(true, false) f(true, true) return }
server/block/wood_slab.go
0.642657
0.409752
wood_slab.go
starcoder
package main import "fmt" // Stack is the Abstract Data type following FIFO (First In First Out) principle which has certain functionalities like- // (a) push- Insert new data at one end // (b) pop- Remove (and return) data from the end insertion has happened // (c) peek- Return the data from the end insertion has happened (without removal) // There are many real-life examples of a stack. Consider an example of plates stacked over one // another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate // which has been placed at the bottommost position remains in the stack for the longest period of time. So, it // can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order. // Since Interface declares the functionalities of the type that defines it, // declaring the above mentioned methods in the interfaces essentially decalres // a Stack ADT. // Any data type which implements the Stack interface becomes the Stack ADT. it can // be an array, a Linked List, etc. In this case we are implementing Stack on a Linked List. // So Stack is the Abstract Data type and Linked List is the data structure here. type Stack interface { push(item int) pop() int peek() isEmpty() bool } // Check if stack is empty func (s *stack) isEmpty() bool { if s.head == nil { return true } return false } // Node of the linked list type node struct { data int next *node } // Stack always stores the address of the head node type stack struct { head *node } // push new element at one end func (s *stack) push(item int) { newNode := node{ data: item, next: nil, } if s.head == nil { s.head = &newNode } else { temp := s.head newNode.next = temp s.head = &newNode } fmt.Printf("PUSHED: %d\n", newNode.data) printStack(s) return } // remove and return the element from the same end as insertion func (s *stack) pop() int { if s.isEmpty() { fmt.Println("STACK UNDERFLOW!") return 0 } temp := s.head s.head = s.head.next return temp.data } // peek the top of the stack func (s *stack) peek() { temp := s.head for temp.next != nil { temp = temp.next } fmt.Println(temp.data) } func printStack(s *stack) { if s.head == nil { return } temp := s.head for temp != nil { fmt.Println(temp.data) temp = temp.next } } // constructor for new node func new() Stack { return &stack{ head: nil, } } func main() { st := new() st.push(1) st.push(2) st.push(3) st.push(4) st.push(5) fmt.Println("POP:", st.pop()) fmt.Println("POP:", st.pop()) fmt.Println("POP:", st.pop()) fmt.Println("POP:", st.pop()) fmt.Println("POP:", st.pop()) fmt.Println("POP:", st.pop()) }
Arpit Mishra/Go practice/stack.go
0.615088
0.536252
stack.go
starcoder
package missing_identity_propagation import ( "github.com/damianmcgrath/threagile/model" ) func Category() model.RiskCategory { return model.RiskCategory{ Id: "missing-identity-propagation", Title: "Missing Identity Propagation", Description: "Technical assets (especially multi-tenant systems), which usually process data for endusers should " + "authorize every request based on the identity of the enduser when the data flow is authenticated (i.e. non-public). " + "For DevOps usages at least a technical-user authorization is required.", Impact: "If this risk is unmitigated, attackers might be able to access or modify foreign data after a successful compromise of a component within " + "the system due to missing resource-based authorization checks.", ASVS: "V4 - Access Control Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Access_Control_Cheat_Sheet.html", Action: "Identity Propagation and Resource-based Authorization", Mitigation: "When processing requests for endusers if possible authorize in the backend against the propagated " + "identity of the enduser. This can be achieved in passing JWTs or similar tokens and checking them in the backend " + "services. For DevOps usages apply at least a technical-user authorization.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: model.Architecture, STRIDE: model.ElevationOfPrivilege, DetectionLogic: "In-scope service-like technical assets which usually process data based on enduser requests, if authenticated " + "(i.e. non-public), should authorize incoming requests based on the propagated enduser identity when their rating is sensitive. " + "This is especially the case for all multi-tenant assets (there even less-sensitive rated ones). " + "DevOps usages are exempted from this risk.", RiskAssessment: "The risk rating (medium or high) " + "depends on the confidentiality, integrity, and availability rating of the technical asset.", FalsePositives: "Technical assets which do not process requests regarding functionality or data linked to end-users (customers) " + "can be considered as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 284, } } func SupportedTags() []string { return []string{} } func GenerateRisks() []model.Risk { risks := make([]model.Risk, 0) for _, id := range model.SortedTechnicalAssetIDs() { technicalAsset := model.ParsedModelRoot.TechnicalAssets[id] if technicalAsset.OutOfScope { continue } if technicalAsset.Technology.IsUsuallyProcessingEnduserRequests() && (technicalAsset.Confidentiality >= model.Confidential || technicalAsset.Integrity >= model.Critical || technicalAsset.Availability >= model.Critical || (technicalAsset.MultiTenant && (technicalAsset.Confidentiality >= model.Restricted || technicalAsset.Integrity >= model.Important || technicalAsset.Availability >= model.Important))) { // check each incoming authenticated data flow commLinks := model.IncomingTechnicalCommunicationLinksMappedByTargetId[technicalAsset.Id] for _, commLink := range commLinks { caller := model.ParsedModelRoot.TechnicalAssets[commLink.SourceId] if !caller.Technology.IsUsuallyAbleToPropagateIdentityToOutgoingTargets() || caller.Type == model.Datastore { continue } if commLink.Authentication != model.NoneAuthentication && commLink.Authorization != model.EnduserIdentityPropagation { if commLink.Usage == model.DevOps && commLink.Authorization != model.NoneAuthorization { continue } highRisk := technicalAsset.Confidentiality == model.StrictlyConfidential || technicalAsset.Integrity == model.MissionCritical || technicalAsset.Availability == model.MissionCritical risks = append(risks, createRisk(technicalAsset, commLink, highRisk)) } } } } return risks } func createRisk(technicalAsset model.TechnicalAsset, incomingAccess model.CommunicationLink, moreRisky bool) model.Risk { impact := model.LowImpact if moreRisky { impact = model.MediumImpact } risk := model.Risk{ Category: Category(), Severity: model.CalculateSeverity(model.Unlikely, impact), ExploitationLikelihood: model.Unlikely, ExploitationImpact: impact, Title: "<b>Missing Enduser Identity Propagation</b> over communication link <b>" + incomingAccess.Title + "</b> " + "from <b>" + model.ParsedModelRoot.TechnicalAssets[incomingAccess.SourceId].Title + "</b> " + "to <b>" + technicalAsset.Title + "</b>", MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: incomingAccess.Id, DataBreachProbability: model.Improbable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.Category.Id + "@" + incomingAccess.Id + "@" + model.ParsedModelRoot.TechnicalAssets[incomingAccess.SourceId].Id + "@" + technicalAsset.Id return risk }
risks/built-in/missing-identity-propagation/missing-identity-propagation-rule.go
0.656328
0.465205
missing-identity-propagation-rule.go
starcoder
// +build ignore package main import ( "math" "math/cmplx" "github.com/cpmech/gosl/fun" "github.com/cpmech/gosl/plt" "github.com/cpmech/gosl/rnd" ) func main() { // fix seed rnd.Init(1111) // generate data π := math.Pi // 3.14159265359... Fs := 1000.0 // Sampling frequency T := 1.0 / Fs // Sampling period L := 1500 // Length of signal t := make([]float64, L) // Time vector xo := make([]float64, L) // Original signal containing a 50 Hz sinusoid of amplitude 0.7 and a 120 Hz sinusoid of amplitude 1. xc := make([]float64, L) // Corrupted signal with zero-mean noise a std-dev of 2. for i := 0; i < L; i++ { t[i] = float64(i) * T xo[i] = 0.7*math.Sin(2*π*50*t[i]) + math.Sin(2*π*120*t[i]) xc[i] = xo[i] + 2.0*rnd.Normal(0, 2) } // allocate data arrays oData := make([]complex128, L) cData := make([]complex128, L) for i := 0; i < L; i++ { oData[i] = complex(xo[i], 0) cData[i] = complex(xc[i], 0) } // compute the Fourier transform of original signal fun.Dft1d(oData, false) // compute the Fourier transform of corrupted signal fun.Dft1d(cData, false) // process results P := make([]float64, L/2+1) // single-sided spectrum of the original signal Q := make([]float64, L/2+1) // single-sided spectrum of the corrupted signal F := make([]float64, L/2+1) // frequency domain f for i := 0; i < L/2+1; i++ { P[i] = 2 * cmplx.Abs(oData[i]) / float64(L) Q[i] = 2 * cmplx.Abs(cData[i]) / float64(L) F[i] = Fs * float64(i) / float64(L) } // plot plt.Reset(true, &plt.A{WidthPt: 450, Dpi: 150, Prop: 1.5}) plt.Subplot(3, 1, 1) plt.Plot(t[:50], xo[:50], &plt.A{C: "b", Ls: "-", L: "signal", NoClip: true}) plt.Plot(t[:50], xc[:50], &plt.A{C: "r", Ls: "-", L: "corrupted", NoClip: true}) plt.Gll("$t\\quad[\\mu s]$", "$x(t)$", nil) plt.HideTRborders() plt.Subplot(3, 1, 2) plt.AxHline(0.7, &plt.A{C: "green", Ls: "--", NoClip: true}) plt.AxHline(1.0, &plt.A{C: "green", Ls: "--", NoClip: true}) plt.Plot(F, P, &plt.A{C: "#0052b8"}) plt.Gll("$f\\quad[Hz]$", "$P(f)$", nil) plt.HideTRborders() plt.Subplot(3, 1, 3) plt.AxHline(0.7, &plt.A{C: "green", Ls: "--", NoClip: true}) plt.AxHline(1.0, &plt.A{C: "green", Ls: "--", NoClip: true}) plt.Plot(F, Q, &plt.A{C: "#ed670d"}) plt.Gll("$f\\quad[Hz]$", "$Q(f)$", nil) plt.HideTRborders() plt.Save("/tmp/gosl", "fun_fft01") }
examples/fun_fft01.go
0.5144
0.490663
fun_fft01.go
starcoder
package parser // IfBlock is the equivalent of [IFB stmt.Condition] stmt.Body [ELSE] stmt.Else [ENDIF], the stmt.Else may be nil type IfBlock struct { *BasicStatement Condition Statement Body []Statement Else []Statement } // Type gets the type of an IFB statement (NULL) func (i *IfBlock) Type() DataType { return NULL } // Keywords gets the keywords of an IFB statement (ELSE and ENDIF) func (i *IfBlock) Keywords() []string { return []string{"ELSE", "ENDIF"} } // EndSignature gets the ending signature of an IFB statement (blank) func (i *IfBlock) EndSignature() []DataType { return []DataType{} } // End parses the end of an IFB statement func (i *IfBlock) End(kind string, _ []Statement, statements []Statement) (bool, error) { if kind == "ELSE" { i.Body = statements return false, nil } if i.Body == nil { i.Body = statements } else { i.Else = statements } return true, nil } // SetupBlocks adds the IFB and WHILE functions func SetupBlocks() { blocks["IFB"] = BlockParser{ Parse: func(args []Statement, pos *Pos) (Block, error) { return &IfBlock{ BasicStatement: &BasicStatement{pos: pos}, Condition: args[0], }, nil }, Signature: []DataType{INT}, } blocks["WHILE"] = BlockParser{ Parse: func(args []Statement, pos *Pos) (Block, error) { return &WhileBlock{ BasicStatement: &BasicStatement{pos: pos}, Condition: args[0], }, nil }, Signature: []DataType{INT}, } } // WhileBlock is the equivalent of [WHILE stmt.Condition] [ENDWHILE] type WhileBlock struct { *BasicStatement Condition Statement Body []Statement } // Type gives the type of a WHILE statement (nothing) func (w *WhileBlock) Type() DataType { return NULL } // Keywords give the keywords of a WHILE statement (just ENDWHILE) func (w *WhileBlock) Keywords() []string { return []string{"ENDWHILE"} } // EndSignature gets the end signature of a WHILE statement (blank) func (w *WhileBlock) EndSignature() []DataType { return []DataType{} } // End parses the ending of a WHILE statement func (w *WhileBlock) End(_ string, _ []Statement, statements []Statement) (bool, error) { w.Body = statements return true, nil }
old/parser/blocks.go
0.590071
0.499878
blocks.go
starcoder
package speg import ( "github.com/SimplePEG/Go/rd" ) func peg() rd.ParserFunc { return rd.Action("peg", rd.Sequence([]rd.ParserFunc{ rd.ZeroOrMore(noop()), parsingHeader(), rd.OneOrMore(noop()), parsingBody(), rd.EndOfFile(), })) } func parsingHeader() rd.ParserFunc { return rd.Action("noop", rd.Sequence([]rd.ParserFunc{ rd.String("GRAMMAR"), rd.OneOrMore(noop()), rd.OneOrMore(parsingRuleName()), })) } func parsingBody() rd.ParserFunc { return rd.Action("parsing_body", rd.OneOrMore(rd.OrderedChoice([]rd.ParserFunc{ rd.String("GRAMMAR"), parsingRule(), rd.OneOrMore(noop()), }))) } func parsingRule() rd.ParserFunc { return rd.Action("parsing_rule", rd.Sequence([]rd.ParserFunc{ parsingRuleName(), rd.ZeroOrMore(noop()), rd.String("->"), rd.ZeroOrMore(noop()), parsingExpression(), rd.ZeroOrMore(noop()), rd.String(";"), rd.ZeroOrMore(noop()), })) } func parsingRuleName() rd.ParserFunc { return rd.Action("noop", rd.Sequence([]rd.ParserFunc{ rd.RegexChar("[a-zA-Z_]"), rd.ZeroOrMore(rd.RegexChar("[a-zA-Z0-9_]")), })) } func parsingExpression() rd.ParserFunc { return rd.Action("parsing_expression", rd.OrderedChoice([]rd.ParserFunc{ parsingSequence(), parsingOrderedChoice(), parsingSubExpression(), })) } func parsingSequence() rd.ParserFunc { return rd.Action("parsing_sequence", rd.Sequence([]rd.ParserFunc{ rd.OrderedChoice([]rd.ParserFunc{ parsingOrderedChoice(), parsingSubExpression(), }), rd.OneOrMore(rd.Sequence([]rd.ParserFunc{ rd.OneOrMore(noop()), rd.OrderedChoice([]rd.ParserFunc{ parsingOrderedChoice(), parsingSubExpression(), }), })), })) } func parsingOrderedChoice() rd.ParserFunc { return rd.Action("parsing_ordered_choice", rd.Sequence([]rd.ParserFunc{ parsingSubExpression(), rd.OneOrMore(rd.Sequence([]rd.ParserFunc{ rd.ZeroOrMore(noop()), rd.String("/"), // rd.string('\/'), rd.ZeroOrMore(noop()), parsingSubExpression(), })), })) } func parsingSubExpression() rd.ParserFunc { return rd.Action("parsing_sub_expression", rd.Sequence([]rd.ParserFunc{ rd.ZeroOrMore(rd.Sequence([]rd.ParserFunc{ tag(), rd.String(":"), })), rd.OrderedChoice([]rd.ParserFunc{ parsing_not_predicate(), parsingAndPredicate(), parsingOptional(), parsingOneOrMore(), parsingZeroOrMore(), parsingGroup(), parsingAtomicExpression(), }), })) } func tag() rd.ParserFunc { return rd.Action("noop", rd.Sequence([]rd.ParserFunc{ rd.RegexChar("[a-zA-Z_]"), rd.ZeroOrMore(rd.RegexChar("[a-zA-Z0-9_]")), })) } func parsingGroup() rd.ParserFunc { return rd.Action("parsing_group", rd.Sequence([]rd.ParserFunc{ rd.String("("), rd.ZeroOrMore(noop()), rd.Rec(parsingExpression), rd.ZeroOrMore(noop()), rd.String(")"), })) } func parsingAtomicExpression() rd.ParserFunc { return rd.Action("parsing_atomic_expression", rd.OrderedChoice([]rd.ParserFunc{ parsingString(), parsingRegexChar(), parsingEof(), parsingRuleCall(), })) } func parsing_not_predicate() rd.ParserFunc { return rd.Action("parsing_not_predicate", rd.Sequence([]rd.ParserFunc{ rd.String("!"), rd.OrderedChoice([]rd.ParserFunc{ parsingGroup(), parsingAtomicExpression(), }), })) } func parsingAndPredicate() rd.ParserFunc { return rd.Action("parsing_and_predicate", rd.Sequence([]rd.ParserFunc{ rd.String("&"), rd.OrderedChoice([]rd.ParserFunc{ parsingGroup(), parsingAtomicExpression(), }), })) } func parsingZeroOrMore() rd.ParserFunc { return rd.Action("parsing_zero_or_more", rd.Sequence([]rd.ParserFunc{ rd.OrderedChoice([]rd.ParserFunc{ parsingGroup(), parsingAtomicExpression(), }), rd.String("*"), })) } func parsingOneOrMore() rd.ParserFunc { return rd.Action("parsing_one_or_more", rd.Sequence([]rd.ParserFunc{ rd.OrderedChoice([]rd.ParserFunc{ parsingGroup(), parsingAtomicExpression(), }), rd.String("+"), })) } func parsingOptional() rd.ParserFunc { return rd.Action("parsing_optional", rd.Sequence([]rd.ParserFunc{ rd.OrderedChoice([]rd.ParserFunc{ parsingGroup(), parsingAtomicExpression(), }), rd.String("?"), })) } func parsingRuleCall() rd.ParserFunc { return rd.Action("parsing_rule_call", parsingRuleName()) } func parsingString() rd.ParserFunc { return rd.Action("parsing_string", rd.Sequence([]rd.ParserFunc{ rd.String("\""), rd.OneOrMore(rd.OrderedChoice([]rd.ParserFunc{ rd.String("\\\\"), rd.String("\\\""), rd.RegexChar("[^\"]"), })), rd.String("\""), })) } func parsingRegexChar() rd.ParserFunc { return rd.Action("parsing_regex_char", rd.OrderedChoice([]rd.ParserFunc{ rd.Sequence([]rd.ParserFunc{ rd.String("["), rd.Optional(rd.String("^")), rd.OneOrMore(rd.OrderedChoice([]rd.ParserFunc{ rd.String("\\]"), rd.String("\\["), rd.RegexChar("[^\\]]"), })), rd.String("]"), }), rd.String("."), })) } func parsingEof() rd.ParserFunc { return rd.Action("parsing_end_of_file", rd.String("EOF")) } func noop() rd.ParserFunc { return rd.Action("noop", rd.RegexChar("[\\s]")) } type SPEGParser struct { state rd.State parser rd.ParserFunc } func NewSPEGParser() SPEGParser { speg := SPEGParser{parser: peg()} return speg } func (sp SPEGParser) ParseGrammar(text string) (rd.Ast, bool) { state := &rd.State{ Text: text, Position: 0, } //sp.state = state return sp.parser(state) } func (sp SPEGParser) GetLastExpectations() []rd.Expectation { return sp.state.LastExpectations } func (sp SPEGParser) GetLastError() (string, bool) { return rd.GetLastError(&sp.state) }
speg/speg_parser.go
0.552057
0.462291
speg_parser.go
starcoder
// Package scene encodes and decodes graphics commands in the format used by the // compute renderer. package scene import ( "fmt" "image/color" "math" "unsafe" "gioui.org/f32" ) type Op uint32 type Command [sceneElemSize / 4]uint32 // GPU commands from scene.h const ( OpNop Op = iota OpLine OpQuad OpCubic OpFillColor OpLineWidth OpTransform OpBeginClip OpEndClip OpFillImage OpSetFillMode ) // FillModes, from setup.h. type FillMode uint32 const ( FillModeNonzero = 0 FillModeStroke = 1 ) const CommandSize = int(unsafe.Sizeof(Command{})) const sceneElemSize = 36 func (c Command) Op() Op { return Op(c[0]) } func (c Command) String() string { switch Op(c[0]) { case OpNop: return "nop" case OpLine: from, to := DecodeLine(c) return fmt.Sprintf("line(%v, %v)", from, to) case OpQuad: from, ctrl, to := DecodeQuad(c) return fmt.Sprintf("quad(%v, %v, %v)", from, ctrl, to) case OpCubic: from, ctrl0, ctrl1, to := DecodeCubic(c) return fmt.Sprintf("cubic(%v, %v, %v, %v)", from, ctrl0, ctrl1, to) case OpFillColor: return "fillcolor" case OpLineWidth: return "linewidth" case OpTransform: t := f32.NewAffine2D( math.Float32frombits(c[1]), math.Float32frombits(c[3]), math.Float32frombits(c[5]), math.Float32frombits(c[2]), math.Float32frombits(c[4]), math.Float32frombits(c[6]), ) return fmt.Sprintf("transform (%v)", t) case OpBeginClip: bounds := f32.Rectangle{ Min: f32.Pt(math.Float32frombits(c[1]), math.Float32frombits(c[2])), Max: f32.Pt(math.Float32frombits(c[3]), math.Float32frombits(c[4])), } return fmt.Sprintf("beginclip (%v)", bounds) case OpEndClip: bounds := f32.Rectangle{ Min: f32.Pt(math.Float32frombits(c[1]), math.Float32frombits(c[2])), Max: f32.Pt(math.Float32frombits(c[3]), math.Float32frombits(c[4])), } return fmt.Sprintf("endclip (%v)", bounds) case OpFillImage: return "fillimage" case OpSetFillMode: return "setfillmode" default: panic("unreachable") } } func Line(start, end f32.Point) Command { return Command{ 0: uint32(OpLine), 1: math.Float32bits(start.X), 2: math.Float32bits(start.Y), 3: math.Float32bits(end.X), 4: math.Float32bits(end.Y), } } func Cubic(start, ctrl0, ctrl1, end f32.Point) Command { return Command{ 0: uint32(OpCubic), 1: math.Float32bits(start.X), 2: math.Float32bits(start.Y), 3: math.Float32bits(ctrl0.X), 4: math.Float32bits(ctrl0.Y), 5: math.Float32bits(ctrl1.X), 6: math.Float32bits(ctrl1.Y), 7: math.Float32bits(end.X), 8: math.Float32bits(end.Y), } } func Quad(start, ctrl, end f32.Point) Command { return Command{ 0: uint32(OpQuad), 1: math.Float32bits(start.X), 2: math.Float32bits(start.Y), 3: math.Float32bits(ctrl.X), 4: math.Float32bits(ctrl.Y), 5: math.Float32bits(end.X), 6: math.Float32bits(end.Y), } } func Transform(m f32.Affine2D) Command { sx, hx, ox, hy, sy, oy := m.Elems() return Command{ 0: uint32(OpTransform), 1: math.Float32bits(sx), 2: math.Float32bits(hy), 3: math.Float32bits(hx), 4: math.Float32bits(sy), 5: math.Float32bits(ox), 6: math.Float32bits(oy), } } func SetLineWidth(width float32) Command { return Command{ 0: uint32(OpLineWidth), 1: math.Float32bits(width), } } func BeginClip(bbox f32.Rectangle) Command { return Command{ 0: uint32(OpBeginClip), 1: math.Float32bits(bbox.Min.X), 2: math.Float32bits(bbox.Min.Y), 3: math.Float32bits(bbox.Max.X), 4: math.Float32bits(bbox.Max.Y), } } func EndClip(bbox f32.Rectangle) Command { return Command{ 0: uint32(OpEndClip), 1: math.Float32bits(bbox.Min.X), 2: math.Float32bits(bbox.Min.Y), 3: math.Float32bits(bbox.Max.X), 4: math.Float32bits(bbox.Max.Y), } } func FillColor(col color.RGBA) Command { return Command{ 0: uint32(OpFillColor), 1: uint32(col.R)<<24 | uint32(col.G)<<16 | uint32(col.B)<<8 | uint32(col.A), } } func FillImage(index int) Command { return Command{ 0: uint32(OpFillImage), 1: uint32(index), } } func SetFillMode(mode FillMode) Command { return Command{ 0: uint32(OpSetFillMode), 1: uint32(mode), } } func DecodeLine(cmd Command) (from, to f32.Point) { if cmd[0] != uint32(OpLine) { panic("invalid command") } from = f32.Pt(math.Float32frombits(cmd[1]), math.Float32frombits(cmd[2])) to = f32.Pt(math.Float32frombits(cmd[3]), math.Float32frombits(cmd[4])) return } func DecodeQuad(cmd Command) (from, ctrl, to f32.Point) { if cmd[0] != uint32(OpQuad) { panic("invalid command") } from = f32.Pt(math.Float32frombits(cmd[1]), math.Float32frombits(cmd[2])) ctrl = f32.Pt(math.Float32frombits(cmd[3]), math.Float32frombits(cmd[4])) to = f32.Pt(math.Float32frombits(cmd[5]), math.Float32frombits(cmd[6])) return } func DecodeCubic(cmd Command) (from, ctrl0, ctrl1, to f32.Point) { if cmd[0] != uint32(OpCubic) { panic("invalid command") } from = f32.Pt(math.Float32frombits(cmd[1]), math.Float32frombits(cmd[2])) ctrl0 = f32.Pt(math.Float32frombits(cmd[3]), math.Float32frombits(cmd[4])) ctrl1 = f32.Pt(math.Float32frombits(cmd[5]), math.Float32frombits(cmd[6])) to = f32.Pt(math.Float32frombits(cmd[7]), math.Float32frombits(cmd[8])) return }
internal/scene/scene.go
0.674908
0.493714
scene.go
starcoder
package pattern import ( "image" "image/color" "math" "github.com/c0nscience/yastgt/pkg/parse/svg" "github.com/c0nscience/yastgt/pkg/unit" ) var gap = 10.0 var dpi = 96.0 var degrees = 45.0 var clr = color.Color(color.NRGBA{R: 255}) var threshold = 4.0 func SetGap(f float64) { gap = f } func SetDpi(f float64) { dpi = f } func SetDegrees(f float64) { degrees = f } func SetColor(c color.Color) { clr = c } func SetThreshold(f float64) { threshold = f } var maxX float64 var maxY float64 var bwd bool func Diagonal(img image.Image) []svg.PointI { bounds := img.Bounds() maxX = float64(bounds.Max.X) maxY = float64(bounds.Max.Y) bwd = false var lines [][]*line if degrees <= 90 { lines = clockwise(img, bounds) } else { lines = counterClockwise(img, bounds) } res := []svg.PointI{} pxToMM := unit.PxToMM(dpi) for _, trace := range lines { for _, line := range trace { res = append(res, &svg.Point{X: pxToMM(px(line.start.x)), Y: pxToMM(px(line.start.y)), MoveTo: true}, &svg.Point{X: pxToMM(px(line.end.x)), Y: pxToMM(px(line.end.y))}) } } return res } func clockwise(img image.Image, bounds image.Rectangle) [][]*line { dist := distance(gap, math.Abs(90-degrees)) distPx := unit.MmToPX(dist, dpi) lines := walk( (bounds.Max.Y/distPx)*distPx, func(t int) bool { return t >= bounds.Min.Y }, func(i int) vector { return vector{y: float64(i)} }, func(i int) int { return i - distPx }, img, ) dist = distance(gap, degrees) distPx = unit.MmToPX(dist, dpi) lines = append(lines, walk( distPx, func(t int) bool { return t >= bounds.Min.X && t <= bounds.Max.X }, func(i int) vector { return vector{x: float64(i)} }, func(i int) int { return i + distPx }, img, )...) return lines } func counterClockwise(img image.Image, bounds image.Rectangle) [][]*line { dist := distance(gap, math.Abs(90-degrees)) distPx := unit.MmToPX(dist, dpi) lines := walk( (bounds.Max.Y/distPx)*distPx, func(t int) bool { return t >= bounds.Min.Y }, func(i int) vector { return vector{x: float64(bounds.Max.X), y: float64(i)} }, func(i int) int { return i - distPx }, img, ) dist = distance(gap, 180-degrees) distPx = unit.MmToPX(dist, dpi) lines = append(lines, walk( bounds.Max.X-distPx, func(t int) bool { return t >= bounds.Min.X && t <= bounds.Max.X }, func(i int) vector { return vector{x: float64(i)} }, func(i int) int { return i - distPx }, img, )...) return lines } func walk(min int, cond func(int) bool, v func(int) vector, incr func(int) int, img image.Image) [][]*line { lines := [][]*line{} for t := min; cond(t); t = incr(t) { res := trace(v(t), img) if len(res) > 0 { if bwd { rev := make([]*line, len(res)) for i, l := range res { l.invertDirection() rev[len(res)-i-1] = l } res = rev } lines = append(lines, res) bwd = !bwd } } return lines } func trace(start vector, img image.Image) []*line { curr := []*line{} dir := fromAngle(degrees) for p := start; p.x >= float64(img.Bounds().Min.X) && p.y >= float64(img.Bounds().Min.Y) && p.x <= maxX && p.y <= maxY; p = p.plus(dir) { c := img.At(px(p.x), px(p.y)) if clr == c { if len(curr) == 0 { curr = append(curr, &line{start: p, end: p}) } l := curr[len(curr)-1] if l.done { l = &line{ start: p, end: p, done: false, } curr = append(curr, l) } if l.end != p { l.end = p } } else { if len(curr) == 0 { continue } l := curr[len(curr)-1] if l.done { continue } if l.length() < float64(unit.MmToPX(threshold, dpi)) { curr = curr[:len(curr)-1] continue } l.done = true } } return curr } func distance(dist, deg float64) float64 { return dist / math.Sin(unit.DegToRad(deg)) } func px(f float64) int { return int(math.Round(f)) } type line struct { start vector end vector done bool } func (l *line) length() float64 { return math.Sqrt(math.Pow(l.start.x-l.end.x, 2) + math.Pow(l.start.y-l.end.y, 2)) } func (l *line) invertDirection() { tmp := l.start l.start = l.end l.end = tmp } type vector struct { x float64 y float64 } func fromAngle(d float64) vector { return vector{ x: precision(math.Cos(unit.DegToRad(d)), 5), y: precision(math.Sin(unit.DegToRad(d)), 5), } } func precision(f float64, i int) float64 { return math.Round(f*math.Pow10(i)) / math.Pow10(i) } func (v vector) plus(v2 vector) vector { return vector{ x: v.x + v2.x, y: v.y + v2.y, } }
pkg/pattern/fill.go
0.680666
0.422743
fill.go
starcoder
package adaptive import ( "errors" "fmt" mc "github.com/kwesiRutledge/ModelChecking" ) type TransitionSystem struct { X []TransitionSystemState U []string Transition map[TransitionSystemState]map[string][]TransitionSystemState Pi []mc.AtomicProposition O map[TransitionSystemState][]mc.AtomicProposition } /* GetTransitionSystem Description: */ func GetTransitionSystem(stateNames []string, actionNames []string, transitionMap map[string]map[string][]string, atomicPropositionsList []string, labelMap map[string][]string) (TransitionSystem, error) { // Constants // Algorithm ts := TransitionSystem{ U: actionNames, Pi: mc.StringSliceToAPs(atomicPropositionsList), } // Create List of States var X []TransitionSystemState //List Of States for _, stateName := range stateNames { X = append(X, TransitionSystemState{Name: stateName, System: &ts}) } ts.X = X // // Create List of Atomic Propositions // ts.AP = StringSliceToAPs(atomicPropositionsList) // Create Transition Map Transition := make(map[TransitionSystemState]map[string][]TransitionSystemState) for siName, perStateMap := range transitionMap { si := TransitionSystemState{Name: siName, System: &ts} tempActionMap := make(map[string][]TransitionSystemState) for actionName, stateArray := range perStateMap { var tempStates []TransitionSystemState for _, siPlus1Name := range stateArray { tempStates = append(tempStates, TransitionSystemState{Name: siPlus1Name, System: &ts}) } tempActionMap[actionName] = tempStates } Transition[si] = tempActionMap } ts.Transition = Transition err := ts.CheckTransition() if err != nil { return ts, err } // Create Label Values fullLabelMap := make(map[TransitionSystemState][]mc.AtomicProposition) for stateName, associatedAPs := range labelMap { tempState := TransitionSystemState{Name: stateName, System: &ts} fullLabelMap[tempState] = mc.StringSliceToAPs(associatedAPs) } ts.O = fullLabelMap return ts, nil } /* CheckTransition Description: Checks that all of the transition states are correct. */ func (ts TransitionSystem) CheckTransition() error { // Checks that all source states are from the state set. for state1 := range ts.Transition { if !state1.In(ts.X) { return fmt.Errorf("One of the source states in the Transition was not in the state set: %v", state1) } } // Checks that all input states are from the action set for _, actionMap := range ts.Transition { for tempAction, targetStates := range actionMap { if _, foundInAct := mc.FindInSlice(tempAction, ts.U); !foundInAct { return fmt.Errorf("The action \"%v\" was found in the transition map but is not in the action set!", tempAction) } // Search through all target states to see if they are in the state set for _, targetState := range targetStates { if !targetState.In(ts.X) { return fmt.Errorf("There is an ancestor state \"%v\" which is not part of the state.", targetState) } } } } // Completed with no errors return nil } /* Check Description: Checks the following components of the transition system object: - Initial State Set is a Subset of the State Space - Transitions map properly between the state space and the action space to the next state space */ func (ts TransitionSystem) Check() error { // Check Transition Map err := ts.CheckTransition() if err != nil { return err } return nil } /* IsNonBlocking Description: Determines if the transition system is non-blocking, that is for any state and action pair the value of Post is not zero. */ func (ts TransitionSystem) IsNonBlocking() bool { // Check the value of Post for each state, action pair. for _, state := range ts.X { for _, action := range ts.U { tempPostValue, _ := Post(state, action) if len(tempPostValue) == 0 { return false } } } return true } /* TransitionSystemState Description: This type is an object which contains the Transition System's State. */ type TransitionSystemState struct { Name string System *TransitionSystem } /* Equals Description: Checks to see if two states in the transition system have the same value. */ func (stateIn TransitionSystemState) Equals(s2 TransitionSystemState) bool { return stateIn.Name == s2.Name } /* In Description: Determines if the state is in a given slice of TransitionSystemState objects. Usage: tf := s1.In( sliceIn ) */ func (stateIn TransitionSystemState) In(stateSliceIn []TransitionSystemState) bool { for _, tempState := range stateSliceIn { if tempState.Equals(stateIn) { return true //If there is a match, then return true. } } //If there is no match in the slice, //then return false return false } /* Satisfies Description: The state of the transition system satisfies the given formula. */ func (stateIn TransitionSystemState) Satisfies(formula interface{}) (bool, error) { // Input Processing if stateIn.System == nil { return false, errors.New("The system pointer is not defined for the input state.") } // Algorithm var tf = false var err error = nil if singleAP, ok := formula.(mc.AtomicProposition); ok { System := stateIn.System return singleAP.In(System.O[stateIn]), nil } return tf, err } /* AppendIfUniqueTo Description: Appends to the input slice sliceIn if and only if the new state is actually a unique state. Usage: newSlice := stateIn.AppendIfUniqueTo(sliceIn) */ func (stateIn TransitionSystemState) AppendIfUniqueTo(sliceIn []TransitionSystemState) []TransitionSystemState { for _, tempState := range sliceIn { if tempState.Equals(stateIn) { return sliceIn } } //If all checks were passed return append(sliceIn, stateIn) } /* Post Description: Finds the set of states that can follow a given state (or set of states). Usage: tempPost, err := Post( s0 ) tempPost, err := Post( s0 , a0 ) */ func Post(SorSA ...interface{}) ([]TransitionSystemState, error) { switch len(SorSA) { case 1: // Only State Is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } System := stateIn.System allActions := System.U var nextStates []TransitionSystemState var tempPost []TransitionSystemState var err error for _, action := range allActions { tempPost, err = Post(stateIn, action) if err != nil { return []TransitionSystemState{}, err } for _, postElt := range tempPost { nextStates = postElt.AppendIfUniqueTo(nextStates) } } return nextStates, nil case 2: // State and Action is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } actionIn, ok := SorSA[1].(string) if !ok { return []TransitionSystemState{}, errors.New("The second input to post is not of type string!") } // Get Transition value System := stateIn.System tValues := System.Transition[stateIn][actionIn] var nextStates []TransitionSystemState for _, nextState := range tValues { nextStates = nextState.AppendIfUniqueTo(nextStates) } return nextStates, nil } // Return error return []TransitionSystemState{}, errors.New(fmt.Sprintf("Unexpected number of inputs to post (%v).", len(SorSA))) } /* Pre Description: Finds the set of states that can precede a given state (or set of states). Usage: tempPreSet , err := Pre( s0 ) tempPreSet , err := Pre( s0 , a0 ) */ func Pre(SorSA ...interface{}) ([]TransitionSystemState, error) { switch len(SorSA) { case 1: // Only State Is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } System := stateIn.System allActions := System.U var predecessors []TransitionSystemState var tempPre []TransitionSystemState var err error for _, action := range allActions { tempPre, err = Pre(stateIn, action) if err != nil { return []TransitionSystemState{}, err } for _, preElt := range tempPre { predecessors = preElt.AppendIfUniqueTo(predecessors) } } return predecessors, nil case 2: // State and Action is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } actionIn, ok := SorSA[1].(string) if !ok { return []TransitionSystemState{}, errors.New("The second input to post is not of type string!") } // Get Transition value System := stateIn.System var matchingPredecessors []TransitionSystemState for predecessor, actionMap := range System.Transition { if stateIn.In(actionMap[actionIn]) { // If the target state is in the result of (predecessor,actionIn) -> stateIn, // then save the value of stateIn matchingPredecessors = append(matchingPredecessors, predecessor) } } return matchingPredecessors, nil } // Return error return []TransitionSystemState{}, errors.New(fmt.Sprintf("Unexpected number of inputs to post (%v).", len(SorSA))) } /* String Description: Returns the value of the state if the value is of type string. Otherwise, this returns the value of each part of the Value */ func (stateIn TransitionSystemState) String() string { return stateIn.Name } /* HasStateSpacePartition Description: Determines if a collection of subsets of states (slice of slices of states) forms a partition of the state space for a transition system. According to the paper Q is a partition if: - Empty set is not in Q - Union of the subsets in Q makes X - There is no overlap of sets in Q */ func (ts TransitionSystem) HasStateSpacePartition(Q [][]TransitionSystemState) bool { // Verify that empty set is not in Q for _, tempSubset := range Q { if len(tempSubset) == 0 { return false // Q contains the empty set. Return false. } } // Verify that the union of all of these sets in Q // make up the state space when considered in total. unionOfQ := UnionOfStates(Q...) // Unrolls Q tf, _ := SliceEquals(unionOfQ, ts.X) if !tf { return false // union of Q does not make X } // Verify that for each pair, the two sets are disjoint for subsetIndex1, subset1 := range Q { for subsetIndex2 := subsetIndex1 + 1; subsetIndex2 < len(Q); subsetIndex2++ { subset2 := Q[subsetIndex2] subsetsAreDisjoint := len(IntersectionOfStates(subset1, subset2)) == 0 if !subsetsAreDisjoint { return false } } } return true } /* UnionOfStates Description: Computes the union of a collection of TransitionSystemState slices. */ func UnionOfStates(stateSlicesIn ...[]TransitionSystemState) []TransitionSystemState { // Constants //numSubsets := len(stateSlicesIn) // Algorithm var unionOut []TransitionSystemState for _, tempSubset := range stateSlicesIn { for _, tempState := range tempSubset { unionOut = tempState.AppendIfUniqueTo(unionOut) } } return unionOut } /* IntersectionOfStates Description: Computes the intersection of a collection of TransitionSystemState slices. */ func IntersectionOfStates(stateSlicesIn ...[]TransitionSystemState) []TransitionSystemState { // Constants //numSubsets := len(stateSlicesIn) // Algorithm var intersectionOut []TransitionSystemState if len(stateSlicesIn) == 0 { return []TransitionSystemState{} } else { slice0 := stateSlicesIn[0] for _, xi := range slice0 { // Search through all other slices var xiExistsInAll = true for _, sliceI := range stateSlicesIn { if !xi.In(sliceI) { xiExistsInAll = false } } if xiExistsInAll { intersectionOut = append(intersectionOut, xi) } } return intersectionOut } } /* ToQuotientTransitionSystemFor */ func (ts TransitionSystem) ToQuotientTransitionSystemFor(partition [][]TransitionSystemState) (QuotientTransitionSystem, error) { // Check to see if partition is a true partition if !ts.HasObservationPreservingStateSpacePartition(partition) { return QuotientTransitionSystem{}, errors.New("The provided partition is not valid.") } // Copy over some of the old members of the Transition System to the QuotientTransitionSystem qtsOut := QuotientTransitionSystem{ U: ts.U, Pi: ts.Pi, } // Create State Space var Q []QTSState for _, stateSubset := range partition { Q = append(Q, QTSState{ Subset: stateSubset, System: &qtsOut, }, ) } qtsOut.Q = Q // Define the Transitions that may (or may not) exist tempBeta := make(map[*QTSState]map[string][]*QTSState) for _, q := range qtsOut.Q { tempBetaOfQ := make(map[string][]*QTSState) for _, q_prime := range qtsOut.Q { // Determine if there exists an input u which links q and q_prime for _, u := range qtsOut.U { // Compute post for some of the items in q for _, x := range q.Subset { tempPost, err := Post(x, u) if err != nil { return qtsOut, fmt.Errorf("There was an issue computing Post(\"%v\",\"%v\"): %v", x, u, err) } // Determine if the intersection of tempPost with q_prime is nonempty tempIntersection := IntersectionOfStates(tempPost, q_prime.Subset) if len(tempIntersection) != 0 { tempBetaOfQ[u] = (&q_prime).AppendIfUniqueTo(tempBetaOfQ[u]) } } } } tempBeta[&q] = tempBetaOfQ } qtsOut.BetaQ = tempBeta // After all of these modifications have been made, we return the value of the Quotient Transition System return qtsOut, nil } /* HasObservationPreservingStateSpacePartition Description: Determines if a collection of subsets of states (slice of slices of states) forms a partition of the state space for a transition system. According to the paper Q is an observation-preserving state space partition if: - it is a state space partition, - each cell has the same output value. */ func (ts TransitionSystem) HasObservationPreservingStateSpacePartition(Q [][]TransitionSystemState) bool { // Verify that Q is a State Space partition if !ts.HasStateSpacePartition(Q) { return false } // Verify that for each pair, the two sets are disjoint for _, subset := range Q { candidateO := ts.O[subset[0]] for _, x := range subset { if tf, _ := SliceEquals(candidateO, ts.O[x]); !tf { // If the observation does not match candidateO, // then this cell does not preserve the observation property. return false } } } return true }
adaptive/transitionsystem.go
0.651687
0.401512
transitionsystem.go
starcoder
package tetra3d import ( "strconv" "strings" "github.com/kvartborg/vector" ) // INode represents an object that exists in 3D space and can be positioned relative to an origin point. // By default, this origin point is {0, 0, 0} (or world origin), but Nodes can be parented // to other Nodes to change this origin (making their movements relative and their transforms // successive). Models and Cameras are two examples of objects that fully implement the INode interface // by means of embedding Node. type INode interface { Name() string SetName(name string) Clone() INode Data() interface{} setParent(INode) Parent() INode Unparent() Root() INode Children() []INode ChildrenRecursive(onlyVisible bool) []INode AddChildren(...INode) RemoveChildren(...INode) updateLocalTransform(newParent INode) dirtyTransform() LocalRotation() Matrix4 SetLocalRotation(rotation Matrix4) LocalPosition() vector.Vector SetLocalPosition(position vector.Vector) LocalScale() vector.Vector SetLocalScale(scale vector.Vector) WorldRotation() Matrix4 SetWorldRotation(rotation Matrix4) WorldPosition() vector.Vector SetWorldPosition(position vector.Vector) WorldScale() vector.Vector SetWorldScale(scale vector.Vector) Move(x, y, z float64) Rotate(x, y, z, angle float64) Scale(x, y, z float64) Transform() Matrix4 Visible() bool SetVisible(visible bool) Get(path string) INode FindByName(name string) []INode FindByTags(tags ...string) []INode TreeToString() string Path() string Tags() *Tags } // Tags is an unordered set of string tags to values, representing a means of identifying Nodes or carrying data on Nodes. type Tags struct { tags map[string]interface{} } // NewTags returns a new Tags object. func NewTags() *Tags { return &Tags{map[string]interface{}{}} } func (tags *Tags) Clone() *Tags { newTags := NewTags() for k, v := range tags.tags { newTags.Set(k, v) } return newTags } // Clear clears the Tags object of all tags. func (tags *Tags) Clear() { tags.tags = map[string]interface{}{} } // Set sets all the tag specified to the Tags object. func (tags *Tags) Set(tagName string, value interface{}) { tags.tags[tagName] = value } // Remove removes the tag specified from the Tags object. func (tags *Tags) Remove(tag string) { delete(tags.tags, tag) } // Has returns true if the Tags object has all of the tags specified, and false otherwise. func (tags *Tags) Has(nodeTags ...string) bool { for _, t := range nodeTags { if _, exists := tags.tags[t]; !exists { return false } } return true } // Get returns the value associated with the specified tag (key). func (tags *Tags) Get(tagName string) interface{} { return tags.tags[tagName] } // IsString returns true if the value associated with the specified tag is a string. func (tags *Tags) IsString(tagName string) bool { if _, exists := tags.tags[tagName]; exists { if _, ok := tags.tags[tagName].(string); ok { return true } } return false } // GetAsString returns the value associated with the specified tag (key) as a string. func (tags *Tags) GetAsString(tagName string) string { return tags.tags[tagName].(string) } // IsFloat returns true if the value associated with the specified tag is a float64. func (tags *Tags) IsFloat(tagName string) bool { if _, exists := tags.tags[tagName]; exists { if _, ok := tags.tags[tagName].(float64); ok { return true } } return false } // GetAsFloat returns the value associated with the specified tag (key) as a float. func (tags *Tags) GetAsFloat(tagName string) float64 { return tags.tags[tagName].(float64) } // Node represents a minimal struct that fully implements the Node interface. Model and Camera embed Node // into their structs to automatically easily implement Node. type Node struct { name string parent INode position vector.Vector scale vector.Vector rotation Matrix4 data interface{} // A place to store a pointer to something if you need it cachedTransform Matrix4 isTransformDirty bool onTransformUpdate func() children []INode visible bool tags *Tags // Tags is an unordered set of string tags, representing a means of identifying Nodes. AnimationPlayer *AnimationPlayer inverseBindMatrix Matrix4 // Specifically for bones in an armature used for animating skinned meshes } // NewNode returns a new Node. func NewNode(name string) *Node { nb := &Node{ name: name, position: vector.Vector{0, 0, 0}, scale: vector.Vector{1, 1, 1}, rotation: NewMatrix4(), children: []INode{}, visible: true, isTransformDirty: true, tags: NewTags(), } nb.AnimationPlayer = NewAnimationPlayer(nb) return nb } // Name returns the object's name. func (node *Node) Name() string { return node.name } // SetName sets the object's name. func (node *Node) SetName(name string) { node.name = name } // Clone returns a new Node. func (node *Node) Clone() INode { newNode := NewNode(node.name) newNode.position = node.position.Clone() newNode.scale = node.scale.Clone() newNode.rotation = node.rotation.Clone() newNode.parent = node.parent newNode.AnimationPlayer = node.AnimationPlayer.Clone() for _, child := range node.children { childClone := child.Clone() childClone.setParent(newNode) newNode.children = append(newNode.children, childClone) } return newNode } // SetData sets user-customizeable data that could be usefully stored on this node. func (node *Node) SetData(data interface{}) { node.data = data } // Data returns a pointer to user-customizeable data that could be usefully stored on this node. func (node *Node) Data() interface{} { return node.data } // Transform returns a Matrix4 indicating the global position, rotation, and scale of the object, transforming it by any parents'. // If there's no change between the previous Transform() call and this one, Transform() will return a cached version of the // transform for efficiency. func (node *Node) Transform() Matrix4 { // T * R * S * O if !node.isTransformDirty { return node.cachedTransform } transform := NewMatrix4Scale(node.scale[0], node.scale[1], node.scale[2]) transform = transform.Mult(node.rotation) transform = transform.Mult(NewMatrix4Translate(node.position[0], node.position[1], node.position[2])) if node.parent != nil { transform = transform.Mult(node.parent.Transform()) } node.cachedTransform = transform node.isTransformDirty = false if node.onTransformUpdate != nil { node.onTransformUpdate() } return transform } // dirtyTransform sets this Node and all recursive children's isTransformDirty flags to be true, indicating that they need to be // rebuilt. This should be called when modifying the transformation properties (position, scale, rotation) of the Node. func (node *Node) dirtyTransform() { if !node.isTransformDirty { for _, child := range node.ChildrenRecursive(false) { child.dirtyTransform() } } node.isTransformDirty = true } // updateLocalTransform updates the local transform properties for a Node given a change in parenting. This is done so that, for example, // parenting an object with a given postiion, scale, and rotation keeps those visual properties when parenting (by updating them to take into // account the parent's transforms as well). func (node *Node) updateLocalTransform(newParent INode) { if newParent != nil { parentTransform := newParent.Transform() parentPos, parentScale, parentRot := parentTransform.Decompose() diff := node.position.Sub(parentPos) diff[0] /= parentScale[0] diff[1] /= parentScale[1] diff[2] /= parentScale[2] node.position = parentRot.Transposed().MultVec(diff) node.rotation = node.rotation.Mult(parentRot.Transposed()) node.scale[0] /= parentScale[0] node.scale[1] /= parentScale[1] node.scale[2] /= parentScale[2] } else { // Reverse parentTransform := node.Parent().Transform() parentPos, parentScale, parentRot := parentTransform.Decompose() pr := parentRot.MultVec(node.position) pr[0] *= parentScale[0] pr[1] *= parentScale[1] pr[2] *= parentScale[2] node.position = parentPos.Add(pr) node.rotation = node.rotation.Mult(parentRot) node.scale[0] *= parentScale[0] node.scale[1] *= parentScale[1] node.scale[2] *= parentScale[2] } node.dirtyTransform() } // LocalPosition returns a 3D Vector consisting of the object's local position (position relative to its parent). If this object has no parent, the position will be // relative to world origin (0, 0, 0). func (node *Node) LocalPosition() vector.Vector { return node.position } // SetLocalPosition sets the object's local position (position relative to its parent). If this object has no parent, the position should be // relative to world origin (0, 0, 0). position should be a 3D vector (i.e. X, Y, and Z components). func (node *Node) SetLocalPosition(position vector.Vector) { node.position = position node.dirtyTransform() } // ResetLocalTransformProperties resets the local transform properties (position, scale, and rotation) for the Node. This can be useful because // by default, when you parent one Node to another, the local transform properties (position, scale, and rotation) are altered to keep the // object in the same absolute location, even though the origin changes. func (node *Node) ResetLocalTransformProperties() { node.position[0] = 0 node.position[1] = 0 node.position[2] = 0 node.scale[0] = 1 node.scale[1] = 1 node.scale[2] = 1 node.rotation = NewMatrix4() node.dirtyTransform() } // WorldPosition returns a 3D Vector consisting of the object's world position (position relative to the world origin point of {0, 0, 0}). func (node *Node) WorldPosition() vector.Vector { // position, _, _ := node.Transform().Decompose() position := node.Transform().Row(3)[:3] // We don't want to have to decompose if we don't have to return position } // SetWorldPosition sets the object's world position (position relative to the world origin point of {0, 0, 0}). // position needs to be a 3D vector (i.e. X, Y, and Z components). func (node *Node) SetWorldPosition(position vector.Vector) { if node.parent != nil { parentTransform := node.parent.Transform() parentPos, parentScale, parentRot := parentTransform.Decompose() pr := parentRot.Transposed().MultVec(position.Sub(parentPos)) pr[0] /= parentScale[0] pr[1] /= parentScale[1] pr[2] /= parentScale[2] node.position = pr } else { node.position = position } node.dirtyTransform() } // LocalScale returns the object's local scale (scale relative to its parent). If this object has no parent, the scale will be absolute. func (node *Node) LocalScale() vector.Vector { return node.scale } // SetLocalScale sets the object's local scale (scale relative to its parent). If this object has no parent, the scale would be absolute. // scale should be a 3D vector (i.e. X, Y, and Z components). func (node *Node) SetLocalScale(scale vector.Vector) { node.scale = scale node.dirtyTransform() } // WorldScale returns the object's absolute world scale as a 3D vector (i.e. X, Y, and Z components). func (node *Node) WorldScale() vector.Vector { _, scale, _ := node.Transform().Decompose() return scale } // SetWorldScale sets the object's absolute world scale. scale should be a 3D vector (i.e. X, Y, and Z components). func (node *Node) SetWorldScale(scale vector.Vector) { if node.parent != nil { parentTransform := node.parent.Transform() _, parentScale, _ := parentTransform.Decompose() node.scale = vector.Vector{ scale[0] / parentScale[0], scale[1] / parentScale[1], scale[2] / parentScale[2], } } else { node.scale = scale } node.dirtyTransform() } // LocalRotation returns the object's local rotation Matrix4. func (node *Node) LocalRotation() Matrix4 { return node.rotation } // SetLocalRotation sets the object's local rotation Matrix4 (relative to any parent). func (node *Node) SetLocalRotation(rotation Matrix4) { node.rotation = rotation node.dirtyTransform() } // WorldRotation returns an absolute rotation Matrix4 representing the object's rotation. func (node *Node) WorldRotation() Matrix4 { _, _, rotation := node.Transform().Decompose() return rotation } // SetWorldRotation sets an object's rotation to the provided rotation Matrix4. func (node *Node) SetWorldRotation(rotation Matrix4) { if node.parent != nil { parentTransform := node.parent.Transform() _, _, parentRot := parentTransform.Decompose() node.rotation = parentRot.Transposed().Mult(rotation) } else { node.rotation = rotation } node.dirtyTransform() } func (node *Node) Move(x, y, z float64) { localPos := node.LocalPosition() localPos[0] += x localPos[1] += y localPos[2] += z node.SetLocalPosition(localPos) } func (node *Node) Rotate(x, y, z, angle float64) { localRot := node.LocalRotation() localRot = localRot.Rotated(x, y, z, angle) node.SetLocalRotation(localRot) } func (node *Node) Scale(x, y, z float64) { scale := node.LocalScale() scale[0] += x scale[1] += y scale[2] += z node.SetLocalScale(scale) } // Parent returns the Node's parent. If the Node has no parent, this will return nil. func (node *Node) Parent() INode { return node.parent } // setParent sets the Node's parent. func (node *Node) setParent(parent INode) { node.parent = parent } // addChildren adds the children to the parent node, but sets their parent to be the parent node passed. This is done so children have the // correct, specific Node as parent (because I can't really think of a better way to do this rn). Basically, without this approach, // after parent.AddChildren(child), child.Parent() wouldn't be parent, but rather parent.Node, which is no good. func (node *Node) addChildren(parent INode, children ...INode) { for _, child := range children { child.updateLocalTransform(parent) if child.Parent() != nil { child.Parent().RemoveChildren(child) } child.setParent(parent) node.children = append(node.children, child) } } // AddChildren parents the provided children Nodes to the passed parent Node, inheriting its transformations and being under it in the scenegraph // hierarchy. If the children are already parented to other Nodes, they are unparented before doing so. func (node *Node) AddChildren(children ...INode) { node.addChildren(node, children...) } // RemoveChildren removes the provided children from this object. func (node *Node) RemoveChildren(children ...INode) { for _, child := range children { for i, c := range node.children { if c == child { child.updateLocalTransform(nil) child.setParent(nil) node.children[i] = nil node.children = append(node.children[:i], node.children[i+1:]...) break } } } } // Unparent unparents the Node from its parent, removing it from the scenegraph. func (node *Node) Unparent() { if node.parent != nil { node.parent.RemoveChildren(node) } } // Children() returns the Node's children. func (node *Node) Children() []INode { return append([]INode{}, node.children...) } // ChildrenRecursive returns all related children Nodes underneath this one. If onlyVisible is true, ChildrenRecursive will only return // Nodes that are visible. func (node *Node) ChildrenRecursive(onlyVisible bool) []INode { out := []INode{} for _, child := range node.children { if !onlyVisible || child.Visible() { out = append(out, child) out = append(out, child.ChildrenRecursive(onlyVisible)...) } } return out } // Visible returns whether the Object is visible. func (node *Node) Visible() bool { return node.visible } // SetVisible sets the object's visibility. func (node *Node) SetVisible(visible bool) { node.visible = visible } // Tags represents an unordered set of string tags that can be used to identify this object. func (node *Node) Tags() *Tags { return node.tags } // TreeToString returns a string displaying the hierarchy of this Node, and all recursive children. // Nodes will have a "+" next to their name, Models an "M", and Cameras a "C". // This is a useful function to debug the layout of a node tree, for example. func (node *Node) TreeToString() string { var printNode func(node INode, level int) string printNode = func(node INode, level int) string { nodeType := "+" if _, ok := node.(*Model); ok { nodeType = "M" } else if _, ok := node.(*Camera); ok { nodeType = "C" } else if _, ok := node.(*BoundingSphere); ok { nodeType = "BS" } else if _, ok := node.(*BoundingAABB); ok { nodeType = "AABB" } str := "" if level == 0 { str = "-: [+] " + node.Name() + "\n" } else { for i := 0; i < level; i++ { str += " " } wp := node.LocalPosition() wpStr := "[" + strconv.FormatFloat(wp[0], 'f', -1, 64) + ", " + strconv.FormatFloat(wp[1], 'f', -1, 64) + ", " + strconv.FormatFloat(wp[2], 'f', -1, 64) + "]" str += "\\-: [" + nodeType + "] " + node.Name() + " : " + wpStr + "\n" } for _, child := range node.Children() { str += printNode(child, level+1) } return str } return printNode(node, 0) } // Get searches a node's hierarchy using a string to find a specified node. The path is in the format of names of nodes, separated by forward // slashes ('/'), and is relative to the node you use to call Get. As an example of Get, if you had a cup parented to a desk, which was // parented to a room, that was finally parented to the root of the scene, it would be found at "Room/Desk/Cup". Note also that you can use "../" to // "go up one" in the hierarchy (so cup.Get("../") would return the Desk node). // Since Get uses forward slashes as path separation, it would be good to avoid using forward slashes in your object names. func (node *Node) Get(path string) INode { var search func(node INode) INode split := strings.Split(path, `/`) search = func(node INode) INode { if node == nil { return nil } else if len(split) == 0 { return node } if split[0] == ".." { split = split[1:] return search(node.Parent()) } for _, child := range node.Children() { if child.Name() == split[0] { if len(split) <= 1 { return child } else { split = split[1:] return search(child) } } } return nil } return search(node) } // Path returns a string indicating the hierarchical path to get this Node from the root. The path returned will be absolute, such that // passing it to Get() called on the scene root node will return this node. The path returned will not contain the root node's name ("Root"). func (node *Node) Path() string { root := node.Root() if root == nil { return "" } parent := node.Parent() path := node.Name() for parent != nil && parent != root { path = parent.Name() + "/" + path parent = parent.Parent() } return path } // FindByName allows you to search the node's tree for Nodes with the provided name, returning a slice // of Nodes with the name given. If none are found, an empty slice is returned. // After finding a Node, you can convert it to a more specific type as necessary via type assertion. func (node *Node) FindByName(name string) []INode { out := []INode{} for _, node := range node.ChildrenRecursive(false) { if node.Name() == name { out = append(out, node) } } return out } // FindBytags allows you to search the node's tree for Nodes with the provided tags, returning a slice // of Nodes with the tags given. If none are found, an empty slice is returned. // After finding a Node, you can convert it to a more specific type as necessary via type assertion. func (node *Node) FindByTags(tagNames ...string) []INode { out := []INode{} for _, node := range node.ChildrenRecursive(false) { if node.Tags().Has(tagNames...) { out = append(out, node) } } return out } // GetMultipleByTags allows you to search the node's tree for multiple Nodes with the provided tag. // After finding Nodes, you can convert it to a more specific type as necessary via type assertion. func (node *Node) GetMultipleByTags(tagNames ...string) []INode { out := []INode{} for _, node := range node.ChildrenRecursive(false) { if node.Tags().Has(tagNames...) { out = append(out, node) } } return out } // Root returns the root node in this tree by recursively traversing this node's hierarchy of // parents upwards. func (node *Node) Root() INode { if node.parent == nil { return node } parent := node.Parent() for parent != nil { next := parent.Parent() if next == nil { break } parent = next } return parent }
node.go
0.87728
0.562898
node.go
starcoder
package bayes import ( . "code.google.com/p/probab/dst" "fmt" "math" ) // PMF of the posterior distribution of unknown Normal μ, with KNOWN σ, and discrete prior, for single observation. // Bolstad 2007 (2e): 200-201. func NormMuSinglePMFDPri(y, σ float64, μ []float64, μPri []float64) (post []float64) { // y single observation taken from Normal distribution // σ standard deviation of population, assumed to be known // μ array of possible discrete values of μ // μPri array of associated prior probability masses nPoss := len(μ) if len(μPri) != nPoss { panic(fmt.Sprintf("len(μ) != len(μPri)")) } post = make([]float64, nPoss) sum := 0.0 for i := 0; i < nPoss; i++ { z := (y - μ[i]) / σ like := ZPDFAt(z) post[i] = μPri[i] * like sum += post[i] } for i := 0; i < nPoss; i++ { post[i] /= sum } return } // PMF of the posterior distribution of unknown Normal μ, with KNOWN σ, and discrete prior, for sample // Bolstad 2007 (2e): 203, eq. 11.2 func NormMuPMFDPri(nObs int, ȳ, σ float64, μ []float64, μPri []float64) (post []float64) { // nObs number of observations in the sample (= length of the samle array) // ȳ sample mean of the observed values // σ standard deviation of population, assumed to be known // μ array of possible discrete values of μ // μPri array of associated prior probability masses nPoss := len(μ) // number of possible values of the parameter μ if len(μPri) != nPoss { panic(fmt.Sprintf("len(μ) != len(μPri)")) } post = make([]float64, nPoss) n := float64(nObs) sum := 0.0 for i := 0; i < nPoss; i++ { σ2 := σ * σ ẟ := ȳ - μ[i] like := math.Exp(-1 / (2 * σ2 / n) * ẟ * ẟ) post[i] = μPri[i] * like sum += post[i] } for i := 0; i < nPoss; i++ { post[i] /= sum } return } // Posterior mean for unknown Normal μ, with KNOWN σ. // Bolstad 2007 (2e): 209, eq. 11.6 func NormMuPostMean(nObs int, ȳ, σ, μPri, σPri float64) float64 { // μPri prior mean // σPri prior standard deviation // nObs size of sample == number of measurements // σ standard deviation of population, assumed to be known (alternatively, use an estimate) σ2 := σ * σ n := float64(nObs) σ2Pri := σPri * σPri μPost := (μPri/σ2Pri)/(n/σ2+1/σ2Pri) + ȳ*(n/σ2)/(n/σ2+1/σ2Pri) return (μPost) } // Posterior standard deviation for unknown Normal μ, with KNOWN σ. // Bolstad 2007 (2e): 209, eq. 11.5 func NormMuPostStd(nObs int, σ, μPri, σPri float64) float64 { // μPri prior mean // σPri prior standard deviation // nObs size of sample == number of measurements // σ standard deviation of population, assumed to be known (alternatively, use an estimate) σ2 := σ * σ n := float64(nObs) σ2Pri := σPri * σPri σ2Post := (σ2 * σ2Pri) / (σ2 + n*σ2Pri) σPost := math.Sqrt(σ2Post) return (σPost) } // Quantile for posterior distribution of unknown Normal μ, with KNOWN σ, and flat prior (Jeffrey's prior), for single observation // Bolstad 2007 (2e): 206 func NormMuSingleQtlFPri(y, σ, p float64) float64 { // y single observation taken from Normal distribution // σ standard deviation of population, assumed to be known // p probability for which the quantile will be returned // untested ... μPost := y σPost := σ qtl := NormalQtlFor(μPost, σPost, p) return (qtl) } // Quantile for posterior distribution of unknown Normal μ, with KNOWN σ, and flat prior (Jeffrey's prior), for sample // Bolstad 2007 (2e): 207 func NormMuQtlFPri(nObs int, ȳ, σ, p float64) float64 { // ȳ sample mean of observations taken from Normal distribution // σ standard deviation of population, assumed to be known // nObs number of observations // p probability for which the quantile will be returned if σ <= 0 { panic(fmt.Sprintf("Prior standard deviation must be greater than zero")) } n := float64(nObs) σ2 := σ * σ μPost := ȳ σ2Post := σ2 / n σPost := math.Sqrt(σ2Post) return NormalQtlFor(μPost, σPost, p) } // Quantile for posterior distribution of unknown Normal μ, with KNOWN σ, and Normal prior, for single observation // Bolstad 2007 (2e): 208, eq. 11.4 func NormMuSingleQtlNPri(y, σ, μPri, σPri, p float64) float64 { // y single observation taken from Normal distribution // σ standard deviation of population, assumed to be known // μPri Normal prior mean // σPri Normal prior standard deviation // p probability for which the quantile will be returned // untested ... if σ <= 0 { panic(fmt.Sprintf("Prior standard deviation must be greater than zero")) } σ2 := σ * σ σ2Pri := σPri * σPri μPost := (σ2*μPri + σ2Pri*y) / (σ2 + σ2Pri) σ2Post := (σ2 * σ2Pri) / (σ2 + σ2Pri) σPost := math.Sqrt(σ2Post) return NormalQtlFor(μPost, σPost, p) } // Quantile for posterior distribution of unknown Normal μ, with KNOWN σ, and Normal prior, for sample // Bolstad 2007 (2e): 209, eq. 11.5, 11.6 func NormMuQtlNPri(nObs int, ȳ, σ, μPri, σPri, p float64) float64 { // ȳ sample mean of observations taken from Normal dist // σ standard deviation of population, assumed to be known // nObs number of observations // μPri Normal prior mean // σPri Normal prior standard deviation // p probability for which the quantile will be returned n := float64(nObs) σ2 := σ * σ σ2Pri := σPri * σPri σ2Post := (σ2 * σ2Pri) / (σ2 + n*σ2Pri) μPost := (μPri/σ2Pri)/(n/σ2+1/σ2Pri) + ȳ*(n/σ2)/(n/σ2+1/σ2Pri) σPost := math.Sqrt(σ2Post) return NormalQtlFor(μPost, σPost, p) } // Credible interval for unknown Normal μ, with KNOWN σ, and Normal prior // Bolstad 2007 (2e): 212, eq. 11.7 func NormMuCrINPriKnown(nObs int, ȳ, σ, μPri, σPri, α float64) (lo, hi float64) { // ȳ sample mean of observations taken from Normal distribution // σ standard deviation of population, assumed to be known // nObs number of observations // μPri Normal prior mean // σPri Normal prior standard deviation // α posterior probability that the true μ lies outside the credible interval n := float64(nObs) σ2 := σ * σ σ2Pri := σPri * σPri σ2Post := (σ2 * σ2Pri) / (σ2 + n*σ2Pri) μPost := (μPri/σ2Pri)/(n/σ2+1/σ2Pri) + ȳ*(n/σ2)/(n/σ2+1/σ2Pri) // μPost := (μPri/σ2Pri)/(n*ȳ/σ2+1/σ2Pri) + ((n / σ2) / (n/σ2 + 1/σ2Pri)) σPost := math.Sqrt(σ2Post) lo = NormalQtlFor(μPost, σPost, α/2) hi = NormalQtlFor(μPost, σPost, 1-α/2) return lo, hi } /* waiting for StudentsTQtlFor() to be implemented // Credible interval for unknown Normal μ, with UNKNOWN σ, and Normal prior, equal tail area // Bolstad 2007 (2e): 212, eq. 11.8 func NormMuCrINPriUnkn(nObs int, ȳ, sampσ, μPri, σPri, α float64) (lo, hi float64) { // nObs number of observations // ȳ sample mean of observations taken from Normal distribution // sampσ standard deviation of the sample // μPri Normal prior mean // σPri Normal prior standard deviation // α posterior probability that the true μ lies outside the credible interval // untested ... n := float64(nObs) nu := float64(nObs - 1) sampvar := sampσ * sampσ σ2Pri := σPri * σPri σ2Post := (sampvar * σ2Pri) / (sampvar + n*σ2Pri) μPost := (μPri/σ2Pri)/(n*ȳ/sampvar+1/σ2Pri) + ((n / sampvar) / (n/sampvar + 1/σ2Pri)) σPost := math.Sqrt(σ2Post) t := StudentsTQtlFor(α/2, nu) lo = μPost - t*σPost hi = μPost + t*σPost return lo, hi } */ // Credible interval for unknown Normal μ, with KNOWN σ, and flat prior // Bolstad 2007 (2e): 212, eq. 11.7 func NormMuCrIFPriKnown(nObs int, ȳ, σ, α float64) (lo, hi float64) { // untested ... // ȳ sample mean of observations taken from Normal distribution // σ standard deviation of population, assumed to be known // nObs number of observations // α posterior probability that the true μ lies outside the credible interval n := float64(nObs) μPost := ȳ σ2Post := (σ * σ / n) σPost := math.Sqrt(σ2Post) lo = NormalQtlFor(μPost, σPost, α/2) hi = NormalQtlFor(μPost, σPost, 1-α/2) return lo, hi } /* waiting for StudentsTQtlFor() to be implemented // Credible interval for unknown Normal μ, with UNKNOWN σ, and flat prior // Bolstad 2007 (2e): 212, eq. 11.8 func NormMuCrIFPriUnkn(nObs int, ȳ, σ, α float64) (lo, hi float64) { // ȳ sample mean of observations taken from Normal distribution // σ standard deviation of population, unknown // nObs number of observations // α posterior probability that the true μ lies outside the credible interval // untested ... n := float64(nObs) nu := float64(nObs - 1) μPost := ȳ σ2Post := (σ * σ / n) σPost := math.Sqrt(σ2Post) t := StudentsTQtlFor(α/2, nu) lo = μPost - t*σPost hi = μPost + t*σPost return lo, hi } */
bayes/normal_mu.go
0.701611
0.566438
normal_mu.go
starcoder
package rle import "io" // Compress compresses the given byte array into the given writer. // The optional reference array is used as a delta basis. If provided, bytes will be skipped // where the data equals the reference. func Compress(writer io.Writer, data []byte, reference []byte) error { end := len(data) refLen := len(reference) ref := func(index int) byte { if index < refLen { return reference[index] } return 0x00 } countIdenticalBytes := func(from int) int { index := from for (index < end) && (data[index] == ref(index)) { index++ } return index - from } countConstantBytes := func(from int, value byte) int { index := from for (index < end) && (data[index] == value) { index++ } return index - from } { trailingSkip := 0 for temp := end - 1; (temp >= 0) && (data[temp] == ref(temp)); temp-- { trailingSkip++ } end -= trailingSkip % 0x7FFF } start := 0 for start < end { identicalByteCount := countIdenticalBytes(start) constByteCount := countConstantBytes(start, data[start]) switch { case identicalByteCount > 3: err := skipBytes(writer, identicalByteCount) if err != nil { return err } start += identicalByteCount case constByteCount > 3: err := writeConstant(writer, constByteCount, data[start]) if err != nil { return err } start += constByteCount default: diffByteCount := 0 abort := false for (start+diffByteCount) < end && !abort { nextIdenticalByteCount := countIdenticalBytes(start + diffByteCount) nextConstByteCount := countConstantBytes(start+diffByteCount, data[start+diffByteCount]) if nextIdenticalByteCount < 4 && nextConstByteCount < 4 { if nextIdenticalByteCount > nextConstByteCount { diffByteCount += nextIdenticalByteCount } else { diffByteCount += nextConstByteCount } } else { abort = true } } err := writeRaw(writer, data[start:start+diffByteCount]) if err != nil { return err } start += diffByteCount } } return writeExtended(writer, 0x0000) } func writeExtended(writer io.Writer, control uint16, extra ...byte) error { _, err := writer.Write([]byte{0x80, byte(control & 0xFF), byte((control >> 8) & 0xFF)}) if err != nil { return err } _, err = writer.Write(extra) return err } func skipBytes(writer io.Writer, size int) error { remain := size for remain > 0 { if remain < 0x80 { _, err := writer.Write([]byte{byte(0x80 + remain)}) if err != nil { return err } remain = 0 } else { lenControl := 0x7FFF if remain < lenControl { lenControl = remain } err := writeExtended(writer, uint16(lenControl)) if err != nil { return err } remain -= lenControl } } return nil } func writeConstant(writer io.Writer, size int, value byte) error { start := 0 for start < size { remain := size - start if remain < 0x100 { _, err := writer.Write([]byte{0x00, byte(remain), value}) if err != nil { return err } start = size } else { lenControl := 0x3FFF if remain < lenControl { lenControl = remain } err := writeExtended(writer, 0xC000+uint16(lenControl), value) if err != nil { return err } start += lenControl } } return nil } func writeRaw(writer io.Writer, data []byte) error { end := len(data) start := 0 for start < end { remain := end - start if remain < 0x80 { _, err := writer.Write([]byte{byte(remain)}) if err != nil { return err } _, err = writer.Write(data[start:]) if err != nil { return err } start = end } else { lenControl := 0x3FFF if remain < lenControl { lenControl = remain } err := writeExtended(writer, 0x8000+uint16(lenControl), data[start:start+lenControl]...) if err != nil { return err } start += lenControl } } return nil }
ss1/serial/rle/Compress.go
0.566498
0.556159
Compress.go
starcoder
package heraldry import ( "math/rand" "github.com/ironarachne/random" ) // Tincture is a tincture type Tincture struct { Type string Name string Hexcode string } // Charge is a charge type Charge struct { Identifier string Name string Noun string NounPlural string Descriptor string Article string SingleOnly bool Tags []string } // ChargeGroup is a group of charges with a common tincture type ChargeGroup struct { Charges []Charge Tincture } // Division is a division of the field type Division struct { Name string Blazon string Tincture } // Variation is a variation of the field type Variation struct { Name string Tincture1 Tincture Tincture2 Tincture } // Field is the field of a coat of arms type Field struct { Division Tincture HasVariation bool Variation } // Device is the entire coat of arms type Device struct { Field ChargeGroups []ChargeGroup AllTinctures []Tincture } func randomCharge() Charge { return AvailableCharges[rand.Intn(len(AvailableCharges))] } func randomDivision() Division { return AvailableDivisions[rand.Intn(len(AvailableDivisions))] } func randomTincture() Tincture { typeOfTincture := random.ItemFromThresholdMap(tinctureChances) if typeOfTincture == "metal" { return randomTinctureMetal() } else if typeOfTincture == "color" { return randomTinctureColor() } else if typeOfTincture == "stain" { return randomTinctureStain() } return randomTinctureFur() } func randomTinctureColor() Tincture { t := Colors[rand.Intn(len(Colors))] return t } func randomTinctureFur() Tincture { t := Furs[rand.Intn(len(Furs))] return t } func randomTinctureMetal() Tincture { t := Metals[rand.Intn(len(Metals))] return t } func randomTinctureStain() Tincture { t := Stains[rand.Intn(len(Stains))] return t } func randomComplementaryTincture(t Tincture) Tincture { var availableTinctures []Tincture if t.Type == "color" || t.Type == "stain" { typeOfTincture := random.ItemFromThresholdMap(colorOrStainChances) if typeOfTincture == "color" { for _, color := range Colors { if color.Name != t.Name { availableTinctures = append(availableTinctures, color) } } } else { for _, stain := range Stains { if stain.Name != t.Name { availableTinctures = append(availableTinctures, stain) } } } } else { for _, metal := range Metals { if metal.Name != t.Name { availableTinctures = append(availableTinctures, metal) } } } t2 := availableTinctures[rand.Intn(len(availableTinctures))] return t2 } func randomContrastingTincture(t Tincture) Tincture { t2 := Tincture{} if t.Type == "metal" { typeOfTincture := random.ItemFromThresholdMap(colorOrStainChances) if typeOfTincture == "color" { t2 = randomTinctureColor() } else { t2 = randomTinctureStain() } } else { t2 = randomTinctureMetal() } return t2 } func shallWeIncludeCharges() bool { someRandomValue := rand.Intn(10) if someRandomValue > 2 { return true } return false } // Generate procedurally generates a random heraldic device and returns it. func Generate() Device { fieldTincture1 := randomTincture() fieldTincture2 := randomComplementaryTincture(fieldTincture1) chargeTincture := randomContrastingTincture(fieldTincture1) var tinctures []Tincture fieldHasContrastingTinctures := false if rand.Intn(10) > 1 { fieldHasContrastingTinctures = true } if fieldHasContrastingTinctures { fieldTincture2 = randomContrastingTincture(fieldTincture1) } division := randomDivision() division.Tincture = fieldTincture2 field := Field{Division: division, Tincture: fieldTincture1, HasVariation: false, Variation: Variation{}} if shallWeHaveAVariation() { variation := randomVariation() variation.Tincture1 = randomTincture() variation.Tincture2 = randomContrastingTincture(variation.Tincture1) tinctures = append(tinctures, variation.Tincture1, variation.Tincture2) field.HasVariation = true field.Variation = variation } tinctures = append(tinctures, fieldTincture1) tinctures = append(tinctures, fieldTincture2) var charges []Charge var chargeGroups []ChargeGroup if shallWeIncludeCharges() { charge := randomCharge() chargeCountRanking := rand.Intn(10) countOfCharges := 1 if chargeCountRanking >= 9 && !charge.SingleOnly { countOfCharges = 3 } else if chargeCountRanking >= 7 && chargeCountRanking < 9 && !charge.SingleOnly { countOfCharges = 2 } for i := 0; i < countOfCharges; i++ { charges = append(charges, charge) } chargeGroup := ChargeGroup{charges, chargeTincture} tinctures = append(tinctures, chargeTincture) chargeGroups = append(chargeGroups, chargeGroup) } d := Device{Field: field, ChargeGroups: chargeGroups, AllTinctures: tinctures} return d }
heraldry.go
0.573917
0.408218
heraldry.go
starcoder
package rotateflip import ( "image" "image/color" "github.com/ncruces/go-image/imageutil" ) // Operation specifies a clockwise rotation and flip operation to apply to an image. type Operation int const ( None Operation = iota Rotate90 Rotate180 Rotate270 FlipX Transpose FlipY Transverse FlipXY = Rotate180 Rotate90FlipX = Transpose Rotate180FlipX = FlipY Rotate270FlipX = Transverse Rotate90FlipY = Transverse Rotate180FlipY = FlipX Rotate270FlipY = Transpose Rotate90FlipXY = Rotate270 Rotate180FlipXY = None Rotate270FlipXY = Rotate90 ) // Orientation is an image orientation as specified by EXIF 2.2 and TIFF 6.0. type Orientation int const ( TopLeft Orientation = iota + 1 TopRight BottomRight BottomLeft LeftTop RightTop RightBottom LeftBottom ) // Op gets the Operation that restores an image with this Orientation to TopLeft Orientation. func (or Orientation) Op() Operation { switch or { default: return None case TopRight: return FlipX case BottomRight: return FlipXY case BottomLeft: return FlipY case LeftTop: return Transpose case RightTop: return Rotate90 case RightBottom: return Transverse case LeftBottom: return Rotate270 } } // Image applies an Operation to an image. func Image(src image.Image, op Operation) image.Image { op &= 7 // sanitize if op == 0 { return src // nop } bounds := rotateBounds(src.Bounds(), op) // fast path, eager switch src := src.(type) { case *image.Alpha: dst := image.NewAlpha(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 1) return dst case *image.Alpha16: dst := image.NewAlpha16(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 2) return dst case *image.CMYK: dst := image.NewCMYK(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 4) return dst case *image.Gray: dst := image.NewGray(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 1) return dst case *image.Gray16: dst := image.NewGray16(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 2) return dst case *image.NRGBA: dst := image.NewNRGBA(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 4) return dst case *image.NRGBA64: dst := image.NewNRGBA64(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 8) return dst case *image.RGBA: dst := image.NewRGBA(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 4) return dst case *image.RGBA64: dst := image.NewRGBA64(bounds) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 8) return dst case *image.Paletted: dst := image.NewPaletted(bounds, src.Palette) rotateFlip(dst.Pix, dst.Stride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Pix, src.Stride, src.Bounds().Dx(), src.Bounds().Dy(), op, 1) return dst case *image.YCbCr: sr, ok := rotateYCbCrSubsampleRatio(src.SubsampleRatio, src.Bounds(), op) if !ok { src = imageutil.YCbCrUpsample(src) sr = src.SubsampleRatio } dst := image.NewYCbCr(bounds, sr) srcCBounds := subsampledBounds(src.Bounds(), src.SubsampleRatio) dstCBounds := subsampledBounds(dst.Bounds(), dst.SubsampleRatio) rotateFlip(dst.Y, dst.YStride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Y, src.YStride, src.Bounds().Dx(), src.Bounds().Dy(), op, 1) rotateFlip(dst.Cb, dst.CStride, dstCBounds.Dx(), dstCBounds.Dy(), src.Cb, src.CStride, srcCBounds.Dx(), srcCBounds.Dy(), op, 1) rotateFlip(dst.Cr, dst.CStride, dstCBounds.Dx(), dstCBounds.Dy(), src.Cr, src.CStride, srcCBounds.Dx(), srcCBounds.Dy(), op, 1) return dst case *image.NYCbCrA: sr, ok := rotateYCbCrSubsampleRatio(src.SubsampleRatio, src.Bounds(), op) if !ok { src = imageutil.NYCbCrAUpsample(src) sr = src.SubsampleRatio } dst := image.NewNYCbCrA(bounds, sr) srcCBounds := subsampledBounds(src.Bounds(), src.SubsampleRatio) dstCBounds := subsampledBounds(dst.Bounds(), dst.SubsampleRatio) rotateFlip(dst.Y, dst.YStride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.Y, src.YStride, src.Bounds().Dx(), src.Bounds().Dy(), op, 1) rotateFlip(dst.A, dst.AStride, dst.Bounds().Dx(), dst.Bounds().Dy(), src.A, src.AStride, src.Bounds().Dx(), src.Bounds().Dy(), op, 1) rotateFlip(dst.Cb, dst.CStride, dstCBounds.Dx(), dstCBounds.Dy(), src.Cb, src.CStride, srcCBounds.Dx(), srcCBounds.Dy(), op, 1) rotateFlip(dst.Cr, dst.CStride, dstCBounds.Dx(), dstCBounds.Dy(), src.Cr, src.CStride, srcCBounds.Dx(), srcCBounds.Dy(), op, 1) return dst } // slow path, lazy return &rotateFlipImage{src, op} } type rotateFlipImage struct { src image.Image op Operation } func (rft *rotateFlipImage) ColorModel() color.Model { return rft.src.ColorModel() } func (rft *rotateFlipImage) Bounds() image.Rectangle { return rotateBounds(rft.src.Bounds(), rft.op) } func (rft *rotateFlipImage) At(x, y int) color.Color { bounds := rft.src.Bounds() switch rft.op { default: return rft.src.At(bounds.Min.X+x, bounds.Min.Y+y) case FlipX: return rft.src.At(bounds.Max.X-x-1, bounds.Min.Y+y) case FlipXY: return rft.src.At(bounds.Max.X-x-1, bounds.Max.Y-y-1) case FlipY: return rft.src.At(bounds.Min.X+x, bounds.Max.Y-y-1) case Transpose: return rft.src.At(bounds.Min.X+y, bounds.Min.Y+x) case Rotate90: return rft.src.At(bounds.Min.X+y, bounds.Max.Y-x-1) case Transverse: return rft.src.At(bounds.Max.X-y-1, bounds.Max.Y-x-1) case Rotate270: return rft.src.At(bounds.Max.X-y-1, bounds.Min.Y+x) } } func rotateFlip(dst []uint8, dst_stride, dst_width, dst_height int, src []uint8, src_stride, src_width, src_height int, op Operation, bpp int) { rotate := op&1 != 0 flip_y := op&2 != 0 flip_x := parity(op) var dst_row, src_row int if flip_x { dst_row += bpp * (dst_width - 1) } if flip_y { dst_row += dst_stride * (dst_height - 1) } var dst_x_offset, dst_y_offset int if rotate { if flip_x { dst_y_offset = -bpp } else { dst_y_offset = +bpp } if flip_y { dst_x_offset = -dst_stride } else { dst_x_offset = +dst_stride } } else { if flip_x { dst_x_offset = -bpp } else { dst_x_offset = +bpp } if flip_y { dst_y_offset = -dst_stride } else { dst_y_offset = +dst_stride } } if dst_x_offset == bpp { for y := 0; y < src_height; y++ { copy(dst[dst_row:], src[src_row:src_row+src_width*bpp]) dst_row += dst_y_offset src_row += src_stride } } else { for y := 0; y < src_height; y++ { dst_pix := dst_row src_pix := src_row for x := 0; x < src_width; x++ { copy(dst[dst_pix:], src[src_pix:src_pix+bpp]) dst_pix += dst_x_offset src_pix += bpp } dst_row += dst_y_offset src_row += src_stride } } } func rotateBounds(bounds image.Rectangle, op Operation) image.Rectangle { var dx, dy int if rotate := op&1 != 0; rotate { dx = bounds.Dy() dy = bounds.Dx() } else { dx = bounds.Dx() dy = bounds.Dy() } return image.Rectangle{image.ZP, image.Point{dx, dy}} } func rotateYCbCrSubsampleRatio(subsampleRatio image.YCbCrSubsampleRatio, bounds image.Rectangle, op Operation) (image.YCbCrSubsampleRatio, bool) { switch subsampleRatio { case image.YCbCrSubsampleRatio444: return subsampleRatio, true case image.YCbCrSubsampleRatio420: if (bounds.Min.X|bounds.Max.X|bounds.Min.Y|bounds.Max.Y)&1 != 0 { break } return subsampleRatio, true case image.YCbCrSubsampleRatio422: if (bounds.Min.X|bounds.Max.X)&1 != 0 { break } if rotate := op&1 != 0; rotate { return image.YCbCrSubsampleRatio440, true } return subsampleRatio, true case image.YCbCrSubsampleRatio440: if (bounds.Min.Y|bounds.Max.Y)&1 != 0 { break } if rotate := op&1 != 0; rotate { return image.YCbCrSubsampleRatio422, true } return subsampleRatio, true case image.YCbCrSubsampleRatio411, image.YCbCrSubsampleRatio410: if (bounds.Min.X|bounds.Max.X)&3 != 0 { break } if (bounds.Min.Y|bounds.Max.Y)&1 != 0 { break } if rotate := op&1 != 0; rotate { break } return subsampleRatio, true } return -1, false } func subsampledBounds(bounds image.Rectangle, subsampleRatio image.YCbCrSubsampleRatio) image.Rectangle { switch subsampleRatio { default: panic("Unknown YCbCrSubsampleRatio") case image.YCbCrSubsampleRatio440: bounds.Min.Y = (bounds.Min.Y + 0) / 2 bounds.Max.Y = (bounds.Max.Y + 1) / 2 fallthrough case image.YCbCrSubsampleRatio444: case image.YCbCrSubsampleRatio420: bounds.Min.Y = (bounds.Min.Y + 0) / 2 bounds.Max.Y = (bounds.Max.Y + 1) / 2 fallthrough case image.YCbCrSubsampleRatio422: bounds.Min.X = (bounds.Min.X + 0) / 2 bounds.Max.X = (bounds.Max.X + 1) / 2 case image.YCbCrSubsampleRatio410: bounds.Min.Y = (bounds.Min.Y + 0) / 2 bounds.Max.Y = (bounds.Max.Y + 1) / 2 fallthrough case image.YCbCrSubsampleRatio411: bounds.Min.X = (bounds.Min.X + 0) / 4 bounds.Max.X = (bounds.Max.X + 3) / 4 } return bounds } func parity(op Operation) bool { op = 0226 >> uint8(op) return op&1 != 0 }
rotateflip/rotateflip.go
0.773644
0.41947
rotateflip.go
starcoder
package geom import ( "fmt" "math" "github.com/peterstace/simplefeatures/rtree" ) // XY represents a pair of X and Y coordinates. This can either represent a // location on the XY plane, or a 2D vector in the real vector space. type XY struct { X, Y float64 } // validate checks if the XY value contains NaN, -inf, or +inf. func (w XY) validate() error { if math.IsNaN(w.X) || math.IsInf(w.X, 0) { return fmt.Errorf("invalid X value: %v", w.X) } if math.IsNaN(w.Y) || math.IsInf(w.Y, 0) { return fmt.Errorf("invalid Y value: %v", w.Y) } return nil } // AsPoint is a convenience function to convert this XY value into a Point // geometry. func (w XY) AsPoint(opts ...ConstructorOption) (Point, error) { coords := Coordinates{XY: w, Type: DimXY} return NewPoint(coords, opts...) } // asUncheckedPoint is a convenience function to convert this XY value into a // Point. The Point is constructed without checking any validations. It may be // used internally when the caller is sure that the XY value doesn't come // directly from outside of the library without first being validated. func (w XY) asUncheckedPoint() Point { coords := Coordinates{XY: w, Type: DimXY} return newUncheckedPoint(coords) } // uncheckedEnvelope is a convenience function to convert this XY value into // a (degenerate) envelope that represents a single XY location (i.e. a zero // area envelope). It may be used internally when the caller is sure that the // XY value doesn't come directly from outline the library without first being // validated. func (w XY) uncheckedEnvelope() Envelope { return newUncheckedEnvelope(w, w) } // Sub returns the result of subtracting the other XY from this XY (in the same // manner as vector subtraction). func (w XY) Sub(o XY) XY { return XY{ w.X - o.X, w.Y - o.Y, } } // Add returns the result of adding this XY to another XY (in the same manner // as vector addition). func (w XY) Add(o XY) XY { return XY{ w.X + o.X, w.Y + o.Y, } } // Scale returns the XY where the X and Y have been scaled by s. func (w XY) Scale(s float64) XY { return XY{ w.X * s, w.Y * s, } } // Cross returns the 2D cross product of this and another XY. This is defined // as the 'z' coordinate of the regular 3D cross product. func (w XY) Cross(o XY) float64 { return (w.X * o.Y) - (w.Y * o.X) } // Midpoint returns the midpoint of this and another XY. func (w XY) Midpoint(o XY) XY { return w.Add(o).Scale(0.5) } // Dot returns the dot product of this and another XY. func (w XY) Dot(o XY) float64 { return w.X*o.X + w.Y*o.Y } // Unit treats the XY as a vector, and scales it to have unit length. func (w XY) Unit() XY { return w.Scale(1 / w.Length()) } // Length treats XY as a vector, and returns its length. func (w XY) Length() float64 { return math.Sqrt(w.Dot(w)) } // Less gives an ordering on XYs. If two XYs have different X values, then the // one with the lower X value is ordered before the one with the higher X // value. If the X values are then same, then the Y values are used (the lower // Y value comes first). func (w XY) Less(o XY) bool { if w.X != o.X { return w.X < o.X } return w.Y < o.Y } func (w XY) distanceTo(o XY) float64 { return math.Sqrt(w.distanceSquaredTo(o)) } func (w XY) distanceSquaredTo(o XY) float64 { delta := o.Sub(w) return delta.Dot(delta) } func (w XY) box() rtree.Box { return rtree.Box{ MinX: w.X, MinY: w.Y, MaxX: w.X, MaxY: w.Y, } }
geom/xy.go
0.901877
0.653521
xy.go
starcoder
package main import ( "context" "fmt" "strconv" "strings" "github.com/pkg/errors" ) // performanceExpectations is a map from workload to a map from core count to // expected throughput below which we consider the test to have failed. var performanceExpectations = map[string]map[int]float64{ // The below numbers are minimum expectations based on historical data. "A": {8: 2000}, "B": {8: 15000}, } func getPerformanceExpectation(wl string, cpus int) (float64, bool) { m, exists := performanceExpectations[cloud] if !exists { return 0, false } expected, exists := m[cpus] return expected, exists } func parseThroughputFromOutput(output string) (opsPerSec float64, _ error) { prefix := "__result\n" // this string precedes the cumulative results idx := strings.LastIndex(output, prefix) if idx == -1 { return 0, fmt.Errorf("failed to find %q in output", prefix) } return strconv.ParseFloat(strings.Fields(output[idx+len(prefix):])[3], 64) } func registerYCSB(r *registry) { runYCSB := func(ctx context.Context, t *test, c *cluster, wl string, cpus int) { nodes := c.nodes - 1 c.Put(ctx, cockroach, "./cockroach", c.Range(1, nodes)) c.Put(ctx, workload, "./workload", c.Node(nodes+1)) c.Start(ctx, t, c.Range(1, nodes)) t.Status("running workload") m := newMonitor(ctx, c, c.Range(1, nodes)) m.Go(func(ctx context.Context) error { ramp := " --ramp=" + ifLocal("0s", "1m") duration := " --duration=" + ifLocal("10s", "10m") cmd := fmt.Sprintf( "./workload run ycsb --init --initial-rows=1000000 --splits=100"+ " --workload=%s --concurrency=64 --histograms=logs/stats.json"+ ramp+duration+" {pgurl:1-%d}", wl, nodes) out, err := c.RunWithBuffer(ctx, t.l, c.Node(nodes+1), cmd) if err != nil { return errors.Wrapf(err, "failed with output %q", string(out)) } if expected, ok := getPerformanceExpectation(wl, cpus); ok { throughput, err := parseThroughputFromOutput(string(out)) if err != nil { return err } t.debugEnabled = teamCity if throughput < expected { return fmt.Errorf("%v failed to meet throughput expectations: "+ "observed %v, expected at least %v", t.Name(), expected, throughput) } c.l.Printf("Observed throughput of %v > %v", throughput, expected) } return nil }) m.Wait() } for _, wl := range []string{"A", "B", "C", "D", "E", "F"} { if wl == "D" || wl == "E" { // These workloads are currently unsupported by workload. // See TODOs in workload/ycsb/ycsb.go. continue } for _, cpus := range []int{8, 32} { var name string if cpus == 8 { // support legacy test name which didn't include cpu name = fmt.Sprintf("ycsb/%s/nodes=3", wl) } else { name = fmt.Sprintf("ycsb/%s/nodes=3/cpu=%d", wl, cpus) } wl, cpus := wl, cpus r.Add(testSpec{ Name: name, Cluster: makeClusterSpec(4, cpu(cpus)), Run: func(ctx context.Context, t *test, c *cluster) { runYCSB(ctx, t, c, wl, cpus) }, }) } } }
pkg/cmd/roachtest/ycsb.go
0.624179
0.46557
ycsb.go
starcoder
package common import ( "fmt" "sort" "go.opentelemetry.io/collector/model/pdata" ) func SortResourceMetrics(rm pdata.ResourceMetricsSlice) { for i := 0; i < rm.Len(); i++ { r := rm.At(i) for j := 0; j < r.InstrumentationLibraryMetrics().Len(); j++ { il := r.InstrumentationLibraryMetrics().At(j) for k := 0; k < il.Metrics().Len(); k++ { m := il.Metrics().At(k) switch m.DataType() { case pdata.MetricDataTypeGauge: for l := 0; l < m.Gauge().DataPoints().Len(); l++ { m.Gauge().DataPoints().At(l).Attributes().Sort() } case pdata.MetricDataTypeSum: for l := 0; l < m.Sum().DataPoints().Len(); l++ { m.Sum().DataPoints().At(l).Attributes().Sort() } case pdata.MetricDataTypeHistogram: for l := 0; l < m.Histogram().DataPoints().Len(); l++ { sortBuckets(m.Histogram().DataPoints().At(l)) m.Histogram().DataPoints().At(l).Attributes().Sort() } case pdata.MetricDataTypeSummary: for l := 0; l < m.Summary().DataPoints().Len(); l++ { m.Summary().DataPoints().At(l).Attributes().Sort() m.Summary().DataPoints().At(l).QuantileValues().Sort(func(a, b pdata.ValueAtQuantile) bool { return a.Quantile() < b.Quantile() }) } default: panic(fmt.Sprintf("unsupported metric data type %d", m.DataType())) } } il.Metrics().Sort(func(a, b pdata.Metric) bool { return a.Name() < b.Name() }) } r.InstrumentationLibraryMetrics().Sort(func(a, b pdata.InstrumentationLibraryMetrics) bool { if a.InstrumentationLibrary().Name() == b.InstrumentationLibrary().Name() { return a.InstrumentationLibrary().Version() < b.InstrumentationLibrary().Version() } return a.InstrumentationLibrary().Name() < b.InstrumentationLibrary().Name() }) r.Resource().Attributes().Sort() } } func sortBuckets(hdp pdata.HistogramDataPoint) { buckets := make(sortableBuckets, len(hdp.ExplicitBounds())) for i := range hdp.ExplicitBounds() { buckets[i] = sortableBucket{hdp.BucketCounts()[i], hdp.ExplicitBounds()[i]} } sort.Sort(buckets) for i, bucket := range buckets { hdp.BucketCounts()[i], hdp.ExplicitBounds()[i] = bucket.count, bucket.bound } } type sortableBucket struct { count uint64 bound float64 } type sortableBuckets []sortableBucket func (s sortableBuckets) Len() int { return len(s) } func (s sortableBuckets) Less(i, j int) bool { return s[i].bound < s[j].bound } func (s sortableBuckets) Swap(i, j int) { s[i].count, s[j].count = s[j].count, s[i].count s[i].bound, s[j].bound = s[j].bound, s[i].bound }
common/metrics_sort.go
0.559531
0.487978
metrics_sort.go
starcoder
package packed import ( "github.com/gzg1984/golucene/core/util" ) // Direct wrapping of 32-bits values to a backing array. type Direct32 struct { *MutableImpl values []int32 } func newDirect32(valueCount int) *Direct32 { ans := &Direct32{ values: make([]int32, valueCount), } ans.MutableImpl = newMutableImpl(ans, valueCount, 32) return ans } func newDirect32FromInput(version int32, in DataInput, valueCount int) (r PackedIntsReader, err error) { ans := newDirect32(valueCount) for i, _ := range ans.values { if ans.values[i], err = in.ReadInt(); err != nil { break } } if err == nil { // because packed ints have not always been byte-aligned remaining := PackedFormat(PACKED).ByteCount(version, int32(valueCount), 32) - 4*int64(valueCount) for i := int64(0); i < remaining; i++ { if _, err = in.ReadByte(); err != nil { break } } } return ans, err } func (d *Direct32) Get(index int) int64 { return int64(d.values[index]) & 0xFFFFFFFF } func (d *Direct32) Set(index int, value int64) { d.values[index] = int32(value) } func (d *Direct32) RamBytesUsed() int64 { return util.AlignObjectSize( util.NUM_BYTES_OBJECT_HEADER + 2*util.NUM_BYTES_INT + util.NUM_BYTES_OBJECT_REF + util.SizeOf(d.values)) } func (d *Direct32) Clear() { for i, _ := range d.values { d.values[i] = 0 } } func (d *Direct32) getBulk(index int, arr []int64) int { assert2(len(arr) > 0, "len must be > 0 (got %v)", len(arr)) assert(index >= 0 && index < d.valueCount) gets := d.valueCount - index if len(arr) < gets { gets = len(arr) } for i, _ := range arr[:gets] { arr[i] = int64(d.values[index+i]) & 0xFFFFFFFF } return gets } func (d *Direct32) setBulk(index int, arr []int64) int { assert2(len(arr) > 0, "len must be > 0 (got %v)", len(arr)) assert(index >= 0 && index < d.valueCount) sets := d.valueCount - index if len(arr) < sets { sets = len(arr) } for i, _ := range arr { d.values[index+i] = int32(arr[i]) } return sets } func (d *Direct32) fill(from, to int, val int64) { assert(val == val & 0xFFFFFFFF) for i := from; i < to; i ++ { d.values[i] = int32(val) } }
core/util/packed/direct32.go
0.523177
0.497986
direct32.go
starcoder
package toml import ( "fmt" "reflect" "time" ) // supported values: // string, bool, int64, uint64, float64, time.Time, int, int8, int16, int32, uint, uint8, uint16, uint32, float32 var kindToTypeMapping = map[reflect.Kind]reflect.Type{ reflect.Bool: reflect.TypeOf(true), reflect.String: reflect.TypeOf(""), reflect.Float32: reflect.TypeOf(float64(1)), reflect.Float64: reflect.TypeOf(float64(1)), reflect.Int: reflect.TypeOf(int64(1)), reflect.Int8: reflect.TypeOf(int64(1)), reflect.Int16: reflect.TypeOf(int64(1)), reflect.Int32: reflect.TypeOf(int64(1)), reflect.Int64: reflect.TypeOf(int64(1)), reflect.Uint: reflect.TypeOf(uint64(1)), reflect.Uint8: reflect.TypeOf(uint64(1)), reflect.Uint16: reflect.TypeOf(uint64(1)), reflect.Uint32: reflect.TypeOf(uint64(1)), reflect.Uint64: reflect.TypeOf(uint64(1)), } func simpleValueCoercion(object interface{}) (interface{}, error) { switch original := object.(type) { case string, bool, int64, uint64, float64, time.Time: return original, nil case int: return int64(original), nil case int8: return int64(original), nil case int16: return int64(original), nil case int32: return int64(original), nil case uint: return uint64(original), nil case uint8: return uint64(original), nil case uint16: return uint64(original), nil case uint32: return uint64(original), nil case float32: return float64(original), nil case fmt.Stringer: return original.String(), nil default: return nil, fmt.Errorf("cannot convert type %T to Tree", object) } } func sliceToTree(object interface{}) (interface{}, error) { // arrays are a bit tricky, since they can represent either a // collection of simple values, which is represented by one // *tomlValue, or an array of tables, which is represented by an // array of *Tree. // holding the assumption that this function is called from toTree only when value.Kind() is Array or Slice value := reflect.ValueOf(object) insideType := value.Type().Elem() length := value.Len() if length > 0 { insideType = reflect.ValueOf(value.Index(0).Interface()).Type() } if insideType.Kind() == reflect.Map { // this is considered as an array of tables tablesArray := make([]*Tree, 0, length) for i := 0; i < length; i++ { table := value.Index(i) tree, err := toTree(table.Interface()) if err != nil { return nil, err } tablesArray = append(tablesArray, tree.(*Tree)) } return tablesArray, nil } sliceType := kindToTypeMapping[insideType.Kind()] if sliceType == nil { sliceType = insideType } arrayValue := reflect.MakeSlice(reflect.SliceOf(sliceType), 0, length) for i := 0; i < length; i++ { val := value.Index(i).Interface() simpleValue, err := simpleValueCoercion(val) if err != nil { return nil, err } arrayValue = reflect.Append(arrayValue, reflect.ValueOf(simpleValue)) } return &tomlValue{arrayValue.Interface(), Position{}}, nil } func toTree(object interface{}) (interface{}, error) { value := reflect.ValueOf(object) if value.Kind() == reflect.Map { values := map[string]interface{}{} keys := value.MapKeys() for _, key := range keys { if key.Kind() != reflect.String { if _, ok := key.Interface().(string); !ok { return nil, fmt.Errorf("map key needs to be a string, not %T (%v)", key.Interface(), key.Kind()) } } v := value.MapIndex(key) newValue, err := toTree(v.Interface()) if err != nil { return nil, err } values[key.String()] = newValue } return &Tree{values, Position{}}, nil } if value.Kind() == reflect.Array || value.Kind() == reflect.Slice { return sliceToTree(object) } simpleValue, err := simpleValueCoercion(object) if err != nil { return nil, err } return &tomlValue{simpleValue, Position{}}, nil }
vendor/github.com/pelletier/go-toml/tomltree_create.go
0.59408
0.424651
tomltree_create.go
starcoder
package mlmetrics import ( "math" "sync" ) // ConfusionMatrix can be used to visualize the performance of a binary // classifier. type ConfusionMatrix struct { mat resizableMatrix mu sync.RWMutex } // NewConfusionMatrix inits a new ConfusionMatrix. func NewConfusionMatrix() *ConfusionMatrix { return new(ConfusionMatrix) } // Reset resets the state. func (m *ConfusionMatrix) Reset() { m.mu.Lock() m.mat = resizableMatrix{} m.mu.Unlock() } // Observe records an observation of the actual vs the predicted category. func (m *ConfusionMatrix) Observe(actual, predicted int) { m.ObserveWeight(actual, predicted, 1.0) } // ObserveWeight records an observation of the actual vs the predicted category with a given weight. func (m *ConfusionMatrix) ObserveWeight(actual, predicted int, weight float64) { if !isValidCategory(actual) || !isValidCategory(predicted) || !isValidWeight(weight) { return } m.mu.Lock() m.mat.Set(actual, predicted, m.mat.At(actual, predicted)+weight) m.mu.Unlock() } // Order returns the matrix order (number or rows/cols). func (m *ConfusionMatrix) Order() int { m.mu.RLock() size := m.mat.size m.mu.RUnlock() return size } // TotalWeight returns the total weight observed (sum of the matrix). func (m *ConfusionMatrix) TotalWeight() float64 { m.mu.RLock() sum := m.mat.Sum() m.mu.RUnlock() return sum } // Row returns the distribution of predicted weights for category x. func (m *ConfusionMatrix) Row(x int) []float64 { m.mu.RLock() defer m.mu.RUnlock() if x >= m.mat.size { return nil } row := make([]float64, m.mat.size) copy(row, m.mat.Row(x)) return row } // Column returns the distribution of actual weights for category x. func (m *ConfusionMatrix) Column(x int) []float64 { m.mu.RLock() defer m.mu.RUnlock() if x >= m.mat.size { return nil } col := make([]float64, m.mat.size) for i := 0; i < m.mat.size; i++ { col[i] = m.mat.At(i, x) } return col } // Accuracy returns the overall accuracy rate. func (m *ConfusionMatrix) Accuracy() float64 { m.mu.RLock() defer m.mu.RUnlock() sum := m.mat.Sum() if sum == 0.0 { return 0.0 } var pos float64 for i := 0; i < m.mat.size; i++ { pos += m.mat.At(i, i) } return pos / sum } // Precision calculates the positive predictive value for category x. func (m *ConfusionMatrix) Precision(x int) float64 { m.mu.RLock() defer m.mu.RUnlock() sum := m.mat.ColSum(x) if sum == 0.0 { return 0.0 } return m.mat.At(x, x) / sum } // Sensitivity calculates the recall (aka 'hit rate') for category x. func (m *ConfusionMatrix) Sensitivity(x int) float64 { m.mu.RLock() defer m.mu.RUnlock() sum := m.mat.RowSum(x) if sum == 0.0 { return 0.0 } return m.mat.At(x, x) / sum } // F1 calculates the F1 score for category x, the harmonic mean of precision and sensitivity. func (m *ConfusionMatrix) F1(x int) float64 { m.mu.RLock() defer m.mu.RUnlock() csm := m.mat.ColSum(x) if csm == 0 { return 0 } rsm := m.mat.RowSum(x) if rsm == 0 { return 0 } pos := m.mat.At(x, x) precision := pos / csm sensitivity := pos / rsm return 2 * precision * sensitivity / (precision + sensitivity) } // Kappa represents the Cohen's Kappa, a statistic which measures inter-rater agreement for qualitative // (categorical) items. It is generally thought to be a more robust measure than simple percent agreement // calculation, as κ takes into account the possibility of the agreement occurring by chance. // https://en.wikipedia.org/wiki/Cohen%27s_kappa func (m *ConfusionMatrix) Kappa() float64 { m.mu.RLock() defer m.mu.RUnlock() sum := m.mat.Sum() if sum == 0.0 { return 0.0 } var obs, exp float64 for i := 0; i < m.mat.size; i++ { obs += m.mat.At(i, i) exp += m.mat.RowSum(i) * m.mat.ColSum(i) / sum } if div := sum - exp; div != 0 { return (obs - exp) / div } return 1.0 } // Matthews is a correlation coefficient used as a measure of the quality of binary // and multiclass classifications. It takes into account true and false positives // and negatives and is generally regarded as a balanced measure which can be // used even if the classes are of very different sizes. The MCC is in essence // a correlation coefficient value between -1 and +1. A coefficient of +1 represents // a perfect prediction, 0 an average random prediction and -1 an inverse prediction. // The statistic is also known as the phi coefficient. [source: Wikipedia] func (m *ConfusionMatrix) Matthews() float64 { m.mu.RLock() defer m.mu.RUnlock() sum := m.mat.Sum() if sum == 0.0 { return 0.0 } var exp, cf1, cf2, cf3 float64 for i := 0; i < m.mat.size; i++ { rsum := m.mat.RowSum(i) csum := m.mat.ColSum(i) exp += m.mat.At(i, i) cf1 += rsum * csum cf2 += rsum * rsum cf3 += csum * csum } sum2 := sum * sum if pdt := (sum2 - cf2) * (sum2 - cf3); pdt != 0 { return ((exp * sum) - cf1) / math.Sqrt(pdt) } return 0 } type resizableMatrix struct { size int data []float64 } // Set sets the field at (i, j) to v func (m *resizableMatrix) Set(i, j int, v float64) { m.resize(maxInt(i+1, j+1)) m.data[i*m.size+j] = v } // At returns the value at (i, j) func (m *resizableMatrix) At(i, j int) float64 { if i < m.size && j < m.size { return m.data[i*m.size+j] } return 0 } // Row returns the slice of row at i. func (m *resizableMatrix) Row(i int) []float64 { if i >= 0 && i < m.size { offset := i * m.size return m.data[offset : offset+m.size] } return nil } // RowSum returns the sum of values in row (i). func (m *resizableMatrix) RowSum(i int) (sum float64) { if i >= 0 && i < m.size { offset := (i * m.size) for k := offset; k < offset+m.size; k++ { sum += m.data[k] } } return } // RowSum returns the sum of values in col (j). func (m *resizableMatrix) ColSum(j int) (sum float64) { if j >= 0 && j < m.size { for k := j; k < len(m.data); k += m.size { sum += m.data[k] } } return } // Sum calculates the sum of all cells. func (m *resizableMatrix) Sum() float64 { sum := 0.0 for _, v := range m.data { sum += v } return sum } func (m *resizableMatrix) resize(n int) { if n <= m.size { return } data := make([]float64, n*n) for row := 0; row < m.size; row++ { offset := row * m.size copy(data[row*n:], m.data[offset:offset+m.size]) } m.size = n m.data = data }
confusion.go
0.844088
0.583767
confusion.go
starcoder
package main import ( "flag" "fmt" "log" "math" "os" "strconv" ) func main() { flag.Parse() if flag.NArg() != 3 { usage() } val, _ := strconv.ParseFloat(flag.Arg(0), 64) from := flag.Arg(1) to := flag.Arg(2) val, err := conv(val, from, to) if err != nil { log.Fatal(err) } fmt.Println(val) } func usage() { fmt.Fprintln(os.Stderr, "usage: value from to") flag.PrintDefaults() fmt.Fprintln(os.Stderr, "") fmt.Fprintln(os.Stderr, "available conversions:") fmt.Fprintln(os.Stderr, "arcsec deg rad") fmt.Fprintln(os.Stderr, "nautical_mile meter mile") os.Exit(2) } func unitcode(unit string) int { switch unit { case "arcsec", "deg", "rad": return 1 case "nautical_mile", "meter", "mile": return 2 } return 0 } func conv(val float64, from, to string) (float64, error) { if unitcode(from) != unitcode(to) { return 0, fmt.Errorf("conversion %q to %q not supported", from, to) } var x, y float64 switch from { case "rad": x = val case "deg": x = deg2rad(val) case "arcsec": x = arcsec2rad(val) case "nautical_mile": x = nautical2meter(val) case "mile": x = mile2meter(val) case "meter": x = val default: return 0, fmt.Errorf("unsupported type: %v", from) } switch to { case "rad": y = x case "deg": y = rad2deg(x) case "arcsec": y = rad2arcsec(x) case "nautical_mile": y = meter2nautical(x) case "mile": y = meter2mile(x) case "meter": y = x default: return 0, fmt.Errorf("unsupported type: %v", to) } return y, nil } // https://en.wikipedia.org/wiki/Minute_and_second_of_arc func arcsec2deg(a float64) float64 { return a / 3600 } func deg2arcsec(a float64) float64 { return a * 3600 } func arcsec2rad(a float64) float64 { return a * math.Pi / 648000 } func rad2arcsec(r float64) float64 { return r * 648000 / math.Pi } func deg2rad(d float64) float64 { return d * math.Pi / 180 } func rad2deg(r float64) float64 { return r * 180 / math.Pi } // https://en.wikipedia.org/wiki/Nautical_mile func nautical2meter(n float64) float64 { return 1852 * n } func meter2nautical(m float64) float64 { return m / 1852 } func meter2mile(m float64) float64 { return m / 1609.344 } func mile2meter(m float64) float64 { return m * 1609.344 }
gis/units.go
0.670608
0.400222
units.go
starcoder
package tilearea import ( "github.com/kasworld/goguelike-single/enum/tile_flag" "github.com/kasworld/goguelike-single/game/terrain/corridor" "github.com/kasworld/goguelike-single/game/terrain/room" "github.com/kasworld/goguelike-single/lib/boolmatrix" "github.com/kasworld/walk2d" ) func (ta TileArea) DrawRooms(rs []*room.Room) { xWrap, yWrap := ta.GetXYWrapper() for _, r := range rs { roomRect := r.Area for x, xv := range r.Tiles { for y, yv := range xv { tax, tay := xWrap(roomRect.X+x), yWrap(roomRect.Y+y) ta[tax][tay] |= r.BgTile | yv } } } } func (ta TileArea) DrawCorridors(corridorList []*corridor.Corridor) { for _, v := range corridorList { for _, w := range v.P { ta[w[0]][w[1]] |= v.Tile } } } func (ta TileArea) HLine(x, w, y int, tl tile_flag.TileFlag) { fn := func(ax, ay int) bool { ta[ax][ay] |= tl return false } walk2d.HLine(x, x+w, y, fn) } func (ta TileArea) VLine(x, y, h int, tl tile_flag.TileFlag) { fn := func(ax, ay int) bool { ta[ax][ay] |= tl return false } walk2d.VLine(y, y+h, x, fn) } func (ta TileArea) Line(x1, y1, x2, y2 int, tl tile_flag.TileFlag) { fn := func(ax, ay int) bool { ta[ax][ay] |= tl return false } walk2d.Line(x1, y1, x2, y2, fn) } func (ta TileArea) Rect(x, w, y, h int, tl tile_flag.TileFlag) { fn := func(ax, ay int) bool { ta[ax][ay] |= tl return false } walk2d.Rect(x, y, x+w, y+h, fn) } func (ta TileArea) FillRect(x, w, y, h int, tl tile_flag.TileFlag) { fn := func(ax, ay int) bool { ta[ax][ay] |= tl return false } walk2d.FillHV(x, y, x+w, y+h, fn) } func (ta TileArea) Ellipses(x, w, y, h int, tl tile_flag.TileFlag) { fn := func(ax, ay int) bool { ta[ax][ay] |= tl return false } walk2d.Ellipses(x, y, x+w, y+h, fn) } func (ta TileArea) DrawBoolMapTrue(xWrap, yWrap func(i int) int, maX, maY int, ma boolmatrix.BoolMatrix, tl tile_flag.TileFlag) { for x, xv := range ma { for y, yv := range xv { if yv { ta[xWrap(maX+x)][yWrap(maY+y)] |= tl } } } } func (ta TileArea) DrawBoolMapFalse(xWrap, yWrap func(i int) int, maX, maY int, ma boolmatrix.BoolMatrix, tl tile_flag.TileFlag) { for x, xv := range ma { for y, yv := range xv { if !yv { ta[xWrap(maX+x)][yWrap(maY+y)] |= tl } } } }
game/tilearea/tilearea_draw.go
0.502197
0.44065
tilearea_draw.go
starcoder
package trea import ( "encoding/xml" "github.com/figassis/bankiso/iso20022" ) type Document00100102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:trea.001.001.02 Document"` Message *CreateNonDeliverableForwardOpeningV02 `xml:"CretNDFOpngV02"` } func (d *Document00100102) AddMessage() *CreateNonDeliverableForwardOpeningV02 { d.Message = new(CreateNonDeliverableForwardOpeningV02) return d.Message } // Scope // The CreateNonDeliverableForwardOpening message is sent by a participant to a central system or to a counterparty to notify the opening of a non deliverable trade. // Usage // The trading parties will send similar messages to the central settlement system and the central settlement system will send notifications to both parties. type CreateNonDeliverableForwardOpeningV02 struct { // Provides identification and date of the non deliverable trade which is created. TradeInformation *iso20022.TradeAgreement1 `xml:"TradInf"` // Specifies the trading side of the non deliverable trade which is created. TradingSideIdentification *iso20022.TradePartyIdentification3 `xml:"TradgSdId"` // Specifies the counterparty of the non deliverable trade which is created. CounterpartySideIdentification *iso20022.TradePartyIdentification3 `xml:"CtrPtySdId"` // Specifies the amounts of the non deliverable trade which is created. TradeAmounts *iso20022.AmountsAndValueDate1 `xml:"TradAmts"` // Specifies the rate agreed at the opening of a non deliverable trade. AgreedRate *iso20022.AgreedRate1 `xml:"AgrdRate"` // Specifies the valuation conditions of the non deliverable trade which is created. ValuationConditions *iso20022.NonDeliverableForwardValuationConditions2 `xml:"ValtnConds"` } func (c *CreateNonDeliverableForwardOpeningV02) AddTradeInformation() *iso20022.TradeAgreement1 { c.TradeInformation = new(iso20022.TradeAgreement1) return c.TradeInformation } func (c *CreateNonDeliverableForwardOpeningV02) AddTradingSideIdentification() *iso20022.TradePartyIdentification3 { c.TradingSideIdentification = new(iso20022.TradePartyIdentification3) return c.TradingSideIdentification } func (c *CreateNonDeliverableForwardOpeningV02) AddCounterpartySideIdentification() *iso20022.TradePartyIdentification3 { c.CounterpartySideIdentification = new(iso20022.TradePartyIdentification3) return c.CounterpartySideIdentification } func (c *CreateNonDeliverableForwardOpeningV02) AddTradeAmounts() *iso20022.AmountsAndValueDate1 { c.TradeAmounts = new(iso20022.AmountsAndValueDate1) return c.TradeAmounts } func (c *CreateNonDeliverableForwardOpeningV02) AddAgreedRate() *iso20022.AgreedRate1 { c.AgreedRate = new(iso20022.AgreedRate1) return c.AgreedRate } func (c *CreateNonDeliverableForwardOpeningV02) AddValuationConditions() *iso20022.NonDeliverableForwardValuationConditions2 { c.ValuationConditions = new(iso20022.NonDeliverableForwardValuationConditions2) return c.ValuationConditions } func ( d *Document00100102 ) String() (result string, ok bool) { return }
generate/iso20022/trea/CreateNonDeliverableForwardOpeningV02.go
0.778228
0.423696
CreateNonDeliverableForwardOpeningV02.go
starcoder
package bn256 import ( "crypto/cipher" "crypto/sha256" "crypto/subtle" "errors" "io" "math/big" "go.dedis.ch/kyber/v3" "go.dedis.ch/kyber/v3/group/mod" ) type pointG1 struct { g *curvePoint group kyber.Group } func newPointG1(group kyber.Group) *pointG1 { p := &pointG1{g: &curvePoint{}, group: group} return p } func (p *pointG1) Group() kyber.Group { return p.group } func (p *pointG1) Equal(q kyber.Point) bool { x, _ := p.MarshalBinary() y, _ := q.MarshalBinary() return subtle.ConstantTimeCompare(x, y) == 1 } func (p *pointG1) Null() kyber.Point { p.g.SetInfinity() return p } func (p *pointG1) Base() kyber.Point { p.g.Set(curveGen) return p } func (p *pointG1) Pick(rand cipher.Stream) kyber.Point { s := &scalarDescribing{ Int: mod.NewInt64(0, Order), group: p.group, } s.Pick(rand) p.Base() p.g.Mul(p.g, &s.V) return p } func (p *pointG1) Set(q kyber.Point) kyber.Point { x := q.(*pointG1).g p.g.Set(x) return p } // Clone makes a hard copy of the point func (p *pointG1) Clone() kyber.Point { q := newPointG1(p.group) q.g = p.g.Clone() return q } func (p *pointG1) EmbedLen() int { panic("bn256.G1: unsupported operation") } func (p *pointG1) Embed(data []byte, rand cipher.Stream) kyber.Point { // XXX: An approach to implement this is: // - Encode data as the x-coordinate of a point on y²=x³+3 where len(data) // is stored in the least significant byte of x and the rest is being // filled with random values, i.e., x = rand || data || len(data). // - Use the Tonelli-Shanks algorithm to compute the y-coordinate. // - Convert the new point to Jacobian coordinates and set it as p. panic("bn256.G1: unsupported operation") } func (p *pointG1) Data() ([]byte, error) { panic("bn256.G1: unsupported operation") } func (p *pointG1) Add(a, b kyber.Point) kyber.Point { x := a.(*pointG1).g y := b.(*pointG1).g p.g.Add(x, y) // p = a + b return p } func (p *pointG1) Sub(a, b kyber.Point) kyber.Point { q := newPointG1(p.group) return p.Add(a, q.Neg(b)) } func (p *pointG1) Neg(q kyber.Point) kyber.Point { x := q.(*pointG1).g p.g.Neg(x) return p } func (p *pointG1) Mul(s kyber.Scalar, q kyber.Point) kyber.Point { if q == nil { q = newPointG1(p.group).Base() } t := s.(*scalarDescribing).V r := q.(*pointG1).g p.g.Mul(r, &t) return p } func (p *pointG1) MarshalBinary() ([]byte, error) { // Clone is required as we change the point p = p.Clone().(*pointG1) n := p.ElementSize() // Take a copy so that p is not written to, so calls to MarshalBinary // are threadsafe. pgtemp := *p.g pgtemp.MakeAffine() ret := make([]byte, p.MarshalSize()) if pgtemp.IsInfinity() { return ret, nil } tmp := &gfP{} montDecode(tmp, &pgtemp.x) tmp.Marshal(ret) montDecode(tmp, &pgtemp.y) tmp.Marshal(ret[n:]) return ret, nil } func (p *pointG1) MarshalTo(w io.Writer) (int, error) { buf, err := p.MarshalBinary() if err != nil { return 0, err } return w.Write(buf) } func (p *pointG1) UnmarshalBinary(buf []byte) error { n := p.ElementSize() if len(buf) < p.MarshalSize() { return errors.New("bn256.G1: not enough data") } if p.g == nil { p.g = &curvePoint{} } else { p.g.x, p.g.y = gfP{0}, gfP{0} } p.g.x.Unmarshal(buf) p.g.y.Unmarshal(buf[n:]) montEncode(&p.g.x, &p.g.x) montEncode(&p.g.y, &p.g.y) zero := gfP{0} if p.g.x == zero && p.g.y == zero { // This is the point at infinity p.g.y = *newGFp(1) p.g.z = gfP{0} p.g.t = gfP{0} } else { p.g.z = *newGFp(1) p.g.t = *newGFp(1) } if !p.g.IsOnCurve() { return errors.New("bn256.G1: malformed point") } return nil } func (p *pointG1) UnmarshalFrom(r io.Reader) (int, error) { buf := make([]byte, p.MarshalSize()) n, err := io.ReadFull(r, buf) if err != nil { return n, err } return n, p.UnmarshalBinary(buf) } func (p *pointG1) MarshalSize() int { return 2 * p.ElementSize() } func (p *pointG1) ElementSize() int { return 256 / 8 } func (p *pointG1) String() string { return "bn256.G1:" + p.g.String() } func (p *pointG1) Hash(m []byte) kyber.Point { leftPad32 := func(in []byte) []byte { if len(in) > 32 { panic("input cannot be more than 32 bytes") } out := make([]byte, 32) copy(out[32-len(in):], in) return out } bigX, bigY := hashToPoint(m) if p.g == nil { p.g = new(curvePoint) } x, y := new(gfP), new(gfP) x.Unmarshal(leftPad32(bigX.Bytes())) y.Unmarshal(leftPad32(bigY.Bytes())) montEncode(x, x) montEncode(y, y) p.g.Set(&curvePoint{*x, *y, *newGFp(1), *newGFp(1)}) return p } // hashes a byte slice into two points on a curve represented by big.Int // ideally we want to do this using gfP, but gfP doesn't have a ModSqrt function func hashToPoint(m []byte) (*big.Int, *big.Int) { // we need to convert curveB into a bigInt for our computation intCurveB := new(big.Int) { decodedCurveB := new(gfP) montDecode(decodedCurveB, curveB) bufCurveB := make([]byte, 32) decodedCurveB.Marshal(bufCurveB) intCurveB.SetBytes(bufCurveB) } h := sha256.Sum256(m) x := new(big.Int).SetBytes(h[:]) x.Mod(x, p) for { xxx := new(big.Int).Mul(x, x) xxx.Mul(xxx, x) xxx.Mod(xxx, p) t := new(big.Int).Add(xxx, intCurveB) y := new(big.Int).ModSqrt(t, p) if y != nil { return x, y } x.Add(x, big.NewInt(1)) } } type pointG2 struct { g *twistPoint group kyber.Group } func newPointG2(group kyber.Group) *pointG2 { p := &pointG2{g: &twistPoint{}, group: group} return p } func (p *pointG2) Group() kyber.Group { return p.group } func (p *pointG2) Equal(q kyber.Point) bool { x, _ := p.MarshalBinary() y, _ := q.MarshalBinary() return subtle.ConstantTimeCompare(x, y) == 1 } func (p *pointG2) Null() kyber.Point { p.g.SetInfinity() return p } func (p *pointG2) Base() kyber.Point { p.g.Set(twistGen) return p } func (p *pointG2) Pick(rand cipher.Stream) kyber.Point { s := &scalarDescribing{ Int: mod.NewInt64(0, Order), group: p.group, } s.Pick(rand) p.Base() p.g.Mul(p.g, &s.V) return p } func (p *pointG2) Set(q kyber.Point) kyber.Point { x := q.(*pointG2).g p.g.Set(x) return p } // Clone makes a hard copy of the field func (p *pointG2) Clone() kyber.Point { q := newPointG2(p.group) q.g = p.g.Clone() return q } func (p *pointG2) EmbedLen() int { panic("bn256.G2: unsupported operation") } func (p *pointG2) Embed(data []byte, rand cipher.Stream) kyber.Point { panic("bn256.G2: unsupported operation") } func (p *pointG2) Data() ([]byte, error) { panic("bn256.G2: unsupported operation") } func (p *pointG2) Add(a, b kyber.Point) kyber.Point { x := a.(*pointG2).g y := b.(*pointG2).g p.g.Add(x, y) // p = a + b return p } func (p *pointG2) Sub(a, b kyber.Point) kyber.Point { q := newPointG2(p.group) return p.Add(a, q.Neg(b)) } func (p *pointG2) Neg(q kyber.Point) kyber.Point { x := q.(*pointG2).g p.g.Neg(x) return p } func (p *pointG2) Mul(s kyber.Scalar, q kyber.Point) kyber.Point { if q == nil { q = newPointG2(p.group).Base() } t := s.(*scalarDescribing).Int.V r := q.(*pointG2).g p.g.Mul(r, &t) return p } func (p *pointG2) MarshalBinary() ([]byte, error) { // Clone is required as we change the point during the operation p = p.Clone().(*pointG2) n := p.ElementSize() if p.g == nil { p.g = &twistPoint{} } p.g.MakeAffine() ret := make([]byte, p.MarshalSize()) if p.g.IsInfinity() { return ret, nil } temp := &gfP{} montDecode(temp, &p.g.x.x) temp.Marshal(ret[0*n:]) montDecode(temp, &p.g.x.y) temp.Marshal(ret[1*n:]) montDecode(temp, &p.g.y.x) temp.Marshal(ret[2*n:]) montDecode(temp, &p.g.y.y) temp.Marshal(ret[3*n:]) return ret, nil } func (p *pointG2) MarshalTo(w io.Writer) (int, error) { buf, err := p.MarshalBinary() if err != nil { return 0, err } return w.Write(buf) } func (p *pointG2) UnmarshalBinary(buf []byte) error { n := p.ElementSize() if p.g == nil { p.g = &twistPoint{} } if len(buf) < p.MarshalSize() { return errors.New("bn256.G2: not enough data") } p.g.x.x.Unmarshal(buf[0*n:]) p.g.x.y.Unmarshal(buf[1*n:]) p.g.y.x.Unmarshal(buf[2*n:]) p.g.y.y.Unmarshal(buf[3*n:]) montEncode(&p.g.x.x, &p.g.x.x) montEncode(&p.g.x.y, &p.g.x.y) montEncode(&p.g.y.x, &p.g.y.x) montEncode(&p.g.y.y, &p.g.y.y) if p.g.x.IsZero() && p.g.y.IsZero() { // This is the point at infinity. p.g.y.SetOne() p.g.z.SetZero() p.g.t.SetZero() } else { p.g.z.SetOne() p.g.t.SetOne() if !p.g.IsOnCurve() { return errors.New("bn256.G2: malformed point") } } return nil } func (p *pointG2) UnmarshalFrom(r io.Reader) (int, error) { buf := make([]byte, p.MarshalSize()) n, err := io.ReadFull(r, buf) if err != nil { return n, err } return n, p.UnmarshalBinary(buf) } func (p *pointG2) MarshalSize() int { return 4 * p.ElementSize() } func (p *pointG2) ElementSize() int { return 256 / 8 } func (p *pointG2) String() string { return "bn256.G2:" + p.g.String() } type pointGT struct { g *gfP12 group kyber.Group } func newPointGT(group kyber.Group) *pointGT { p := &pointGT{g: &gfP12{}, group: group} return p } func (p *pointGT) Group() kyber.Group { return p.group } func (p *pointGT) Equal(q kyber.Point) bool { x, _ := p.MarshalBinary() y, _ := q.MarshalBinary() return subtle.ConstantTimeCompare(x, y) == 1 } func (p *pointGT) Null() kyber.Point { p.g.Set(gfP12Inf) return p } func (p *pointGT) Base() kyber.Point { p.g.Set(gfP12Gen) return p } func (p *pointGT) Pick(rand cipher.Stream) kyber.Point { s := &scalarDescribing{ Int: mod.NewInt64(0, Order), group: p.group, } s.Pick(rand) p.Base() p.g.Exp(p.g, &s.V) return p } func (p *pointGT) Set(q kyber.Point) kyber.Point { x := q.(*pointGT).g p.g.Set(x) return p } // Clone makes a hard copy of the point func (p *pointGT) Clone() kyber.Point { q := newPointGT(p.group) q.g = p.g.Clone() return q } func (p *pointGT) EmbedLen() int { panic("bn256.GT: unsupported operation") } func (p *pointGT) Embed(data []byte, rand cipher.Stream) kyber.Point { panic("bn256.GT: unsupported operation") } func (p *pointGT) Data() ([]byte, error) { panic("bn256.GT: unsupported operation") } func (p *pointGT) Add(a, b kyber.Point) kyber.Point { x := a.(*pointGT).g y := b.(*pointGT).g p.g.Mul(x, y) return p } func (p *pointGT) Sub(a, b kyber.Point) kyber.Point { q := newPointGT(p.group) return p.Add(a, q.Neg(b)) } func (p *pointGT) Neg(q kyber.Point) kyber.Point { x := q.(*pointGT).g p.g.Conjugate(x) return p } func (p *pointGT) Mul(s kyber.Scalar, q kyber.Point) kyber.Point { if q == nil { q = newPointGT(p.group).Base() } t := s.(*scalarDescribing).Int.V r := q.(*pointGT).g p.g.Exp(r, &t) return p } func (p *pointGT) MarshalBinary() ([]byte, error) { n := p.ElementSize() ret := make([]byte, p.MarshalSize()) temp := &gfP{} montDecode(temp, &p.g.x.x.x) temp.Marshal(ret[0*n:]) montDecode(temp, &p.g.x.x.y) temp.Marshal(ret[1*n:]) montDecode(temp, &p.g.x.y.x) temp.Marshal(ret[2*n:]) montDecode(temp, &p.g.x.y.y) temp.Marshal(ret[3*n:]) montDecode(temp, &p.g.x.z.x) temp.Marshal(ret[4*n:]) montDecode(temp, &p.g.x.z.y) temp.Marshal(ret[5*n:]) montDecode(temp, &p.g.y.x.x) temp.Marshal(ret[6*n:]) montDecode(temp, &p.g.y.x.y) temp.Marshal(ret[7*n:]) montDecode(temp, &p.g.y.y.x) temp.Marshal(ret[8*n:]) montDecode(temp, &p.g.y.y.y) temp.Marshal(ret[9*n:]) montDecode(temp, &p.g.y.z.x) temp.Marshal(ret[10*n:]) montDecode(temp, &p.g.y.z.y) temp.Marshal(ret[11*n:]) return ret, nil } func (p *pointGT) MarshalTo(w io.Writer) (int, error) { buf, err := p.MarshalBinary() if err != nil { return 0, err } return w.Write(buf) } func (p *pointGT) UnmarshalBinary(buf []byte) error { n := p.ElementSize() if len(buf) < p.MarshalSize() { return errors.New("bn256.GT: not enough data") } if p.g == nil { p.g = &gfP12{} } p.g.x.x.x.Unmarshal(buf[0*n:]) p.g.x.x.y.Unmarshal(buf[1*n:]) p.g.x.y.x.Unmarshal(buf[2*n:]) p.g.x.y.y.Unmarshal(buf[3*n:]) p.g.x.z.x.Unmarshal(buf[4*n:]) p.g.x.z.y.Unmarshal(buf[5*n:]) p.g.y.x.x.Unmarshal(buf[6*n:]) p.g.y.x.y.Unmarshal(buf[7*n:]) p.g.y.y.x.Unmarshal(buf[8*n:]) p.g.y.y.y.Unmarshal(buf[9*n:]) p.g.y.z.x.Unmarshal(buf[10*n:]) p.g.y.z.y.Unmarshal(buf[11*n:]) montEncode(&p.g.x.x.x, &p.g.x.x.x) montEncode(&p.g.x.x.y, &p.g.x.x.y) montEncode(&p.g.x.y.x, &p.g.x.y.x) montEncode(&p.g.x.y.y, &p.g.x.y.y) montEncode(&p.g.x.z.x, &p.g.x.z.x) montEncode(&p.g.x.z.y, &p.g.x.z.y) montEncode(&p.g.y.x.x, &p.g.y.x.x) montEncode(&p.g.y.x.y, &p.g.y.x.y) montEncode(&p.g.y.y.x, &p.g.y.y.x) montEncode(&p.g.y.y.y, &p.g.y.y.y) montEncode(&p.g.y.z.x, &p.g.y.z.x) montEncode(&p.g.y.z.y, &p.g.y.z.y) // TODO: check if point is on curve return nil } func (p *pointGT) UnmarshalFrom(r io.Reader) (int, error) { buf := make([]byte, p.MarshalSize()) n, err := io.ReadFull(r, buf) if err != nil { return n, err } return n, p.UnmarshalBinary(buf) } func (p *pointGT) MarshalSize() int { return 12 * p.ElementSize() } func (p *pointGT) ElementSize() int { return 256 / 8 } func (p *pointGT) String() string { return "bn256.GT:" + p.g.String() } func (p *pointGT) Finalize() kyber.Point { buf := finalExponentiation(p.g) p.g.Set(buf) return p } func (p *pointGT) Miller(p1, p2 kyber.Point) kyber.Point { a := p1.(*pointG1).g b := p2.(*pointG2).g p.g.Set(miller(b, a)) return p } func (p *pointGT) Pair(p1, p2 kyber.Point) kyber.Point { a := p1.(*pointG1).g b := p2.(*pointG2).g p.g.Set(optimalAte(b, a)) return p }
vendor/go.dedis.ch/kyber/v3/pairing/bn256/point.go
0.691185
0.481941
point.go
starcoder