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 uvr1611 import ( "fmt" "github.com/brutella/gouvr/uvr" ) // IsUnusedInputValue returns true when the value for an input is unused func IsUnusedInputValue(value uvr.Value) bool { return InputTypeFromValue(value) == InputTypeUnused } // RoomTemperatureModeFromValue returns the room temperature mode from the value. func RoomTemperatureModeFromValue(value uvr.Value) RoomTemperatureMode { if InputTypeFromValue(value) == InputTypeRoomTemperature { return RoomTemperatureMode(value.High & InputTypeRoomTemperatureOperationModeMask) } return RoomTemperatureModeUndefined } // InputTypeFromValue returns the input type of the value. func InputTypeFromValue(value uvr.Value) InputType { return InputType(value.High & InputTypeMask) } func IsDigitalInputValueOn(value uvr.Value) bool { input_type, f := DecodeInputValue(value) return input_type == InputTypeDigital && f == 1.0 } // DecodeInputValue returns the input type and the float value. func DecodeInputValue(value uvr.Value) (InputType, float32) { input_type := InputTypeFromValue(value) var result float32 var low_byte = uvr.Byte(0) var high_byte = uvr.Byte(0) if input_type != InputTypeUnused { low_byte = value.Low & InputTypeLowValueMask // Room temperature input is handled differently if input_type == InputTypeRoomTemperature { high_byte = value.High & InputTypeRoomTemperatureHighValueMask } else { // Extract only interesting bits high_byte = value.High & InputTypeHighValueMask } if value.High&InputTypeSignMask == InputTypeSignMask { // 1000 0000 if input_type == InputTypeDigital { // bit 7 = 1 (On) result = 1.0 } else { // For negative values, set bit 4,5,6 in high byte to 1 high_byte |= 0xF0 // 1111 0000 result = float32(low_byte) + float32(high_byte)*256 - 65536 result /= 10.0 } } else { if input_type == InputTypeDigital { // bit 7 = 0 (Off) result = 0.0 } else { // For positive values, set bit 4,5,6 in high byte to 0 high_byte &= 0x0F // 0000 1111 result = float32(low_byte) + float32(high_byte)*256 result /= 10.0 } } } return input_type, result } // InputValueToString returns the value properly formatted as string (e.g. 10.5 °C). func InputValueToString(v uvr.Value) string { input_type, value := DecodeInputValue(v) var suffix string switch input_type { case InputTypeUnused: return "?" case InputTypeDigital: if value == 1.0 { return "On" } return "Off" case InputTypeRoomTemperature: suffix = "°C" suffix += " " switch RoomTemperatureModeFromValue(v) { case RoomTemperatureModeAutomatic: suffix += "[Auto]" case RoomTemperatureModeNormal: suffix += "[Normal]" case RoomTemperatureModeLowering: suffix += "[Lowering]" case RoomTemperatureModeStandby: suffix += "[Standby]" } case InputTypeTemperature: suffix = "°C" case InputTypeVolumeFlow: suffix = "l/h" case InputTypeRadiation: suffix = "W/m^2" } return fmt.Sprintf("%.01f %s", value, suffix) }
uvr/1611/input_value.go
0.78469
0.476092
input_value.go
starcoder
package shuffle import ( "errors" "math/bits" ) func masks(max FeistelWord) (int, FeistelWord) { /* special case when you want to traverse all the inclusive range of FeistelWord type space */ if max == 0 { max = MaxFeistelWord } /* bit offset and bit mask */ bitOffset := (bits.Len64(uint64(max-1)) + 1) >> 1 bitMask := FeistelWord(1)<<bitOffset - 1 return bitOffset, bitMask } // RandomIndex returns the shuffled index of a given index and the higher bound of the set to be shuffled. // If max is 0 then max act as the FesitelWord max value +1. func RandomIndex(idx, max FeistelWord, cipher *Feistel) (FeistelWord, error) { if len(cipher.keys) == 0 { return MaxFeistelWord, errors.New("RandomIndex: Feistel context have a zero rounds key") } if max != 0 && idx >= max { return MaxFeistelWord, errors.New("RandomIndex: requested index surpass higher bound") } bitOffset, bitMask := masks(max) permutation := idx for { left, right := cipher.Cipher(permutation>>bitOffset, permutation&bitMask, bitMask) permutation = left<<bitOffset | right if permutation < max || max == 0 { return permutation, nil } } } // GetIndex returns the unshuffled index of a given shuffle index and the higher bound of the shuffled set. // If max is 0 then max act as the FesitelWord max value +1. func GetIndex(permutation, max FeistelWord, cipher *Feistel) (FeistelWord, error) { if len(cipher.keys) == 0 { return MaxFeistelWord, errors.New("GetIndex: Feistel context have a zero rounds key") } if max != 0 && permutation >= max { return MaxFeistelWord, errors.New("GetIndex: requested permutation surpass higher bound") } bitOffset, bitMask := masks(max) idx := permutation //fmt.Println(idx) for { left, right := cipher.Decipher(idx>>bitOffset, idx&bitMask, bitMask) idx = left<<bitOffset | right if idx < max || max == 0 { return idx, nil } } } // Shuffle creates a channel that stream shuffled values from a given minimum and maximum. // If max is 0 then max act as the FesitelWord max value +1. func Shuffle(min, max FeistelWord, cipher *Feistel) (<-chan FeistelWord, error) { if len(cipher.keys) == 0 { return nil, errors.New("Shuffle: Feistel context have a zero rounds key") } shuffle := make(chan FeistelWord) if min > max { min, max = max, min } diff := max - min go func(max, offset FeistelWord) { var permutation FeistelWord bitOffset, bitMask := masks(max) for i := FeistelWord(0); i < max || max == 0; i++ { permutation = i for { left, right := cipher.Cipher(permutation>>bitOffset, permutation&bitMask, bitMask) permutation = left<<bitOffset | right if permutation < max || max == 0 { shuffle <- permutation + offset break } } if i == MaxFeistelWord { break } } close(shuffle) }(diff, min) return shuffle, nil }
shuffle.go
0.685529
0.432902
shuffle.go
starcoder
package set const orderedFunctions = ` {{if .Type.Ordered}} //------------------------------------------------------------------------------------------------- // These methods require {{.TName}} be ordered. // Min returns the element with the minimum value. In the case of multiple items being equally minimal, // any such element is returned. Panics if the collection is empty. func (set {{.TName}}Set) Min() (result {{.PName}}) { if len(set) == 0 { panic("Cannot determine the minimum of an empty set.") } first := true for v := range set { if first { first = false result = {{.Ptr}}v } else if v < result { result = {{.Ptr}}v } } return } // Max returns the element with the maximum value. In the case of multiple items being equally maximal, // any such element is returned. Panics if the collection is empty. func (set {{.TName}}Set) Max() (result {{.PName}}) { if len(set) == 0 { panic("Cannot determine the maximum of an empty set.") } first := true for v := range set { if first { first = false result = {{.Ptr}}v } else if v > result { result = {{.Ptr}}v } } return } {{else}} //------------------------------------------------------------------------------------------------- // These methods are included when {{.TName}} is not ordered. // Min returns an element containing the minimum value, when compared to other elements // using a specified comparator function defining ‘less’. // Panics if the collection is empty. func (set {{.TName}}Set) Min(less func({{.PName}}, {{.PName}}) bool) (result {{.PName}}) { l := len(set) if l == 0 { panic("Cannot determine the minimum of an empty set.") } first := true for v := range set { if first { first = false result = {{.Ptr}}v } else if less(v, result) { result = {{.Ptr}}v } } return } // Max returns an element containing the maximum value, when compared to other elements // using a specified comparator function defining ‘less’. // Panics if the collection is empty. func (set {{.TName}}Set) Max(less func({{.PName}}, {{.PName}}) bool) (result {{.PName}}) { l := len(set) if l == 0 { panic("Cannot determine the maximum of an empty set.") } first := true for v := range set { if first { first = false result = {{.Ptr}}v } else if less(result, v) { result = {{.Ptr}}v } } return } {{end}} `
internal/set/ordered.go
0.794584
0.59887
ordered.go
starcoder
package structural import "fmt" // TimeImp is the interface for different implementations of telling the time. type TimeImp interface { Tell() } // BasicTimeImp defines a TimeImp which tells the time in 24 hour format. type BasicTimeImp struct { hour int minute int } // NewBasicTimeImp creates a new TimeImp. func NewBasicTimeImp(hour, minute int) TimeImp { return &BasicTimeImp{hour, minute} } // Tell tells the time in 24 hour format. func (t *BasicTimeImp) Tell() { fmt.Fprintf(outputWriter, "The time is %2.2d:%2.2d\n", t.hour, t.minute) } // CivilianTimeImp defines a TimeImp which tells the time in 12 hour format with meridem. type CivilianTimeImp struct { BasicTimeImp meridiem string } // NewCivilianTimeImp creates a new TimeImp. func NewCivilianTimeImp(hour, minute int, pm bool) TimeImp { meridiem := "AM" if pm { meridiem = "PM" } time := &CivilianTimeImp{meridiem: meridiem} time.hour = hour time.minute = minute return time } // Tell tells the time in 12 hour format. func (t *CivilianTimeImp) Tell() { fmt.Fprintf(outputWriter, "The time is %2.2d:%2.2d %s\n", t.hour, t.minute, t.meridiem) } // ZuluTimeImp defines a TimeImp which tells the time in Zulu zone format. type ZuluTimeImp struct { BasicTimeImp zone string } // NewZuluTimeImp creates a new TimeImp. func NewZuluTimeImp(hour, minute, zoneID int) TimeImp { zone := "" if zoneID == 5 { zone = "Eastern Standard Time" } else if zoneID == 6 { zone = "Central Standard Time" } time := &ZuluTimeImp{zone: zone} time.hour = hour time.minute = minute return time } // Tell tells the time in 24 hour format in Zulu time zone. func (t *ZuluTimeImp) Tell() { fmt.Fprintf(outputWriter, "The time is %2.2d:%2.2d %s\n", t.hour, t.minute, t.zone) } // Time is the base struct for Time containing the implementation. type Time struct { imp TimeImp } // NewTime creates a new time which uses a basic time for its implementation. func NewTime(hour, minute int) *Time { return &Time{imp: NewBasicTimeImp(hour, minute)} } // Tell tells the time with the given implementation. func (t *Time) Tell() { t.imp.Tell() } // CivilianTime is a time with a civilian time implementation. type CivilianTime struct { Time } // NewCivilianTime creates a new civilian time. func NewCivilianTime(hour, minute int, pm bool) *Time { time := &CivilianTime{} time.imp = NewCivilianTimeImp(hour, minute, pm) return &time.Time } // ZuluTime is a time with a Zulu time implementation. type ZuluTime struct { Time } // NewZuluTime creates a new Zulu time. func NewZuluTime(hour, minute, zoneID int) *Time { time := &ZuluTime{} time.imp = NewZuluTimeImp(hour, minute, zoneID) return &time.Time }
structural/bridge.go
0.785514
0.455744
bridge.go
starcoder
package tt import "testing" // Assertions provides assertion methods around the // TestingT interface. type Assertions struct { t TestingT } // New makes a new Assertions object for the specified TestingT. func New(t TestingT) *Assertions { return &Assertions{ t: t, } } // BM func Benchmark1(b *testing.B, fn func()) func (at *Assertions) BM(b *testing.B, fn func()) { for i := 0; i < b.N; i++ { fn() } } // Equal asserts that two objects are equal. func (at *Assertions) Equal(expect, actual interface{}, args ...int) bool { call := 5 if len(args) > 0 { call = args[0] } return Equal(at.t, expect, actual, call) } // Expect asserts that string and objects are equal. func (at *Assertions) Expect(expect string, actual interface{}, args ...int) bool { call := 4 if len(args) > 0 { call = args[0] } return Expect(at.t, expect, actual, call) } // Nil asserts that nil and objects are equal. func (at *Assertions) Nil(actual interface{}, args ...int) bool { call := 4 if len(args) > 0 { call = args[0] } return Expect(at.t, "<nil>", actual, call) } // Empty asserts that empty and objects are equal. func (at *Assertions) Empty(actual interface{}, args ...int) bool { call := 4 if len(args) > 0 { call = args[0] } return Expect(at.t, "", actual, call) } // Bool asserts that true and objects are equal. func (at *Assertions) Bool(actual interface{}, args ...int) bool { call := 4 if len(args) > 0 { call = args[0] } return Expect(at.t, "true", actual, call) } // True asserts that true and objects are equal. func (at *Assertions) True(actual interface{}, args ...int) bool { call := 4 if len(args) > 0 { call = args[0] } return Expect(at.t, "true", actual, call) } // False asserts that flase and objects are equal. func (at *Assertions) False(actual interface{}, args ...int) bool { call := 4 if len(args) > 0 { call = args[0] } return Expect(at.t, "false", actual, call) } // Not asserts that two objects are not equal. func (at *Assertions) Not(expect, actual interface{}, args ...int) bool { call := 5 if len(args) > 0 { call = args[0] } return Not(at.t, expect, actual, call) } // NotEqual asserts that two objects are not equal. func (at *Assertions) NotEqual(expect, actual interface{}, args ...int) bool { call := 5 if len(args) > 0 { call = args[0] } return NotEqual(at.t, expect, actual, call) } // NotExpect asserts that string and objects are not equal. func (at *Assertions) NotExpect(expect string, actual interface{}, args ...int) bool { call := 4 if len(args) > 0 { call = args[0] } return NotExpect(at.t, expect, actual, call) }
vendor/github.com/vcaesar/tt/assert.go
0.688887
0.653362
assert.go
starcoder
package intcode // Instruction is a single instruction read from the memory of a VM. type Instruction struct { // Op is the opcode for the action the instruction should perform. Op Op // Params is the list of parameters provided to the instruction. Params []Param } // Get reads the value for a parameter of the instruction. It uses the parameter's // mode to read from the correct location. func (inst Instruction) Get(vm *VM, i int) int { p := inst.Params[i] switch p.Mode { case ModePosition: return vm.At(p.Value) case ModeImmediate: return p.Value case ModeRelative: return vm.At(p.Value + vm.relativeBase) default: panic("unexpected param mode") } } // Set updates a value in memory for a parameter of the instruction. It uses the // parameter's mode to determine the correct location to write to. func (inst Instruction) Set(vm *VM, i int, value int) { p := inst.Params[i] switch p.Mode { case ModePosition: vm.Set(p.Value, value) case ModeRelative: vm.Set(p.Value+vm.relativeBase, value) default: panic("unexpected param mode") } } // Op is an opcode for an Intcode instruction. type Op int // The supported opcodes for this Intcode interpreter. const ( OpAdd Op = 1 OpMultiply Op = 2 OpInput Op = 3 OpOutput Op = 4 OpJumpIfTrue Op = 5 OpJumpIfFalse Op = 6 OpLessThan Op = 7 OpEquals Op = 8 OpSetRelativeBase Op = 9 OpHalt Op = 99 ) // ParamMode represents how to use the value in an Intcode instruction parameter. type ParamMode int const ( // ModePosition indicates the parameter's value refers to an absolute address // memory. ModePosition ParamMode = 0 // ModeImmediate indicates the parameter's value should be used directly, and // does not correspond to another address in memory. ModeImmediate ParamMode = 1 // ModeRelative indicates the parameter's value refers to an offset from the // VM's current relative base. ModeRelative ParamMode = 2 ) // Param is a single parameter from an Intcode instruction. type Param struct { // Value is the integer value of the parameter. Value int // Mode is the mode that should be used to interpret the value. Mode ParamMode }
pkg/intcode/instruction.go
0.715821
0.587085
instruction.go
starcoder
package smartapi import ( "errors" "fmt" "reflect" "strings" ) func parseArgument(tag string, fieldType reflect.Type) (Argument, error) { var kind string var data string eqAt := strings.Index(tag, "=") if eqAt >= 0 { kind = tag[:eqAt] data = tag[(eqAt + 1):] } else { kind = tag } a, err := getArgument(kind, data, fieldType) if err != nil { return nil, err } return a, nil } func getArgument(kind string, data string, fieldType reflect.Type) (Argument, error) { switch kind { case "header": return headerArgument{name: data}, nil case "r_header": return requiredHeaderArgument{name: data}, nil case "json_body": return jsonBodyDirectArgument{typ: fieldType}, nil case "string_body": return stringBodyArgument{}, nil case "byte_slice_body": return byteSliceBodyArgument{}, nil case "body_reader": return bodyReaderArgument{}, nil case "url_param": return urlParamArgument{name: data}, nil case "context": return contextArgument{}, nil case "query_param": return queryParamArgument{name: data}, nil case "r_query_param": return requiredQueryParamArgument{name: data}, nil case "post_query_param": return postQueryParamArgument{name: data}, nil case "r_post_query_param": return requiredPostQueryParamArgument{name: data}, nil case "cookie": return cookieArgument{name: data}, nil case "response_headers": return headerSetterArgument{}, nil case "response_cookies": return cookieSetterArgument{}, nil case "response_writer": return responseWriterArgument{}, nil case "request": return fullRequestArgument{}, nil case "as_int": arg, err := parseArgument(data, reflect.TypeOf("")) if err != nil { return nil, fmt.Errorf("(as int) %w", err) } asInt := AsInt(arg) if asInt.options().has(flagError) { return nil, fmt.Errorf("(as int) %w", asInt.(errorEndpointParam).err) } return asInt.(Argument), nil case "as_byte_slice": arg, err := parseArgument(data, reflect.TypeOf("")) if err != nil { return nil, fmt.Errorf("(as byte slice) %w", err) } asByteSlice := AsByteSlice(arg) if asByteSlice.options().has(flagError) { return nil, fmt.Errorf("(as byte slice) %w", asByteSlice.(errorEndpointParam).err) } return AsByteSlice(arg).(Argument), nil case "request_struct": if fieldType.Kind() != reflect.Ptr { if fieldType.Kind() != reflect.Struct { return nil, errors.New("invalid type of request_struct") } s, err := requestStruct(fieldType) if err != nil { return nil, err } return tagStructDirectArgument{ structType: s.structType, flags: s.flags, arguments: s.arguments, }, nil } return requestStruct(fieldType.Elem()) } return nil, errors.New("unsupported tag") }
tagstruct.go
0.539711
0.406214
tagstruct.go
starcoder
package astmodel import ( "fmt" "go/token" "sort" "github.com/Azure/azure-service-operator/hack/generator/pkg/astbuilder" "github.com/dave/dst" "github.com/pkg/errors" kerrors "k8s.io/apimachinery/pkg/util/errors" ) // StoragePropertyConversion represents a function that generates the correct AST to convert a single property value // Different functions will be used, depending on the types of the properties to be converted. // source is an expression for the source value that will be read. // destination is an expression the target value that will be written. type StoragePropertyConversion func( source dst.Expr, destination dst.Expr, generationContext *CodeGenerationContext) []dst.Stmt // StorageConversionFunction represents a function that performs conversions for storage versions type StorageConversionFunction struct { // name of this conversion function name string // otherType is the type we are converting to (or from). This will be a type which is "closer" // to the hub storage type, making this a building block of the final conversion. otherType TypeDefinition // conversions is a map of all property conversions we are going to use, keyed by name of the // receiver property conversions map[string]StoragePropertyConversion // idFactory is a reference to an identifier factory used for creating Go identifiers idFactory IdentifierFactory // conversionDirection indicates the kind of conversion we are generating conversionDirection StorageConversionDirection // knownLocals is a cached set of local identifiers that have already been used, to avoid conflicts knownLocals *KnownLocalsSet // conversionContext is additional information about the context in which this conversion was made conversionContext *StorageConversionContext } // StorageConversionDirection specifies the direction of conversion we're implementing with this function type StorageConversionDirection int const ( // Indicates the conversion is from the passed other instance, populating the receiver ConvertFrom = StorageConversionDirection(1) // Indicate the conversion is to the passed other type, populating other ConvertTo = StorageConversionDirection(2) ) // Ensure that StorageConversionFunction implements Function var _ Function = &StorageConversionFunction{} // NewStorageConversionFromFunction creates a new StorageConversionFunction to convert from the specified source func NewStorageConversionFromFunction( receiver TypeDefinition, otherType TypeDefinition, idFactory IdentifierFactory, conversionContext *StorageConversionContext, ) (*StorageConversionFunction, error) { result := &StorageConversionFunction{ otherType: otherType, idFactory: idFactory, conversionDirection: ConvertFrom, conversions: make(map[string]StoragePropertyConversion), knownLocals: NewKnownLocalsSet(idFactory), } version := idFactory.CreateIdentifier(otherType.Name().PackageReference.PackageName(), Exported) result.name = "ConvertFrom" + version result.conversionContext = conversionContext.WithFunctionName(result.name) err := result.createConversions(receiver) if err != nil { return nil, errors.Wrapf(err, "creating '%s()'", result.name) } return result, nil } // NewStorageConversionToFunction creates a new StorageConversionFunction to convert to the specified destination func NewStorageConversionToFunction( receiver TypeDefinition, otherType TypeDefinition, idFactory IdentifierFactory, conversionContext *StorageConversionContext, ) (*StorageConversionFunction, error) { result := &StorageConversionFunction{ otherType: otherType, idFactory: idFactory, conversionDirection: ConvertTo, conversions: make(map[string]StoragePropertyConversion), knownLocals: NewKnownLocalsSet(idFactory), } version := idFactory.CreateIdentifier(otherType.Name().PackageReference.PackageName(), Exported) result.name = "ConvertTo" + version result.conversionContext = conversionContext.WithFunctionName(result.name) err := result.createConversions(receiver) if err != nil { return nil, errors.Wrapf(err, "creating '%s()'", result.name) } return result, nil } // Name returns the name of this function func (fn *StorageConversionFunction) Name() string { return fn.name } // RequiredPackageReferences returns the set of package references required by this function func (fn *StorageConversionFunction) RequiredPackageReferences() *PackageReferenceSet { result := NewPackageReferenceSet( ErrorsReference, fn.otherType.Name().PackageReference) return result } // References returns the set of types referenced by this function func (fn *StorageConversionFunction) References() TypeNameSet { return NewTypeNameSet(fn.otherType.Name()) } // Equals checks to see if the supplied function is the same as this one func (fn *StorageConversionFunction) Equals(f Function) bool { if other, ok := f.(*StorageConversionFunction); ok { if fn.name != other.name { // Different name means not-equal return false } if len(fn.conversions) != len(other.conversions) { // Different count of conversions means not-equal return false } for name := range fn.conversions { if _, found := other.conversions[name]; !found { // Missing conversion means not-equal return false } } return true } return false } // AsFunc renders this function as an AST for serialization to a Go source file func (fn *StorageConversionFunction) AsFunc(generationContext *CodeGenerationContext, receiver TypeName) *dst.FuncDecl { var parameterName string var description string switch fn.conversionDirection { case ConvertFrom: parameterName = "source" description = fmt.Sprintf("populates our %s from the provided source %s", receiver.Name(), fn.otherType.Name().Name()) case ConvertTo: parameterName = "destination" description = fmt.Sprintf("populates the provided destination %s from our %s", fn.otherType.Name().Name(), receiver.Name()) default: panic(fmt.Sprintf("unexpected conversion direction %q", fn.conversionDirection)) } receiverName := fn.idFactory.CreateIdentifier(receiver.Name(), NotExported) funcDetails := &astbuilder.FuncDetails{ ReceiverIdent: receiverName, ReceiverType: receiver.AsType(generationContext), Name: fn.Name(), Body: fn.generateBody(receiverName, parameterName, generationContext), } parameterPackage := generationContext.MustGetImportedPackageName(fn.otherType.Name().PackageReference) funcDetails.AddParameter( parameterName, &dst.StarExpr{ X: &dst.SelectorExpr{ X: dst.NewIdent(parameterPackage), Sel: dst.NewIdent(fn.otherType.Name().Name()), }, }) funcDetails.AddReturns("error") funcDetails.AddComments(description) return funcDetails.DefineFunc() } // generateBody returns all of the statements required for the conversion function // receiver is an expression for access our receiver type, used to qualify field access // parameter is an expression for access to our parameter passed to the function, also used for field access // generationContext is our code generation context, passed to allow resolving of identifiers in other packages func (fn *StorageConversionFunction) generateBody( receiver string, parameter string, generationContext *CodeGenerationContext, ) []dst.Stmt { switch fn.conversionDirection { case ConvertFrom: return fn.generateDirectConversionFrom(receiver, parameter, generationContext) case ConvertTo: return fn.generateDirectConversionTo(receiver, parameter, generationContext) default: panic(fmt.Sprintf("unexpected conversion direction %q", fn.conversionDirection)) } } // generateDirectConversionFrom returns the method body required to directly copy information from // the parameter instance onto our receiver func (fn *StorageConversionFunction) generateDirectConversionFrom( receiver string, parameter string, generationContext *CodeGenerationContext, ) []dst.Stmt { result := fn.generateAssignments(dst.NewIdent(parameter), dst.NewIdent(receiver), generationContext) result = append(result, astbuilder.ReturnNoError()) return result } // generateDirectConversionTo returns the method body required to directly copy information from // our receiver onto the parameter instance func (fn *StorageConversionFunction) generateDirectConversionTo( receiver string, parameter string, generationContext *CodeGenerationContext, ) []dst.Stmt { result := fn.generateAssignments(dst.NewIdent(receiver), dst.NewIdent(parameter), generationContext) result = append(result, astbuilder.ReturnNoError()) return result } // generateAssignments generates a sequence of statements to copy information between the two types func (fn *StorageConversionFunction) generateAssignments( source dst.Expr, destination dst.Expr, generationContext *CodeGenerationContext, ) []dst.Stmt { var result []dst.Stmt // Find all the properties for which we have a conversion var properties []string for p := range fn.conversions { properties = append(properties, p) } // Sort the properties into alphabetical order to ensure deterministic generation sort.Slice(properties, func(i, j int) bool { return properties[i] < properties[j] }) // Accumulate all the statements required for conversions, in alphabetical order for _, prop := range properties { conversion := fn.conversions[prop] block := conversion(source, destination, generationContext) if len(block) > 0 { firstStatement := block[0] firstStatement.Decorations().Before = dst.EmptyLine firstStatement.Decorations().Start.Prepend("// " + prop) result = append(result, block...) } } return result } // createConversions iterates through the properties on our receiver type, matching them up with // our other type and generating conversions where possible func (fn *StorageConversionFunction) createConversions(receiver TypeDefinition) error { receiverObject, ok := AsObjectType(receiver.Type()) if !ok { return errors.Errorf( "expected TypeDefinition %q to wrap receiver object type, but found %q", receiver.name.String(), receiver.Type()) } var otherObject *ObjectType otherObject, ok = AsObjectType(fn.otherType.Type()) if !ok { return errors.Errorf("expected TypeDefinition %q to wrap object type, but none found", fn.otherType.Name().String()) } var errs []error // Flag receiver name as used fn.knownLocals.Add(receiver.Name().Name()) for _, receiverProperty := range receiverObject.Properties() { otherProperty, ok := otherObject.Property(receiverProperty.propertyName) //TODO: Handle renames if ok { var conv StoragePropertyConversion var err error switch fn.conversionDirection { case ConvertFrom: conv, err = fn.createPropertyConversion(otherProperty, receiverProperty) case ConvertTo: conv, err = fn.createPropertyConversion(receiverProperty, otherProperty) default: panic(fmt.Sprintf("unexpected conversion direction %q", fn.conversionDirection)) } if err != nil { // An error was returned; this can happen even if a conversion was created as well. errs = append(errs, err) continue } if conv != nil { // A conversion was created, keep it for later fn.conversions[string(receiverProperty.propertyName)] = conv } } } return kerrors.NewAggregate(errs) } // createPropertyConversion tries to create a property conversion between the two provided properties, using all of the // available conversion functions in priority order to do so. If no valid conversion could be created an error is returned. func (fn *StorageConversionFunction) createPropertyConversion( sourceProperty *PropertyDefinition, destinationProperty *PropertyDefinition) (StoragePropertyConversion, error) { sourceEndpoint := NewStorageConversionEndpoint( sourceProperty.propertyType, string(sourceProperty.propertyName), fn.knownLocals) destinationEndpoint := NewStorageConversionEndpoint( destinationProperty.propertyType, string(destinationProperty.propertyName), fn.knownLocals) conversion, err := createTypeConversion(sourceEndpoint, destinationEndpoint, fn.conversionContext) if err != nil { return nil, errors.Wrapf( err, "trying to assign %q (%s) from %q (%s)", destinationProperty.PropertyName(), destinationProperty.PropertyType(), sourceProperty.PropertyName(), sourceProperty.PropertyType()) } return func(source dst.Expr, destination dst.Expr, generationContext *CodeGenerationContext) []dst.Stmt { reader := astbuilder.Selector(source, string(sourceProperty.PropertyName())) writer := func(expr dst.Expr) []dst.Stmt { return []dst.Stmt{ astbuilder.SimpleAssignment( astbuilder.Selector(destination, string(destinationProperty.PropertyName())), token.ASSIGN, expr), } } return conversion(reader, writer, generationContext) }, nil }
hack/generator/pkg/astmodel/storage_conversion_function.go
0.80525
0.418637
storage_conversion_function.go
starcoder
package yarn import ( "fmt" "math" "strconv" yarnpb "github.com/DrJosh9000/yarn/bytecode" ) // ConvertToBool attempts conversion of the standard Yarn Spinner VM types // (bool, number, string, null) to bool. func ConvertToBool(x interface{}) (bool, error) { if x == nil { return false, nil } switch x := x.(type) { case bool: return x, nil case float32: return !math.IsNaN(float64(x)) && x != 0, nil case float64: return !math.IsNaN(x) && x != 0, nil case int: return x != 0, nil case string: return x != "", nil default: return false, fmt.Errorf("%T %w to bool", x, ErrNotConvertible) } } // ConvertToInt attempts conversion of the standard Yarn Spinner VM types to // (bool, number, string, null) to int. func ConvertToInt(x interface{}) (int, error) { if x == nil { return 0, nil } switch t := x.(type) { case bool: if t { return 1, nil } return 0, nil case float32: return int(t), nil case float64: return int(t), nil case int: return t, nil case string: return strconv.Atoi(t) default: if t == nil { return 0, nil } return 0, fmt.Errorf("%T %w to int", x, ErrNotConvertible) } } // ConvertToFloat32 attempts conversion of the standard Yarn Spinner VM types // (bool, number, string, null) to a float32. func ConvertToFloat32(x interface{}) (float32, error) { if x == nil { return 0, nil } switch t := x.(type) { case bool: if t { return 1, nil } return 0, nil case float32: return t, nil case float64: return float32(t), nil case int: return float32(t), nil case string: y, err := strconv.ParseFloat(t, 32) if err != nil { return 0, err } return float32(y), nil default: if t == nil { return 0, nil } return 0, fmt.Errorf("%T %w to float32", x, ErrNotConvertible) } } // ConvertToFloat64 attempts conversion of the standard Yarn Spinner VM types // (bool, number, string, null) to a float64. func ConvertToFloat64(x interface{}) (float64, error) { if x == nil { return 0, nil } switch t := x.(type) { case bool: if t { return 1, nil } return 0, nil case float32: return float64(t), nil case float64: return t, nil case int: return float64(t), nil case string: return strconv.ParseFloat(t, 64) default: if t == nil { return 0, nil } return 0, fmt.Errorf("%T %w to float64", x, ErrNotConvertible) } } // ConvertToString converts a value to a string, in a way that matches what Yarn // Spinner does. nil becomes "null", and booleans are title-cased. func ConvertToString(x interface{}) string { if x == nil { return "null" } if x, ok := x.(bool); ok { if x { return "True" } return "False" } return fmt.Sprint(x) } // operandToInt is a helper for turning a number value into an int. func operandToInt(op *yarnpb.Operand) (int, error) { if op == nil { return 0, ErrNilOperand } f, ok := op.Value.(*yarnpb.Operand_FloatValue) if !ok { return 0, fmt.Errorf("%w for operand [%T != Operand_FloatValue]", ErrWrongType, op.Value) } return int(f.FloatValue), nil }
convert.go
0.68215
0.504639
convert.go
starcoder
package node // AbstractVisitor holds a concrete visitor // and implements the basic tree traversal logic using the visitor pattern. // By doing so, concrete visitors should not re-implement the same traversal logic in their visit functions. type AbstractVisitor struct { ConcreteVisitor Visitor } // VisitProgramNode traverses the contract node. func (v *AbstractVisitor) VisitProgramNode(node *ProgramNode) { node.Contract.Accept(v.ConcreteVisitor) } // VisitContractNode traverses the variable and function nodes. func (v *AbstractVisitor) VisitContractNode(node *ContractNode) { for _, variable := range node.Fields { variable.Accept(v.ConcreteVisitor) } if node.Constructor != nil { node.Constructor.Accept(v.ConcreteVisitor) } for _, function := range node.Functions { function.Accept(v.ConcreteVisitor) } } // VisitFieldNode traverses the type node and the expression (if present). func (v *AbstractVisitor) VisitFieldNode(node *FieldNode) { node.Type.Accept(v.ConcreteVisitor) if node.Expression != nil { node.Expression.Accept(v.ConcreteVisitor) } } // VisitStructNode traverses the struct fields func (v *AbstractVisitor) VisitStructNode(node *StructNode) { for _, field := range node.Fields { field.Accept(v.ConcreteVisitor) } } // VisitStructFieldNode traverses the type node func (v *AbstractVisitor) VisitStructFieldNode(node *StructFieldNode) { node.Type.Accept(v.ConcreteVisitor) } // VisitConstructorNode traverses the parameters and the statement block func (v *AbstractVisitor) VisitConstructorNode(node *ConstructorNode) { for _, paramType := range node.Parameters { paramType.Accept(v.ConcreteVisitor) } v.ConcreteVisitor.VisitStatementBlock(node.Body) } // VisitFunctionNode traverses the return types, parameters and finally the statement block. func (v *AbstractVisitor) VisitFunctionNode(node *FunctionNode) { for _, returnType := range node.ReturnTypes { returnType.Accept(v.ConcreteVisitor) } for _, paramType := range node.Parameters { paramType.Accept(v.ConcreteVisitor) } v.ConcreteVisitor.VisitStatementBlock(node.Body) } // VisitParameterNode traverses the type node func (v *AbstractVisitor) VisitParameterNode(node *ParameterNode) { node.Type.Accept(v.ConcreteVisitor) } // VisitStatementBlock traverses the statement node. func (v *AbstractVisitor) VisitStatementBlock(stmts []StatementNode) { for _, statement := range stmts { statement.Accept(v.ConcreteVisitor) } } // VisitVariableNode traverses the type node and the expression (if present). func (v *AbstractVisitor) VisitVariableNode(node *VariableNode) { node.Type.Accept(v.ConcreteVisitor) if node.Expression != nil { node.Expression.Accept(v.ConcreteVisitor) } } // VisitMultiVariableNode traverses multiple variables declarations and func (v *AbstractVisitor) VisitMultiVariableNode(node *MultiVariableNode) { for _, t := range node.Types { t.Accept(v.ConcreteVisitor) } node.FuncCall.Accept(v.ConcreteVisitor) } // VisitBasicTypeNode does nothing because it is the terminal node. func (v *AbstractVisitor) VisitBasicTypeNode(node *BasicTypeNode) { // Nothing to do here } // VisitArrayTypeNode visits the type node func (v *AbstractVisitor) VisitArrayTypeNode(node *ArrayTypeNode) { node.ElementType.Accept(v.ConcreteVisitor) } // VisitMapTypeNode visits the key and value type nodes func (v *AbstractVisitor) VisitMapTypeNode(node *MapTypeNode) { node.KeyType.Accept(v.ConcreteVisitor) node.ValueType.Accept(v.ConcreteVisitor) } // VisitIfStatementNode traverses the condition, then-block and finally else-block. func (v *AbstractVisitor) VisitIfStatementNode(node *IfStatementNode) { node.Condition.Accept(v.ConcreteVisitor) v.ConcreteVisitor.VisitStatementBlock(node.Then) v.ConcreteVisitor.VisitStatementBlock(node.Else) } // VisitReturnStatementNode traverses all the available expressions. func (v *AbstractVisitor) VisitReturnStatementNode(node *ReturnStatementNode) { for _, expr := range node.Expressions { expr.Accept(v.ConcreteVisitor) } } // VisitAssignmentStatementNode traverses the target designator and the value expression. func (v *AbstractVisitor) VisitAssignmentStatementNode(node *AssignmentStatementNode) { node.Left.Accept(v.ConcreteVisitor) node.Right.Accept(v.ConcreteVisitor) } // VisitMultiAssignmentStatementNode traverses the target designators and the function call func (v *AbstractVisitor) VisitMultiAssignmentStatementNode(node *MultiAssignmentStatementNode) { for _, designator := range node.Designators { designator.Accept(v.ConcreteVisitor) } node.FuncCall.Accept(v.ConcreteVisitor) } // VisitShorthandAssignmentNode traverses the target designator and the expression func (v *AbstractVisitor) VisitShorthandAssignmentNode(node *ShorthandAssignmentStatementNode) { node.Designator.Accept(v.ConcreteVisitor) node.Expression.Accept(v.ConcreteVisitor) } // VisitCallStatementNode traverses the function call expression func (v *AbstractVisitor) VisitCallStatementNode(node *CallStatementNode) { node.Call.Accept(v.ConcreteVisitor) } // VisitDeleteStatementNode traverses the map element func (v *AbstractVisitor) VisitDeleteStatementNode(node *DeleteStatementNode) { node.Element.Accept(v.ConcreteVisitor) } // VisitTernaryExpressionNode traverses the condition, true and false expressions. func (v *AbstractVisitor) VisitTernaryExpressionNode(node *TernaryExpressionNode) { node.Condition.Accept(v.ConcreteVisitor) node.Then.Accept(v.ConcreteVisitor) node.Else.Accept(v.ConcreteVisitor) } // VisitBinaryExpressionNode traverses the left and right expressions. func (v *AbstractVisitor) VisitBinaryExpressionNode(node *BinaryExpressionNode) { node.Left.Accept(v.ConcreteVisitor) node.Right.Accept(v.ConcreteVisitor) } // VisitUnaryExpressionNode traverses the expression. func (v *AbstractVisitor) VisitUnaryExpressionNode(node *UnaryExpressionNode) { node.Expression.Accept(v.ConcreteVisitor) } // VisitTypeCastNode traverses the type and the designator. func (v *AbstractVisitor) VisitTypeCastNode(node *TypeCastNode) { node.Type.Accept(v.ConcreteVisitor) node.Expression.Accept(v.ConcreteVisitor) } // VisitFuncCallNode traverses the funcCall expression func (v *AbstractVisitor) VisitFuncCallNode(node *FuncCallNode) { node.Designator.Accept(v.ConcreteVisitor) for _, expr := range node.Args { expr.Accept(v.ConcreteVisitor) } } // VisitStructCreationNode traverses the field initialization expressions func (v *AbstractVisitor) VisitStructCreationNode(node *StructCreationNode) { for _, expr := range node.FieldValues { expr.Accept(v.ConcreteVisitor) } } // VisitStructNamedCreationNode traverses the named field initialization expressions func (v *AbstractVisitor) VisitStructNamedCreationNode(node *StructNamedCreationNode) { for _, namedField := range node.FieldValues { namedField.Accept(v.ConcreteVisitor) } } // VisitStructFieldAssignmentNode traverse the field initialization expression func (v *AbstractVisitor) VisitStructFieldAssignmentNode(node *StructFieldAssignmentNode) { node.Expression.Accept(v.ConcreteVisitor) } // VisitArrayLengthCreationNode traverses the size expression nodes func (v *AbstractVisitor) VisitArrayLengthCreationNode(node *ArrayLengthCreationNode) { for _, exp := range node.Lengths { exp.Accept(v.ConcreteVisitor) } } // VisitArrayValueCreationNode traverses the element expression nodes func (v *AbstractVisitor) VisitArrayValueCreationNode(node *ArrayValueCreationNode) { node.Elements.Accept(v.ConcreteVisitor) } // VisitArrayInitializationNode traverses the value expressions func (v *AbstractVisitor) VisitArrayInitializationNode(node *ArrayInitializationNode) { for _, expr := range node.Values { expr.Accept(v.ConcreteVisitor) } } // VisitBasicDesignatorNode does nothing because it is the terminal node. func (v *AbstractVisitor) VisitBasicDesignatorNode(node *BasicDesignatorNode) { // Nothing to do here } // VisitElementAccessNode visits the designator and the expression. func (v *AbstractVisitor) VisitElementAccessNode(node *ElementAccessNode) { node.Designator.Accept(v.ConcreteVisitor) node.Expression.Accept(v.ConcreteVisitor) } // VisitMemberAccessNode visit the designator. func (v *AbstractVisitor) VisitMemberAccessNode(node *MemberAccessNode) { node.Designator.Accept(v.ConcreteVisitor) } // VisitIntegerLiteralNode does nothing because it is the terminal node. func (v *AbstractVisitor) VisitIntegerLiteralNode(node *IntegerLiteralNode) { // Nothing to do here } // VisitStringLiteralNode does nothing because it is the terminal node. func (v *AbstractVisitor) VisitStringLiteralNode(node *StringLiteralNode) { // Nothing to do here } // VisitCharacterLiteralNode does nothing because it is the terminal node. func (v *AbstractVisitor) VisitCharacterLiteralNode(node *CharacterLiteralNode) { // Nothing to do here } // VisitBoolLiteralNode does nothing because it is the terminal node. func (v *AbstractVisitor) VisitBoolLiteralNode(node *BoolLiteralNode) { // Nothing to do here } // VisitErrorNode does nothing because it is the terminal node. func (v *AbstractVisitor) VisitErrorNode(node *ErrorNode) { // Nothing to do here }
parser/node/abstract_visitor.go
0.834879
0.625924
abstract_visitor.go
starcoder
package vaporization import ( "fmt" "sort" g "github.com/chr-ras/advent-of-code-2019/util/geometry" ) // VaporizeAsteroids simulates a laser going clockwise vaporizing the asteroids one by one. func VaporizeAsteroids(asteroidMap []string, monitoringStation g.Point) { asteroidsByAngleMap, angles, totalAsteroids := getAsteroidsByAngle(asteroidMap, monitoringStation) sort.Float64s(angles) numberOfAsteroidsVaporized := 0 for true { for _, angle := range angles { asteroidsForAngle := asteroidsByAngleMap[angle] if len(asteroidsForAngle) == 0 { continue } numberOfAsteroidsVaporized++ fmt.Printf("[%03d] Vaporizing %v\n", numberOfAsteroidsVaporized, asteroidsForAngle[0]) if len(asteroidsForAngle) == 1 { asteroidsByAngleMap[angle] = []g.Point{} fmt.Printf("[%03d] All asteroids for angle %v vaporized\n", numberOfAsteroidsVaporized, angle) continue } asteroidsByAngleMap[angle] = asteroidsForAngle[1:len(asteroidsForAngle)] } if numberOfAsteroidsVaporized == totalAsteroids { fmt.Printf("Vaporized all %v asteroids!", totalAsteroids) return } } } func getAsteroidsByAngle(asteroidMap []string, monitoringStation g.Point) (map[float64][]g.Point, []float64, int) { asteroidsByAngleMap := make(map[float64][]g.Point) angles := []float64{} totalAsteroids := 0 mapWidth := len(asteroidMap[0]) for y := 0; y < len(asteroidMap); y++ { for x := 0; x < mapWidth; x++ { if x == monitoringStation.X && y == monitoringStation.Y { continue } if asteroidMap[y][x:x+1] == "#" { asteroidPoint := g.Point{X: x, Y: y} angleToStation := monitoringStation.GetAngle(asteroidPoint) asteroidsByAngleMap[angleToStation] = append(asteroidsByAngleMap[angleToStation], asteroidPoint) totalAsteroids++ } } } for angle, asteroidsForAngle := range asteroidsByAngleMap { sort.Slice(asteroidsForAngle, func(i, j int) bool { firstPoint := asteroidsForAngle[i] secondPoint := asteroidsForAngle[j] firstVectorLength := g.GetDirectionVector(monitoringStation, firstPoint).Length() secondVectorLength := g.GetDirectionVector(monitoringStation, secondPoint).Length() return firstVectorLength < secondVectorLength }) angles = append(angles, angle) } return asteroidsByAngleMap, angles, totalAsteroids }
10-monitoring-station/vaporization/vaporization.go
0.775945
0.528108
vaporization.go
starcoder
package main /***************************************************************************************************** * * There are a total of n courses you have to take labelled from 0 to n - 1. * * Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you * must take the course bi before the course ai. * * Given the total number of courses numCourses and a list of the prerequisite pairs, return the * ordering of courses you should take to finish all courses. * * If there are many valid answers, return any of them. If it is impossible to finish all courses, * return an empty array. * * Example 1: * * Input: numCourses = 2, prerequisites = [[1,0]] * Output: [0,1] * Explanation: There are a total of 2 courses to take. To take course 1 you should have finished * course 0. So the correct course order is [0,1]. * * Example 2: * * Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] * Output: [0,2,1,3] * Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both * courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. * So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. * * Example 3: * * Input: numCourses = 1, prerequisites = [] * Output: [0] * * Constraints: * * 1 <= numCourses <= 2000 * 0 <= prerequisites.length <= numCourses * (numCourses - 1) * prerequisites[i].length == 2 * 0 <= ai, bi < numCourses * ai != bi * All the pairs [ai, bi] are distinct. ******************************************************************************************************/ // 思路:特殊得图遍历,当记录结果时,应该当这们课所有的依赖都修完后才能入栈,最后再逆序,即为结果 func findOrder(numCourses int, prerequisites [][]int) []int { var ( edges = make([][]int, numCourses) visited = make([]int, numCourses) result []int valid = true dfs func(u int) ) dfs = func(u int) { visited[u]++ for _, v := range edges[u] { if visited[v] == 0 { dfs(v) if !valid { return } } else if visited[v] == 1 { valid = false return } } visited[u]++ result = append(result, u) } for _, v := range prerequisites { //临接表 edges[v[0]] = append(edges[v[0]], v[1]) } for i := 0; i < numCourses && valid; i++ { if visited[i] == 0 { dfs(i) } } if !valid { return []int{} } return result }
basic/Algorithm/graph/210.course_schedule_ii/210.CourseScheduleII_zmillionaire.go
0.546254
0.64607
210.CourseScheduleII_zmillionaire.go
starcoder
package exchange import "fmt" func FmtBalance(balance float64, usdt float64, usdtFrozen float64, currency float64, currencyFrozen float64, ft float64, ftFrozen float64) string { return fmt.Sprintf("balance: %s, usdt: %s, usdtFrozen: %s, currency: %s, currencyFrozen: %s, ft: %s, ftFrozen: %s", FloatToStringForEx(balance), FloatToStringForEx(usdt), FloatToStringForEx(usdtFrozen), FloatToStringForEx(currency), FloatToStringForEx(currencyFrozen), FloatToStringForEx(ft), FloatToStringForEx(ftFrozen), ) } func FmtBalanceExt(balance float64, usdt float64, usdtFrozen float64, fmex float64, fmexFrozen float64, ft float64, ftFrozen float64) string { return fmt.Sprintf("balance: %s, usdt: %s, usdtFrozen: %s, fmex: %s, fmexFrozen: %s, ft: %s, ftFrozen: %s", FloatToStringForEx(balance), FloatToStringForEx(usdt), FloatToStringForEx(usdtFrozen), FloatToStringForEx(fmex), FloatToStringForEx(fmexFrozen), FloatToStringForEx(ft), FloatToStringForEx(ftFrozen), ) } func FmtOrder(symbol string, price float64, amount float64, state string, filledAmount float64) string { return fmt.Sprintf("{ symbol: %s, price: %s, amount: %s, state: %s, filledAmount: %s }", symbol, FloatToStringForEx(price), FloatToStringForEx(amount), state, FloatToStringForEx(filledAmount), ) } func FmtTicker(ticker *Ticker) string { return fmt.Sprintf("symbol: %s, last: %s, lastVol: %s, buy: %s, buyVol: %s, sell: %s, sellVol: %s, high: %s, low: %s, baseVol: %s", ticker.Symbol, FloatToStringForEx(ticker.Last), FloatToStringForEx(ticker.LastVol), FloatToStringForEx(ticker.Buy), FloatToStringForEx(ticker.BuyVol), FloatToStringForEx(ticker.Sell), FloatToStringForEx(ticker.SellVol), FloatToStringForEx(ticker.High), FloatToStringForEx(ticker.Low), FloatToStringForEx(ticker.BaseVol), ) } func FmtPaxMemoryStates(curBuyPrice float64, curSellPrice float64, lastBuyPrice float64, lastSellPrice float64, maxBuyPrice float64, minSellPrice float64) string { return fmt.Sprintf("curBuyPrice: %s, curSellPrice: %s, lastBuyPrice: %s, lastSellPrice: %s, maxBuyPrice: %s, minSellPrice: %s", FloatToStringForEx(curBuyPrice), FloatToStringForEx(curSellPrice), FloatToStringForEx(lastBuyPrice), FloatToStringForEx(lastSellPrice), FloatToStringForEx(maxBuyPrice), FloatToStringForEx(minSellPrice), ) }
exchange/format_utils.go
0.772874
0.486454
format_utils.go
starcoder
package delegated import ( "encoding/binary" "fmt" "github.com/pkg/errors" "github.com/skythen/gobalplatform/aid" "github.com/skythen/gobalplatform/command" "github.com/skythen/gobalplatform/internal/util" "github.com/skythen/gobalplatform/open" ) // Confirmation is a confirmation for a delegated card content management operation. type Confirmation struct { Receipt []byte // A cryptographic value provided by the card (if so required by the Card Issuer) as proof that a Delegated Management operation has occurred. Data ConfirmationData } // ParseConfirmationStructure parses an LV encoded Confirmation Structure and returns Confirmation. func ParseConfirmationStructure(b []byte) (*Confirmation, error) { if len(b) < 6 { return nil, fmt.Errorf("confirmation must be at least 6 bytes long, got %d", len(b)) } var lenReceipt uint16 confirmationIndex := uint16(0) // check if length of confirmation is encoded in more than one byte if b[0] == 0x81 { lenReceipt = binary.BigEndian.Uint16(b[:2]) confirmationIndex += 2 } else { lenReceipt = uint16(b[0]) confirmationIndex++ } if uint16(len(b)) < (confirmationIndex + lenReceipt) { return nil, errors.New("invalid length of receipt") } confirmation := Confirmation{} confirmation.Receipt = b[confirmationIndex : confirmationIndex+lenReceipt] confirmationIndex += lenReceipt // check if more data is available if len(b) > int(confirmationIndex) { confirmationData, err := parseConfirmationData(b[confirmationIndex:]) if err != nil { return nil, err } confirmation.Data = *confirmationData } return &confirmation, nil } type ConfirmationData struct { Counter uint16 // Security Domain unique data is the concatenation without delimiters of the // Security Domain Provider Identification Number ('42') and the Security Domain Image Number (SDIN, tag '45') of // the Security Domain generating the confirmation (with the Receipt Generation Privilege). SDUniqueData []byte TokenIdentifier []byte // Presence depends on whether a Token identifier was included in the original Token. TokenDataDigest []byte // Presence depends on the policy of the Security Domain with Receipt Generation privilege. } func parseConfirmationData(b []byte) (*ConfirmationData, error) { if len(b) < 5 { return nil, fmt.Errorf("confirmation data must be at least 5 byte long, got %d", len(b)) } data := &ConfirmationData{} data.Counter = binary.BigEndian.Uint16(b[1:3]) index := 3 lenCardUniqueData := int(b[index]) index++ data.SDUniqueData = b[index : index+lenCardUniqueData] index += lenCardUniqueData if len(b) > index { lenTokenIdentifier := int(b[index]) index++ data.TokenIdentifier = b[index : index+lenTokenIdentifier] index += lenTokenIdentifier } if len(b) > index { lenTokenDataDigest := int(b[index]) index++ data.TokenDataDigest = b[index : index+lenTokenDataDigest] } return data, nil } // InputForLoad generates input data for signature for the creation of a LOAD token. func InputForLoad(p1, p2 byte, lfAID, sdAID aid.AID, lfdbHash []byte, loadParams command.LoadParameters) ([]byte, error) { bParams := loadParams.Bytes() return inputForLoad(p1, p2, lfAID, sdAID, lfdbHash, bParams) } func inputForLoad(p1, p2 byte, elfAID, sdAID aid.AID, lfdbh []byte, params []byte) ([]byte, error) { paramsLength, err := util.BuildGPBerLength(uint(len(params))) if err != nil { return nil, errors.Wrap(err, "invalid parameters length") } data := make([]byte, 0, 3+len(sdAID)+len(elfAID)+len(lfdbh)+len(paramsLength)+len(params)) data = append(data, byte(len(elfAID))) data = append(data, elfAID...) data = append(data, byte(len(sdAID))) data = append(data, sdAID...) data = append(data, byte(len(lfdbh))) data = append(data, lfdbh...) data = append(data, paramsLength...) data = append(data, params...) tokenData, err := makeTokenData(p1, p2, data) if err != nil { return nil, errors.Wrap(err, "invalid token data") } return tokenData, nil } // InputForInstall generates input data for signature for the creation of an INSTALL token. func InputForInstall(p1, p2 byte, elfAID, emAID, instanceAID aid.AID, privileges open.Privileges, installParams command.InstallParameters) ([]byte, error) { bPrivs, err := privileges.Bytes() if err != nil { return nil, errors.Wrap(err, "invalid Privileges") } bParams := installParams.Bytes() return inputForInstall(p1, p2, elfAID, emAID, instanceAID, bPrivs, bParams) } func inputForInstall(p1, p2 byte, elfAID, emAID, instanceAID aid.AID, privs, params []byte) ([]byte, error) { paramsLength, err := util.BuildGPBerLength(uint(len(params))) if err != nil { return nil, errors.Wrap(err, "invalid parameters length") } data := make([]byte, 0, 4+len(elfAID)+len(emAID)+len(instanceAID)+len(privs)+len(paramsLength)+len(params)) data = append(data, byte(len(elfAID))) data = append(data, elfAID...) data = append(data, byte(len(emAID))) data = append(data, emAID...) data = append(data, byte(len(instanceAID))) data = append(data, instanceAID...) data = append(data, byte(len(privs))) data = append(data, privs...) data = append(data, paramsLength...) data = append(data, params...) tokenData, err := makeTokenData(p1, p2, data) if err != nil { return nil, errors.Wrap(err, "invalid token data") } return tokenData, nil } // InputForMakeSelectable generates input data for signature for the creation of a MAKE SELECTABLE token. func InputForMakeSelectable(p1, p2 byte, instanceAID aid.AID, privs open.Privileges, makeSelectableParams command.MakeSelectableParameters) ([]byte, error) { bPrivs, err := privs.Bytes() if err != nil { return nil, errors.Wrap(err, "invalid Privileges") } bParams := makeSelectableParams.Bytes() paramsLength, err := util.BuildGPBerLength(uint(len(bParams))) if err != nil { return nil, errors.Wrap(err, "invalid parameters length") } data := make([]byte, 0, 4+len(instanceAID)+len(bPrivs)+len(paramsLength)+len(bParams)) data = append(data, 0x00) data = append(data, 0x00) data = append(data, byte(len(instanceAID))) data = append(data, instanceAID...) data = append(data, byte(len(bPrivs))) data = append(data, bPrivs...) data = append(data, paramsLength...) data = append(data, bParams...) tokenData, err := makeTokenData(p1, p2, data) if err != nil { return nil, errors.Wrap(err, "invalid token data") } return tokenData, nil } // InputForExtradition generates input data for signature for the creation of an EXTRADITION token. func InputForExtradition(p1, p2 byte, sdAID, elfOrAppAID aid.AID, extraditionParams command.ExtraditionParameters) ([]byte, error) { bParams := extraditionParams.Bytes() paramsLength, err := util.BuildGPBerLength(uint(len(bParams))) if err != nil { return nil, errors.Wrap(err, "invalid parameters length") } data := make([]byte, 0, 4+len(sdAID)+len(elfOrAppAID)+len(bParams)+len(paramsLength)) data = append(data, byte(len(sdAID))) data = append(data, sdAID...) data = append(data, 0x00) data = append(data, byte(len(elfOrAppAID))) data = append(data, elfOrAppAID...) data = append(data, 0x00) data = append(data, paramsLength...) data = append(data, bParams...) tokenData, err := makeTokenData(p1, p2, data) if err != nil { return nil, errors.Wrap(err, "invalid token data") } return tokenData, nil } // InputForRegistryUpdate generates input data for signature for the creation of an REGISTRY UPDATE token. func InputForRegistryUpdate(p1, p2 byte, sdAID, instanceAID aid.AID, privs open.Privileges, registryUpdateParams command.RegistryUpdateParameters) ([]byte, error) { bPrivs, err := privs.Bytes() if err != nil { return nil, errors.Wrap(err, "invalid Privileges") } bParams := registryUpdateParams.Bytes() paramsLength, err := util.BuildGPBerLength(uint(len(bParams))) if err != nil { return nil, errors.Wrap(err, "invalid parameters length") } data := make([]byte, 0, 4+len(sdAID)+len(instanceAID)+len(bPrivs)+len(bParams)+len(paramsLength)) data = append(data, byte(len(sdAID))) data = append(data, sdAID...) data = append(data, 0x00) data = append(data, byte(len(instanceAID))) data = append(data, instanceAID...) data = append(data, byte(len(bPrivs))) data = append(data, bPrivs...) data = append(data, paramsLength...) data = append(data, bParams...) tokenData, err := makeTokenData(p1, p2, data) if err != nil { return nil, errors.Wrap(err, "invalid token data") } return tokenData, nil } // InputForDelete generates input data for signature for the creation of a DELETE token. func InputForDelete(p1, p2 byte, elfOrAppAID aid.AID, crtDigitalSignature command.CRTDigitalSignature) ([]byte, error) { bCrtDigitalSignature := crtDigitalSignature.Bytes() data := make([]byte, 0, 2+len(elfOrAppAID)+len(bCrtDigitalSignature)) data = append(data, 0x4F) data = append(data, byte(len(elfOrAppAID))) data = append(data, elfOrAppAID...) data = append(data, bCrtDigitalSignature...) tokenData, err := makeTokenData(p1, p2, data) if err != nil { return nil, errors.Wrap(err, "invalid token data") } return tokenData, nil } type LoadInstallAndMakeSelectableTokenInput struct { LoadP1 byte // P1 of the Install [for LOAD] command. LoadP2 byte // P2 of the Install [for LOAD] command. LoadELFAID aid.AID // AID of the ELF to be loaded. SDAID aid.AID // AID of the Security Domain in the Install [for LOAD] command. LFDBHash []byte // Conditional hash of the Load File Data Block. LoadParameters *command.LoadParameters // Additional parameters for the Install [for LOAD] command. InstallP1 byte // P1 of the Install [for load,install and make selectable] command. InstallP2 byte // P2 of the Install [for load,install and make selectable] command. InstallELFAID aid.AID // AID of the ELF that contains the application to be installed. EMAID aid.AID // AID of the EM that the application shall be instantiated from. InstanceAID aid.AID // AID of the application instance. Privileges open.Privileges // Privileges that shall be assigned to the application instance. InstallParameters *command.InstallParameters // Additional parameters for the Install [for load,install and make selectable] command. } // InputForLoadInstallAndMakeSelectable generates input data for signature for the creation of a LOAD, INSTALl and MAKE SELECTABLE token. func InputForLoadInstallAndMakeSelectable(inputData *LoadInstallAndMakeSelectableTokenInput) ([]byte, error) { var ( bLoadParams []byte bInstallParams []byte ) if inputData.LoadParameters != nil { bLoadParams = inputData.LoadParameters.Bytes() } if inputData.InstallParameters != nil { bInstallParams = inputData.InstallParameters.Bytes() } bPrivs, err := inputData.Privileges.Bytes() if err != nil { return nil, errors.Wrap(err, "invalid Privileges") } loadTokenData, err := inputForLoad(inputData.LoadP1, inputData.LoadP2, inputData.LoadELFAID, inputData.SDAID, inputData.LFDBHash, bLoadParams) if err != nil { return nil, errors.Wrap(err, "invalid data for LOAD token") } installTokenData, err := inputForInstall(inputData.InstallP1, inputData.InstallP2, inputData.InstallELFAID, inputData.EMAID, inputData.InstanceAID, bPrivs, bInstallParams) if err != nil { return nil, errors.Wrap(err, "invalid data for INSTALL token") } input := append(loadTokenData, installTokenData...) return input, nil } func makeTokenData(p1, p2 byte, data []byte) ([]byte, error) { length, err := lengthFollowingDataFields(len(data)) if err != nil { return nil, errors.Wrap(err, "invalid length of following data") } tokenData := make([]byte, 0, len(length)+len(data)+2) tokenData = append(tokenData, []byte{p1, p2}...) tokenData = append(tokenData, length...) tokenData = append(tokenData, data...) return tokenData, nil } func lengthFollowingDataFields(length int) ([]byte, error) { if length > 65535 { return nil, errors.Errorf("length must not exceed 65535, got: %d", length) } if length > 255 { return []byte{0x00, (byte)((length >> 8) & 0xFF), (byte)(length & 0xFF)}, nil } return []byte{byte(length)}, nil }
delegated/delegated.go
0.637821
0.441854
delegated.go
starcoder
package cartego import ( "math" ) // Radius of the earth in meters const R = 6378100 const TILESIZE = 256 type Point struct { Lat, Lon float64 } func toRad(deg float64) float64 { return deg * math.Pi / 180 } func toDeg(rad float64) float64 { return rad * 180 / math.Pi } func latToYPixels(lat float64, zoom int) int { latM := math.Atanh(math.Sin(lat)) pixY := -((latM * TILESIZE * math.Exp(float64(zoom) * math.Log(2))) / (2*math.Pi)) + (math.Exp(float64(zoom)*math.Log(2)) * (TILESIZE/2)) return int(math.Floor(pixY)) } func lonToXPixels(lon float64, zoom int) int { pixX := ((lon * TILESIZE * math.Exp(float64(zoom) * math.Log(2)))) / (2 * math.Pi) + (math.Exp(float64(zoom) * math.Log(2)) * (TILESIZE / 2)) return int(math.Floor(pixX)) } func getMercatorFromGPS(p Point, zoom int) Tile { pixX := lonToXPixels(toRad(p.Lon), zoom) pixY := latToYPixels(toRad(p.Lat), zoom) maxTile := int(math.Pow(2, float64(zoom))) maxPix := maxTile * TILESIZE if pixX < 0 { pixX += maxPix } else if pixX > maxPix { pixX -= maxPix } tileX := int(math.Floor(float64(pixX) / TILESIZE)) tileY := int(math.Floor(float64(pixY) / TILESIZE)) if tileX >= maxTile { tileX -= maxTile } return Tile{X: tileX, Y: tileY, Zoom: zoom} } func translate(lat, lon, d, bearing float64) Point { lat, lon, bearing = toRad(lat), toRad(lon), toRad(bearing) lat2 := math.Asin(math.Sin(lat) * math.Cos(d/R) + math.Cos(lat) * math.Sin(d/R) * math.Cos(bearing)) lon2 := lon + math.Atan2(math.Sin(bearing) * math.Sin(d/R) * math.Cos(lat), math.Cos(d/R) - math.Sin(lat)*math.Sin(lat2)) lon2 = math.Mod((lon2 + 3*math.Pi), (2 * math.Pi)) - math.Pi return Point{toDeg(lat2), toDeg(lon2)} } func GetTileCoords(lat, lon, radius float64, minZoom, maxZoom int) (ret []Tile) { north := translate(lat, lon, radius, 0) south := translate(lat, lon, radius, 180) west := translate(lat, lon, radius, 270) east := translate(lat, lon, radius, 90) for zoom := minZoom; zoom <= maxZoom; zoom++ { y0 := getMercatorFromGPS(north, zoom) y1 := getMercatorFromGPS(south, zoom) x0 := getMercatorFromGPS(west, zoom) x1 := getMercatorFromGPS(east, zoom) for i := x0.X; i <= x1.X; i++ { for j := y0.Y; j <= y1.Y; j++ { ret = append(ret, Tile{X: i, Y: j, Zoom: zoom}) } } } return ret }
coords.go
0.858807
0.601477
coords.go
starcoder
package terminal import "github.com/lucasb-eyer/go-colorful" const ( Xterm0 = 0 Xterm1 = 128.0 / 255.0 Xterm2 = 95.0 / 255.0 Xterm3 = 135.0 / 255.0 Xterm4 = 175.0 / 255.0 Xterm5 = 215.0 / 255.0 Xterm6 = 1 ) // Based on https://www.ditig.com/256-colors-cheat-sheet var Xterm256 = []colorful.Color{ {R: Xterm0, G: Xterm0, B: Xterm0}, {R: Xterm1, G: Xterm0, B: Xterm0}, {R: Xterm0, G: Xterm1, B: Xterm0}, {R: Xterm1, G: Xterm1, B: Xterm0}, {R: Xterm0, G: Xterm0, B: Xterm1}, {R: Xterm1, G: Xterm0, B: Xterm1}, {R: Xterm0, G: Xterm1, B: Xterm1}, {R: 192.0 / 255.0, G: 192.0 / 255.0, B: 192.0 / 255.0}, {R: Xterm1, G: Xterm1, B: Xterm1}, {R: Xterm6, G: Xterm0, B: Xterm0}, {R: Xterm0, G: Xterm6, B: Xterm0}, {R: Xterm6, G: Xterm6, B: Xterm0}, {R: Xterm0, G: Xterm0, B: Xterm6}, {R: Xterm6, G: Xterm0, B: Xterm6}, {R: Xterm0, G: Xterm6, B: Xterm6}, {R: Xterm6, G: Xterm6, B: Xterm6}, {R: Xterm0, G: Xterm0, B: Xterm0}, {R: Xterm0, G: Xterm0, B: Xterm2}, {R: Xterm0, G: Xterm0, B: Xterm3}, {R: Xterm0, G: Xterm0, B: Xterm4}, {R: Xterm0, G: Xterm0, B: Xterm5}, {R: Xterm0, G: Xterm0, B: Xterm6}, {R: Xterm0, G: Xterm2, B: Xterm0}, {R: Xterm0, G: Xterm2, B: Xterm2}, {R: Xterm0, G: Xterm2, B: Xterm3}, {R: Xterm0, G: Xterm2, B: Xterm4}, {R: Xterm0, G: Xterm2, B: Xterm5}, {R: Xterm0, G: Xterm2, B: Xterm6}, {R: Xterm0, G: Xterm3, B: Xterm0}, {R: Xterm0, G: Xterm3, B: Xterm2}, {R: Xterm0, G: Xterm3, B: Xterm3}, {R: Xterm0, G: Xterm3, B: Xterm4}, {R: Xterm0, G: Xterm3, B: Xterm5}, {R: Xterm0, G: Xterm3, B: Xterm6}, {R: Xterm0, G: Xterm4, B: Xterm0}, {R: Xterm0, G: Xterm4, B: Xterm2}, {R: Xterm0, G: Xterm4, B: Xterm3}, {R: Xterm0, G: Xterm4, B: Xterm4}, {R: Xterm0, G: Xterm4, B: Xterm5}, {R: Xterm0, G: Xterm4, B: Xterm6}, {R: Xterm0, G: Xterm5, B: Xterm0}, {R: Xterm0, G: Xterm5, B: Xterm2}, {R: Xterm0, G: Xterm5, B: Xterm3}, {R: Xterm0, G: Xterm5, B: Xterm4}, {R: Xterm0, G: Xterm5, B: Xterm5}, {R: Xterm0, G: Xterm5, B: Xterm6}, {R: Xterm0, G: Xterm6, B: Xterm0}, {R: Xterm0, G: Xterm6, B: Xterm2}, {R: Xterm0, G: Xterm6, B: Xterm3}, {R: Xterm0, G: Xterm6, B: Xterm4}, {R: Xterm0, G: Xterm6, B: Xterm5}, {R: Xterm0, G: Xterm6, B: Xterm6}, {R: Xterm2, G: Xterm0, B: Xterm0}, {R: Xterm2, G: Xterm0, B: Xterm2}, {R: Xterm2, G: Xterm0, B: Xterm3}, {R: Xterm2, G: Xterm0, B: Xterm4}, {R: Xterm2, G: Xterm0, B: Xterm5}, {R: Xterm2, G: Xterm0, B: Xterm6}, {R: Xterm2, G: Xterm2, B: Xterm0}, {R: Xterm2, G: Xterm2, B: Xterm2}, {R: Xterm2, G: Xterm2, B: Xterm3}, {R: Xterm2, G: Xterm2, B: Xterm4}, {R: Xterm2, G: Xterm2, B: Xterm5}, {R: Xterm2, G: Xterm2, B: Xterm6}, {R: Xterm2, G: Xterm3, B: Xterm0}, {R: Xterm2, G: Xterm3, B: Xterm2}, {R: Xterm2, G: Xterm3, B: Xterm3}, {R: Xterm2, G: Xterm3, B: Xterm4}, {R: Xterm2, G: Xterm3, B: Xterm5}, {R: Xterm2, G: Xterm3, B: Xterm6}, {R: Xterm2, G: Xterm4, B: Xterm0}, {R: Xterm2, G: Xterm4, B: Xterm2}, {R: Xterm2, G: Xterm4, B: Xterm3}, {R: Xterm2, G: Xterm4, B: Xterm4}, {R: Xterm2, G: Xterm4, B: Xterm5}, {R: Xterm2, G: Xterm4, B: Xterm6}, {R: Xterm2, G: Xterm5, B: Xterm0}, {R: Xterm2, G: Xterm5, B: Xterm2}, {R: Xterm2, G: Xterm5, B: Xterm3}, {R: Xterm2, G: Xterm5, B: Xterm4}, {R: Xterm2, G: Xterm5, B: Xterm5}, {R: Xterm2, G: Xterm5, B: Xterm6}, {R: Xterm2, G: Xterm6, B: Xterm0}, {R: Xterm2, G: Xterm6, B: Xterm2}, {R: Xterm2, G: Xterm6, B: Xterm3}, {R: Xterm2, G: Xterm6, B: Xterm4}, {R: Xterm2, G: Xterm6, B: Xterm5}, {R: Xterm2, G: Xterm6, B: Xterm6}, {R: Xterm3, G: Xterm0, B: Xterm0}, {R: Xterm3, G: Xterm0, B: Xterm2}, {R: Xterm3, G: Xterm0, B: Xterm3}, {R: Xterm3, G: Xterm0, B: Xterm4}, {R: Xterm3, G: Xterm0, B: Xterm5}, {R: Xterm3, G: Xterm0, B: Xterm6}, {R: Xterm3, G: Xterm2, B: Xterm0}, {R: Xterm3, G: Xterm2, B: Xterm2}, {R: Xterm3, G: Xterm2, B: Xterm3}, {R: Xterm3, G: Xterm2, B: Xterm4}, {R: Xterm3, G: Xterm2, B: Xterm5}, {R: Xterm3, G: Xterm2, B: Xterm6}, {R: Xterm3, G: Xterm3, B: Xterm0}, {R: Xterm3, G: Xterm3, B: Xterm2}, {R: Xterm3, G: Xterm3, B: Xterm3}, {R: Xterm3, G: Xterm3, B: Xterm4}, {R: Xterm3, G: Xterm3, B: Xterm5}, {R: Xterm3, G: Xterm3, B: Xterm6}, {R: Xterm3, G: Xterm4, B: Xterm0}, {R: Xterm3, G: Xterm4, B: Xterm2}, {R: Xterm3, G: Xterm4, B: Xterm3}, {R: Xterm3, G: Xterm4, B: Xterm4}, {R: Xterm3, G: Xterm4, B: Xterm5}, {R: Xterm3, G: Xterm4, B: Xterm6}, {R: Xterm3, G: Xterm5, B: Xterm0}, {R: Xterm3, G: Xterm5, B: Xterm2}, {R: Xterm3, G: Xterm5, B: Xterm3}, {R: Xterm3, G: Xterm5, B: Xterm4}, {R: Xterm3, G: Xterm5, B: Xterm5}, {R: Xterm3, G: Xterm5, B: Xterm6}, {R: Xterm3, G: Xterm6, B: Xterm0}, {R: Xterm3, G: Xterm6, B: Xterm2}, {R: Xterm3, G: Xterm6, B: Xterm3}, {R: Xterm3, G: Xterm6, B: Xterm4}, {R: Xterm3, G: Xterm6, B: Xterm5}, {R: Xterm3, G: Xterm6, B: Xterm6}, {R: Xterm4, G: Xterm0, B: Xterm0}, {R: Xterm4, G: Xterm0, B: Xterm2}, {R: Xterm4, G: Xterm0, B: Xterm3}, {R: Xterm4, G: Xterm0, B: Xterm4}, {R: Xterm4, G: Xterm0, B: Xterm5}, {R: Xterm4, G: Xterm0, B: Xterm6}, {R: Xterm4, G: Xterm2, B: Xterm0}, {R: Xterm4, G: Xterm2, B: Xterm2}, {R: Xterm4, G: Xterm2, B: Xterm3}, {R: Xterm4, G: Xterm2, B: Xterm4}, {R: Xterm4, G: Xterm2, B: Xterm5}, {R: Xterm4, G: Xterm2, B: Xterm6}, {R: Xterm4, G: Xterm3, B: Xterm0}, {R: Xterm4, G: Xterm3, B: Xterm2}, {R: Xterm4, G: Xterm3, B: Xterm3}, {R: Xterm4, G: Xterm3, B: Xterm4}, {R: Xterm4, G: Xterm3, B: Xterm5}, {R: Xterm4, G: Xterm3, B: Xterm6}, {R: Xterm4, G: Xterm4, B: Xterm0}, {R: Xterm4, G: Xterm4, B: Xterm2}, {R: Xterm4, G: Xterm4, B: Xterm3}, {R: Xterm4, G: Xterm4, B: Xterm4}, {R: Xterm4, G: Xterm4, B: Xterm5}, {R: Xterm4, G: Xterm4, B: Xterm6}, {R: Xterm4, G: Xterm5, B: Xterm0}, {R: Xterm4, G: Xterm5, B: Xterm2}, {R: Xterm4, G: Xterm5, B: Xterm3}, {R: Xterm4, G: Xterm5, B: Xterm4}, {R: Xterm4, G: Xterm5, B: Xterm5}, {R: Xterm4, G: Xterm5, B: Xterm6}, {R: Xterm4, G: Xterm6, B: Xterm0}, {R: Xterm4, G: Xterm6, B: Xterm2}, {R: Xterm4, G: Xterm6, B: Xterm3}, {R: Xterm4, G: Xterm6, B: Xterm4}, {R: Xterm4, G: Xterm6, B: Xterm5}, {R: Xterm4, G: Xterm6, B: Xterm6}, {R: Xterm5, G: Xterm0, B: Xterm0}, {R: Xterm5, G: Xterm0, B: Xterm2}, {R: Xterm5, G: Xterm0, B: Xterm3}, {R: Xterm5, G: Xterm0, B: Xterm4}, {R: Xterm5, G: Xterm0, B: Xterm5}, {R: Xterm5, G: Xterm0, B: Xterm6}, {R: Xterm5, G: Xterm2, B: Xterm0}, {R: Xterm5, G: Xterm2, B: Xterm2}, {R: Xterm5, G: Xterm2, B: Xterm3}, {R: Xterm5, G: Xterm2, B: Xterm4}, {R: Xterm5, G: Xterm2, B: Xterm5}, {R: Xterm5, G: Xterm2, B: Xterm6}, {R: Xterm5, G: Xterm3, B: Xterm0}, {R: Xterm5, G: Xterm3, B: Xterm2}, {R: Xterm5, G: Xterm3, B: Xterm3}, {R: Xterm5, G: Xterm3, B: Xterm4}, {R: Xterm5, G: Xterm3, B: Xterm5}, {R: Xterm5, G: Xterm3, B: Xterm6}, {R: Xterm5, G: Xterm4, B: Xterm0}, {R: Xterm5, G: Xterm4, B: Xterm2}, {R: Xterm5, G: Xterm4, B: Xterm3}, {R: Xterm5, G: Xterm4, B: Xterm4}, {R: Xterm5, G: Xterm4, B: Xterm5}, {R: Xterm5, G: Xterm4, B: Xterm6}, {R: Xterm5, G: Xterm5, B: Xterm0}, {R: Xterm5, G: Xterm5, B: Xterm2}, {R: Xterm5, G: Xterm5, B: Xterm3}, {R: Xterm5, G: Xterm5, B: Xterm4}, {R: Xterm5, G: Xterm5, B: Xterm5}, {R: Xterm5, G: Xterm5, B: Xterm6}, {R: Xterm5, G: Xterm6, B: Xterm0}, {R: Xterm5, G: Xterm6, B: Xterm2}, {R: Xterm5, G: Xterm6, B: Xterm3}, {R: Xterm5, G: Xterm6, B: Xterm4}, {R: Xterm5, G: Xterm6, B: Xterm5}, {R: Xterm5, G: Xterm6, B: Xterm6}, {R: Xterm6, G: Xterm0, B: Xterm0}, {R: Xterm6, G: Xterm0, B: Xterm2}, {R: Xterm6, G: Xterm0, B: Xterm3}, {R: Xterm6, G: Xterm0, B: Xterm4}, {R: Xterm6, G: Xterm0, B: Xterm5}, {R: Xterm6, G: Xterm0, B: Xterm6}, {R: Xterm6, G: Xterm2, B: Xterm0}, {R: Xterm6, G: Xterm2, B: Xterm2}, {R: Xterm6, G: Xterm2, B: Xterm3}, {R: Xterm6, G: Xterm2, B: Xterm4}, {R: Xterm6, G: Xterm2, B: Xterm5}, {R: Xterm6, G: Xterm2, B: Xterm6}, {R: Xterm6, G: Xterm3, B: Xterm0}, {R: Xterm6, G: Xterm3, B: Xterm2}, {R: Xterm6, G: Xterm3, B: Xterm3}, {R: Xterm6, G: Xterm3, B: Xterm4}, {R: Xterm6, G: Xterm3, B: Xterm5}, {R: Xterm6, G: Xterm3, B: Xterm6}, {R: Xterm6, G: Xterm4, B: Xterm0}, {R: Xterm6, G: Xterm4, B: Xterm2}, {R: Xterm6, G: Xterm4, B: Xterm3}, {R: Xterm6, G: Xterm4, B: Xterm4}, {R: Xterm6, G: Xterm4, B: Xterm5}, {R: Xterm6, G: Xterm4, B: Xterm6}, {R: Xterm6, G: Xterm5, B: Xterm0}, {R: Xterm6, G: Xterm5, B: Xterm2}, {R: Xterm6, G: Xterm5, B: Xterm3}, {R: Xterm6, G: Xterm5, B: Xterm4}, {R: Xterm6, G: Xterm5, B: Xterm5}, {R: Xterm6, G: Xterm5, B: Xterm6}, {R: Xterm6, G: Xterm6, B: Xterm0}, {R: Xterm6, G: Xterm6, B: Xterm2}, {R: Xterm6, G: Xterm6, B: Xterm3}, {R: Xterm6, G: Xterm6, B: Xterm4}, {R: Xterm6, G: Xterm6, B: Xterm5}, {R: Xterm6, G: Xterm6, B: Xterm6}, {R: 8.0 / 255.0, G: 8.0 / 255.0, B: 8.0 / 255.0}, {R: 18.0 / 255.0, G: 18.0 / 255.0, B: 18.0 / 255.0}, {R: 28.0 / 255.0, G: 28.0 / 255.0, B: 28.0 / 255.0}, {R: 38.0 / 255.0, G: 38.0 / 255.0, B: 38.0 / 255.0}, {R: 48.0 / 255.0, G: 48.0 / 255.0, B: 48.0 / 255.0}, {R: 58.0 / 255.0, G: 58.0 / 255.0, B: 58.0 / 255.0}, {R: 68.0 / 255.0, G: 68.0 / 255.0, B: 68.0 / 255.0}, {R: 78.0 / 255.0, G: 78.0 / 255.0, B: 78.0 / 255.0}, {R: 88.0 / 255.0, G: 88.0 / 255.0, B: 88.0 / 255.0}, {R: 98.0 / 255.0, G: 98.0 / 255.0, B: 98.0 / 255.0}, {R: 108.0 / 255.0, G: 108.0 / 255.0, B: 108.0 / 255.0}, {R: 118.0 / 255.0, G: 118.0 / 255.0, B: 118.0 / 255.0}, {R: 128.0 / 255.0, G: 128.0 / 255.0, B: 128.0 / 255.0}, {R: 138.0 / 255.0, G: 138.0 / 255.0, B: 138.0 / 255.0}, {R: 148.0 / 255.0, G: 148.0 / 255.0, B: 148.0 / 255.0}, {R: 158.0 / 255.0, G: 158.0 / 255.0, B: 158.0 / 255.0}, {R: 168.0 / 255.0, G: 168.0 / 255.0, B: 168.0 / 255.0}, {R: 178.0 / 255.0, G: 178.0 / 255.0, B: 178.0 / 255.0}, {R: 188.0 / 255.0, G: 188.0 / 255.0, B: 188.0 / 255.0}, {R: 198.0 / 255.0, G: 198.0 / 255.0, B: 198.0 / 255.0}, {R: 208.0 / 255.0, G: 208.0 / 255.0, B: 208.0 / 255.0}, {R: 218.0 / 255.0, G: 218.0 / 255.0, B: 218.0 / 255.0}, {R: 228.0 / 255.0, G: 228.0 / 255.0, B: 228.0 / 255.0}, {R: 238.0 / 255.0, G: 238.0 / 255.0, B: 238.0 / 255.0}, }
terminal/xterm.go
0.524882
0.563018
xterm.go
starcoder
package continuous import ( "github.com/jtejido/ggsl/specfunc" "github.com/jtejido/stats" "github.com/jtejido/stats/err" smath "github.com/jtejido/stats/math" "math" "math/rand" ) // Kumaraswamy distribution // https://en.wikipedia.org/wiki/Kumaraswamy_distribution type Kumaraswamy struct { a, b float64 src rand.Source } func NewKumaraswamy(a, b float64) (*Kumaraswamy, error) { return NewKumaraswamyWithSource(a, b, nil) } func NewKumaraswamyWithSource(a, b float64, src rand.Source) (*Kumaraswamy, error) { if a <= 0 || b <= 0 { return nil, err.Invalid() } return &Kumaraswamy{a, b, nil}, nil } // a ∈ [0,∞) // b ∈ [0,∞) func (k *Kumaraswamy) Parameters() stats.Limits { return stats.Limits{ "a": stats.Interval{0, math.Inf(1), false, true}, "b": stats.Interval{0, math.Inf(1), false, true}, } } // x ∈ (0,1) func (k *Kumaraswamy) Support() stats.Interval { return stats.Interval{0, 1, false, false} } func (k *Kumaraswamy) Probability(x float64) float64 { if k.Support().IsWithinInterval(x) { return k.a * k.b * math.Pow(x, k.a-1) * math.Pow(1-math.Pow(x, k.a), k.b-1) } return 0 } func (k *Kumaraswamy) Distribution(x float64) float64 { if k.Support().IsWithinInterval(x) { return 1 - math.Pow(1-math.Pow(x, k.a), k.b) } else if x >= 1 { return 1 } return 0 } func (k *Kumaraswamy) Mean() float64 { return (k.b * specfunc.Gamma(1+(1./k.a)) * specfunc.Gamma(k.b)) / specfunc.Gamma(1+(1./k.a)+k.b) } func (k *Kumaraswamy) Median() float64 { return math.Pow(1-math.Pow(2., -1/k.b), 1./k.a) } func (k *Kumaraswamy) Mode() float64 { if k.a >= 1 && k.b >= 1 { return math.Pow((k.a-1)/(k.a*k.b)-1, 1./k.a) } return math.NaN() } func (k *Kumaraswamy) Variance() float64 { m1 := k.rm(1) return -(m1 * m1) + k.rm(2) } func (k *Kumaraswamy) Skewness() float64 { m1 := k.rm(1) m2 := k.rm(2) m3 := k.rm(3) return (m1*(2*(m1*m1)-3*m2) + m3) / math.Pow(m2-(m1*m1), 3./2) } func (k *Kumaraswamy) ExKurtosis() float64 { m1 := k.rm(1) m2 := k.rm(2) m3 := k.rm(3) m4 := k.rm(4) return (-3*(m1*m1*m1*m1) + 6*(m1*m1)*m2 - 4*m1*m3 + m4 - 3*((m2-(m1*m1))*(m2-(m1*m1)))) / ((m2 - (m1 * m1)) * (m2 - (m1 * m1))) } // Raw Moment func (k *Kumaraswamy) rm(n int) float64 { return (k.b * specfunc.Beta(1.0+float64(n)/k.a, k.b)) } func (k *Kumaraswamy) Entropy() float64 { return (1 - (1. / k.b)) + (1-(1./k.a))*smath.Harmonic(k.b) - math.Log(k.a*k.b) } func (k *Kumaraswamy) Inverse(p float64) float64 { if p <= 0 { return 0 } if p >= 1 { return 1 } return math.Pow(1-math.Pow(1-p, 1/k.b), 1/k.a) } func (k *Kumaraswamy) Rand() float64 { var rnd float64 if k.src != nil { rnd = rand.New(k.src).Float64() } else { rnd = rand.Float64() } return k.Inverse(rnd) }
dist/continuous/kumaraswamy.go
0.687105
0.416737
kumaraswamy.go
starcoder
package stats import ( "bytes" "fmt" "sync" ) // MatrixType provides a common interface for Matrix and MatrixFunc. type MatrixType interface { LabelX() string LabelY() string Data() map[string]map[string]int64 } // Matrix provides a two-dimentional map from string.string to int64. // It also provides a Data method which can be used for dumping data. type Matrix struct { mu sync.Mutex labelX string labelY string data map[string]map[string]int64 } func NewMatrix(name, labelX, labelY string) *Matrix { m := &Matrix{ labelX: labelX, labelY: labelY, data: make(map[string]map[string]int64), } if name != "" { Publish(name, m) } return m } func (m *Matrix) String() string { m.mu.Lock() defer m.mu.Unlock() return matrixToString(m.labelX, m.labelY, m.data) } func (m *Matrix) Add(name1, name2 string, value int64) { m.mu.Lock() defer m.mu.Unlock() mat, ok := m.data[name1] if !ok { mat = make(map[string]int64) m.data[name1] = mat } mat[name2] += value } func (m *Matrix) LabelX() string { return m.labelX } func (m *Matrix) LabelY() string { return m.labelY } func (m *Matrix) Data() map[string]map[string]int64 { m.mu.Lock() defer m.mu.Unlock() data := make(map[string]map[string]int64, len(m.data)) for k1, v1 := range m.data { temp := make(map[string]int64, len(v1)) for k2, v2 := range v1 { temp[k2] = v2 } data[k1] = temp } return data } // MatrixFunc converts a function that returns // a two-dimentional map of int64 as an expvar. type MatrixFunc struct { labelX string labelY string f func() map[string]map[string]int64 } func NewMatrixFunc(labelX, labelY string, f func() map[string]map[string]int64) *MatrixFunc { m := &MatrixFunc{labelX: labelX, labelY: labelY, f: f} return m } func (m *MatrixFunc) LabelX() string { return m.labelX } func (m *MatrixFunc) LabelY() string { return m.labelY } func (m *MatrixFunc) Data() map[string]map[string]int64 { return m.f() } func (m *MatrixFunc) String() string { data := m.f() if data == nil { return "{}" } return matrixToString(m.labelX, m.labelY, data) } func matrixToString(labelX, labelY string, m map[string]map[string]int64) string { b := bytes.NewBuffer(make([]byte, 0, 4096)) fmt.Fprintf(b, "[") firstValue := true for k1, v1 := range m { for k2, v2 := range v1 { if firstValue { firstValue = false } else { fmt.Fprintf(b, ", ") } fmt.Fprintf(b, `{"%v": "%v", "%v": "%v", "Value": %v}`, labelX, k1, labelY, k2, v2) } } fmt.Fprintf(b, "]") return b.String() }
go/stats/matrix.go
0.641759
0.54256
matrix.go
starcoder
package calver import ( "fmt" "math" ) type Convention struct { representation string format string extract func(*Version) int validate func(int) error } func (c *Convention) Format(value int) string { return fmt.Sprintf(c.format, value) } var ( YYYY = Convention{ representation: "YYYY", extract: extractYear, format: "%04d", validate: validateInRange(2000, 2500), } YY = Convention{ representation: "YY", extract: truncInt(2, extractYear), format: "%d", validate: validateInRange(0, 99), } zeroY = Convention{ representation: "0Y", extract: truncInt(2, extractYear), format: "%02d", validate: validateInRange(0, 99), } MM = Convention{ representation: "MM", extract: extractMonth, format: "%d", validate: validateInRange(1, 12), } M0 = Convention{ representation: "M0", extract: extractMonth, format: "%02d", validate: validateInRange(1, 12), } zeroM = Convention{ representation: "0M", extract: extractMonth, format: "%02d", validate: validateInRange(1, 12), } DD = Convention{ representation: "DD", extract: extractDay, format: "%d", validate: validateInRange(1, 31), } D0 = Convention{ representation: "D0", extract: extractDay, format: "%02d", validate: validateInRange(1, 31), } zeroD = Convention{ representation: "0D", extract: extractDay, format: "%02d", validate: validateInRange(1, 31), } MICRO = Convention{ representation: "MICRO", extract: extractMicro, format: "%d", validate: validatePositive, } CONVENTIONS = map[string]Convention{ YYYY.representation: YYYY, YY.representation: YY, zeroY.representation: zeroY, MM.representation: MM, M0.representation: M0, zeroM.representation: zeroM, DD.representation: DD, D0.representation: D0, zeroD.representation: zeroD, MICRO.representation: MICRO, } ) func extractYear(version *Version) int { return version.time.Year() } func extractMonth(version *Version) int { return int(version.time.Month()) } func extractDay(version *Version) int { return version.time.Day() } func extractMicro(version *Version) int { return version.micro } func truncInt(width int, fn func(*Version) int) func(*Version) int { return func(version *Version) int { multiplier := int(math.Pow10(width)) val := fn(version) truncated := val - (val / multiplier * multiplier) return truncated } } func validateInRange(minVal, maxVal int) func(int) error { return func(val int) error { if minVal > val || maxVal < val { return fmt.Errorf("invalid value %d", val) } return nil } } func validatePositive(val int) error { if val <= 0 { return fmt.Errorf("invalid value %d", val) } return nil }
calver/conventions.go
0.517083
0.482795
conventions.go
starcoder
package graph // V is a vertex/node of the graph represented as an integer value type V int // G is a graph represented as an adjacency list of nodes type G map[V][]V // E is an edge between two vertexes u and v type E [2]V // NewNode returns a new node func NewNode(i int) V { return V(i) } // Value returns the integer value of the node func (v V) Value() int { return int(v) } // NewEdge returns an edge between the vertexes u and v func NewEdge(u, v V) E { return E([2]V{u, v}) } // NewGraph returns a new empty graph of capacity n func NewGraph(n int) G { return make(G, n) } // Has returns true if the graph has that vertex otherwise false func (g G) Has(v V) bool { _, ok := g[v] return ok } // Node return the node with given key i, or nil if not present func (g G) Node(i int) *V { if !g.Has(V(i)) { return nil } for _, v := range g.Nodes() { if i == v.Value() { return &v } } return nil } // AddEdge adds an endge to the graph between the nodes u and v if not already present: // returns true if added or false if already present func (g G) AddEdge(u, v V) bool { if g.AreNeighbours(u, v) { return false } g[u] = append(g[u], v) return true } // AreNeighbours returns true if the u and v are neighbours in the graph func (g G) AreNeighbours(u, v V) bool { uE, ok := g[u] if !ok { return false } vE, ok := g[v] if !ok { return false } if in(v, uE) && in(u, vE) { return true } return false } // Add adds a node to the graph func (g G) Add(v V, e []V) bool { if g.Has(v) { return false } g[v] = e return true } func in(x V, array []V) bool { for _, i := range array { if i == x { return true } } return false } // Nodes returns a slice containigs all the graph's nodes func (g G) Nodes() []V { nodes := make([]V, 0, len(g)) for n := range g { nodes = append(nodes, n) } return nodes } // Edges returns a slice containing all the graph's edges func (g G) Edges() []E { edges := make([]E, 0, len(g)) for u := range g { edges = append(edges, g.EdgeList(u)...) } return edges } // EdgeList returns a slice containing all the edges hitting node u func (g G) EdgeList(u V) []E { edges := make([]E, 0, len(g[u])) for _, v := range g[u] { edges = append(edges, NewEdge(u, v)) } return edges }
graph/graph.go
0.8746
0.646125
graph.go
starcoder
package deltas_computation import ( . "github.com/protolambda/zrnt/eth2/beacon" . "github.com/protolambda/zrnt/eth2/core" "github.com/protolambda/zrnt/eth2/util/math" ) type ValidatorStatusFlag uint64 func (flags ValidatorStatusFlag) hasMarkers(markers ValidatorStatusFlag) bool { return flags & markers == markers } const ( prevEpochAttester ValidatorStatusFlag = 1 << iota matchingHeadAttester epochBoundaryAttester unslashed eligibleAttester ) const noInclusionMarker = ^Slot(0) type ValidatorStatus struct { InclusionSlot Slot DataSlot Slot Flags ValidatorStatusFlag } // Retrieves the inclusion slot of the earliest attestation in the previous epoch. // Ok == true if there is such attestation, false otherwise. func (status *ValidatorStatus) inclusionSlot() (slot Slot, ok bool) { if status.InclusionSlot == noInclusionMarker { return 0, false } else { return status.InclusionSlot, true } } // Note: ONLY safe to call when vIndex is known to be an active validator in the previous epoch func (status *ValidatorStatus) inclusionDistance() Slot { return status.InclusionSlot - status.DataSlot } func DeltasJustificationAndFinalizationDeltas(state *BeaconState,) *Deltas { validatorCount := ValidatorIndex(len(state.ValidatorRegistry)) deltas := NewDeltas(uint64(validatorCount)) currentEpoch := state.Epoch() data := make([]ValidatorStatus, validatorCount, validatorCount) for i := 0; i < len(data); i++ { data[i].InclusionSlot = noInclusionMarker } { previousBoundaryBlockRoot, _ := state.GetBlockRootAtSlot(state.PreviousEpoch().GetStartSlot()) for _, att := range state.PreviousEpochAttestations { attBlockRoot, _ := state.GetBlockRootAtSlot(att.Data.Slot) participants, _ := state.GetAttestingIndicesUnsorted(&att.Data, &att.AggregationBitfield) for _, p := range participants { status := &data[p] // If the attestation is the earliest: if status.InclusionSlot > att.InclusionSlot { status.InclusionSlot = att.InclusionSlot status.DataSlot = att.Data.Slot } if !state.ValidatorRegistry[p].Slashed { status.Flags |= unslashed } // remember the participant as one of the good validators status.Flags |= prevEpochAttester // If the attestation is for the boundary: if att.Data.TargetRoot == previousBoundaryBlockRoot { status.Flags |= epochBoundaryAttester } // If the attestation is for the head (att the time of attestation): if att.Data.BeaconBlockRoot == attBlockRoot { status.Flags |= matchingHeadAttester } } } } var totalBalance, totalAttestingBalance, epochBoundaryBalance, matchingHeadBalance Gwei for i := ValidatorIndex(0); i < validatorCount; i++ { status := &data[i] v := state.ValidatorRegistry[i] b := v.EffectiveBalance totalBalance += b if status.Flags.hasMarkers(prevEpochAttester | unslashed) { totalAttestingBalance += b } if status.Flags.hasMarkers(epochBoundaryAttester | unslashed) { epochBoundaryBalance += b } if status.Flags.hasMarkers(matchingHeadAttester | unslashed) { matchingHeadBalance += b } if v.IsActive(currentEpoch) || (v.Slashed && currentEpoch < v.WithdrawableEpoch) { status.Flags |= eligibleAttester } } previousTotalBalance := state.GetTotalBalanceOf( state.ValidatorRegistry.GetActiveValidatorIndices(state.PreviousEpoch())) adjustedQuotient := math.IntegerSquareroot(uint64(previousTotalBalance)) / BASE_REWARD_QUOTIENT epochsSinceFinality := currentEpoch + 1 - state.FinalizedEpoch for i := ValidatorIndex(0); i < validatorCount; i++ { status := &data[i] if status.Flags & eligibleAttester != 0 { v := state.ValidatorRegistry[i] baseReward := Gwei(0) if adjustedQuotient != 0 { baseReward = v.EffectiveBalance / Gwei(adjustedQuotient) / 5 } inactivityPenalty := baseReward if epochsSinceFinality > 4 { inactivityPenalty += v.EffectiveBalance * Gwei(epochsSinceFinality) / INACTIVITY_PENALTY_QUOTIENT / 2 } // Expected FFG source if status.Flags.hasMarkers(prevEpochAttester | unslashed) { // Justification-participation reward deltas.Rewards[i] += baseReward * totalAttestingBalance / totalBalance // Inclusion speed bonus inclusionDelay := status.inclusionDistance() deltas.Rewards[i] += baseReward * Gwei(MIN_ATTESTATION_INCLUSION_DELAY) / Gwei(inclusionDelay) } else { //Justification-non-participation R-penalty deltas.Penalties[i] += baseReward } // Expected FFG target if status.Flags.hasMarkers(epochBoundaryAttester | unslashed) { // Boundary-attestation reward deltas.Rewards[i] += baseReward * epochBoundaryBalance / totalBalance } else { //Boundary-attestation-non-participation R-penalty deltas.Penalties[i] += inactivityPenalty } // Expected head if status.Flags.hasMarkers(matchingHeadAttester | unslashed) { // Canonical-participation reward deltas.Rewards[i] += baseReward * matchingHeadBalance / totalBalance } else { // Non-canonical-participation R-penalty deltas.Penalties[i] += baseReward } // Take away max rewards if we're not finalizing if epochsSinceFinality > 4 { deltas.Penalties[i] += baseReward * 4 } } } return deltas }
eth2/beacon/deltas_computation/deltas_justification.go
0.558568
0.428293
deltas_justification.go
starcoder
package proj import ( "fmt" "math" ) // EqdC is an Equidistant Conic projection. func EqdC(this *SR) (forward, inverse Transformer, err error) { // Standard Parallels cannot be equal and on opposite sides of the equator if math.Abs(this.Lat1+this.Lat2) < epsln { return nil, nil, fmt.Errorf("proj: Equidistant Conic parallels cannot be equal and on opposite sides of the equator but are %g and %g", this.Lat1, this.Lat2) } if math.IsNaN(this.Lat2) { this.Lat2 = this.Lat1 } temp := this.B / this.A this.Es = 1 - math.Pow(temp, 2) this.E = math.Sqrt(this.Es) e0 := e0fn(this.Es) e1 := e1fn(this.Es) e2 := e2fn(this.Es) e3 := e3fn(this.Es) sinphi := math.Sin(this.Lat1) cosphi := math.Cos(this.Lat1) ms1 := msfnz(this.E, sinphi, cosphi) ml1 := mlfn(e0, e1, e2, e3, this.Lat1) var ns float64 if math.Abs(this.Lat1-this.Lat2) < epsln { ns = sinphi } else { sinphi = math.Sin(this.Lat2) cosphi = math.Cos(this.Lat2) ms2 := msfnz(this.E, sinphi, cosphi) ml2 := mlfn(e0, e1, e2, e3, this.Lat2) ns = (ms1 - ms2) / (ml2 - ml1) } g := ml1 + ms1/ns ml0 := mlfn(e0, e1, e2, e3, this.Lat0) rh := this.A * (g - ml0) /* Equidistant Conic forward equations--mapping lat,long to x,y -----------------------------------------------------------*/ forward = func(lon, lat float64) (x, y float64, err error) { var rh1 float64 /* Forward equations -----------------*/ if this.sphere { rh1 = this.A * (g - lat) } else { var ml = mlfn(e0, e1, e2, e3, lat) rh1 = this.A * (g - ml) } var theta = ns * adjust_lon(lon-this.Long0) x = this.X0 + rh1*math.Sin(theta) y = this.Y0 + rh - rh1*math.Cos(theta) return x, y, nil } /* Inverse equations -----------------*/ inverse = func(x, y float64) (lon, lat float64, err error) { x -= this.X0 y = rh - y + this.Y0 var con, rh1 float64 if ns >= 0 { rh1 = math.Sqrt(x*x + y*y) con = 1 } else { rh1 = -math.Sqrt(x*x + y*y) con = -1 } var theta float64 if rh1 != 0 { theta = math.Atan2(con*x, con*y) } if this.sphere { lon = adjust_lon(this.Long0 + theta/ns) lat = adjust_lat(g - rh1/this.A) return } var ml = g - rh1/this.A lat, err = imlfn(ml, e0, e1, e2, e3) if err != nil { return math.NaN(), math.NaN(), err } lon = adjust_lon(this.Long0 + theta/ns) return } return } func init() { registerTrans(EqdC, "Equidistant_Conic", "eqdc") }
proj/eqdc.go
0.672117
0.468912
eqdc.go
starcoder
package decstree import ( "fmt" "strings" ) type ( // Question represent one question that can be answered by data // We answer question by looking Data and find it's key. // Question only can be answered by choosing the Answer that have // correct value Question struct { ID string `json:"i,omitempty"` Label string `json:"l"` Key string `json:"k"` Answers Answers `json:"a"` } // Answer are represent Answer that can be choosed when we answer // the Question. You can think that Question like multiple-choice question // and the answer are the one of the choice. // Answer can have Result, or Next Question. If the answer that we choose, // contains Next, then we can ask next Question. If it doesn't contain next, // we can mark Result as the final Answer, and return the Result Answer struct { ID string `json:"i,omitempty"` Label string `json:"l"` Value string `json:"v"` Next *Question `json:"n,omitempty"` Result string `json:"r,omitempty"` } // Answers are type Alias for []*Answer created so we can add function to it Answers []*Answer // Data are needed to answer the question. You can access the data by // using key that is in question. And match the value with value in Answer Data map[string]string // Traces are collection of ID that have been visit by Data and Answer. // It will contains ID of the first question until the last result // you can use package draw to see what question and answer that has been answerd // by data Traces []string ) // Answer is the fastest way to get the result, based on the data func (q *Question) Answer(data Data) (string, error) { val := data[q.Key] for _, a := range q.Answers { if a.Value != val { continue } if a.Next != nil { return a.Next.Answer(data) } return a.Result, nil } return "", fmt.Errorf("data '%s' in '%s' don't match with any '%s'", val, q.Key, q.Answers) } // AnswerWithTrace will answer all the questions until we gate result, and then also return the traces // that can be used in package draw func (q *Question) AnswerWithTrace(data Data) (ids Traces, answer string, err error) { val := data[q.Key] for _, a := range q.Answers { if a.Value != val { continue } if a.Next != nil { ids, answer, err = a.Next.AnswerWithTrace(data) ids = append(ids, a.ID, q.ID) return ids, answer, err } return []string{a.ID, q.ID, a.Result}, a.Result, nil } return []string{q.ID}, "", fmt.Errorf("data '%s' in '%s' cannot been answer with '%s'", val, q.Key, q.Answers) } // String implementation of stringer func (a Answers) String() string { var res []string for _, v := range a { if v != nil { res = append(res, v.Label) } } return strings.Join(res, ",") }
main.go
0.593727
0.478894
main.go
starcoder
package g4 import ( "github.com/go-gl/gl/v3.3-core/gl" "github.com/amortaza/go-g4/ace" ) type ColorRect struct { program *ace.Program vao uint32 vbo uint32 } func NewColorRect() *ColorRect { r := &ColorRect{} r.program = ace.NewProgram("github.com/amortaza/go-g4/shader/rgb.vertex.txt", "github.com/amortaza/go-g4/shader/rgb.fragment.txt") gl.GenVertexArrays(1, &r.vao) gl.GenBuffers(1, &r.vbo) return r } func (r *ColorRect) Draw( left, top, width, height int, leftTopColor []float32, rightTopColor []float32, rightBottomColor []float32, leftBottomColor []float32, projection *float32 ) { r.program.Activate() gl.UniformMatrix4fv(r.program.GetUniformLocation("project"), 1, false, projection) gl.BindVertexArray(r.vao) gl.BindBuffer(gl.ARRAY_BUFFER, r.vbo) right := left + width bottom := top + height vertices := []float32{ float32(left), float32(top), leftTopColor[0], leftTopColor[1], leftTopColor[2], leftTopColor[3], float32(right), float32(top), rightTopColor[0], rightTopColor[1], rightTopColor[2], rightTopColor[3], float32(right), float32(bottom), rightBottomColor[0], rightBottomColor[1], rightBottomColor[2], rightBottomColor[3], float32(left), float32(bottom), leftBottomColor[0], leftBottomColor[1], leftBottomColor[2], leftBottomColor[3] } colorRect_setVertexData(vertices) gl.DrawArrays(gl.TRIANGLE_FAN, 0, 4) gl.BindVertexArray(0) } func (r *ColorRect) DrawSolid( left, top, width, height int, red, green, blue float32, projection *float32 ) { r.program.Activate() gl.UniformMatrix4fv(r.program.GetUniformLocation("project"), 1, false, projection) gl.BindVertexArray(r.vao) gl.BindBuffer(gl.ARRAY_BUFFER, r.vbo) right := left + width bottom := top + height vertices := []float32{ float32(left), float32(top), red, green, blue, 1, float32(right), float32(top), red, green, blue, 1, float32(right), float32(bottom), red, green, blue, 1, float32(left), float32(bottom), red, green, blue, 1 } colorRect_setVertexData(vertices) gl.DrawArrays(gl.TRIANGLE_FAN, 0, 4) gl.BindVertexArray(0) } func (r *ColorRect) Free() { gl.DeleteVertexArrays(1, &r.vao) gl.DeleteBuffers(1, &r.vbo) r.program.Free() } func colorRect_setVertexData(data []float32) { // copy vertices data into VBO (it needs to be bound first) gl.BufferData(gl.ARRAY_BUFFER, len(data)*4, gl.Ptr(data), gl.STATIC_DRAW) // size of one whole vertex (sum of attrib sizes) var stride int32 = 2 /*posPartCount*/ *4 + 4 /*colorPartCount*/ *4 var offset int = 0 // position gl.VertexAttribPointer(0, 2 /*posPartCount*/, gl.FLOAT, false, stride, gl.PtrOffset(offset)) gl.EnableVertexAttribArray(0) offset += 2 /*posPartCount*/ * 4 // color gl.VertexAttribPointer(1, 4 /*colorPartCount*/, gl.FLOAT, false, stride, gl.PtrOffset(offset)) gl.EnableVertexAttribArray(1) }
ColorRect.go
0.683525
0.432842
ColorRect.go
starcoder
package cache import ( "mmapcache/byteio" ) const ( mmapDataHeadLen = 12 mmapDataHeadUsedPos = 4 mmapDataHeadTagPos = mmapDataHeadUsedPos + 4 mmapDataHeadKeyLenPos = mmapDataHeadTagPos + 2 mmapDataPos = mmapDataHeadLen ) // MMapData mmap数据块 // | ------------------------------------------- head ----------------------------------------| ---------- data ---------- | // | -- 4byte:data.size -- | -- 4byte:data.used -- | -- 2byte:datatag -- | -- 2byte:keylen -- | -- keydata -- | -- data -- | type MMapData struct { buf []byte data []byte keyLen int dataLen int val interface{} } // GetSize 返回Size func (m *MMapData) GetSize() uint32 { return byteio.BytesToUint32(m.buf) } // GetTag 返回Tag func (m *MMapData) GetTag() uint16 { return byteio.BytesToUint16(m.buf[mmapDataHeadTagPos:]) } // GetKey 返回Key func (m *MMapData) GetKey() []byte { return m.buf[mmapDataPos : mmapDataPos+m.keyLen] } // GetData 返回Data func (m *MMapData) GetData() []byte { return m.data[:m.dataLen] } // GetVal 返回Val func (m *MMapData) GetVal() interface{} { return m.val } // ReloadVal 通过GetData方法可获取之前val对象序列化后的数据 // 反序列化后可继续通过Val属性绑定文件缓存与内存对象之间的关系 func (m *MMapData) ReloadVal(val interface{}) { m.val = val } func reloadMMapData(buf []byte) *MMapData { mmapData := &MMapData{ buf: buf, } mmapData.keyLen = int(byteio.BytesToUint16(buf[mmapDataHeadKeyLenPos:])) mmapData.dataLen = int(byteio.BytesToUint32(buf[mmapDataHeadUsedPos:])) - mmapData.keyLen mmapData.data = mmapData.buf[mmapDataHeadLen+mmapData.keyLen:] return mmapData } func newMMapData(size uint32, tag uint16, buf, key, data []byte, val interface{}) *MMapData { used := len(key) + len(data) if (used + mmapDataHeadLen) > int(size) { return nil } mmapData := &MMapData{ buf: buf, data: buf[mmapDataHeadLen+len(key):], keyLen: len(key), dataLen: len(data), val: val, } byteio.Uint32ToBytes(size, mmapData.buf) byteio.Uint16ToBytes(tag, mmapData.buf[mmapDataHeadTagPos:]) byteio.Uint16ToBytes(uint16(len(key)), mmapData.buf[mmapDataHeadKeyLenPos:]) copy(mmapData.buf[mmapDataPos:], key) mmapData.writeData(data) return mmapData } func (m *MMapData) writeData(data []byte) { m.dataLen = len(data) byteio.Uint32ToBytes(uint32(m.keyLen+m.dataLen), m.buf[mmapDataHeadUsedPos:]) copy(m.data, data) } func (m *MMapData) getUsed() uint32 { return byteio.BytesToUint32(m.buf[mmapDataHeadUsedPos:]) } func (m *MMapData) getKeyUsed() uint32 { return uint32(byteio.BytesToUint16(m.buf[mmapDataHeadKeyLenPos:])) } func (m *MMapData) getDataUsed() uint32 { return byteio.BytesToUint32(m.buf[mmapDataHeadUsedPos:]) - m.getKeyUsed() } func (m *MMapData) getHead() []byte { return m.buf[:mmapDataPos] }
src/cache/mmapdata.go
0.516595
0.518973
mmapdata.go
starcoder
package model import ( "fmt" "sort" "strconv" mat "github.com/nlpodyssey/spago/pkg/mat32" ) // NameMap implements a bidirectional mapping between a name and an index type NameMap struct { NameToIndex map[string]int IndexToName map[int]string } func (f *NameMap) Set(name string, index int) { f.NameToIndex[name] = index f.IndexToName[index] = name } func (f *NameMap) ValueFor(name string) (int, bool) { value, ok := f.NameToIndex[name] if !ok { value = len(f.NameToIndex) f.NameToIndex[name] = value f.IndexToName[value] = name } return value, !ok } func (f *NameMap) Size() int { return len(f.IndexToName) } func (f *NameMap) ContainsName(name string) (int, bool) { index, ok := f.NameToIndex[name] return index, ok } func NewNameMap() *NameMap { return &NameMap{ NameToIndex: map[string]int{}, IndexToName: map[int]string{}, } } // ColumnMap is a bidirectional mapping between a column index and a dense matrix index type ColumnMap struct { ColumnToIndex map[int]int IndexToColumn map[int]int } func (f ColumnMap) Set(column int, index int) { f.ColumnToIndex[column] = index f.IndexToColumn[index] = column } func (f ColumnMap) Size() int { return len(f.ColumnToIndex) } func (f ColumnMap) GetColumn(column int) (int, bool) { index, ok := f.ColumnToIndex[column] return index, ok } func (f ColumnMap) Columns() []int { result := make([]int, 0, len(f.ColumnToIndex)) for i := range f.ColumnToIndex { result = append(result, i) } sort.Ints(result) return result } func NewColumnMap() *ColumnMap { return &ColumnMap{ ColumnToIndex: map[int]int{}, IndexToColumn: map[int]int{}, } } type CategoricalValue struct { // Column identifies the column corresponding to this value in the dataset Column int // Value is the plain value of this categorical value Value string } type CategoricalValuesMap struct { ValueToIndex map[CategoricalValue]int IndexToValue map[int]CategoricalValue } func (c *CategoricalValuesMap) ValueFor(value CategoricalValue) int { result, ok := c.ValueToIndex[value] if !ok { result = len(c.ValueToIndex) c.ValueToIndex[value] = result c.IndexToValue[result] = value } return result } func (c *CategoricalValuesMap) Size() int { return len(c.ValueToIndex) } type ColumnType int const ( Continuous ColumnType = iota Categorical ) type Column struct { Name string Type ColumnType // Average value for this column (for continuous values only) Average float64 // Standard deviation for this column (for continuous values only) StdDev float64 } type Metadata struct { Columns []*Column // ContinuousFeaturesMap maps a data row column index to a dense matrix column index ContinuousFeaturesMap *ColumnMap // CategoricalFeaturesMap maps a data row column index to the categorical features index CategoricalFeaturesMap *ColumnMap // CategoricalValuesMap maps a given categorical column to a map from values to indexes CategoricalValuesMap *CategoricalValuesMap // TargetColumn points to the column in the data row that contains the prediction target TargetColumn int // TargetMap contains a mapping of target category names to target category indexes TargetMap *NameMap } func NewMetadata() *Metadata { return &Metadata{ Columns: nil, ContinuousFeaturesMap: NewColumnMap(), CategoricalFeaturesMap: NewColumnMap(), CategoricalValuesMap: NewCategoricalValuesMap(), TargetMap: NewNameMap(), } } func NewCategoricalValuesMap() *CategoricalValuesMap { return &CategoricalValuesMap{ ValueToIndex: map[CategoricalValue]int{}, IndexToValue: map[int]CategoricalValue{}, } } func (d *Metadata) FeatureCount() int { return d.CategoricalFeaturesMap.Size() + d.ContinuousFeaturesMap.Size() } func (d *Metadata) ParseCategoricalTarget(value string) (mat.Float, error) { index, ok := d.TargetMap.ContainsName(value) if !ok { return 0, fmt.Errorf("unknown categorical target value %s", value) } return mat.Float(index), nil } // ParseOrAddCategoricalTarget always succeeds by returning the existing or new // categorical target value index func (d *Metadata) ParseOrAddCategoricalTarget(value string) (mat.Float, error) { target, _ := d.TargetMap.ValueFor(value) return mat.Float(target), nil } func (d *Metadata) ParseContinuousTarget(s string) (mat.Float, error) { v, err := strconv.ParseFloat(s, 32) if err != nil { return 0.0, err } return mat.Float(v), nil } func (d *Metadata) TargetType() ColumnType { return d.Columns[d.TargetColumn].Type }
pkg/model/metadata.go
0.795221
0.559711
metadata.go
starcoder
package main import ( "fmt" "github.com/keep94/gocombinatorics" ) const ( kMax = 1000000000 // operands must be less than this number ) const ( kNumExpressions = 200 ) // postfixEntry represents an entry in a postfix expression. type postfixEntry struct { value int64 // The value of the entry op byte // '+', '-', '*', '/', '^' 0 means the entry is a value } func (s postfixEntry) String() string { if s.op != 0 { return fmt.Sprintf("%c", s.op) } return fmt.Sprintf("%d", s.value) } // postfix represents a postfix expression. type postfix []postfixEntry // clear clears the postfix expression. func (p *postfix) clear() { *p = (*p)[:0] } // appendValue appends a value to this expression. func (p *postfix) appendValue(x int64) { *p = append(*p, postfixEntry{value: x}) } // appendOp appends an operation to this expression. func (p *postfix) appendOp(op byte) { *p = append(*p, postfixEntry{op: op}) } // copy returns a copy of this postfix expression. func (p postfix) copy() postfix { result := make(postfix, len(p)) copy(result, p) return result } // eval evaluates this postfix expression. scratch is used to perform the // calculation. Caller can declare a single []int64 slice and pass that same // slice to multiple eval() calls. eval returns the value of the postfix // expression and true or if the postfix expression can't be evaluated, it // returns 0 and false. Reasons that a postfix expression can't be evaluated // include division by zero, divisions that result in a non integer value etc. func (p postfix) eval(scratch *[]int64) (result int64, ok bool) { *scratch = (*scratch)[:0] for _, entry := range p { if entry.op == 0 { *scratch = append(*scratch, entry.value) } else { length := len(*scratch) second := (*scratch)[length-1] first := (*scratch)[length-2] *scratch = (*scratch)[:length-2] var answer int64 var valid bool if entry.op == '+' { answer, valid = add(first, second) } else if entry.op == '-' { answer, valid = sub(first, second) } else if entry.op == '*' { answer, valid = mul(first, second) } else if entry.op == '/' { answer, valid = div(first, second) } else if entry.op == '^' { answer, valid = pow(first, second) } else { panic("Unrecognized op code") } if !valid { return } *scratch = append(*scratch, answer) } } if len(*scratch) != 1 { panic("Malformed postfix expression") } return (*scratch)[0], true } func checkRange(first, second int64) bool { if first <= -kMax || first >= kMax { return false } if second <= -kMax || second >= kMax { return false } return true } func add(first, second int64) (result int64, ok bool) { if !checkRange(first, second) { return } return first + second, true } func sub(first, second int64) (result int64, ok bool) { if !checkRange(first, second) { return } return first - second, true } func mul(first, second int64) (result int64, ok bool) { if !checkRange(first, second) { return } return first * second, true } func div(first, second int64) (result int64, ok bool) { if !checkRange(first, second) { return } if second == 0 || first%second != 0 { return } return first / second, true } func pow(first, second int64) (result int64, ok bool) { if second < 0 || second > 30 { return } product := int64(1) var valid bool for i := int64(0); i < second; i++ { product, valid = mul(product, first) if !valid { return } } return product, true } // The generator type generates postfix expressions type generator struct { opsStream gocombinatorics.Stream positsStream gocombinatorics.Stream valuesStream gocombinatorics.Stream ops []int posits []int values []int actualOps []byte actualValues []int64 done bool } // newGenerator returns a new generator that yields all the possible postfix // expressions containing the given values and operations. Both values and // ops must have a length of at least 1. func newGenerator(values []int, ops []byte) *generator { if len(values) == 0 || len(ops) == 0 { panic("Length of both values and ops must be non-zero") } actualValues := make([]int64, len(values)) for i := range values { actualValues[i] = int64(values[i]) } actualOps := make([]byte, len(ops)) copy(actualOps, ops) result := &generator{ opsStream: gocombinatorics.Product(len(ops), len(values)-1), positsStream: gocombinatorics.OpsPosits(len(values) - 1), valuesStream: gocombinatorics.Permutations(len(values), len(values)), ops: make([]int, len(values)-1), posits: make([]int, len(values)-1), values: make([]int, len(values)), actualOps: actualOps, actualValues: actualValues} result.opsStream.Next(result.ops) result.positsStream.Next(result.posits) result.valuesStream.Next(result.values) return result } // Next stores the next postfix expression in p and returns true. If there // are no more postfix expressions, Next leaves p unchanged and returns false. // Caller must ensure that len(p) == 2*n - 1 where n is the length of the // values slice passed to newGenerator. func (g *generator) Next(p postfix) bool { if len(p) < 2*len(g.actualValues)-1 { panic("postfix slice passed to Next is too small") } if g.done { return false } g.populate(p) g.increment() return true } func (g *generator) increment() { if g.valuesStream.Next(g.values) { return } g.valuesStream.Reset() g.valuesStream.Next(g.values) if g.positsStream.Next(g.posits) { return } g.positsStream.Reset() g.positsStream.Next(g.posits) if g.opsStream.Next(g.ops) { return } g.done = true } func (g *generator) populate(p postfix) { p.clear() valueIdx := 0 positIdx := 0 for valueIdx < len(g.values) || positIdx < len(g.posits) { if positIdx == len(g.posits) || valueIdx <= g.posits[positIdx] { p.appendValue(g.actualValues[g.values[valueIdx]]) valueIdx++ } else { p.appendOp(g.actualOps[g.ops[positIdx]]) positIdx++ } } } func main() { // expressions[0] contains an expression that evaluates to 0. // expressions[1] contains an expression that evaluates to 1 // expressions[2] contains an expression that evaluates to 2 etc. // If expressions[n] is nil then there is no known expression that // evaluates to n. expressions := make([]postfix, kNumExpressions) // Our postfix expressions will have 5 values (1 to 5 inclusvalue) and // 4 operators p := make(postfix, 9) g := newGenerator([]int{1, 2, 3, 4, 5}, []byte{'+', '-', '*', '/', '^'}) // Evaluate each possible expression. // Store that expression in the expressions array var scratch []int64 for g.Next(p) { result, ok := p.eval(&scratch) if !ok || result < 0 || result >= int64(len(expressions)) { continue } if expressions[result] == nil { expressions[result] = p.copy() } } // Print the expression that evaluates to 0, 1, 2, 3, 4, ... for i := range expressions { fmt.Println(i, expressions[i]) } }
reach.go
0.668556
0.411879
reach.go
starcoder
package scaler import ( "strconv" "strings" "time" ) type Expression string func (e Expression) Match(t time.Time) bool { a := strings.Split(string(e), " ") if len(a) != 6 { return false } minute := pattern(a[0]) hour := pattern(a[1]) day := pattern(a[2]) month := pattern(a[3]) year := pattern(a[4]) weekday := pattern(a[5]) return minute.Match(t.Minute(), convert) && hour.Match(t.Hour(), convert) && day.Match(t.Day(), convert) && month.Match(int(t.Month()), convertMonth) && year.Match(t.Year(), convert) && weekday.Match(int(t.Weekday()), convertWeekday) } type pattern string type convertFunc func(s string) (int, error) func convert(s string) (int, error) { return strconv.Atoi(s) } var months = map[string]int{ "Jan": 1, "Feb": 2, "Mar": 3, "Apr": 4, "May": 5, "Jun": 6, "Jul": 7, "Aug": 8, "Sep": 9, "Oct": 10, "Nov": 11, "Dec": 12, } func convertMonth(s string) (int, error) { n, ok := months[s] if ok { return n, nil } return strconv.Atoi(s) } var weekdays = map[string]int{ "Sun": 0, "Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5, "Sat": 6, } func convertWeekday(s string) (int, error) { n, ok := weekdays[s] if ok { return n, nil } return strconv.Atoi(s) } func (p pattern) Match(n int, cf convertFunc) bool { if p == "*" { return true } a := strings.Split(string(p), ",") for _, b := range a { c := strings.Split(b, "-") if len(c) == 0 || len(c) >= 3 { continue } if len(c) == 2 { d, e := c[0], c[1] if len(d) >= 1 && len(e) >= 1 { f, err := cf(d) if err != nil { continue } g, err := cf(e) if err != nil { continue } if n >= f && n <= g { return true } continue } if len(d) >= 1 && len(e) == 0 { f, err := cf(d) if err != nil { continue } if n >= f { return true } continue } if len(d) == 0 && len(e) >= 1 { f, err := cf(e) if err != nil { return false } if n <= f { return true } continue } continue } d, err := cf(c[0]) if err != nil { continue } if n == d { return true } } return false }
internal/scaler/expression.go
0.592902
0.400046
expression.go
starcoder
package nanodate import ( "fmt" "log" "strconv" "errors" ) var DebugLevel int = 0 /// Definition of what a Date contains type Date struct { Milis uint16 `json:"milis"` Seconds uint8 `json:"seconds"` Minutes uint8 `json:"minutes"` Hour uint8 `json:"hour"` Day uint8 `json:"day"` Month uint8 `json:"month"` Year uint16 `json:"year"` } /// Returns a string formatted to match the given structure of a Date. /// If a date field contains a 0, the field will be omitted from the string result. /// Does not include Hours or Minutes. /// Returns either yyyymmdd or yyyy based on the date template. func MatchDateStringFormatToTemplate (dateTemplate Date) string { /// If the date template contains nothing. if dateTemplate.Year == 0 && dateTemplate.Month == 0 && dateTemplate.Day == 0 { return "" } year, month, day, _, _, _, _ := dateTemplate.ToString() /// If either month or day are 0, both will be omitted. if dateTemplate.Month == 0 || dateTemplate.Day == 0 { return year } else { return year + month + day } /// Return default if nothing else at this point. return "" } /// Takes two dates and returns a list of every date between. func MakeDateList (fromDate Date, toDate Date) []Date { var listDates []Date if DebugLevel == 1 { yr1, mo1, da1, _, _, _, _ := fromDate.ToString() yr2, mo2, da2, _, _, _, _ := toDate.ToString() fmt.Print("\n") log.Printf("Building date list between %s-%s-%s and %s-%s-%s", yr1, mo1, da1, yr2, mo2, da2) } var newDate Date = fromDate for { if newDate.IsGreaterThanOrEqualTo(&toDate) { listDates = append(listDates, newDate) break } else { listDates = append(listDates, newDate) } newDate.IterateDay() } if DebugLevel == 1 { log.Println("List size:", len(listDates), "\n") } return listDates } /// Outputs all data fields to the console. func (this *Date) Print() { fmt.Print(" Miliseconds:", this.Milis) fmt.Print(" Seconds:", this.Seconds) fmt.Print(" Minutes:", this.Minutes) fmt.Print(" Hour:", this.Hour) fmt.Print(" Day:", this.Day) fmt.Print(" Month:", this.Month) fmt.Println(" Year:", this.Year) } /// Returns several parts of a date formatted as strings. /// Single digit numbers are preceded with a `0`. func (this *Date) ToString() (string, string, string, string, string, string, string) { var yr string = strconv.Itoa(int(this.Year)) var mo string = "" var da string = "" var hr string = "" var mt string = "" var sc string = "" var ms string = "" if this.Month < 10 { mo = "0" + strconv.Itoa(int(this.Month)) } else { mo=strconv.Itoa(int(this.Month)) } if this.Day < 10 { da = "0" + strconv.Itoa(int(this.Day)) } else { da = strconv.Itoa(int(this.Day)) } if this.Hour < 10 { hr = "0" + strconv.Itoa(int(this.Hour)) } else { hr = strconv.Itoa(int(this.Hour)) } if this.Minutes < 10 { mt = "0" + strconv.Itoa(int(this.Minutes)) } else { mt = strconv.Itoa(int(this.Minutes)) } if this.Seconds < 10 { sc = "0" + strconv.Itoa(int(this.Seconds)) } else { sc = strconv.Itoa(int(this.Seconds)) } if this.Milis < 100 { ms = "0" + strconv.Itoa(int(this.Milis)) if this.Milis < 10 { ms = "00" + strconv.Itoa(int(this.Milis)) } } else { ms = strconv.Itoa(int(this.Milis)) } return yr, mo, da, hr, mt, sc, ms } /// Returns a string date based on the following formats /// 0: yyyymmdd /// 1: yyyy-mm-dd /// 2: yyyymmddHHmm /// 3: yyyy-mm-dd-HHmm /// 4: yyyy func (this *Date) ToStringWithFormat (formatType int) string { /// TODO: /// Needs to append a 0 if any of the months or days are single digit. /// Fix other cases with strconv.Atoi switch formatType { // case 0:{ // return string(d.Year) + string(d.Month) + string(d.Day) // } // case 1:{ // return strconv.Atoi(d.Year) + "-" +strconv.Atoi(d.Month) + "-" + strconv.Atoi(d.Day) // } // case 2:{ // return string(d.Year) + string(d.Month) + string(d.Day) + string(d.Hour) + string(d.Minutes) // } // case 3:{ // return string(d.Year) + "-" +string(d.Month) + "-" + string(d.Day) + "-" + string(d.Hour) + string(d.Minutes) // } // case 4:{ // return string(d.Year) // } default: { yr := strconv.Itoa((int(this.Year))) var mo string if this.Month >= 10 { mo = strconv.Itoa((int(this.Month))) } else { mo = "0" + strconv.Itoa((int(this.Month))) } var da string if this.Day >= 10 { da = strconv.Itoa((int(this.Day))) } else { da = "0" + strconv.Itoa((int(this.Day))) } return yr + "-" + mo + "-" + da } } } func (this *Date) ConvertFromDateStamp (dateStamp string) { /// WIP } /// Imports date from a string using the following formats: /// "yyyymmddHHmm+" Trunkcates any additional seconds. /// "yyyymmddHHmm" /// "yyyymmdd" /// All other string forms will be rejected. func (this *Date) ImportFromStringTypeA (str string) error { if DebugLevel >= 3 { log.Println("Parsing date", str) } /// Shared place holder for string to number converstion. var tempNumber int var err error if len(str) >= 12 { tempNumber, err = strconv.Atoi(str[0:4]) this.Year = uint16(tempNumber) if err != nil { return err } tempNumber, err = strconv.Atoi(str[4:6]) this.Month = uint8(tempNumber) if err != nil { return err } tempNumber, err = strconv.Atoi(str[6:8]) this.Day = uint8(tempNumber) if err != nil { return err } tempNumber, err = strconv.Atoi(str[8:10]) this.Hour = uint8(tempNumber) if err != nil { return err } tempNumber, err = strconv.Atoi(str[10:12]) this.Minutes = uint8(tempNumber) if err != nil { return err } } else if len(str) == 8 { tempNumber, err = strconv.Atoi(str[0:4]) this.Year = uint16(tempNumber) if err != nil { return err } tempNumber, err = strconv.Atoi(str[4:6]) this.Month = uint8(tempNumber) if err != nil { return err } tempNumber, err = strconv.Atoi(str[6:8]) this.Day = uint8(tempNumber) if err != nil { return err } } else { return errors.New("String to date formatting error.") } return nil } /// Returns true if this date is between two other given dates func (this *Date) IsDateInRange (fromDate *Date, toDate *Date) bool { /// Check if any dates are valid. if fromDate == nil || toDate == nil { return true } /// Check if the date range should be ignored. if fromDate.IsValidAsEmpty() && toDate.IsValidAsEmpty() { return true } /// Return false if any field from any date contains a 0 month or a 0 day. if !this.IsValid() || !fromDate.IsValid() || !toDate.IsValid() { return false } var yr string var mo string var da string if DebugLevel == 1 { fmt.Printf("\n\n") log.Println("Checking date range.") log.Println("This date:") this.Print() fmt.Printf("\n") log.Println("From date:") fromDate.Print() fmt.Printf("\n") log.Println("To date:") toDate.Print() fmt.Printf("\n") } yr, mo, da, _, _, _, _ = this.ToString() nThisDate, _ := strconv.Atoi(yr + mo + da) yr, mo, da, _, _, _, _ = fromDate.ToString() nFromDate, _ := strconv.Atoi(yr + mo + da) yr, mo, da, _, _, _, _ = toDate.ToString() nToDate, _ := strconv.Atoi(yr + mo + da) if nThisDate >= nFromDate && nThisDate <= nToDate { if DebugLevel == 1 { log.Println("Date is in range.") fmt.Printf("\n") } return true } else { if DebugLevel == 1 { log.Println("Date is NOT in range.") fmt.Printf("\n") } return false } } func (this *Date) DoesDateMatch (date Date) bool { if (date == Date{}) { return true } if date.Year != 0 || date.Year != 0 { if this.Year != date.Year { return false } } if date.Month != 0 || date.Month != 0 { if this.Month != date.Month { return false } } if date.Day != 0 || date.Day != 0 { if this.Day != date.Day { return false } } if date.Hour != 0 || date.Hour != 0 { if this.Hour != date.Hour { return false } } if date.Minutes != 0 || date.Minutes != 0 { if this.Minutes != date.Minutes { return false } } return true } /// Checks if this date contains a 0 for month or day func (this *Date) IsValid () bool { if this.Year == 0 || this.Month == 0 || this.Day == 0 { return false } return true } /// Checks if this date contains a 0 for all it's fields indicating /// that this date as a property is to be considered empty and to be ignored. func (this *Date) IsValidAsEmpty () bool { if this.Year == 0 && this.Month == 0 && this.Day == 0 && this.Hour == 0 && this.Minutes == 0 { return true } return false } /// Iterates the current day of this date by 1. func (this *Date) IterateDay () { this.Day += 1 if (this.Month == 1 || this.Month == 3 || this.Month == 5 || this.Month == 7 || this.Month == 8 || this.Month == 10 || this.Month == 12) && this.Day > 31 { this.Day = 1 this.Month += 1 } if (this.Month == 4 || this.Month == 6 || this.Month == 9 || this.Month == 11) && this.Day > 30 { this.Day = 1 this.Month += 1 } if this.Month == 2 && this.Day > 28 { this.Day = 1 this.Month += 1 } if this.Month > 12 { this.Month = 1 this.Year += 1 } } /// Inequality check for < func (this *Date) IsLessThan (date *Date) bool { if DebugLevel == 1 { fmt.Printf("Evaluating %d-%d-%d is less than %d-%d-%d", this.Year, this.Month, this.Day, date.Year, date.Month, date.Day) } if this.Year == date.Year && this.Month == date.Month && this.Day >= date.Day { return false } if this.Year == date.Year && this.Month > date.Month { return false } if this.Year > date.Year { return false } return true } /// Inequality check for <= func (this *Date) IsLessThanOrEqualTo (date *Date) bool { if DebugLevel == 1 { fmt.Printf("Evaluating %d-%d-%d is less than or equal to %d-%d-%d", this.Year, this.Month, this.Day, date.Year, date.Month, date.Day) } if this.Year == date.Year && this.Month == date.Month && this.Day > date.Day { return false } if this.Year == date.Year && this.Month > date.Month { return false } if this.Year > date.Year { return false } return true } /// Inequality check for > func (this *Date) IsGreaterThan (date *Date) bool { if DebugLevel == 1 { fmt.Printf("Evaluating %d-%d-%d is greater than %d-%d-%d", this.Year, this.Month, this.Day, date.Year, date.Month, date.Day) } if this.Year == date.Year && this.Month == date.Month && this.Day <= date.Day { return false } if this.Year == date.Year && this.Month < date.Month { return false } if this.Year < date.Year { return false } return true } /// Inequality check for >= func (this *Date) IsGreaterThanOrEqualTo (date *Date) bool { if DebugLevel == 1 { log.Printf("Evaluating %d-%d-%d is greater than or equal to %d-%d-%d", this.Year, this.Month, this.Day, date.Year, date.Month, date.Day) } if this.Year == date.Year && this.Month == date.Month && this.Day < date.Day { if DebugLevel == 1 { log.Printf("Date is NOT greater than or equal - step 1") } return false } if this.Year == date.Year && this.Month < date.Month { if DebugLevel == 1 { log.Printf("Date is NOT greater than or equal - step 2") } return false } if this.Year < date.Year { if DebugLevel == 1 { log.Printf("Date is NOT greater than or equal - step 3") } return false } if DebugLevel == 1 { log.Printf("Date is greater and/or equal") } return true }
nanodate.go
0.757256
0.410638
nanodate.go
starcoder
package kurobako import ( "encoding/json" "fmt" ) // Capabilities of a solver. type Capabilities int64 const ( // UniformContinuous indicates that the solver can handle numerical parameters that have uniform continuous range. UniformContinuous Capabilities = 1 << iota // UniformDiscrete indicates that the solver can handle numerical parameters that have uniform discrete range. UniformDiscrete // LogUniformContinuous indicates that the solver can handle numerical parameters that have log-uniform continuous range. LogUniformContinuous // LogUniformDiscrete indicates that the solver can handle numerical parameters that have log-uniform discrete range. LogUniformDiscrete // Categorical indicates that the solver can handle categorical parameters. Categorical // Conditional indicates that the solver can handle conditional parameters. Conditional // MultiObjective indicates that the solver supports multi-objective optimization. MultiObjective // Concurrent indicates that the solver supports concurrent invocations of the ask method. Concurrent // AllCapabilities represents all of the capabilities. AllCapabilities Capabilities = UniformContinuous | UniformDiscrete | LogUniformContinuous | LogUniformDiscrete | Categorical | Conditional | MultiObjective | Concurrent ) // MarshalJSON encodes a Capabilities value to JSON bytes. func (r Capabilities) MarshalJSON() ([]byte, error) { var xs []string if (r & UniformContinuous) != 0 { xs = append(xs, "UNIFORM_CONTINUOUS") } if (r & UniformDiscrete) != 0 { xs = append(xs, "UNIFORM_DISCRETE") } if (r & LogUniformContinuous) != 0 { xs = append(xs, "LOG_UNIFORM_CONTINUOUS") } if (r & LogUniformDiscrete) != 0 { xs = append(xs, "LOG_UNIFORM_DISCRETE") } if (r & Categorical) != 0 { xs = append(xs, "CATEGORICAL") } if (r & Conditional) != 0 { xs = append(xs, "CONDITIONAL") } if (r & MultiObjective) != 0 { xs = append(xs, "MULTI_OBJECTIVE") } if (r & Concurrent) != 0 { xs = append(xs, "CONCURRENT") } return json.Marshal(xs) } // UnmarshalJSON decodes a Capabilities value from JSON bytes. func (r *Capabilities) UnmarshalJSON(data []byte) error { var xs []string if err := json.Unmarshal(data, &xs); err != nil { return err } *r = 0 for _, s := range xs { switch s { case "UNIFORM_CONTINUOUS": *r |= UniformContinuous case "UNIFORM_DISCRETE": *r |= UniformDiscrete case "LOG_UNIFORM_CONTINUOUS": *r |= LogUniformContinuous case "LOG_UNIFORM_DISCRETE": *r |= LogUniformDiscrete case "CATEGORICAL": *r |= Categorical case "CONDITIONAL": *r |= Conditional case "MULTI_OBJECTIVE": *r |= MultiObjective case "CONCURRENT": *r |= Concurrent default: return fmt.Errorf("unknown `Capability`: %s", s) } } return nil }
capability.go
0.752195
0.40342
capability.go
starcoder
package edlib import ( "errors" "github.com/hbollon/go-edlib/internal/utils" ) // LCS takes two strings and compute their LCS(Longuest Common Subsequence) func LCS(str1, str2 string) int { // Convert strings to rune array to handle no-ASCII characters runeStr1 := []rune(str1) runeStr2 := []rune(str2) if len(runeStr1) == 0 || len(runeStr2) == 0 { return 0 } else if utils.Equal(runeStr1, runeStr2) { return len(runeStr1) } lcsMatrix := lcsProcess(runeStr1, runeStr2) return lcsMatrix[len(runeStr1)][len(runeStr2)] } // Return computed lcs matrix func lcsProcess(runeStr1, runeStr2 []rune) [][]int { // 2D Array that will contain str1 and str2 LCS lcsMatrix := make([][]int, len(runeStr1)+1) for i := 0; i <= len(runeStr1); i++ { lcsMatrix[i] = make([]int, len(runeStr2)+1) for j := 0; j <= len(runeStr2); j++ { lcsMatrix[i][j] = 0 } } for i := 1; i <= len(runeStr1); i++ { for j := 1; j <= len(runeStr2); j++ { if runeStr1[i-1] == runeStr2[j-1] { lcsMatrix[i][j] = lcsMatrix[i-1][j-1] + 1 } else { lcsMatrix[i][j] = utils.Max(lcsMatrix[i][j-1], lcsMatrix[i-1][j]) } } } return lcsMatrix } // LCSBacktrack returns all choices taken during LCS process func LCSBacktrack(str1, str2 string) (string, error) { runeStr1 := []rune(str1) runeStr2 := []rune(str2) if len(runeStr1) == 0 || len(runeStr2) == 0 { return "", errors.New("Can't process and backtrack any LCS with empty string") } else if utils.Equal(runeStr1, runeStr2) { return str1, nil } return processLCSBacktrack(str1, str2, lcsProcess(runeStr1, runeStr2), len(runeStr1), len(runeStr2)), nil } func processLCSBacktrack(str1, str2 string, lcsMatrix [][]int, m, n int) string { // Convert strings to rune array to handle no-ASCII characters runeStr1 := []rune(str1) runeStr2 := []rune(str2) if m == 0 || n == 0 { return "" } else if runeStr1[m-1] == runeStr2[n-1] { return processLCSBacktrack(str1, str2, lcsMatrix, m-1, n-1) + string(runeStr1[m-1]) } else if lcsMatrix[m][n-1] > lcsMatrix[m-1][n] { return processLCSBacktrack(str1, str2, lcsMatrix, m, n-1) } return processLCSBacktrack(str1, str2, lcsMatrix, m-1, n) } // LCSBacktrackAll returns an array containing all common substrings between str1 and str2 func LCSBacktrackAll(str1, str2 string) ([]string, error) { runeStr1 := []rune(str1) runeStr2 := []rune(str2) if len(runeStr1) == 0 || len(runeStr2) == 0 { return nil, errors.New("Can't process and backtrack any LCS with empty string") } else if utils.Equal(runeStr1, runeStr2) { return []string{str1}, nil } return processLCSBacktrackAll(str1, str2, lcsProcess(runeStr1, runeStr2), len(runeStr1), len(runeStr2)).ToArray(), nil } func processLCSBacktrackAll(str1, str2 string, lcsMatrix [][]int, m, n int) utils.StringHashMap { // Convert strings to rune array to handle no-ASCII characters runeStr1 := []rune(str1) runeStr2 := []rune(str2) // Map containing all commons substrings (Hash set builded from map) substrings := make(utils.StringHashMap) if m == 0 || n == 0 { substrings[""] = struct{}{} } else if runeStr1[m-1] == runeStr2[n-1] { for key := range processLCSBacktrackAll(str1, str2, lcsMatrix, m-1, n-1) { substrings[key+string(runeStr1[m-1])] = struct{}{} } } else { if lcsMatrix[m-1][n] >= lcsMatrix[m][n-1] { substrings.AddAll(processLCSBacktrackAll(str1, str2, lcsMatrix, m-1, n)) } if lcsMatrix[m][n-1] >= lcsMatrix[m-1][n] { substrings.AddAll(processLCSBacktrackAll(str1, str2, lcsMatrix, m, n-1)) } } return substrings } // LCSDiff will backtrack through the lcs matrix and return the diff between the two sequences func LCSDiff(str1, str2 string) ([]string, error) { runeStr1 := []rune(str1) runeStr2 := []rune(str2) if len(runeStr1) == 0 || len(runeStr2) == 0 { return nil, errors.New("Can't process LCS diff with empty string") } else if utils.Equal(runeStr1, runeStr2) { return []string{str1}, nil } diff := processLCSDiff(str1, str2, lcsProcess(runeStr1, runeStr2), len(runeStr1), len(runeStr2)) return diff, nil } func processLCSDiff(str1 string, str2 string, lcsMatrix [][]int, m, n int) []string { // Convert strings to rune array to handle no-ASCII characters runeStr1 := []rune(str1) runeStr2 := []rune(str2) diff := make([]string, 2) if m > 0 && n > 0 && runeStr1[m-1] == runeStr2[n-1] { diff = processLCSDiff(str1, str2, lcsMatrix, m-1, n-1) diff[0] = diff[0] + " " + string(runeStr1[m-1]) diff[1] = diff[1] + " " return diff } else if n > 0 && (m == 0 || lcsMatrix[m][n-1] > lcsMatrix[m-1][n]) { diff = processLCSDiff(str1, str2, lcsMatrix, m, n-1) diff[0] = diff[0] + " " + string(runeStr2[n-1]) diff[1] = diff[1] + " +" return diff } else if m > 0 && (n == 0 || lcsMatrix[m][n-1] <= lcsMatrix[m-1][n]) { diff = processLCSDiff(str1, str2, lcsMatrix, m-1, n) diff[0] = diff[0] + " " + string(runeStr1[m-1]) diff[1] = diff[1] + " -" return diff } return diff } // LCSEditDistance determines the edit distance between two strings using LCS function // (allow only insert and delete operations) func LCSEditDistance(str1, str2 string) int { if len(str1) == 0 { return len(str2) } else if len(str2) == 0 { return len(str1) } else if str1 == str2 { return 0 } lcs := LCS(str1, str2) return (len([]rune(str1)) - lcs) + (len([]rune(str2)) - lcs) }
vendor/github.com/hbollon/go-edlib/lcs.go
0.602763
0.414366
lcs.go
starcoder
package gfmatrix import ( "fmt" "github.com/OpenWhiteBox/primitives/number" ) // Row is a row / vector of elements from GF(2^8). type Row []number.ByteFieldElem // NewRow returns an empty n-component row. func NewRow(n int) Row { return Row(make([]number.ByteFieldElem, n)) } // LessThan returns true if row i is "less than" row j. If you use sort a permutation matrix according to LessThan, // you'll always get the identity matrix. func LessThan(i, j Row) bool { if i.Size() != j.Size() { panic("Can't compare rows that are different sizes!") } for k, _ := range i { if i[k] != 0x00 || j[k] != 0x00 { if j[k] == 0x00 { return true } else { return false } } } return false } // Add adds two vectors from GF(2^8)^n. func (e Row) Add(f Row) Row { if e.Size() != f.Size() { panic("Can't add rows that are different sizes!") } out := e.Dup() for i, f_i := range f { out[i] = out[i].Add(f_i) } return out } // ScalarMul multiplies a row by a scalar. func (e Row) ScalarMul(f number.ByteFieldElem) Row { out := e.Dup() for i, _ := range out { out[i] = out[i].Mul(f) } return out } // DotProduct computes the dot product of two vectors. func (e Row) DotProduct(f Row) number.ByteFieldElem { if e.Size() != f.Size() { panic("Can't compute dot product of two vectors of different sizes!") } res := number.ByteFieldElem(0x00) for i, _ := range e { res = res.Add(e[i].Mul(f[i])) } return res } // IsPermutation returns true if the row is a permutation of the first len(e) elements of GF(2^8) and false otherwise. func (e Row) IsPermutation() bool { sums := [256]int{} for _, e_i := range e { sums[e_i]++ } for _, x := range sums[0:len(e)] { if x != 1 { return false } } return true } // Height returns the position of the first non-zero entry in the row, or -1 if the row is zero. func (e Row) Height() int { for i, e_i := range e { if !e_i.IsZero() { return i } } return -1 } // Equals returns true if two rows are equal and false otherwise. func (e Row) Equals(f Row) bool { if e.Size() != f.Size() { panic("Can't compare rows that are different sizes!") } for i, _ := range e { if e[i] != f[i] { return false } } return true } // IsZero returns whether or not the row is identically zero. func (e Row) IsZero() bool { for _, e_i := range e { if !e_i.IsZero() { return false } } return true } // Size returns the dimension of the vector. func (e Row) Size() int { return len(e) } // Dup returns a duplicate of this row. func (e Row) Dup() Row { out := NewRow(e.Size()) copy(out, e) return out } func (e Row) String() string { out := []rune{} out = append(out, []rune(fmt.Sprintf("%2.2x", []number.ByteFieldElem(e)))...) out = out[1 : len(out)-1] return string(out) } // OctaveString converts the row into a string that can be imported into Octave. func (e Row) OctaveString() string { out := []rune{} for _, elem := range e { temp := fmt.Sprintf("%3.3v ", elem) out = append(out, []rune(temp)...) } return string(append(out, '\n')) }
gfmatrix/row.go
0.841956
0.434641
row.go
starcoder
package core import ( "image" "math" ) var NoDirection = Vector{0, 0, 0} type Tracer interface { Trace(x, y float64, ray Vector) (bool, float64, Vector, Color) TraceDeep(x, y float64, ray Vector) (bool, TraceIntervals) GetBounds() Bounds Pruned(rp RenderingParameters) Tracer // okay to return nil or self } func DeepifyTrace(t Tracer, x, y float64, ray Vector) (bool, TraceIntervals) { ok, z, dir, col := t.Trace(x, y, ray) inter := TraceIntervals{TraceInterval{ Start: TraceResult{z, dir, col}, End: TraceResult{math.Inf(1), dir, col}, }} return ok, inter } func UnDeepifyTrace(t Tracer, x, y float64, ray Vector) (bool, float64, Vector, Color) { ok, r := t.TraceDeep(x, y, ray) if ok { first := r[0].Start return true, first.Z, first.Direction, first.Color } return false, 0, NoDirection, Color{} } func SimplyPruned(t Tracer, rp RenderingParameters) Tracer { if rp.Contains(t.GetBounds()) { return t } return nil } func DrawTracerPartial(t Tracer, wv WorldView, img *image.RGBA, yCallback func(int), bounds image.Rectangle, c chan bool) { r := bounds.Intersect(t.GetBounds().ToRect()) rp := RenderingParameters{ 1, float64(r.Min.X - 1), float64(r.Max.X + 1), float64(r.Min.Y - 1), float64(r.Max.Y + 1), } pruned := t.Pruned(rp) if pruned != nil { for y := r.Min.Y; y <= r.Max.Y; y++ { for x := r.Min.X; x <= r.Max.X; x++ { fx, fy := float64(x), float64(y) any, _, _, col := pruned.Trace(fx, fy, wv.Ray(fx, fy)) if any { img.SetRGBA(x, y, col.ToRGBA()) } } if yCallback != nil { yCallback(y) } } } if c != nil { c <- true } } func DrawTracer(t Tracer, wv WorldView, img *image.RGBA, yCallback func(int)) { DrawTracerPartial(t, wv, img, yCallback, img.Bounds(), nil) } func DrawTracerParallel(t Tracer, wv WorldView, img *image.RGBA, yCallback func(int), partsRoot int) { full := img.Bounds() c := make(chan bool) parts := partsRoot * partsRoot partsLeft := parts for x := 0; x < partsRoot; x++ { for y := 0; y < partsRoot; y++ { r := image.Rect(full.Dx()*x/partsRoot, full.Dy()*y/partsRoot, full.Dx()*(x+1)/partsRoot-1, full.Dy()*(y+1)/partsRoot-1) go DrawTracerPartial(t, wv, img, nil, r, c) } } for partsLeft > 0 { <-c partsLeft-- if yCallback != nil { yCallback(full.Dy() * (parts - partsLeft) / parts) } } }
unicornify/core/tracer.go
0.692018
0.480844
tracer.go
starcoder
package torch // #include "gotorch.h" import "C" import ( "runtime" "unsafe" "github.com/pkg/errors" ) type Tensor struct { ptr C.AtTensor data []float32 } func TensorFromScalar(f float32) *Tensor { t, err := TensorFromBlob([]float32{f}, nil) if err != nil { panic(err) } return t } func TensorFromBlob(data []float32, sizes []int64) (*Tensor, error) { if totalSize(sizes) != len(data) { return nil, errors.Errorf("input data doesn't match size") } var startPtr *C.int64_t if len(sizes) > 0 { startPtr = (*C.int64_t)(&sizes[0]) } t := tensorFromPtr(C.TorchTensorFromBlob( unsafe.Pointer(&data[0]), startPtr, C.int(len(sizes)), )) // we still own the data so we have to hold on to it t.data = data return t, nil } func tensorFromPtr(ptr C.AtTensor) *Tensor { t := &Tensor{ ptr: ptr, } runtime.SetFinalizer(t, func(t *Tensor) { C.TorchTensorDelete(t.ptr) t.ptr = nil t.data = nil }) return t } func (t *Tensor) Dim() int { return int(C.TorchTensorDim(t.ptr)) } func (t *Tensor) Sizes() []int64 { if t.Dim() == 0 { return nil } sizes := make([]int64, t.Dim()) C.TorchTensorSizes(t.ptr, (*C.int64_t)(&sizes[0])) return sizes } func totalSize(sizes []int64) int { length := 1 for _, size := range sizes { length *= int(size) } return length } func (t *Tensor) Blob() []float32 { data_ptr := C.TorchTensorData(t.ptr) length := totalSize(t.Sizes()) data := (*[1 << 28]C.float)(unsafe.Pointer(data_ptr))[:length:length] out := make([]float32, length) for i, v := range data { out[i] = float32(v) } return out } func (t *Tensor) Backward() { C.TorchTensorBackward(t.ptr) } func (t *Tensor) Grad() *Tensor { return tensorFromPtr(C.TorchTensorGrad(t.ptr)) } func (t *Tensor) RequiresGrad() bool { return bool(C.TorchTensorRequiresGrad(t.ptr)) } func (t *Tensor) SetRequiresGrad(requiresGrad bool) { C.TorchTensorSetRequiresGrad(t.ptr, C.bool(requiresGrad)) } func RandN(sizes ...int64) *Tensor { return tensorFromPtr(C.TorchRandN( (*C.int64_t)(&sizes[0]), C.int(len(sizes)), )) } func (t *Tensor) Dot(b *Tensor) *Tensor { return tensorFromPtr(C.TorchDot(t.ptr, b.ptr)) } func (t *Tensor) Add(b *Tensor) *Tensor { return tensorFromPtr(C.TorchAdd(t.ptr, b.ptr)) } func (t *Tensor) Sub(b *Tensor) *Tensor { return tensorFromPtr(C.TorchSub(t.ptr, b.ptr)) } func (t *Tensor) Div(b *Tensor) *Tensor { return tensorFromPtr(C.TorchDiv(t.ptr, b.ptr)) } func (t *Tensor) Eq(b *Tensor) *Tensor { return tensorFromPtr(C.TorchEq(t.ptr, b.ptr)) } func NLLLoss(a, b *Tensor) *Tensor { return tensorFromPtr(C.TorchNLLLoss(a.ptr, b.ptr)) } func L1Loss(a, b *Tensor) *Tensor { return tensorFromPtr(C.TorchL1Loss(a.ptr, b.ptr)) } func MSELoss(a, b *Tensor) *Tensor { return tensorFromPtr(C.TorchMSELoss(a.ptr, b.ptr)) } func Stack(dim int64, tensors ...*Tensor) *Tensor { tptrs := tensorToTensorPtrs(tensors) return tensorFromPtr(C.TorchStack( (*C.AtTensor)(unsafe.Pointer(&tptrs[0])), C.int(len(tptrs)), C.int64_t(dim), )) } func (t *Tensor) Reshape(sizes ...int64) *Tensor { return tensorFromPtr(C.TorchReshape( t.ptr, (*C.int64_t)(&sizes[0]), C.int(len(sizes)), )) }
tensor.go
0.601711
0.495545
tensor.go
starcoder
package graphs import ( "errors" "fmt" ) // UnDirectedGraph defines a undirected graph type UnDirectedGraph struct { vertexCount int edgeCount int adjacentVertices [][]int visited []bool pathTo []int distanceTo []int connectedComponent [][]int } // NewUnDirectedGraph initalises a new undirected graph with vertexCount vertices. func NewUnDirectedGraph(vertexCount int) *UnDirectedGraph { return &UnDirectedGraph{ vertexCount, 0, make([][]int, vertexCount), nil, nil, nil, nil, } } func (u *UnDirectedGraph) isVertexValid(vertex int) bool { return vertex >= 0 && vertex < u.vertexCount } // GetVertexCount gets vertex count func (u *UnDirectedGraph) GetVertexCount() int { return u.vertexCount } // GetEdgeCount gets the edge count func (u *UnDirectedGraph) GetEdgeCount() int { return u.edgeCount } // AddEdge adds an edge to the graph func (u *UnDirectedGraph) AddEdge(vertex1, vertex2 int) error { if u.isVertexValid(vertex1) && u.isVertexValid(vertex2) { u.adjacentVertices[vertex1] = append(u.adjacentVertices[vertex1], vertex2) u.adjacentVertices[vertex2] = append(u.adjacentVertices[vertex2], vertex1) u.edgeCount++ return nil } return errors.New("vertex not found") } // GetAdjacentVertices gets all adjacent vertices for a given vertex func (u *UnDirectedGraph) GetAdjacentVertices(vertex int) ([]int, error) { if u.isVertexValid(vertex) { return u.adjacentVertices[vertex], nil } return nil, errors.New("vertex not found") } // GetVertexDegree gets the degree of a given vertex func (u *UnDirectedGraph) GetVertexDegree(vertex int) (int, error) { if u.isVertexValid(vertex) { return len(u.adjacentVertices[vertex]), nil } return 0, errors.New("vertex not found") } // Print prints the graph. func (u *UnDirectedGraph) Print() string { res := "" res += fmt.Sprintf("Vertex Count: %d, Edge Count: %d\n", u.vertexCount, u.edgeCount) for vertex, adjacentVertices := range u.adjacentVertices { res += fmt.Sprintf("Vertex %d: %v\n", vertex, adjacentVertices) } return res } func (u *UnDirectedGraph) dfsRecursively(startingVertex int, visited *[]bool) (vertices []int) { vertices = append(vertices, startingVertex) (*visited)[startingVertex] = true adjs, _ := u.GetAdjacentVertices(startingVertex) for _, v := range adjs { if !(*visited)[v] { vertices = append(vertices, u.dfsRecursively(v, visited)...) u.pathTo[v] = startingVertex } } return } // DFSRecursively does a dfs search using rescursive method func (u *UnDirectedGraph) DFSRecursively(startingVertex int) (vertices []int, err error) { if !u.isVertexValid(startingVertex) { return nil, errors.New("vertex not found") } u.visited = make([]bool, u.vertexCount) u.pathTo = make([]int, u.vertexCount) return u.dfsRecursively(startingVertex, &u.visited), nil } // DFS does a depth first search func (u *UnDirectedGraph) DFS(startingVertex int) (vertices []int, err error) { if !u.isVertexValid(startingVertex) { return nil, errors.New("vertex not found") } u.visited = make([]bool, u.vertexCount) u.pathTo = make([]int, u.vertexCount) stack := []int{startingVertex} for len(stack) != 0 { // pop stack vertex := stack[len(stack)-1] stack = stack[:len(stack)-1] // only if this vertex has not been visited, we mark it as visited and add into result. if !u.visited[vertex] { vertices = append(vertices, vertex) u.visited[vertex] = true } // get all its adjacent vertices. adjs, _ := u.GetAdjacentVertices(vertex) for i := len(adjs) - 1; i >= 0; i-- { // only add to stack if it's not visited yet. if !u.visited[adjs[i]] { stack = append(stack, adjs[i]) u.pathTo[adjs[i]] = vertex } } } return } // BFS does a breadth first search starting from startingVertex in graph func (u *UnDirectedGraph) BFS(startingVertex int) (vertices []int, err error) { if !u.isVertexValid(startingVertex) { return nil, errors.New("vertex not found") } u.visited = make([]bool, u.vertexCount) u.pathTo = make([]int, u.vertexCount) u.distanceTo = make([]int, u.vertexCount) queue := []int{startingVertex} u.visited[startingVertex] = true for len(queue) != 0 { // dequeue vertex := queue[0] queue = queue[1:] vertices = append(vertices, vertex) // get all its adjacent vertices. adjs, _ := u.GetAdjacentVertices(vertex) for i := 0; i < len(adjs); i++ { if !u.visited[adjs[i]] { queue = append(queue, adjs[i]) u.visited[adjs[i]] = true u.pathTo[adjs[i]] = vertex u.distanceTo[adjs[i]] = u.distanceTo[vertex] + 1 } } } return } // GetDFSPath gets the path from startingVertex to endingVertex using DFS func (u *UnDirectedGraph) GetDFSPath(startingVertex int, endingVertex int) (path []int, err error) { if !u.isVertexValid(startingVertex) || !u.isVertexValid(endingVertex) { return nil, errors.New("vertex not found") } u.pathTo = make([]int, u.vertexCount) u.visited = make([]bool, u.vertexCount) u.DFS(startingVertex) if !u.visited[endingVertex] { return nil, errors.New("path not found") } vertex := endingVertex for vertex != startingVertex { path = append([]int{vertex}, path...) vertex = u.pathTo[vertex] } path = append([]int{vertex}, path...) return } // GetBFSPath gets the BFS path from startingVertex to endingVertex. // Using BFS, the path is also the mimimum path (mimimum number of edges). func (u *UnDirectedGraph) GetBFSPath(startingVertex int, endingVertex int) (path []int, err error) { if !u.isVertexValid(startingVertex) || !u.isVertexValid(endingVertex) { return nil, errors.New("vertex not found") } u.pathTo = make([]int, u.vertexCount) u.distanceTo = make([]int, u.vertexCount) u.visited = make([]bool, u.vertexCount) u.BFS(startingVertex) if !u.visited[endingVertex] { return nil, errors.New("path not found") } vertex := endingVertex for u.distanceTo[vertex] != 0 { path = append([]int{vertex}, path...) vertex = u.pathTo[vertex] } path = append([]int{vertex}, path...) return } // GetConnectedComponents gets all the connected component of a graph func (u *UnDirectedGraph) GetConnectedComponents() (connectedCompoent [][]int) { u.visited = make([]bool, u.vertexCount) u.pathTo = make([]int, u.vertexCount) u.connectedComponent = make([][]int, 0) for i := 0; i < u.vertexCount; i++ { if !u.visited[i] { vertices := u.dfsRecursively(i, &u.visited) u.connectedComponent = append(u.connectedComponent, vertices) } } return u.connectedComponent } func (u *UnDirectedGraph) selfLoop(vertex int) bool { adjs, _ := u.GetAdjacentVertices(vertex) for _, adj := range adjs { if adj == vertex { return true } } return false } func (u *UnDirectedGraph) parallel(vertex1, vertex2 int) bool { adjs, _ := u.GetAdjacentVertices(vertex1) count := 0 for _, adj := range adjs { if adj == vertex2 { count++ } if count == 2 { return true } } return false } // GetCyclicPath gets a cyclic path in the graph, if not found, return nil. func (u *UnDirectedGraph) GetCyclicPath() (path []int) { // Self loop, can return directly. for i := 0; i < u.vertexCount; i++ { if u.selfLoop(i) { return []int{i, i} } } // Parallel edges, can return directly. for i := 0; i < u.vertexCount-1; i++ { for j := i + 1; j < u.vertexCount; j++ { if u.parallel(i, j) { return []int{i, j, i} } } } u.visited = make([]bool, u.vertexCount) u.pathTo = make([]int, u.vertexCount) for i := 0; i < u.vertexCount; i++ { if !u.visited[i] && len(path) == 0 { u.dfsForCyclicPath(i, -1, &path) } } return } func (u *UnDirectedGraph) dfsForCyclicPath(vertex int, pathToVertex int, path *[]int) { u.visited[vertex] = true adjs, _ := u.GetAdjacentVertices(vertex) for _, adj := range adjs { // If we already found the cyclic path, don't do anything but quit the recursive loop if len(*path) != 0 { return } if !u.visited[adj] { u.pathTo[adj] = vertex u.dfsForCyclicPath(adj, vertex, path) } else if pathToVertex != adj { // found it for v := vertex; v != adj; v = u.pathTo[v] { (*path) = append([]int{v}, (*path)...) } (*path) = append([]int{adj}, (*path)...) (*path) = append((*path), adj) } } } // GetBipartiteParts gets the two parties if the graph is a bi-partite graph func (u *UnDirectedGraph) GetBipartiteParts() (parts [][]int) { u.visited = make([]bool, u.vertexCount) color := make([]bool, u.vertexCount) for i := 0; i < u.vertexCount; i++ { if !u.visited[i] { stack := []int{i} // run a dfs. for len(stack) != 0 { vertex := stack[len(stack)-1] stack = stack[:len(stack)-1] if !u.visited[vertex] { u.visited[vertex] = true } adjs, _ := u.GetAdjacentVertices(vertex) for _, adj := range adjs { if !u.visited[adj] { color[adj] = !color[vertex] stack = append(stack, adj) } else if color[adj] == color[vertex] { return nil } } } } } parts = make([][]int, 2) for i, c := range color { if c { parts[0] = append(parts[0], i) } else { parts[1] = append(parts[1], i) } } return }
datastructure/graphs/undirected_graph.go
0.806052
0.617426
undirected_graph.go
starcoder
package solid import "github.com/cpmech/gosl/fun/dbf" // OnedLinElast implements a linear elastic model for 1D elements type OnedLinElast struct { E float64 // Young's modulus G float64 // shear modulus A float64 // cross-sectional area I22 float64 // moment of inertia of cross section about y2-axis I11 float64 // moment of inertia of cross section about y1-axis Jtt float64 // torsional constant Rho float64 // density } // add model to factory func init() { allocators["oned-elast"] = func() Model { return new(OnedLinElast) } } // Free frees memory func (o *OnedLinElast) Free() { } // GetRho returns density func (o *OnedLinElast) GetRho() float64 { return o.Rho } // GetA returns cross-sectional area func (o *OnedLinElast) GetA() float64 { return o.A } // Init initialises model func (o *OnedLinElast) Init(ndim int, pstress bool, prms dbf.Params) (err error) { prms.Connect(&o.E, "E", "oned-elast model") prms.Connect(&o.G, "G", "oned-elast model") prms.Connect(&o.A, "A", "oned-elast model") prms.Connect(&o.I22, "I22", "oned-elast model") prms.Connect(&o.I11, "I11", "oned-elast model") prms.Connect(&o.Jtt, "Jtt", "oned-elast model") prms.Connect(&o.Rho, "rho", "oned-elast model") return } // InitIntVars: unused func (o *OnedLinElast) InitIntVars(σ []float64) (s *State, err error) { return } // GetPrms gets (an example) of parameters func (o OnedLinElast) GetPrms() dbf.Params { return []*dbf.P{ &dbf.P{N: "E", V: 2.0000e+08}, &dbf.P{N: "G", V: 7.5758e+07}, &dbf.P{N: "A", V: 1.0000e-02}, &dbf.P{N: "I22", V: 8.3333e-06}, &dbf.P{N: "I11", V: 8.3333e-06}, &dbf.P{N: "Jtt", V: 1.4063e-05}, &dbf.P{N: "rho", V: 7.8500e+00}, } } // InitIntVars initialises internal (secondary) variables func (o OnedLinElast) InitIntVars1D() (s *OnedState, err error) { s = NewOnedState(0, 0) return } // Update updates stresses for given strains func (o OnedLinElast) Update(s *OnedState, ε, Δε, aux float64) (err error) { s.Sig += o.E * Δε return } // CalcD computes D = dσ_new/dε_new consistent with StressUpdate func (o OnedLinElast) CalcD(s *OnedState, firstIt bool) (float64, float64, error) { return o.E, 0, nil }
mdl/solid/onedlinelast.go
0.793586
0.41253
onedlinelast.go
starcoder
package lsp import "github.com/nokia/ntt/internal/lsp/protocol" type PredefFunctionDetails struct { Label string InsertText string Signature string Documentation string NrOfParameters int TextFormat protocol.InsertTextFormat } var PredefinedFunctions = []PredefFunctionDetails{ { Label: "int2char(...)", InsertText: "int2char(${1:invalue})$0", Signature: "int2char(in integer invalue) return charstring", Documentation: "## (TTCN-3)\nThe __int2char__ function converts an __integer__ value in the range of 0 to 127 (8-bit encoding) into a single-character-length\n __charstring__ value. The __integer__ value describes the 8-bit encoding of the character", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "int2unichar(...)", InsertText: "int2unichar(${1:invalue})$0", Signature: `int2unichar( in integer invalue ) return universal charstring`, Documentation: "## (TTCN-3)\nThe __int2unichar__ function n converts an __integer__ value in the range of 0 to 2147483647 (32-bit encoding) into a single-character-length __universal charstring__ value. The __integer__ value describes the 32-bit encoding of the character.", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "int2bit(...)", InsertText: "int2bit(${1:invalue}, ${2:length})$0", Signature: `int2bit( in integer invalue, in integer length ) return bitstring`, Documentation: "## (TTCN-3)\nThe __int2bit__ function converts a single __integer__ value to a single __bitstring__ value. The resulting string is length bits long. Error causes are:\n* invalue is less than zero;\n* the conversion yields a return value with more bits than specified by length.", NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "int2enum(...)", InsertText: "int2enum(${1:invalue}, ${2:outpar})$0", Signature: `int2enum( in integer inpar, out Enumerated_type outpar)`, Documentation: "## (TTCN-3)\nThe __int2enum__ function converts an integer value into an enumerated value of a given enumerated type. The integer value shall be provided as in parameter and the result of the conversion shall be stored in an out parameter. The type of the out parameter determines the type into which the in parameter is converted.", NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "int2hex(...)", InsertText: "int2hex(${1:invalue},${2:length})$0", Signature: `int2hex( in integer invalue, in integer length ) return hexstring`, Documentation: "## (TTCN-3)\nThe __int2hex__ function converts a single __integer__ value to a single __hexstring__ value. The resulting string is length hexadecimal digits long. Error causes are:\n* invalue is less than zero;\n* the conversion yields a return value with more hexadecimal characters than specified by length.", NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "int2oct(...)", InsertText: "int2oct(${1:invalue},${2:length})$0", Signature: `int2oct( in integer invalue, in integer length ) return octetstring`, Documentation: "## (TTCN-3)\nThe __int2oct__ function converts a single __integer__ value to a single __octetstring__ value. The resulting string is length octets long. Error causes are:\n* invalue is less than zero;\n* the conversion yields a return value with more octets than specified by length.", NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "int2str(...)", InsertText: "int2str(${1:invalue})$0", Signature: "int2str(in integer invalue) return charstring", Documentation: "## (TTCN-3)\nThe __int2str__ function converts the __integer__ value into its string equivalent (the base of the return string is always decimal). ", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "int2float(...)", InsertText: "int2float(${1:invalue})$0", Signature: "int2float(in integer invalue) return float", Documentation: "## (TTCN-3)\nThe __int2float__ function converts an __integer__ value into a __float__ value.", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "float2int(...)", InsertText: "float2int(${1:invalue})$0", Signature: "float2int(in float invalue) return integer", Documentation: "## (TTCN-3)\nThe __float2int__ function converts a __float__ value into an __integer__ value by removing the fractional part of the argument and returning the resulting __integer__. Error causes are:\n*invalue is __infinity__, __-infinity__ or not_a_number.", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "char2int(...)", InsertText: "char2int(${1:invalue})$0", Signature: "char2int(in charstring invalue) return integer", Documentation: "## (TTCN-3)\nThe __char2int__ function converts a single-character-length __charstring__ value into an __integer__ value in the range of 0 to 127. The __integer__ value describes the 8-bit encoding of the character. Error causes are:\n* length of invalue does not equal 1.", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "char2oct(...)", InsertText: "char2oct(${1:invalue})$0", Signature: "char2oct(in charstring invalue) return octetstring", Documentation: "## (TTCN-3)\nThe __char2oct__ function converts a __charstring__ invalue to an __octetstring__. Each octet of the octetstring will contain the Recommendation _ITU-T T.50 [4]_ codes (according to the IRV) of the appropriate characters of invalue.", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "unichar2int(...)", InsertText: "unichar2int(${1:invalue})$0", Signature: `unichar2int( in universal charstring invalue ) return integer`, Documentation: `## (TTCN-3) The __unichar2int__ function converts a single-character-length __universal charstring__ value into an __integer__ value in the range of 0 to 2147483647. The __integer__ value describes the 32-bit encoding of the character. Error causes are: * length of invalue does not equal 1.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "unichar2oct(...)", InsertText: "unichar2oct(${1:invalue})$0", Signature: `unichar2oct( in universal charstring invalue, in charstring string_encoding := "UTF-8" ) return octetstring`, Documentation: `## (TTCN-3) The __unichar2oct__ function This function converts a universal charstring invalue to an octetstring. Each octet of the octetstring will contain the octets mandated by mapping the characters of invalue using the standardized mapping associated with the given string_encoding in the same order as the characters appear in inpar. If the optional string_encoding parameter is omitted, the default value "UTF-8". The following values (see _ISO/IEC 10646 [2]_) are allowed as string_encoding actual parameter: a) __"UTF-8"__ b) __"UTF-16"__ c) __"UTF-16LE"__ d) __"UTF-16BE"__ e) __"UTF-32"__ f) __"UTF-32LE"__ g) __"UTF-32BE"__`, NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "bit2int(...)", InsertText: "bit2int(${1:invalue})$0", Signature: "bit2int(in bitstring invalue) return integer", Documentation: `## (TTCN-3) The __bit2int__ function This function converts a single __bitstring__ value to a single __integer__ value.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "bit2hex(...)", InsertText: "bit2hex(${1:invalue})$0", Signature: "bit2hex(in bitstring invalue) return hexstring", Documentation: `## (TTCN-3) The __bit2hex__ function converts a single __bitstring__ value to a single __hexstring__. The resulting __hexstring__ represents the same value as the __bitstring__. For the purpose of this conversion, a __bitstring__ shall be converted into a __hexstring__, where the __bitstring__ is divided into groups of four bits beginning with the rightmost bit. When the leftmost group of bits does contain less than 4 bits, this group is filled with _'0'B_ from the left until it contains exactly 4 bits and is converted afterwards. The consecutive order of hex digits in the resulting __hexstring__ is the same as the order of groups of 4 bits in the __bitstring__`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "bit2oct(...)", InsertText: "bit2oct(${1:invalue})$0", Signature: "bit2oct(in bitstring invalue) return octetstring", Documentation: `## (TTCN-3) The __bit2oct__ function converts a single __bitstring__ value to a single __octetstring__. The resulting __octetstring__ represents the same value as the __bitstring__. For the conversion the following holds: * bit2oct(value)=hex2oct(bit2hex(value)).`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "bit2str(...)", InsertText: "bit2str(${1:invalue})$0", Signature: "bit2str(in bitstring invalue) return charstring", Documentation: `## (TTCN-3) The __bit2str__ function converts a single __bitstring__ value to a single __charstring__. The resulting __charstring__ has the same length as the __bitstring__ and contains only the __characters__ '0' and '1'.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "hex2int(...)", InsertText: "hex2int(${1:invalue})$0", Signature: "hex2int(in hexstring invalue) return integer", Documentation: `## (TTCN-3) The __hex2int__ function converts a single __hexstring__ value to a single __integer__ value. For the purposes of this conversion, a __hexstring__ shall be interpreted as a positive base 16 __integer__ value. The rightmost hexadecimal digit is least significant, the leftmost hexadecimal digit is the most significant.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "hex2bit(...)", InsertText: "hex2bit(${1:invalue})$0", Signature: "hex2bit(in hexstring invalue) return bitstring", Documentation: `## (TTCN-3) The __hex2bit__ function converts a single __hexstring__ value to a single __bitstring__. The resulting __bitstring__ represents the same value as the __hexstring__.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "hex2oct(...)", InsertText: "hex2oct(${1:invalue})$0", Signature: "hex2oct(in hexstring invalue) return octetstring", Documentation: `## (TTCN-3) The __hex2oct__ function This function converts a single __hexstring__ value to a single __octetstring__. The resulting __octetstring__ represents the same value as the __hexstring__. For the purpose of this conversion, a __hexstring__ shall be converted into a __octetstring__, where the __octetstring__ contains the same sequence of hex digits as the __hexstring__ when the length of the __hexstring__ modulo 2 is 0. Otherwise, the resulting __octetstring__ contains 0 as leftmost hex digit followed by the same sequence of hex digits as in the __hexstring__. `, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "hex2str(...)", InsertText: "hex2str(${1:invalue})$0", Signature: "hex2str(in hexstring invalue) return charstring", Documentation: `## (TTCN-3) The __hex2str__ function converts a single __hexstring__ value to a single __charstring__. The resulting __charstring__ has the same length as the __hexstring__ and contains only the characters '0' to '9'and 'A' to 'F'.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "oct2int(...)", InsertText: "oct2int(${1:invalue})$0", Signature: "oct2int(in octetstring invalue) return integer", Documentation: `## (TTCN-3) The __oct2int__ function converts a single __octetstring__ value to a single __integer__ value. For the purposes of this conversion, an __octetstring__ shall be interpreted as a positive base 16 integer value. The rightmost hexadecimal digit is least significant, the leftmost hexadecimal digit is the most significant. The number of hexadecimal digits provided shall be multiples of 2 since one octet is composed of two hexadecimal digits. The hexadecimal digits 0 to F represent the decimal values 0 to 15 respectively.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "oct2bit(...)", InsertText: "oct2bit(${1:invalue})$0", Signature: "oct2bit(in octetstring invalue) return bitstring", Documentation: `## (TTCN-3) The __oct2bit__ function converts a single __octetstring__ value to a single __bitstring__. The resulting __bitstring__ represents the same value as the octetstring. For the conversion the following holds: * oct2bit(value)=hex2bit(oct2hex(value))`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "oct2hex(...)", InsertText: "oct2hex(${1:invalue})$0", Signature: "oct2hex(in octetstring invalue) return hexstring", Documentation: `## (TTCN-3) The __oct2hex__ function converts a single __octetstring__ value to a single __hexstring__. The resulting __hexstring__ represents the same value as the __octetstring__. For the purpose of this conversion, a __octetstring__ shall be converted into a __hexstring__ containing the same sequence of hex digits as the __octetstring__.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "oct2str(...)", InsertText: "oct2str(${1:invalue})$0", Signature: "oct2str(in octetstring invalue) return charstring", Documentation: `## (TTCN-3) The __oct2str__ function converts an __octetstring__ invalue to an __charstring__ representing the string equivalent of the input value. The resulting __charstring__ shall have double the length as the incoming __octetstring__. For the purpose of this conversion each hex digit of invalue is converted into a character '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E' or 'F' echoing the value of the hex digit. The consecutive order of __characters__ in the resulting __charstring__ is the same as the order of hex digits in the __octetstring__.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "oct2char(...)", InsertText: "oct2char(${1:invalue})$0", Signature: "oct2char(in octetstring invalue) return charstring", Documentation: `## (TTCN-3) The __oct2char__ function converts an __octetstring__ invalue to a __charstring__. The input parameter invalue shall not contain octet values higher than __7F__. The resulting __charstring__ shall have the same length as the input __octetstring__. The octets are interpreted as Recommendation _ITU-T T.50 [4]_ codes (according to the IRV) and the resulting characters are appended to the returned value.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "oct2unichar(...)", InsertText: "oct2unichar(${1:invalue})$0", Signature: `oct2unichar( in octetstring invalue, in charstring string_encoding := "UTF-8" ) return universal charstring`, Documentation: `## (TTCN-3) The __oct2unichar__ function converts an __octetstring__ invalue to a __universal charstring__ by use of the given string_encoding. The octets are interpreted as mandated by the standardized mapping associated with the given string_encoding and the resulting characters are appended to the returned value. If the optional string_encoding parameter is omitted, the default value "UTF-8". The following values (see _ISO/IEC 10646 [2]_) are allowed as string_encoding actual parameters (for the description of the codepoints see clause 27.5): a) __"UTF-8"__ b) __"UTF-16"__ c) __"UTF-16LE"__ d) __"UTF-16BE"__ e) __"UTF-32"__ f) __"UTF-32LE"__ g) __"UTF-32BE"__`, NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "str2int(...)", InsertText: "str2int(${1:invalue})$0", Signature: "str2int(in charstring invalue) return integer", Documentation: `## (TTCN-3) The __str2int__ function converts a __charstring__ representing an __integer__ value to the equivalent integer. Error causes are: * invalue contains characters other than "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" and "-". * invalue contains the character "-" at another position than the leftmost one.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "str2hex(...)", InsertText: "str2hex(${1:invalue})$0", Signature: "str2hex(in charstring invalue) return hexstring", Documentation: `## (TTCN-3) The __str2hex__ function converts a string of the type __charstring__ to a __hexstring__. The string invalue shall contain the "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e" "f", "A", "B", "C", "D", "E" or "F" graphical characters only. Each character of invalue shall be converted to the corresponding hexadecimal digit. The resulting hexstring will have the same length as the incoming charstring. Error cause is: * invalue contains characters other than specified above.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "str2oct(...)", InsertText: "str2oct(${1:invalue})$0", Signature: "str2oct(in charstring invalue) return octetstring", Documentation: `## (TTCN-3) The __str2oct__ function converts a string of the type __charstring__ to an __octetstring__. The string invalue shall contain the "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e" "f", "A", "B", "C", "D", "E" or "F" graphical characters only. When the string invalue contains even number characters the resulting octetstring contains 0 as leftmost character followed by the same sequence of characters as in the charstring. lengthof (see clause C.2.1 for the resulting octetstring) will return half of lengthof of the incoming charstring. In addition to the general error causes in clause 16.1.2, error causes is: * invalue contains characters other than specified above.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "str2float(...)", InsertText: "str2float(${1:invalue})$0", Signature: "str2float(in charstring invalue) return float", Documentation: `## (TTCN-3) The __str2float__ function converts a __charstring__ comprising a number into a __float__ value. The format of the number in the __charstring__ shall follow rules of plain ttcn-3 float values with the following exceptions: * leading zeros are allowed; * leading "+" sign before positive values is allowed; * "-0.0" is allowed; * no numbers after the dot in the decimal notation are allowed. In addition to the general error causes in clause 16.1.2, error causes are: * the format of invalue is different than defined above.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "enum2int(...)", InsertText: "enum2int(${1:invalue})$0", Signature: "enum2int(in Enumerated_type inpar) return integer", Documentation: `## (TTCN-3) The __enum2int__ function accepts an enumerated value and returns the integer value associated to the enumerated value. The actual parameter passed to inpar always shall be a typed object.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "any2unistr(...)", InsertText: "any2unistr(${1:invalue})$0", Signature: `any2unistr( in template any_type invalue, in universal charstring format := "" ) return universal charstring`, Documentation: `## (TTCN-3) The __any2unistr__ function converts the content of a value or template to a single __universal charstring__. The resulting __universal charstring__ is the same as the string produced by the __log__ operation containing the same operand as the one passed to the __any2unistr__ function. The value or template passed as a parameter to the __any2unichar__ function may be uninitialized, partially or completely initialized. The optional format parameter is used for dynamic selection of how the resulting __universal charstring__ should be produced from the provided invalue. * "": the resulting universal charstring is the same as the string produced by the __log__ operation for the same operand. * "canonical": unbound fields are represented in the output as "-", the fields and members of structured types are represented recursively in assignment notation. * <custom string>: tool specific output`, NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "lengthof(...)", InsertText: "lengthof(${1:invalue})$0", Signature: `lengthof( in template (present) any_string_or_list_type inpar ) return integer`, Documentation: `## (TTCN-3) The __lengthof__ function returns the length of a value or template that is of type __bitstring__, __hexstring__, __octetstring__, __charstring__, __universal charstring__, __record of__, __set of__, or __array__.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "sizeof(...)", InsertText: "sizeof(${1:invalue})$0", Signature: `sizeof( in template (present) any_record_set_type inpar ) return integer`, Documentation: `## (TTCN-3) The __sizeof__ function returns the actual number of elements of a value or template of a __record__ or __set__ type (see note). The function __sizeof__ is applicable to templates of __record__ and __set__ types. The function is applicable only if the __sizeof__ function gives the same result on all values that match the template. NOTE: Only elements of the TTCN-3 object, which is the parameter of the function are calculated; i.e. no elements of nested types/values are taken into account at determining the return value. Error causes are: * when inpar is a template and it can match values of different sizes.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "ispresent(...)", InsertText: "ispresent(${1:invalue})$0", Signature: "ispresent(in template any_ type inpar) return boolean", Documentation: `## (TTCN-3) The __ispresent__ function is allowed for templates of all data types and returns: * the value __true__ if the data object reference fulfils the (present) template restriction as described in clause 15.8; * the value __false__ otherwise.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "ischosen(...)", InsertText: "ischosen(${1:invalue})$0", Signature: `ischosen( in template any_union_type_field inpar ) return boolean`, Documentation: `## (TTCN-3) The __ischosen__ function is allowed for templates of all data types that are a union-field-reference or a type alternative of an anytype. This function returns: * the value __true__ if and only if the data object reference specifies the variant of the union type or the type alternative of the anytype that is actually selected for the given data object; * in all other cases __false__.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "isvalue(...)", InsertText: "isvalue(${1:invalue})$0", Signature: "isvalue(in template any_type inpar) return boolean", Documentation: `## (TTCN-3) The __isvalue__ function is allowed for templates of all data types, component and address types and default values. The function shall return __true__, if inpar is completely initialized and resolves to a specific value. If inpar is of __record__ or __set__ type, omitted optional fields shall be considered as initialized, i.e. the function shall also return __true__ if optional fields of inpar are set to omit. The function shall return __false__ otherwise. The __null__ value assigned to default and component references shall be considered as concrete values.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "isbound(...)", InsertText: "isbound(${1:invalue})$0", Signature: "isbound(in template any_type inpar) return boolean", Documentation: `## (TTCN-3) The __isbound__ function is allowed for templates of all data types. The function shall return __true__, if inpar is at least partially initialized. If inpar is of a __record__ or __set__ type, omitted optional fields shall be considered as initialized, i.e. the function shall also return __true__ if at least one optional field of inpar is set to omit. The function shall return __false__ otherwise. Inaccessible fields (e.g. non-selected alternatives of __union__ types, subfields of omitted __record__ and __set__ types or subfields of non-selected __union__ fields) shall be considered as uninitialized, i.e. __isbound__ shall return for them __false__. The __null__ value assigned to default and component references shall be considered as concrete values.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "istemplatekind(...)", InsertText: "istemplatekind(${1:invalue}, ${2:kind})$0", Signature: `istemplatekind ( in template any_type invalue, in charstring kind ) return boolean`, Documentation: `## (TTCN-3) The __istemplatekind__ function allows to examine if a template contains a certain kind of the matching mechanisms. If the matching mechanism kind enquired is matching a _specific value_, a _matching mechanism instead of values_ or matching _character pattern_, the function shall return __true__ if the content of the invalue parameter is of the same kind. If the matching mechanism kind enquired is a matching mechanism _inside values_, the function shall return __true__ if the template in the invalue parameter contains this kind of matching mechanism on the first level of nesting. If the matching mechanism kind enquired is a matching attribute, the function shall return __true__ if the template in the invalue parameter has this kind of matching attribute attached to it directly (i.e. it doesn't count if the attribute is attached to a field of invalue at any level of nesting). In all other cases the function returns __false__. | Value of kind parameter | Searched matching mechanism | | ----------------------- | --------------------------- | | "list" | Template list | | "complement" | Complemented template list | | "AnyValue", "?" | Any value | | "AnyValueOrNone", "*" | Any value or none | | "range" | Value range | | "superset" | SuperSet | | "subset" | SubSet | | "omit" | Omit | | "decmatch" |Matching decoded content | | "AnyElement" | Any element | | "AnyElementsOrNone" | Any number of elements or none | | "permutation" | Permutation | | "length" | Length restriction | | "ifpresent" | The IfPresent indicator | | "pattern" | Matching character pattern | `, NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "regexp(...)", InsertText: "regexp${1}(${2:inpar}, ${3:expression}, ${4:groupno})$0", Signature: `regexp [@nocase] ( in template (value) any_character_string_type inpar, in template (present) any_character_string_type expression, in integer groupno ) return any_character_string_type`, Documentation: `## (TTCN-3) The __regexp__ function first matches the parameter inpar (or in case inpar is a template, its value equivalent) against the expression in the second parameter. If the __@nocase__ modifier is present, this and all subsequent matchings shall be done in a case-insensitive way. If this matching is unsuccessful, an empty string shall be returned. If this matching is successful, the substring of inpar shall be returned, which matched the groupno-s group of expression during the matching. Group numbers are assigned by the order of occurrences of the opening bracket of a group and counted starting from 0 by step 1. _NOTE_: This function differs from other well-known regular expression matching implementations in that: 1. It shall match the whole inpar string instead of only a substring. 2. It starts counting groups from 0, while in some other implementations the first group is referenced by 1 and the whole substring matched by the expression is referenced by 0. `, NrOfParameters: 3, TextFormat: protocol.SnippetTextFormat}, { Label: "substr(...)", InsertText: "substr(${1:inpar}, ${2:index}, ${3:count})$0", Signature: `substr( in template (present) any inpar, in integer index, in integer count ) return input_string_or_sequence_type`, Documentation: `## (TTCN-3) This function returns a substring or subsequence from a value that is of a binary string type (__bitstring__, __hexstring__, __octetstring__), a character string type (__charstring__, __universal charstring__), or a sequence type (__record of__, __set of__ or array). If _inpar_ is a literal (i.e. type is not explicitly given) the corresponding type shall be retrieved from the value contents. The type of the substring or subsequence returned is the root type of the input parameter. The starting point of substring or subsequence to return is defined by the second parameter (_index_). Indexing starts from zero. The third input parameter (_count_) defines the length of the substring or subsequence to be returned. The units of length for string types are as defined in table 4 of the TTCN-3 core language specification. For sequence types, the unit of length is element. Please note that the root types of arrays is __record of__, therefore if _inpar_ is an array the returned type is __record of__. This, in some cases, may lead to different indexing in _inpar_ and in the returned value. When used on templates of character string types, specific values and patterns that contain literal characters and the following metacharacters: "?", "*" are allowed in _inpar_ and the function shall return the character representation of the matching mechanisms. When _inpar_ is a template of binary string or sequence type or is an array, only the specific value combined templates whose elements are specific values, and AnyElement matching mechanisms or combined templates are allowed and the substring or subsequence to be returned shall not contain AnyElement or combined template. In addition to the general error causes in clause 16.1.2, error causes are: * _index_ is less than zero; * _count_ is less than zero; * _index_ + _count___ is greater than __lengthof__(_inpar_); * _inpar_ is a template of a character string type and contains a matching mechanism other than a specific value or pattern; or if the pattern contains other metacharacters than "?", "*"; * _inpar_ is a template of a binary string or sequence type or array and it contains other matching mechanism as specific value or combined template; or if the elements of combined template are any other matching mechanisms than specific values, and AnyElement or combined templates; * _inpar_ is a template of a binary string or sequence type or array and the substring or subsequence to be returned contains the AnyElement matching mechanism or combined templates; * the template passed to the _inpar_ parameter is not of type bitstring, hexstring, octetstring, charstring, universal charstring, __record of__, __set of__, or array. Examples: substr('00100110'B, 3, 4) // returns '0011'B substr('ABCDEF'H, 2, 3) // returns 'CDE'H substr('01AB23CD'O, 1, 2) // returns 'AB23'O substr("My name is JJ", 11, 2) // returns "JJ" substr({ 4, 5, 6 }, 1, 2) // returns {5, 6}`, NrOfParameters: 3, TextFormat: protocol.SnippetTextFormat}, { Label: "replace(...)", InsertText: "replace(${1:inpar}, (${2:index}, (${3:len}, (${4:repl})$0", Signature: `replace( in any inpar, in integer index, in integer len, in any repl ) return any_string_or_sequence type`, Documentation: `## (TTCN-3) This function replaces the substring or subsequence of value _inpar_ at index _index_ of length _len_ with the string or sequence value _repl_ and returns the resulting string or sequence. _inpar_ shall not be modified. If _len_ is 0 the string or sequence _repl_ is inserted. If _index_ is 0, _repl_ is inserted at the beginning of _inpar_. If _index_ is __lengthof(_inpar_), _repl_ is inserted at the end of _inpar_. If _inpar_ is a literal (i.e. type is not explicitly given) the corresponding type shall be retrieved from the value contents. _inpar_ and _repl_, and the returned string or sequence shall be of the same root type. The function replace can be applied to _bitstring_, _hexstring_, _octetstring_, or any character string, __record of__, __set of__, or arrays. Note that indexing in strings starts from zero. Please note that the root types of arrays is __record of__, therefore if _inpar_ or _repl_ or both are an array, the returned type is __record of__. This, in some cases, may lead to different indexing in _inpar_ and/or _repl_ and in the returned value. In addition to the general error causes in clause 16.1.2, error causes are: * _inpar_ or _repl_ are not of string, __record of__, __set of__, or array type; * _inpar_ and _repl_ are of different root type; * _index_ is less than 0 or greater than __lengthof(_inpar_); * _len_ is less than 0 or greater than __lengthof(_inpar_); * _index_+_len_ is greater than __lengthof(_inpar_). Examples: replace ('00000110'B, 1, 3, '111'B) // returns '01110110'B replace ('ABCDEF'H, 0, 2, '123'H) // returns '123CDEF'H replace ('01AB23CD'O, 2, 1, 'FF96'O) // returns '01ABFF96CD'O replace ("My name is JJ", 11, 1, "xx") // returns "My name is xxJ" replace ("My name is JJ", 11, 0, "xx") // returns "My name is xxJJ" replace ("My name is JJ", 2, 2, "x") // returns "Myxame is JJ", replace ("My name is JJ", 12, 2, "xx") // produces test case error replace ("My name is JJ", 13, 2, "xx") // produces test case error replace ("My name is JJ", 13, 0, "xx") // returns "My name is JJxx"`, NrOfParameters: 4, TextFormat: protocol.SnippetTextFormat}, { Label: "encvalue(...)", InsertText: "encvalue(${1:inpar}, ${2:encoding_info}, ${3:dynamic_encoding})$0", Signature: `encvalue( in template (value) any inpar, in universal charstring encoding_info := "", in universal charstring dynamic_encoding := "" ) return bitstring`, Documentation: `## (TTCN-3) The __encvalue__ function encodes a value or template into a bitstring. When the actual parameter that is passed to _inpar_ is a template, it shall resolve to a specific value (the same restrictions apply as for the argument of the send statement). The returned bitstring represents the encoded value of _inpar_, however, the TTCN-3 test system need not make any check on its correctness. The optional _encoding_info_ parameter is used for passing additional encoding information to the codec and, if it is omitted, no additional information is sent to the codec. The optional _dynamic_encoding_ parameter is used for dynamic selection of encode attribute of the _inpar_ value for this single __encvalue__ call. The rules for dynamic selection of the encode attribute are described in clause 27.9 of the TTCN-3 core language specification. In addition to the general error causes in clause 16.1.2, error causes are: * Encoding fails due to a runtime system problem (i.e. no encoding function exists for the actual type of _inpar_).`, NrOfParameters: 3, TextFormat: protocol.SnippetTextFormat}, { Label: "decvalue(...)", InsertText: "decvalue(${1:encoded_value}, ${2:decoded_value}, ${3:decoding_info}, ${4:dynamic_encoding})$0", Signature: `decvalue( inout bitstring encoded_value, out any decoded_value, in universal charstring decoding_info := "", in universal charstring dynamic_encoding := "" ) return integer`, Documentation: `## (TTCN-3) The __decvalue__ function decodes a bitstring into a value. The test system shall suppose that the bitstring _encoded_value_ represents an encoded instance of the actual type of _decoded_value_. The optional _decoding_info_ parameter is used for passing additional decoding information to the codec and, if it is omitted, no additional information is sent to the codec. The optional _dynamic_encoding_ parameter is used for dynamic selection of encode attribute of the _decoded_value_ parameter for this single __decvalue__ call. The rules for dynamic selection of the encode attribute are described in clause 27.9 of the TTCN-3 core language specification. If the decoding was successful, then the used bits are removed from the parameter _encoded_value_, the rest is returned (in the parameter _encoded_value_), and the decoded value is returned in the parameter _decoded_value_. If the decoding was unsuccessful, the actual parameters for _encoded_value_ and _decoded_value_ are not changed. The function shall return an integer value to indicate success or failure of the decoding below: * The return value 0 indicates that decoding was successful. * The return value 1 indicates an unspecified cause of decoding failure. This value is also returned if the _encoded_value_ parameter contains an unitialized value. * The return value 2 indicates that decoding could not be completed as _encoded_value_ did not contain enough bits.`, NrOfParameters: 4, TextFormat: protocol.SnippetTextFormat}, { Label: "encvalue_unichar(...)", InsertText: "encvalue_unichar(${1:inpar}, ${2:string_serialization}, ${3:encoding_info}, ${4:dynamic_encoding})$0", Signature: `encvalue_unichar( in template (value) any inpar, in charstring string_serialization := "UTF-8", in universal charstring encoding_info := "", in universal charstring dynamic_encoding := "" ) return universal charstring`, Documentation: `## (TTCN-3) The __encvalue_unichar__ function encodes a value or template into a universal charstring. When the actual parameter that is passed to _inpar_ is a template, it shall resolve to a specific value (the same restrictions apply as for the argument of the send statement). The returned universal charstring represents the encoded value of _inpar_, however, the TTCN-3 test system need not make any check on its correctness. If the optional _string_serialization_ parameter is omitted, the default value "UTF-8" is used. The optional _encoding_info_ parameter is used for passing additional encoding information to the codec and, if it is omitted, no additional information is sent to the codec. The optional _dynamic_encoding_ parameter is used for dynamic selection of encode attribute of the _inpar_ value for this single __encvalue_unichar__ call. The rules for dynamic selection of the encode attribute are described in clause 27.9 of the TTCN-3 core language specification. The following values (see ISO/IEC 10646 [2]) are allowed as _string_serialization_ actual parameters (for the description of the UCS encoding scheme see clause 27.5): * "UTF-8" * "UTF-16" * "UTF-16LE" * "UTF-16BE" * "UTF-32" * "UTF-32LE" * "UTF-32BE" The serialized bitstring shall not include the optional signature (see clause 10 of ISO/IEC 10646 [2], also known as byte order mark). In case of "UTF-16" and "UTF-32" big-endian ordering shall be used (as described in clauses 10.4 and 10.7 of ISO/IEC 10646 [2]). The specific semantics of this function are explained by the following TTCN-3 definition: function encvalue_unichar(in template(value) any inpar, in charstring enc in universal charstring encoding_info := "", in universal charstring dynamic_encoding := "") return universal charstring { return oct2unichar(bit2oct(encvalue(inpar, encoding_info, dynamic_encoding)), enc); }`, NrOfParameters: 4, TextFormat: protocol.SnippetTextFormat}, { Label: "decvalue_unichar(...)", InsertText: "decvalue_unichar(${1:encoded_value}, ${2:decoded_value}, ${3:string_serialization}, ${4:decoding_info}, ${5:dynamic_encoding},)$0", Signature: `decvalue_unichar( inout universal charstring encoded_value, out any decoded_value, in charstring string_serialization:= "UTF-8", in universal charstring decoding_info := "", in universal charstring dynamic_encoding := "" ) return integer`, Documentation: `## (TTCN-3) The __decvalue_unichar__ function decodes (part of) a universal charstring into a value. The test system shall suppose that a prefix of the universal charstring _encoded_value_ represents an encoded instance of the actual type of _decoded_value_. The optional _decoding_info_ parameter is used for passing additional decoding information to the codec and, if it is omitted, no additional information is sent to the codec. The optional _dynamic_encoding_ parameter is used for dynamic selection of encode attribute of the _decoded_value_ parameter for this single __decvalue_unichar__ call. The rules for dynamic selection of the encode attribute are described in clause 27.9. If the decoding was successful, then the characters used for decoding are removed from the parameter _encoded_value_, the rest is returned (in the parameter _encoded_value_), and the decoded value is returned in the parameter _decoded_value_. If the decoding was unsuccessful, the actual parameters for _encoded_value_ and _decoded_value_ are not changed. The function shall return an integer value to indicate success or failure of the decoding below: * The return value 0 indicates that decoding was successful. * The return value 1 indicates an unspecified cause of decoding failure. This value is also returned if the _encoded_value_ parameter contains an unitialized value. * The return value 2 indicates that decoding could not be completed as _encoded_value_ did not contain enough bits. If the optional _string_serialization_ parameter is omitted, the default value "UTF-8" is used. The following values (see ISO/IEC 10646 [2]) are allowed as _string_serialization_ actual parameters (for the description of the UCS encoding scheme see clause 27.5 of TTCN-3 core language specification): * "UTF-8" * "UTF-16" * "UTF-16LE" * "UTF-16BE" * "UTF-32" * "UTF-32LE" * "UTF-32BE" The serialized bitstring shall not include the optional signature (see clause 10 of ISO/IEC 10646 [2], also known as byte order mark). In case of "UTF-16" and "UTF-32" big-endian ordering shall be used (as described in clauses 10.4 and 10.7 of ISO/IEC 10646 [2]). The semantics of the function can be explained by the following TTCN-3 function: function decvalue_unichar ( inout universal charstring encoded_value, out any decoded_value, in charstring string_encoding := "UTF-8", in universal charstring decoding_info := "", in universal charstring dynamic_encoding := "") return integer { var bitstring v_str = oct2bit(unichar2oct(encoded_value, string_encoding)); var integer v_result := decvalue(v_str, decoded_value, decoding_info, dynamic_encoding); if (v_result == 0) { // success encoded_value := oct2unichar(bit2oct(v_str), string_encoding); } return v_result; }`, NrOfParameters: 5, TextFormat: protocol.SnippetTextFormat}, { Label: "encvalue_o(...)", InsertText: "encvalue_o(${1:inpar}, ${2:encoding_info}, ${3:dynamic_encoding}, ${4:bit_length})$0", Signature: `encvalue_o( in template (value) any inpar, in universal charstring encoding_info := "", in universal charstring dynamic_encoding := "", out integer bit_length ) return octetstring`, Documentation: `## (TTCN-3) The __encvalue_o__ function encodes a value or template into an octetstring. When the actual parameter that is passed to _inpar_ is a template, it shall resolve to a specific value (the same restrictions apply as for the argument of the send statement). The returned octetstring represents the encoded value of _inpar_, however, the TTCN-3 test system need not make any check on its correctness. In case the encoded message is not octet-based and has a bit length not divisable by 8, the encoded message will be left-aligned in the returned octetstring and the least significant (8 - (bit length mod 8)) bits in the least significant octet will be 0. The bit length can be assigned to a variable by usage of the formal out parameter _bit_length_. The optional _encoding_info_ parameter is used for passing additional encoding information to the codec and, if it is omitted, no additional information is sent to the codec. The optional _dynamic_encoding_ parameter is used for dynamic selection of encode attribute of the _inpar_ value for this single __encvalue_o__ call. The rules for dynamic selection of the encode attribute are described in clause 27.9. In addition to the general error causes in clause 16.1.2 of the TTCN-3 core language specification, error causes are: * Encoding fails due to a runtime system problem (i.e. no encoding function exists for the actual type of _inpar_).`, NrOfParameters: 4, TextFormat: protocol.SnippetTextFormat}, { Label: "decvalue_o(...)", InsertText: "decvalue_o(${1:encoded_value}, ${2:decoded_value}, ${3:decoding_info}, ${4:dynamic_encoding})$0", Signature: `decvalue_o( inout octetstring encoded_value, out any decoded_value, in universal charstring decoding_info := "", in universal charstring dynamic_encoding := "" ) return integer`, Documentation: `## (TTCN-3) The __decvalue_o__ function decodes an octetstring into a value. The test system shall suppose that the octetstring _encoded_value_ represents an encoded instance of the actual type of _decoded_value_. The optional _decoding_info_ parameter is used for passing additional decoding information to the codec and, if it is omitted, no additional information is sent to the codec. The optional _dynamic_encoding_ parameter is used for dynamic selection of __encode__ attribute of the decoded_value parameter for this single __decvalue_o__ call. The rules for dynamic selection of the __encode__ attribute are described in clause 27.9 of the TTCN-3 core language specification. If the decoding was successful, then the used octets are removed from the parameter _encoded_value_, the rest is returned (in the parameter _encoded_value_), and the decoded value is returned in the parameter _decoded_value_. If the decoding was unsuccessful, the actual parameters for _encoded_value_ and _decoded_value_ are not changed. The function shall return an integer value to indicate success or failure of the decoding below: * The return value 0 indicates that decoding was successful. * The return value 1 indicates an unspecified cause of decoding failure. This value is also returned if the _encoded_value_ parameter contains an unitialized value. * The return value 2 indicates that decoding could not be completed as _encoded_value_ did not contain enough octets. `, NrOfParameters: 4, TextFormat: protocol.SnippetTextFormat}, { Label: "get_stringencoding(...)", InsertText: "get_stringencoding(${1:encoded_value})$0", Signature: `get_stringencoding( in octettstring encoded_value ) return octettstring`, Documentation: `## (TTCN-3) The __get_stringencoding__ function analyses the encoded_value and returns the UCS encoding scheme according to clause 10 of ISO/IEC 10646 [2] (see also clause 27.5 of the TTCN-3 core language specification). The identified encoding scheme, or the value "<unknown>", if the type of encoding cannot be determined unanimously, shall be returned as a character string. The initial octet sequence (also known as byte order mark, BOM), when present, allows identifying the encoding scheme unanimously. When it is not present, other symptoms may be used to identify the encoding scheme unanimously; for example, only UTF-8 may have odd number of octets and bit distribution according to table 2 of clause 9.1 of ISO/IEC 10646 [2]. Example: match ( get_stringencoding('6869C3BA7A'O),charstring:"UTF-8") // true //(the octetstring contains the UTF-8 encoding of the character sequence "hiúz") `, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "remove_bom(...)", InsertText: "remove_bom(${1:encoded_value})$0", Signature: `remove_bom( in octettstring encoded_value ) return octettstring`, Documentation: `## (TTCN-3) The __remove_bom__ function removes the optional FEFF ZERO WIDTH NO-BREAK SPACE sequence that may be present at the beginning of a stream of serialized (encoded) universal character strings to indicate the order of the octets within the encoding form, as defined in clause 10 of ISO/IEC 10646 [2]. If no FEFF ZERO WIDTH NO-BREAK SPACE sequence present in the _encoded_value_ parameter, the function shall return the value of the parameter without change.`, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "rnd(...)", InsertText: "rnd(${1:seed})$0", Signature: "rnd([in float seed]) return float", Documentation: `## (TTCN-3) The __rnd__ function returns a (pseudo) random number less than 1 but greater or equal to 0. The random number generator is initialized per test component and for the control part by means of an optional seed value (a numerical float value). If no new seed is provided, the last generated number will be used as seed for the next random number. Without a previous initialization a value calculated from the system time will be used as seed value when __rnd__ is used the first time in a test component or the control part. Each time the __rnd__ function is initialized with the same seed value, it shall repeat the same sequence of random numbers. For the purpose of keeping parallel testing deterministic, each test component, as well as the control part has its own random seed. This allows for better reproducibility of test executions. Thus, the __rnd__ function will always use the seed of the component or control part which calls it. To produce a random integers in a given range, the following formula can be used: float2int(int2float(upperbound - lowerbound +1)*rnd()) + lowerbound // Here, upperbound and lowerbound denote highest and lowest number in range. `, NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "testcasename()", InsertText: "testcasename()$0", Signature: "testcasename() return charstring", Documentation: `## (TTCN-3) The __testcasename__ function shall return the unqualified name of the actually executing test case. When the function __testcasename__ is called if the control part is being executed but no testcase, it shall return the empty string.`, NrOfParameters: 0, TextFormat: protocol.SnippetTextFormat}, { Label: "hostid(...)", InsertText: "hostid($1)$0", Signature: `hostid( in charstring idkind := "Ipv4orIPv6" ) return charstring`, Documentation: "## (TTCN-3)\nThe __hostid__ function shall return the host id of the test component or module control executing the hostid function in form of a character string. The in parameter idkind allows to specify the expected id format to be returned. Predefined _idkind_ values are:\n* \"Ipv4orIPv6\": The contents of the returned character string is an Ipv4 address. If no Ipv4 address, but an Ipv6 address is available, a character string representation of the Ipv6 address is returned.\n* \"Ipv4\": The contents of the returned character string shall be an Ipv4 address.\n* \"Ipv6\": The contents of the returned characterstring shall be an Ipv6 address.", NrOfParameters: 1, TextFormat: protocol.SnippetTextFormat}, { Label: "match(...)", InsertText: "match(${1:expression}, ${2:templateInstance})$0", Signature: `match( in expression, in template instance ) return boolean`, Documentation: `## (TTCN-3) The __match__ operation returns a __boolean__ value. It matches an expression, which shall denote a value or a field of a value against a template instance. Types of the expression and the template instance shall be compatible (see clause 6.3). The return value of the match operation indicates whether the expression matches the specified template instance. In the special case, matching a non-optional value expression (e.g. a value variable or non-optional field of a value) with a template instance that matches an omitted field (i.e. one of the matching mechanisms Omit, AnyValueOrNone, IfPresent) shall be allowed and shall be treated as if the value expression were an optional field. Thus, matching a value expression against a template instance which evaluates to the omit matching mechanism shall return false.`, NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}, { Label: "setverdict(...)", InsertText: "setverdict(${1:verdict})$0", Signature: `setverdict( in expression {, in charstring|templateInstance reason})`, Documentation: `## (TTCN-3) The value of the local verdict is changed with the __setverdict__ operation. * The first parameter is either an expression or a literal providing one of the values: __pass__, __fail__, __inconc__ or __none__ * The optional parameters allow to provide information that explain the reasons for assigning the verdict. This information is composed to a string and stored in an implicit __charstring__ variable. On termination of the test component, the actual local verdict is logged together with the implicit __charstring__ variable. Since the optional parameters can be seen as log information, the same rules and restrictions as for the parameters of the __log__ statement apply`, NrOfParameters: 2, TextFormat: protocol.SnippetTextFormat}}
internal/lsp/predef_func_descr.go
0.626924
0.434821
predef_func_descr.go
starcoder
package display import ( "fmt" mgl "github.com/go-gl/mathgl/mgl32" "github.com/inkyblackness/shocked-client/graphics" "github.com/inkyblackness/shocked-client/opengl" ) var basicHighlighterVertexShaderSource = ` #version 150 precision mediump float; in vec3 vertexPosition; uniform mat4 modelMatrix; uniform mat4 viewMatrix; uniform mat4 projectionMatrix; void main(void) { gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(vertexPosition, 1.0); } ` var basicHighlighterFragmentShaderSource = ` #version 150 precision mediump float; uniform vec4 inColor; out vec4 fragColor; void main(void) { fragColor = inColor; } ` // BasicHighlighter draws a simple highlighting of a rectangular area. type BasicHighlighter struct { context *graphics.RenderContext program uint32 vao *opengl.VertexArrayObject vertexPositionBuffer uint32 vertexPositionAttrib int32 modelMatrixUniform opengl.Matrix4Uniform viewMatrixUniform opengl.Matrix4Uniform projectionMatrixUniform opengl.Matrix4Uniform inColorUniform opengl.Vector4Uniform } // NewBasicHighlighter returns a new instance of BasicHighlighter. func NewBasicHighlighter(context *graphics.RenderContext) *BasicHighlighter { gl := context.OpenGl() program, programErr := opengl.LinkNewStandardProgram(gl, basicHighlighterVertexShaderSource, basicHighlighterFragmentShaderSource) if programErr != nil { panic(fmt.Errorf("BasicHighlighter shader failed: %v", programErr)) } highlighter := &BasicHighlighter{ context: context, program: program, vao: opengl.NewVertexArrayObject(gl, program), vertexPositionBuffer: gl.GenBuffers(1)[0], vertexPositionAttrib: gl.GetAttribLocation(program, "vertexPosition"), modelMatrixUniform: opengl.Matrix4Uniform(gl.GetUniformLocation(program, "modelMatrix")), viewMatrixUniform: opengl.Matrix4Uniform(gl.GetUniformLocation(program, "viewMatrix")), projectionMatrixUniform: opengl.Matrix4Uniform(gl.GetUniformLocation(program, "projectionMatrix")), inColorUniform: opengl.Vector4Uniform(gl.GetUniformLocation(program, "inColor"))} { gl.BindBuffer(opengl.ARRAY_BUFFER, highlighter.vertexPositionBuffer) half := float32(0.5) var vertices = []float32{ -half, -half, 0.0, half, -half, 0.0, half, half, 0.0, half, half, 0.0, -half, half, 0.0, -half, -half, 0.0} gl.BufferData(opengl.ARRAY_BUFFER, len(vertices)*4, vertices, opengl.STATIC_DRAW) gl.BindBuffer(opengl.ARRAY_BUFFER, 0) } highlighter.vao.OnShader(func() { gl.EnableVertexAttribArray(uint32(highlighter.vertexPositionAttrib)) gl.BindBuffer(opengl.ARRAY_BUFFER, highlighter.vertexPositionBuffer) gl.VertexAttribOffset(uint32(highlighter.vertexPositionAttrib), 3, opengl.FLOAT, false, 0, 0) gl.BindBuffer(opengl.ARRAY_BUFFER, 0) }) return highlighter } // Dispose releases all resources. func (highlighter *BasicHighlighter) Dispose() { gl := highlighter.context.OpenGl() highlighter.vao.Dispose() gl.DeleteBuffers([]uint32{highlighter.vertexPositionBuffer}) gl.DeleteShader(highlighter.program) } // Render renders the highlights. func (highlighter *BasicHighlighter) Render(areas []Area, color graphics.Color) { gl := highlighter.context.OpenGl() highlighter.vao.OnShader(func() { highlighter.viewMatrixUniform.Set(gl, highlighter.context.ViewMatrix()) highlighter.projectionMatrixUniform.Set(gl, highlighter.context.ProjectionMatrix()) highlighter.inColorUniform.Set(gl, color.AsVector()) for _, area := range areas { x, y := area.Center() width, height := area.Size() modelMatrix := mgl.Ident4(). Mul4(mgl.Translate3D(x, y, 0.0)). Mul4(mgl.Scale3D(width, height, 1.0)) highlighter.modelMatrixUniform.Set(gl, &modelMatrix) gl.DrawArrays(opengl.TRIANGLES, 0, 6) } }) }
src/github.com/inkyblackness/shocked-client/editor/display/BasicHighlighter.go
0.752559
0.538437
BasicHighlighter.go
starcoder
package validator import ( "bytes" "context" "fmt" "math" "reflect" "strconv" "github.com/go-courier/ptr" "github.com/go-courier/validator/errors" "github.com/go-courier/validator/rules" ) var ( TargetFloatValue = "float value" TargetDecimalDigitsOfFloatValue = "decimal digits of float value" TargetTotalDigitsOfFloatValue = "total digits of float value" ) /* Validator for float32 and float64 Rules: ranges @float[min,max] @float[1,10] // value should large or equal than 1 and less or equal than 10 @float(1,10] // value should large than 1 and less or equal than 10 @float[1,10) // value should large or equal than 1 @float[1,) // value should large or equal than 1 @float[,1) // value should less than 1 enumeration @float{1.1,1.2,1.3} // value should be one of these multiple of some float value @float{%multipleOf} @float{%2.2} // value should be multiple of 2.2 max digits and decimal digits. when defined, all values in rule should be under range of them. @float<MAX_DIGITS,DECIMAL_DIGITS> @float<5,2> // will checkout these values invalid: 1.111 (decimal digits too many), 12345.6 (digits too many) composes @float<MAX_DIGITS,DECIMAL_DIGITS>[min,max] aliases: @float32 = @float<7> @float64 = @float<15> */ type FloatValidator struct { MaxDigits uint DecimalDigits *uint Minimum *float64 Maximum *float64 ExclusiveMaximum bool ExclusiveMinimum bool MultipleOf float64 Enums map[float64]string } func init() { ValidatorMgrDefault.Register(&FloatValidator{}) } func (validator *FloatValidator) SetDefaults() { if validator != nil { if validator.MaxDigits == 0 { validator.MaxDigits = 7 } if validator.DecimalDigits == nil { validator.DecimalDigits = ptr.Uint(2) } } } func (FloatValidator) Names() []string { return []string{"float", "double", "float32", "float64"} } func isFloatType(typ reflect.Type) bool { switch typ.Kind() { case reflect.Float32, reflect.Float64: return true } return false } func (validator *FloatValidator) Validate(v interface{}) error { rv, ok := v.(reflect.Value) if !ok { rv = reflect.ValueOf(v) } if !isFloatType(rv.Type()) { return errors.NewUnsupportedTypeError(rv.Type().String(), validator.String()) } val := rv.Float() decimalDigits := *validator.DecimalDigits m, d := lengthOfDigits([]byte(fmt.Sprintf("%v", val))) if m > validator.MaxDigits { return &errors.OutOfRangeError{ Target: TargetTotalDigitsOfFloatValue, Current: m, Maximum: validator.MaxDigits, } } if d > decimalDigits { return &errors.OutOfRangeError{ Target: TargetDecimalDigitsOfFloatValue, Current: d, Maximum: decimalDigits, } } if validator.Enums != nil { if _, ok := validator.Enums[val]; !ok { values := make([]interface{}, 0) for _, v := range validator.Enums { values = append(values, v) } return &errors.NotInEnumError{ Target: TargetFloatValue, Current: v, Enums: values, } } return nil } if validator.Minimum != nil { mininum := *validator.Minimum if (validator.ExclusiveMinimum && val == mininum) || val < mininum { return &errors.OutOfRangeError{ Target: TargetFloatValue, Current: val, Minimum: mininum, ExclusiveMinimum: validator.ExclusiveMinimum, } } } if validator.Maximum != nil { maxinum := *validator.Maximum if (validator.ExclusiveMaximum && val == maxinum) || val > maxinum { return &errors.OutOfRangeError{ Target: TargetFloatValue, Current: val, Maximum: maxinum, ExclusiveMaximum: validator.ExclusiveMaximum, } } } if validator.MultipleOf != 0 { if !multipleOf(val, validator.MultipleOf, decimalDigits) { return &errors.MultipleOfError{ Target: TargetFloatValue, Current: val, MultipleOf: validator.MultipleOf, } } } return nil } func lengthOfDigits(b []byte) (uint, uint) { if b[0] == '-' { b = b[1:] } parts := bytes.Split(b, []byte(".")) n := len(parts[0]) if len(parts) == 2 { d := len(parts[1]) return uint(n + d), uint(d) } return uint(n), 0 } func multipleOf(v float64, div float64, decimalDigits uint) bool { val := round(v/div, int(decimalDigits)) return val == math.Trunc(val) } func round(f float64, n int) float64 { res, _ := strconv.ParseFloat(strconv.FormatFloat(f, 'f', n, 64), 64) return res } func (FloatValidator) New(ctx context.Context, rule *Rule) (Validator, error) { validator := &FloatValidator{} switch rule.Name { case "float", "float32": validator.MaxDigits = 7 case "double", "float64": validator.MaxDigits = 15 } if rule.Params != nil { if len(rule.Params) > 2 { return nil, fmt.Errorf("float should only 1 or 2 parameter, but got %d", len(rule.Params)) } maxDigitsBytes := rule.Params[0].Bytes() if len(maxDigitsBytes) > 0 { maxDigits, err := strconv.ParseUint(string(maxDigitsBytes), 10, 4) if err != nil { return nil, errors.NewSyntaxError("decimal digits should be a uint value which less than 16, but got `%s`", maxDigitsBytes) } validator.MaxDigits = uint(maxDigits) } if len(rule.Params) > 1 { decimalDigitsBytes := rule.Params[1].Bytes() if len(decimalDigitsBytes) > 0 { decimalDigits, err := strconv.ParseUint(string(decimalDigitsBytes), 10, 4) if err != nil || uint(decimalDigits) >= validator.MaxDigits { return nil, errors.NewSyntaxError("decimal digits should be a uint value which less than %d, but got `%s`", validator.MaxDigits, decimalDigitsBytes) } validator.DecimalDigits = ptr.Uint(uint(decimalDigits)) } } } validator.SetDefaults() validator.ExclusiveMinimum = rule.ExclusiveLeft validator.ExclusiveMaximum = rule.ExclusiveRight if rule.Range != nil { min, max, err := floatRange( "float", validator.MaxDigits, validator.DecimalDigits, rule.Range..., ) if err != nil { return nil, err } validator.Minimum = min validator.Maximum = max validator.ExclusiveMinimum = rule.ExclusiveLeft validator.ExclusiveMaximum = rule.ExclusiveRight } if rule.Values != nil { if len(rule.Values) == 1 { mayBeMultipleOf := rule.Values[0].Bytes() if mayBeMultipleOf[0] == '%' { v := mayBeMultipleOf[1:] multipleOf, err := parseFloat(v, validator.MaxDigits, validator.DecimalDigits) if err != nil { return nil, errors.NewSyntaxError("multipleOf should be a valid float<%d> value, but got `%s`", validator.MaxDigits, v) } validator.MultipleOf = multipleOf } } if validator.MultipleOf == 0 { validator.Enums = map[float64]string{} for _, v := range rule.Values { b := v.Bytes() enumValue, err := parseFloat(b, validator.MaxDigits, validator.DecimalDigits) if err != nil { return nil, errors.NewSyntaxError("enum should be a valid float<%d> value, but got `%s`", validator.MaxDigits, b) } validator.Enums[enumValue] = string(b) } } } return validator, validator.TypeCheck(rule) } func (validator *FloatValidator) TypeCheck(rule *Rule) error { switch rule.Type.Kind() { case reflect.Float32: if validator.MaxDigits > 7 { return fmt.Errorf("max digits too large for type %s", rule) } return nil case reflect.Float64: return nil } return errors.NewUnsupportedTypeError(rule.String(), validator.String()) } func floatRange(typ string, maxDigits uint, decimalDigits *uint, ranges ...*rules.RuleLit) (*float64, *float64, error) { fullType := fmt.Sprintf("%s<%d>", typ, maxDigits) if decimalDigits != nil { fullType = fmt.Sprintf("%s<%d,%d>", typ, maxDigits, *decimalDigits) } parseMaybeFloat := func(b []byte) (*float64, error) { if len(b) == 0 { return nil, nil } n, err := parseFloat(b, maxDigits, decimalDigits) if err != nil { return nil, fmt.Errorf("%s value is not correct: %s", fullType, err) } return &n, nil } switch len(ranges) { case 2: min, err := parseMaybeFloat(ranges[0].Bytes()) if err != nil { return nil, nil, fmt.Errorf("min %s", err) } max, err := parseMaybeFloat(ranges[1].Bytes()) if err != nil { return nil, nil, fmt.Errorf("max %s", err) } if min != nil && max != nil && *max < *min { return nil, nil, fmt.Errorf("max %s value must be equal or large than min value %v, current %v", fullType, *min, *max) } return min, max, nil case 1: min, err := parseMaybeFloat(ranges[0].Bytes()) if err != nil { return nil, nil, fmt.Errorf("min %s", err) } return min, min, nil } return nil, nil, nil } func parseFloat(b []byte, maxDigits uint, maybeDecimalDigits *uint) (float64, error) { f, err := strconv.ParseFloat(string(b), 64) if err != nil { return 0, err } if b[0] == '-' { b = b[1:] } if b[0] == '.' { b = append([]byte("0"), b...) } i := bytes.IndexRune(b, '.') decimalDigits := maxDigits - 1 if maybeDecimalDigits != nil && *maybeDecimalDigits < maxDigits { decimalDigits = *maybeDecimalDigits } m := uint(len(b) - 1) if uint(len(b)-1) > maxDigits { return 0, fmt.Errorf("max digits should be less than %d, but got %d", decimalDigits, m) } if i != -1 { d := uint(len(b) - i - 1) if d > decimalDigits { return 0, fmt.Errorf("decimal digits should be less than %d, but got %d", decimalDigits, d) } } return f, nil } func (validator *FloatValidator) String() string { validator.SetDefaults() rule := rules.NewRule(validator.Names()[0]) decimalDigits := *validator.DecimalDigits rule.Params = []rules.RuleNode{ rules.NewRuleLit([]byte(strconv.Itoa(int(validator.MaxDigits)))), rules.NewRuleLit([]byte(strconv.Itoa(int(decimalDigits)))), } if validator.Minimum != nil || validator.Maximum != nil { rule.Range = make([]*rules.RuleLit, 2) if validator.Minimum != nil { rule.Range[0] = rules.NewRuleLit( []byte(fmt.Sprintf("%."+strconv.Itoa(int(decimalDigits))+"f", *validator.Minimum)), ) } if validator.Maximum != nil { rule.Range[1] = rules.NewRuleLit( []byte(fmt.Sprintf("%."+strconv.Itoa(int(decimalDigits))+"f", *validator.Maximum)), ) } rule.ExclusiveLeft = validator.ExclusiveMinimum rule.ExclusiveRight = validator.ExclusiveMaximum } if validator.MultipleOf != 0 { rule.Values = []*rules.RuleLit{ rules.NewRuleLit([]byte("%" + fmt.Sprintf("%."+strconv.Itoa(int(decimalDigits))+"f", validator.MultipleOf))), } } else if validator.Enums != nil { for _, str := range validator.Enums { rule.Values = append(rule.Values, rules.NewRuleLit([]byte(str))) } } return string(rule.Bytes()) }
float_validator.go
0.651687
0.460713
float_validator.go
starcoder
package evo import "math" // A Network provides the ability to process a set of inputs and returns the outputs type Network interface { Activate(Matrix) (Matrix, error) } // Neuron is the type of neuron to create within the network type Neuron byte // Complete list of neuron types const ( Input Neuron = iota + 1 Hidden Output ) func (n Neuron) String() string { switch n { case Input: return "input" case Hidden: return "hidden" case Output: return "output" default: return "unknown" } } // Activation is the type of activation function to use with the neuron type Activation byte // Known list of activation types const ( Direct Activation = iota + 1 Sigmoid SteepenedSigmoid Tanh InverseAbs // Also known as soft sign Sin Gauss ReLU ) func (a Activation) String() string { switch a { case Direct: return "direct" case Sigmoid: return "sigmoid" case SteepenedSigmoid: return "steepened-sigmoid" case Tanh: return "tanh" case InverseAbs: return "inverse-abs" case Sin: return "sin" case Gauss: return "gauss" case ReLU: return "relu" default: return "unknown" } } // Activate the neuron using the appropriate transformation function. func (a Activation) Activate(x float64) float64 { switch a { case Direct: return x case Sigmoid: return 1.0 / (1.0 + math.Exp(-x)) case SteepenedSigmoid: return 1.0 / (1.0 + math.Exp(-4.9*x)) case Tanh: return math.Tanh(x) case InverseAbs: return x / (1.0 + math.Abs(x)) case Sin: return math.Sin(x) case Gauss: return math.Exp(-2.0 * x * x) case ReLU: if x > 0 { return x } return 0 default: panic("unknown activation") } } // Activations provides map of activation functions by name var Activations = map[string]Activation{ "direct": Direct, "sigmoid": Sigmoid, "steepened-sigmoid": SteepenedSigmoid, "tanh": Tanh, "inverse-abs": InverseAbs, "sin": Sin, "gauss": Gauss, "relu": ReLU, }
network.go
0.752195
0.581065
network.go
starcoder
package async import ( "reflect" ) /* Map allows you to manipulate data in a slice in Waterfall mode. Each Routine will be called with the value and index of the current position in the slice. When calling the Done function, an error will cause the mapping to immediately exit. All other arguments are sent back as the replacement for the current value. For example, take a look at one of the tests for this function: func TestMapInt(t *testing.T) { ints := []int{1, 2, 3, 4, 5} expects := []int{2, 4, 6, 8, 10} mapper := func(done async.Done, args ...interface{}) { Status("Hit int") Status("Args: %+v\n", args) done(nil, args[0].(int)*2) } final := func(err error, results ...interface{}) { Status("Hit int end") Status("Results: %+v\n", results) for i := 0; i < len(results); i++ { if results[i] != expects[i] { t.Errorf("Did not map correctly.") break } } } async.Map(ints, mapper, final) } */ func Map(data interface{}, routine Routine, callbacks ...Done) { var ( routines []Routine results []interface{} ) d := reflect.ValueOf(data) for i := 0; i < d.Len(); i++ { v := d.Index(i).Interface() routines = append(routines, func(id int) Routine { return func(done Done, args ...interface{}) { done = func(original Done) Done { return func(err error, args ...interface{}) { results = append(results, args...) if id == (d.Len() - 1) { original(err, results...) return } original(err, args...) } }(done) routine(done, v, id) } }(i)) } Waterfall(routines, callbacks...) } /* MapParallel allows you to manipulate data in a slice in Parallel mode. Each Routine will be called with the value and index of the current position in the slice. When calling the Done function, arguments are sent back as the replacement for the current value. If there is an error, any further results will be discarded but it will not immediately exit. It will continue to run all of the other Routine functions that were passed into it. This is because by the time the error is sent, the goroutines have already been started. At this current time, there is no way to cancel a sleep timer in Go. For example, take a look at one of the tests for this function: func TestMapStringParallel(t *testing.T) { str := []string{ "test", "test2", "test3", "test4", "test5", } expects := []string{ "test1", "test2", "test3", "test4", "test5", } mapper := func(done async.Done, args ...interface{}) { Status("Hit string") Status("Args: %+v\n", args) if args[1] == 0 { done(nil, "test1") return } done(nil, args[0]) } final := func(err error, results ...interface{}) { Status("Hit string end") Status("Results: %+v\n", results) for i := 0; i < len(results); i++ { if results[i] != expects[i] { t.Errorf("Did not map correctly.") break } } } async.MapParallel(str, mapper, final) } The output of mapping in Parallel mode cannot be guaranteed to stay in the same order, due to the fact that it may take longer to process some things in your map routine. If you need the data to stay in the order it is in, use Map instead to ensure it stays in order. */ func MapParallel(data interface{}, routine Routine, callbacks ...Done) { var routines []Routine d := reflect.ValueOf(data) for i := 0; i < d.Len(); i++ { v := d.Index(i).Interface() routines = append(routines, func(id int) Routine { return func(done Done, args ...interface{}) { routine(done, v, id) } }(i)) } Parallel(routines, callbacks...) }
map.go
0.657648
0.502319
map.go
starcoder
package mysql import ( "context" "errors" "testing" "time" sushiapi "github.com/sergiorra/sushi-api-go/pkg" "github.com/DATA-DOG/go-sqlmock" _ "github.com/lib/pq" "github.com/stretchr/testify/assert" ) func Test_SushiRepository_CreateSushi_RepositoryError(t *testing.T) { sushi := buildSushi() db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectExec( "INSERT INTO sushis (id, image_number, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"). WithArgs(sushi.ID, sushi.ImageNumber, sushi.Name, sushi.CreatedAt, sushi.UpdatedAt). WillReturnError(errors.New("database failed")) repo := NewRepository("sushis", db) err = repo.CreateSushi(context.Background(), &sushi) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_CreateSushi_Success(t *testing.T) { sushi := buildSushi() db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectExec( "INSERT INTO sushis (id, image_number, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"). WithArgs(sushi.ID, sushi.ImageNumber, sushi.Name, sushi.CreatedAt, sushi.UpdatedAt). WillReturnResult(sqlmock.NewResult(1, 1)) repo := NewRepository("sushis", db) err = repo.CreateSushi(context.Background(), &sushi) assert.NoError(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_GetSushis_RepositoryError(t *testing.T) { db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis"). WillReturnError(errors.New("something-failed")) repo := NewRepository("sushis", db) _, err = repo.GetSushis(context.Background()) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_GetSushis_NoRows(t *testing.T) { db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis"). WillReturnRows(sqlmock.NewRows( []string{"id", "image_number", "name", "created_at", "updated_at"}), ) repo := NewRepository("sushis", db) sushis, err := repo.GetSushis(context.Background()) assert.NoError(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) assert.Len(t, sushis, 0) } func Test_SushiRepository_GetSushis_RowWithInvalidData(t *testing.T) { db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis"). WillReturnRows(sqlmock.NewRows( []string{"id", "image_number", "name", "created_at", "updated_at"}). AddRow(nil, nil, nil, nil, nil), // This is a row failure as the data type is wrong ) repo := NewRepository("sushis", db) _, err = repo.GetSushis(context.Background()) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_GetSushis_Succeeded(t *testing.T) { expectedSushis := []sushiapi.Sushi{ buildSushi(), buildSushi(), } db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis"). WillReturnRows(sqlmock.NewRows( []string{"id", "image_number", "name", "created_at", "updated_at"}). AddRow(expectedSushis[0].ID, expectedSushis[0].ImageNumber, expectedSushis[0].Name, expectedSushis[0].CreatedAt, expectedSushis[0].UpdatedAt). AddRow(expectedSushis[1].ID, expectedSushis[1].ImageNumber, expectedSushis[1].Name, expectedSushis[1].CreatedAt, expectedSushis[1].UpdatedAt), ) repo := NewRepository("sushis", db) sushis, err := repo.GetSushis(context.Background()) assert.NoError(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) assert.Equal(t, expectedSushis, sushis) } func Test_SushiRepository_DeleteSushi_RepositoryError(t *testing.T) { sushiID := "1" db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectExec( "DELETE FROM sushis WHERE id = ?"). WithArgs(sushiID). WillReturnError(errors.New("database failed")) repo := NewRepository("sushis", db) err = repo.DeleteSushi(context.Background(), sushiID) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_DeleteSushi_Success(t *testing.T) { sushiID := "1" db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectExec( "DELETE FROM sushis WHERE id = ?"). WithArgs(sushiID). WillReturnResult(sqlmock.NewResult(1, 1)) repo := NewRepository("sushis", db) err = repo.DeleteSushi(context.Background(), sushiID) assert.NoError(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_UpdateSushi_RepositoryError(t *testing.T) { sushi := buildSushi() db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectExec( "UPDATE sushis SET id = ?, image_number = ?, name = ?, created_at = ?, updated_at = ? WHERE id = ?"). WithArgs(sushi.ID, sushi.ImageNumber, sushi.Name, sushi.CreatedAt, sushi.UpdatedAt, sushi.ID). WillReturnError(errors.New("database failed")) repo := NewRepository("sushis", db) err = repo.UpdateSushi(context.Background(), sushi.ID, &sushi) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_UpdateSushi_NotFound(t *testing.T) { sushi := buildSushi() db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectExec( "UPDATE sushis SET id = ?, image_number = ?, name = ?, created_at = ?, updated_at = ? WHERE id = ?"). WithArgs(sushi.ID, sushi.ImageNumber, sushi.Name, sushi.CreatedAt, sushi.UpdatedAt, sushi.ID). WillReturnResult(sqlmock.NewResult(0, 0)) repo := NewRepository("sushis", db) err = repo.UpdateSushi(context.Background(), sushi.ID, &sushi) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_UpdateSushi_Success(t *testing.T) { sushi := buildSushi() db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectExec( "UPDATE sushis SET id = ?, image_number = ?, name = ?, created_at = ?, updated_at = ? WHERE id = ?"). WithArgs(sushi.ID, sushi.ImageNumber, sushi.Name, sushi.CreatedAt, sushi.UpdatedAt, sushi.ID). WillReturnResult(sqlmock.NewResult(1, 1)) repo := NewRepository("sushis", db) err = repo.UpdateSushi(context.Background(), sushi.ID, &sushi) assert.NoError(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_GetSushiByID_RepositoryError(t *testing.T) { sushiID := "1" db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis WHERE id = ?"). WithArgs(sushiID). WillReturnError(errors.New("something-failed")) repo := NewRepository("sushis", db) _, err = repo.GetSushiByID(context.Background(), sushiID) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_GetSushiByID_NoRows(t *testing.T) { sushiID := "1" db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis WHERE id = ?"). WithArgs(sushiID). WillReturnRows(sqlmock.NewRows( []string{"id", "image_number", "name", "created_at", "updated_at"}), ) repo := NewRepository("sushis", db) _, err = repo.GetSushiByID(context.Background(), sushiID) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_GetSushiByID_RowWithInvalidData(t *testing.T) { sushiID := "1" db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis WHERE id = ?"). WillReturnRows(sqlmock.NewRows( []string{"id", "image_number", "name", "created_at", "updated_at"}). AddRow(nil, nil, nil, nil, nil), // This is a row failure as the data type is wrong ) repo := NewRepository("sushis", db) _, err = repo.GetSushiByID(context.Background(), sushiID) assert.Error(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) } func Test_SushiRepository_GetSushiByID_Succeeded(t *testing.T) { expectedSushi := buildSushi() db, sqlMock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual)) if err != nil { assert.NoError(t, err) } sqlMock.ExpectQuery( "SELECT sushis.id, sushis.image_number, sushis.name, sushis.created_at, sushis.updated_at FROM sushis WHERE id = ?", ). WithArgs(expectedSushi.ID). WillReturnRows(sqlmock.NewRows( []string{"id", "image_number", "name", "created_at", "updated_at"}). AddRow(expectedSushi.ID, expectedSushi.ImageNumber, expectedSushi.Name, expectedSushi.CreatedAt, expectedSushi.UpdatedAt), ) repo := NewRepository("sushis", db) sushi, err := repo.GetSushiByID(context.Background(), expectedSushi.ID) assert.NoError(t, err) assert.NoError(t, sqlMock.ExpectationsWereMet()) assert.Equal(t, &expectedSushi, sushi) } func buildSushi() sushiapi.Sushi { now := time.Now() return sushiapi.Sushi{ ID: "123ABC", ImageNumber: "Test_image", Name: "Test_name", CreatedAt: &now, UpdatedAt: &now, } }
pkg/storage/mysql/repository_text.go
0.529263
0.409752
repository_text.go
starcoder
// Code has been adapted from Go standard time package. // Copyright 2009 The Go Authors. All rights reserved. //go:generate stringer -type=Weekday,Month // Package date implements support for Gregorian date, following ISO 8601 // standard. package date import ( "time" ) // A Duration represents the elapsed time between two dates as an int32 day count. type Duration int32 const ( Day Duration = 1 Week Duration = 7 ) // A Weekday specifies a day of the week, as per ISO 8601 (Monday = 1, ...). type Weekday int const ( Monday Weekday = 1 + iota Tuesday Wednesday Thursday Friday Saturday Sunday ) // A Month specifies a month of the year (January = 1, ...). type Month int const ( January Month = 1 + iota February March April May June July August September October November December ) // These are predefined layouts for use in Date.Format and Date.Parse. // The reference time used in the layouts is the specific date: // Mon Jan 2 2006 const ( ANSIC = "Mon Jan _2 2006" RFC822 = "02 Jan 06" RFC850 = "Monday, 02-Jan-06" RFC1123 = "Mon, 02 Jan 2006" RFC3339 = "2006-01-02" ) // A Date represents a Gregorian date. type Date struct { // The implementation uses time.Time to keep code simple; it should be // int64. tm time.Time } // New returns the Date corresponding to yyyy-mm-dd. func New(year int, month Month, day int) Date { tm := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) return Date{tm} } // newFromTime returns the Date in witch t occurs. func newFromTime(t time.Time) Date { year, month, day := t.Date() return New(year, Month(month), day) } // Today returns the current date. func Today() Date { tm := time.Now() return newFromTime(tm) } // Parse parses a formatted string and returns the date value it represents. // The layout defines the format by showing how the reference date, defined to be // Mon Jan 2 2006 // would be interpreted if it were the value. func Parse(layout, value string) (Date, error) { tm, err := time.Parse(layout, value) if err != nil { return Date{}, err } return newFromTime(tm), nil } // Format returns a textual representation of the date value formatted // according to layout, which defines the format by showing how the reference // date, defined to be // Mon Jan 2 2006 // would be displayed if it were the value. func (d Date) Format(layout string) string { return d.tm.Format(layout) } // Time returns the Time when the midnight of d occurs, in UTC. func (d Date) Time() time.Time { return d.tm } // String returns an RFC3339/ISO-8601 date string, of the form "2006-01-02". func (d Date) String() string { return d.Format(RFC3339) } // After reports whether the date d is after u. func (d Date) After(u Date) bool { return d.tm.After(u.tm) } // Before reports whether the date d is before u. func (d Date) Before(u Date) bool { return d.tm.Before(u.tm) } // Equal reports whether d and u represent the same date. func (d Date) Equal(u Date) bool { return d.tm.Equal(u.tm) } // IsZero reports whether d represents the zero date, // January 1, year 1. func (d Date) IsZero() bool { return d.tm.IsZero() } // Add returns the date d + dd. func (d Date) Add(dd Duration) Date { tm := d.tm.Add(time.Duration(dd) * 24 * time.Hour) return newFromTime(tm) } // AddDate returns the date corresponding to adding the given number of years, // months, and days to d. func (d Date) AddDate(years int, months int, days int) Date { tm := d.tm.AddDate(years, months, days) return newFromTime(tm) } // Date returns the year, month, and day of d. func (d Date) Date() (year int, month Month, day int) { yy, mm, dd := d.tm.Date() return yy, Month(mm), dd } // Year returns the year of d. func (d Date) Year() int { return d.tm.Year() } // Month returns the month of the year specified by d. func (d Date) Month() Month { return Month(d.tm.Month()) } // Day returns the day of the month specified by d. func (d Date) Day() int { return d.tm.Day() } // Weekday returns the day of the week specified by d. func (d Date) Weekday() Weekday { return Weekday((d.tm.Weekday() + 6) % 7) } // Week returns the week number specified by d. func (d Date) Week() int { _, week := d.tm.ISOWeek() return week }
date.go
0.81946
0.44553
date.go
starcoder
// Package intree provides a very fast, static, flat, augmented interval tree for reverse range searches. package intree import ( "math" "math/rand" ) // Bounds is the main interface expected by NewINTree(); requires Limits method to access interval limits. type Bounds interface { Limits() (lower, upper float64) } // ValuedBounds is the main interface expected by NewINTreeV(), acting as a wrapper for Bounds. // Expects the Value() method for retrieving a value associated with the given boundaries type ValuedBounds interface { Bounds Value() interface{} } // INTree is the main package object; // holds Slice of reference indices and the respective interval limits. type INTree struct { indexes []int limits []float64 } // NewINTree is the main initialization function; // creates the tree from the given Slice of Bounds. func NewINTree(bounds []Bounds) *INTree { tree := INTree{} tree.buildTree(bounds) return &tree } // NewINTreeV is the main initialization function; // creates the tree from the given Slice of ValuedBounds. func NewINTreeV(bounds []ValuedBounds) *INTree { tree := INTree{} tree.buildTreeV(bounds) return &tree } // buildTree is the internal tree construction function; // creates, sorts and augments nodes into Slices. func (t *INTree) buildTree(bounds []Bounds) { t.indexes = make([]int, len(bounds)) t.limits = make([]float64, 3*len(bounds)) for i, v := range bounds { t.indexes[i] = i l, u := v.Limits() t.limits[3*i] = l t.limits[3*i+1] = u t.limits[3*i+2] = 0 } sort(t.limits, t.indexes) augment(t.limits, t.indexes) } // buildTreeV is the internal tree construction function for ValuedBounds; // creates, sorts and augments nodes into Slices. func (t *INTree) buildTreeV(bounds []ValuedBounds) { t.indexes = make([]int, len(bounds)) t.limits = make([]float64, 3*len(bounds)) for i, v := range bounds { t.indexes[i] = i l, u := v.Limits() t.limits[3*i] = l t.limits[3*i+1] = u t.limits[3*i+2] = 0 } sort(t.limits, t.indexes) augment(t.limits, t.indexes) } // Including is the main entry point for bounds searches; // traverses the tree and collects intervals that overlap with the given value. func (t *INTree) Including(val float64) []int { idxStock := []int{0, len(t.indexes) - 1} result := []int{} for len(idxStock) > 0 { // Retrieve right and left boundaries from index stock rBoundIdx := idxStock[len(idxStock)-1] idxStock = idxStock[:len(idxStock)-1] lBoundIdx := idxStock[len(idxStock)-1] idxStock = idxStock[:len(idxStock)-1] if lBoundIdx == rBoundIdx+1 { continue } centerIdx := int(math.Ceil(float64(lBoundIdx+rBoundIdx) / 2.0)) lowerLimit := t.limits[3*centerIdx+2] if val <= lowerLimit { idxStock = append(idxStock, lBoundIdx, centerIdx-1) } l := t.limits[3*centerIdx] if l <= val { idxStock = append(idxStock, centerIdx+1, rBoundIdx) upperLimit := t.limits[3*centerIdx+1] if val <= upperLimit { result = append(result, t.indexes[centerIdx]) } } } return result } // augment is an internal utility function, adding maximum value of all child nodes to the current node. func augment(limits []float64, indexes []int) { if len(indexes) < 1 { return } max := 0.0 for idx := range indexes { if limits[3*idx+1] > max { max = limits[3*idx+1] } } r := len(indexes) >> 1 limits[3*r+2] = max augment(limits[:3*r], indexes[:r]) augment(limits[3*r+3:], indexes[r+1:]) } // sort is an internal utility function, sorting the tree by lowest limits using Random Pivot QuickSearch func sort(limits []float64, indexes []int) { if len(indexes) < 2 { return } // Pick index bounds l, r := 0, len(indexes)-1 // Pick pivot p := rand.Int() % len(indexes) // Perform in-place assignment of limits and indexes indexes[p], indexes[r] = indexes[r], indexes[p] limits[3*p], limits[3*p+1], limits[3*p+2], limits[3*r], limits[3*r+1], limits[3*r+2] = limits[3*r], limits[3*r+1], limits[3*r+2], limits[3*p], limits[3*p+1], limits[3*p+2] for i := range indexes { if limits[3*i] < limits[3*r] { // Perform in-place assignment of limits and indexes indexes[l], indexes[i] = indexes[i], indexes[l] limits[3*l], limits[3*l+1], limits[3*l+2], limits[3*i], limits[3*i+1], limits[3*i+2] = limits[3*i], limits[3*i+1], limits[3*i+2], limits[3*l], limits[3*l+1], limits[3*l+2] l++ } } // Perform in-place assignment of limits and indexes indexes[l], indexes[r] = indexes[r], indexes[l] limits[3*l], limits[3*l+1], limits[3*l+2], limits[3*r], limits[3*r+1], limits[3*r+2] = limits[3*r], limits[3*r+1], limits[3*r+2], limits[3*l], limits[3*l+1], limits[3*l+2] // Tail recursive calls on branches sort(limits[:3*l], indexes[:l]) sort(limits[3*l+3:], indexes[l+1:]) }
intree.go
0.776665
0.641493
intree.go
starcoder
package layout import ( "image" "github.com/gop9/olt/gio/op" "github.com/gop9/olt/gio/unit" ) // Constraints represent a set of acceptable ranges for // a widget's width and height. type Constraints struct { Width Constraint Height Constraint } // Constraint is a range of acceptable sizes in a single // dimension. type Constraint struct { Min, Max int } // Dimensions are the resolved size and baseline for a widget. type Dimensions struct { Size image.Point Baseline int } // Axis is the Horizontal or Vertical direction. type Axis uint8 // Alignment is the mutual alignment of a list of widgets. type Alignment uint8 // Direction is the alignment of widgets relative to a containing // space. type Direction uint8 // Widget is a function scope for drawing, processing events and // computing dimensions for a user interface element. type Widget func() const ( Start Alignment = iota End Middle Baseline ) const ( NW Direction = iota N NE E SE S SW W Center ) const ( Horizontal Axis = iota Vertical ) // Constrain a value to the range [Min; Max]. func (c Constraint) Constrain(v int) int { if v < c.Min { return c.Min } else if v > c.Max { return c.Max } return v } // Constrain a size to the Width and Height ranges. func (c Constraints) Constrain(size image.Point) image.Point { return image.Point{X: c.Width.Constrain(size.X), Y: c.Height.Constrain(size.Y)} } // RigidConstraints returns the constraints that can only be // satisfied by the given dimensions. func RigidConstraints(size image.Point) Constraints { return Constraints{ Width: Constraint{Min: size.X, Max: size.X}, Height: Constraint{Min: size.Y, Max: size.Y}, } } // Inset adds space around a widget. type Inset struct { Top, Right, Bottom, Left unit.Value } // Align aligns a widget in the available space. type Align Direction // Layout a widget. func (in Inset) Layout(gtx *Context, w Widget) { top := gtx.Px(in.Top) right := gtx.Px(in.Right) bottom := gtx.Px(in.Bottom) left := gtx.Px(in.Left) mcs := gtx.Constraints mcs.Width.Max -= left + right if mcs.Width.Max < 0 { left = 0 right = 0 mcs.Width.Max = 0 } if mcs.Width.Min > mcs.Width.Max { mcs.Width.Min = mcs.Width.Max } mcs.Height.Max -= top + bottom if mcs.Height.Max < 0 { bottom = 0 top = 0 mcs.Height.Max = 0 } if mcs.Height.Min > mcs.Height.Max { mcs.Height.Min = mcs.Height.Max } var stack op.StackOp stack.Push(gtx.Ops) op.TransformOp{}.Offset(toPointF(image.Point{X: left, Y: top})).Add(gtx.Ops) dims := ctxLayout(gtx, mcs, w) stack.Pop() gtx.Dimensions = Dimensions{ Size: dims.Size.Add(image.Point{X: right + left, Y: top + bottom}), Baseline: dims.Baseline + bottom, } } // UniformInset returns an Inset with a single inset applied to all // edges. func UniformInset(v unit.Value) Inset { return Inset{Top: v, Right: v, Bottom: v, Left: v} } // Layout a widget. func (a Align) Layout(gtx *Context, w Widget) { var macro op.MacroOp macro.Record(gtx.Ops) cs := gtx.Constraints mcs := cs mcs.Width.Min = 0 mcs.Height.Min = 0 dims := ctxLayout(gtx, mcs, w) macro.Stop() sz := dims.Size if sz.X < cs.Width.Min { sz.X = cs.Width.Min } if sz.Y < cs.Height.Min { sz.Y = cs.Height.Min } var p image.Point switch Direction(a) { case N, S, Center: p.X = (sz.X - dims.Size.X) / 2 case NE, SE, E: p.X = sz.X - dims.Size.X } switch Direction(a) { case W, Center, E: p.Y = (sz.Y - dims.Size.Y) / 2 case SW, S, SE: p.Y = sz.Y - dims.Size.Y } var stack op.StackOp stack.Push(gtx.Ops) op.TransformOp{}.Offset(toPointF(p)).Add(gtx.Ops) macro.Add() stack.Pop() gtx.Dimensions = Dimensions{ Size: sz, Baseline: dims.Baseline + sz.Y - dims.Size.Y - p.Y, } } func (a Alignment) String() string { switch a { case Start: return "Start" case End: return "End" case Middle: return "Middle" case Baseline: return "Baseline" default: panic("unreachable") } } func (a Axis) String() string { switch a { case Horizontal: return "Horizontal" case Vertical: return "Vertical" default: panic("unreachable") } } func (d Direction) String() string { switch d { case NW: return "NW" case N: return "N" case NE: return "NE" case E: return "E" case SE: return "SE" case S: return "S" case SW: return "SW" case W: return "W" case Center: return "Center" default: panic("unreachable") } }
gio/layout/layout.go
0.72086
0.474692
layout.go
starcoder
package merger import "github.com/suggest-go/suggest/pkg/utils" // MaxOverlap is the largest value of an overlap count for a merge candidate const MaxOverlap = 0xFFFF // ListMerger solves `threshold`-occurrence problem: // For given inverted lists find the set of strings ids, that appears at least // `threshold` times. type ListMerger interface { // Merge returns list of candidates, that appears at least `threshold` times. Merge(rid Rid, threshold int, collector Collector) error } // Rid represents inverted lists for ListMerger type Rid []ListIterator // Len is the number of elements in the collection. func (p Rid) Len() int { return len(p) } // Less reports whether the element with // index i should sort before the element with index j. func (p Rid) Less(i, j int) bool { return p[i].Len() < p[j].Len() } // Swap swaps the elements with indexes i and j. func (p Rid) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // MergeCandidate is result of merging Rid type MergeCandidate uint64 // NewMergeCandidate creates a new instance of MergeCandidate func NewMergeCandidate(position, overlap uint32) MergeCandidate { return MergeCandidate(utils.Pack(position, overlap)) } // Position returns the given position of the candidate func (m MergeCandidate) Position() uint32 { return utils.UnpackLeft(uint64(m)) } // Overlap returns the current overlap count of the candidate func (m MergeCandidate) Overlap() int { return int(utils.UnpackRight(uint64(m))) } // increment increments the overlap value of the candidate func (m *MergeCandidate) increment() { if overlap := utils.UnpackRight(uint64(*m)); overlap == MaxOverlap { panic("overlap overflow") } *m++ } // mergerOptimizer internal merger that is aimed to optimize merge workflow type mergerOptimizer struct { merger ListMerger intersector ListIntersector } func newMerger(merger ListMerger) ListMerger { return &mergerOptimizer{ merger: merger, intersector: Intersector(), } } // Merge returns list of candidates, that appears at least `threshold` times. func (m *mergerOptimizer) Merge(rid Rid, threshold int, collector Collector) error { n := len(rid) if n < threshold || n == 0 { return nil } if n == threshold { return m.intersector.Intersect(rid, collector) } return m.merger.Merge(rid, threshold, collector) }
pkg/merger/list_merger.go
0.855685
0.575588
list_merger.go
starcoder
package deepcopy import ( "reflect" "github.com/sirupsen/logrus" ) // MergeInterface can be implemented by types to have custom deep copy logic. type MergeInterface interface { Merge(interface{}) interface{} } // Merge returns a merge of x and y. // Supports everything except Chan, Func and UnsafePointer. func Merge(x interface{}, y interface{}) interface{} { return mergeRecursively(reflect.ValueOf(DeepCopy(x)), reflect.ValueOf(DeepCopy(y))).Interface() } func mergeRecursively(xV reflect.Value, yV reflect.Value) reflect.Value { if !yV.IsValid() { logrus.Debugf("invalid value given to merge recursively value: %+v", yV) return xV } if !xV.IsValid() { logrus.Debugf("invalid value given to merge recursively value: %+v", xV) return yV } xT := xV.Type() xK := xV.Kind() yK := yV.Kind() if xK != yK { logrus.Debugf("Unable to merge due to varying types : %s & %s", xK, yK) return yV } if xV.CanInterface() { if mergable, ok := xV.Interface().(MergeInterface); ok { nV := reflect.ValueOf(mergable.Merge(yV.Interface())) if !nV.IsValid() { return yV } return nV } } switch xK { case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String: return yV case reflect.Array, reflect.Slice: nV := reflect.MakeSlice(xT, xV.Len()+yV.Len(), xV.Cap()+yV.Cap()) itemsYetToBeMerged := map[int]bool{} for i := 0; i < yV.Len(); i++ { itemsYetToBeMerged[i] = true } for i := 0; i < xV.Len(); i++ { merged := false for j := 0; j < yV.Len(); j++ { if compare(xV.Index(i), yV.Index(j)) { nV.Index(i).Set(mergeRecursively(xV.Index(i), yV.Index(j))) merged = true itemsYetToBeMerged[j] = false break } } if !merged { nV.Index(i).Set(copyRecursively(xV.Index(i))) } } for i := 0; i < yV.Len(); i++ { if itemsYetToBeMerged[i] { nV.Index(xV.Len() + i).Set(copyRecursively(yV.Index(i))) } } return nV case reflect.Interface: return mergeRecursively(xV.Elem(), yV.Elem()) case reflect.Map: nV := reflect.MakeMapWithSize(xT, xV.Len()+yV.Len()) for _, key := range xV.MapKeys() { if yV.MapIndex(key) == reflect.Zero(reflect.TypeOf(xV)).Interface() { nV.SetMapIndex(copyRecursively(key), copyRecursively(xV.MapIndex(key))) continue } nV.SetMapIndex(copyRecursively(key), mergeRecursively(xV.MapIndex(key), yV.MapIndex(key))) } for _, key := range yV.MapKeys() { if xV.MapIndex(key) == reflect.Zero(reflect.TypeOf(yV)).Interface() { nV.SetMapIndex(copyRecursively(key), copyRecursively(yV.MapIndex(key))) continue } nV.SetMapIndex(copyRecursively(key), mergeRecursively(xV.MapIndex(key), yV.MapIndex(key))) } return nV case reflect.Ptr: if xV.IsNil() { return xV } nV := reflect.New(xV.Elem().Type()) nV.Elem().Set(mergeRecursively(xV.Elem(), yV.Elem())) return yV case reflect.Struct: nV := reflect.New(xT).Elem() for i := 0; i < xV.NumField(); i++ { if !nV.Field(i).CanSet() { continue } nV.Field(i).Set(mergeRecursively(xV.Field(i), yV.Field(i))) } return nV default: logrus.Debugf("unsupported for deep copy kind: %+v type: %+v value: %+v", xK, xT, xV) return xV } } // CompareInterface can be implemented by types to have custom deep copy logic. type CompareInterface interface { Compare(interface{}, interface{}) bool } func compare(xV reflect.Value, yV reflect.Value) bool { if !yV.IsValid() { logrus.Debugf("invalid value given to merge recursively value: %+v", yV) return false } if !xV.IsValid() { logrus.Debugf("invalid value given to merge recursively value: %+v", xV) return false } xT := xV.Type() xK := xV.Kind() yK := yV.Kind() if xK != yK { logrus.Debugf("Unable to merge due to varying types : %s & %s", xK, yK) return false } if xV.CanInterface() { if comparable, ok := xV.Interface().(CompareInterface); ok { return comparable.Compare(xV.Interface(), yV.Interface()) } } switch xK { case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String: return xV == yV case reflect.Array: // TODO: Check this is the required behaviour return true case reflect.Slice: // TODO: Check this is the required behaviour return true case reflect.Interface: return compare(xV.Elem(), yV.Elem()) case reflect.Map: // TODO: Check this is the required behaviour return true case reflect.Ptr: return compare(xV.Elem(), yV.Elem()) case reflect.Struct: nV := reflect.New(xT).Elem() for i := 0; i < xV.NumField(); i++ { if nV.Type().Field(i).Name == "name" || nV.Type().Field(i).Name == "id" { return compare(xV.Field(i), yV.Field(i)) } } return true default: logrus.Debugf("unsupported for deep compare kind: %+v type: %+v value: %+v", xK, xT, xV) return true } }
common/deepcopy/merge.go
0.538498
0.480418
merge.go
starcoder
package ast import ( "fmt" "path/filepath" "strings" "github.com/Konstantin8105/c4go/util" ) // Position is type of position in source code type Position struct { File string // The relative or absolute file path. Line int // Start line LineEnd int // End line Column int // Start column ColumnEnd int // End column // This is the original string that was converted. This is used for // debugging. We could derive this value from the other properties to save // on a bit of memory, but let worry about that later. StringValue string } // GetSimpleLocation - return a string like : "file:line" in // according to position // Example : " /tmp/1.c:200 " func (p Position) GetSimpleLocation() (loc string) { file := p.File if f, err := filepath.Abs(p.File); err != nil { file = f } return fmt.Sprintf(" %s:%d ", file, p.Line) } // NewPositionFromString create a Position from string line func NewPositionFromString(s string) Position { if strings.Contains(s, "<invalid sloc>") || s == "" { return Position{} } re := util.GetRegex(`^col:(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Column: util.Atoi(groups[1]), } } re = util.GetRegex(`^col:(\d+), col:(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Column: util.Atoi(groups[1]), ColumnEnd: util.Atoi(groups[2]), } } re = util.GetRegex(`^line:(\d+), line:(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Line: util.Atoi(groups[1]), LineEnd: util.Atoi(groups[2]), } } re = util.GetRegex(`^col:(\d+), line:(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Column: util.Atoi(groups[1]), Line: util.Atoi(groups[2]), } } re = util.GetRegex(`^line:(\d+):(\d+), line:(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Line: util.Atoi(groups[1]), Column: util.Atoi(groups[2]), LineEnd: util.Atoi(groups[3]), ColumnEnd: util.Atoi(groups[4]), } } re = util.GetRegex(`^col:(\d+), line:(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Column: util.Atoi(groups[1]), LineEnd: util.Atoi(groups[2]), ColumnEnd: util.Atoi(groups[3]), } } re = util.GetRegex(`^line:(\d+):(\d+), col:(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Line: util.Atoi(groups[1]), Column: util.Atoi(groups[2]), ColumnEnd: util.Atoi(groups[3]), } } re = util.GetRegex(`^line:(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Line: util.Atoi(groups[1]), Column: util.Atoi(groups[2]), } } // This must be below all of the others. re = util.GetRegex(`^((?:[a-zA-Z]\:)?[^:]+):(\d+):(\d+), col:(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, File: groups[1], Line: util.Atoi(groups[2]), Column: util.Atoi(groups[3]), ColumnEnd: util.Atoi(groups[4]), } } re = util.GetRegex(`^((?:[a-zA-Z]\:)?[^:]+):(\d+):(\d+), line:(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, File: groups[1], Line: util.Atoi(groups[2]), Column: util.Atoi(groups[3]), LineEnd: util.Atoi(groups[4]), ColumnEnd: util.Atoi(groups[5]), } } re = util.GetRegex(`^((?:[a-zA-Z]\:)?[^:]+):(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, File: groups[1], Line: util.Atoi(groups[2]), Column: util.Atoi(groups[3]), } } re = util.GetRegex(`^((?:[a-zA-Z]\:)?[^:]+):(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, File: groups[1], Line: util.Atoi(groups[2]), Column: util.Atoi(groups[3]), } } re = util.GetRegex(`^col:(\d+), ((?:[a-zA-Z]\:)?[^:]+):(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, Column: util.Atoi(groups[1]), } } re = util.GetRegex(`^((?:[a-zA-Z]\:)?[^:]+):(\d+):(\d+), ((?:[a-zA-Z]\:)?[^:]+):(\d+):(\d+)$`) if groups := re.FindStringSubmatch(s); len(groups) > 0 { return Position{ StringValue: s, File: groups[1], Line: util.Atoi(groups[2]), Column: util.Atoi(groups[3]), LineEnd: util.Atoi(groups[5]), ColumnEnd: util.Atoi(groups[6]), } } panic("unable to understand position '" + s + "'") } func mergePositions(p1, p2 Position) Position { if p2.File != "" { p1.File = p2.File p1.Line = 0 p1.LineEnd = 0 p1.Column = 0 p1.ColumnEnd = 0 } if p2.Line != 0 { p1.Line = p2.Line p1.LineEnd = 0 } if p2.LineEnd != 0 { p1.LineEnd = p2.LineEnd } if p2.Column != 0 { p1.Column = p2.Column p1.ColumnEnd = 0 } if p2.ColumnEnd != 0 { p1.ColumnEnd = p2.ColumnEnd } return p1 } // PositionBuiltIn - default value for fix position var PositionBuiltIn = "<built-in>" // FixPositions is fix positions of Nodes func FixPositions(nodes []Node) { pos := Position{File: PositionBuiltIn} fixPositions(nodes, pos) } func fixPositions(nodes []Node, pos Position) { for _, node := range nodes { if node != nil { pos = mergePositions(pos, node.Position()) setPosition(node, pos) fixPositions(node.Children(), pos) } } } func setPosition(node Node, position Position) { switch n := node.(type) { case *AccessSpecDecl: n.Pos = position case *AlignedAttr: n.Pos = position case *AllocSizeAttr: n.Pos = position case *AlwaysInlineAttr: n.Pos = position case *ArraySubscriptExpr: n.Pos = position case *AsmLabelAttr: n.Pos = position case *AvailabilityAttr: n.Pos = position case *BinaryOperator: n.Pos = position case *BlockCommandComment: n.Pos = position case *BreakStmt: n.Pos = position case *C11NoReturnAttr: n.Pos = position case *CallExpr: n.Pos = position case *CaseStmt: n.Pos = position case *CharacterLiteral: n.Pos = position case *CompoundStmt: n.Pos = position case *ConditionalOperator: n.Pos = position case *ConstAttr: n.Pos = position case *ContinueStmt: n.Pos = position case *CompoundAssignOperator: n.Pos = position case *CompoundLiteralExpr: n.Pos = position case *CStyleCastExpr: n.Pos = position case *CXXConstructorDecl: n.Pos = position case *CXXConstructExpr: n.Pos = position case *CXXMethodDecl: n.Pos = position case *CXXMemberCallExpr: n.Pos = position case *CXXRecordDecl: n.Pos = position case *CXXThisExpr: n.Pos = position case *DeclRefExpr: n.Pos = position case *DeclStmt: n.Pos = position case *DefaultStmt: n.Pos = position case *DeprecatedAttr: n.Pos = position case *DisableTailCallsAttr: n.Pos = position case *DoStmt: n.Pos = position case *EmptyDecl: n.Pos = position case *EnumConstantDecl: n.Pos = position case *EnumDecl: n.Pos = position case *FieldDecl: n.Pos = position case *FloatingLiteral: n.Pos = position case *FormatAttr: n.Pos = position case *FormatArgAttr: n.Pos = position case *FullComment: n.Pos = position case *FunctionDecl: n.Pos = position case *ForStmt: n.Pos = position case *GCCAsmStmt: n.Pos = position case *HTMLStartTagComment: n.Pos = position case *HTMLEndTagComment: n.Pos = position case *GotoStmt: n.Pos = position case *IfStmt: n.Pos = position case *ImplicitCastExpr: n.Pos = position case *ImplicitValueInitExpr: n.Pos = position case *IndirectFieldDecl: n.Pos = position case *InitListExpr: n.Pos = position case *InlineCommandComment: n.Pos = position case *IntegerLiteral: n.Pos = position case *LabelStmt: n.Pos = position case *LinkageSpecDecl: n.Pos = position case *MallocAttr: n.Pos = position case *MaxFieldAlignmentAttr: n.Pos = position case *MemberExpr: n.Pos = position case *ModeAttr: n.Pos = position case *NoAliasAttr: n.Pos = position case *NoInlineAttr: n.Pos = position case *NoThrowAttr: n.Pos = position case *NotTailCalledAttr: n.Pos = position case *NonNullAttr: n.Pos = position case *OffsetOfExpr: n.Pos = position case *PackedAttr: n.Pos = position case *ParagraphComment: n.Pos = position case *ParamCommandComment: n.Pos = position case *ParenExpr: n.Pos = position case *ParmVarDecl: n.Pos = position case *PredefinedExpr: n.Pos = position case *PureAttr: n.Pos = position case *RecordDecl: n.Pos = position case *RestrictAttr: n.Pos = position case *ReturnStmt: n.Pos = position case *ReturnsTwiceAttr: n.Pos = position case *SentinelAttr: n.Pos = position case *StmtExpr: n.Pos = position case *StringLiteral: n.Pos = position case *SwitchStmt: n.Pos = position case *TextComment: n.Pos = position case *TransparentUnionAttr: n.Pos = position case *TypedefDecl: n.Pos = position case *UnaryExprOrTypeTraitExpr: n.Pos = position case *UnaryOperator: n.Pos = position case *UnusedAttr: n.Pos = position case *VAArgExpr: n.Pos = position case *VarDecl: n.Pos = position case *VerbatimBlockComment: n.Pos = position case *VerbatimBlockLineComment: n.Pos = position case *VerbatimLineComment: n.Pos = position case *VisibilityAttr: n.Pos = position case *WarnUnusedResultAttr: n.Pos = position case *WeakAttr: n.Pos = position case *WhileStmt: n.Pos = position case *TypedefType, *Typedef, *TranslationUnitDecl, *RecordType, *Record, *QualType, *PointerType, *ParenType, *IncompleteArrayType, *FunctionProtoType, *EnumType, *Enum, *ElaboratedType, *ConstantArrayType, *BuiltinType, *ArrayFiller, *Field, *DecayedType, *CXXRecord, *AttributedType: // These do not have positions so they can be ignored. default: panic(fmt.Sprintf("unknown node type: %+#v", node)) } }
ast/position.go
0.602646
0.50354
position.go
starcoder
package main import ( "fmt" "strconv" "time" "github.com/gdamore/tcell/v2" "github.com/rivo/tview" ) const textView1 = `[green]func[white] [yellow]main[white]() { app := tview.[yellow]NewApplication[white]() textView := tview.[yellow]NewTextView[white](). [yellow]SetTextColor[white](tcell.ColorYellow). [yellow]SetScrollable[white](false). [yellow]SetChangedFunc[white]([yellow]func[white]() { app.[yellow]Draw[white]() }) [green]go[white] [yellow]func[white]() { [green]var[white] n [green]int [white] [yellow]for[white] { n++ fmt.[yellow]Fprintf[white](textView, [red]"%d "[white], n) time.[yellow]Sleep[white]([red]200[white] * time.Millisecond) } }() app.[yellow]SetRoot[white](textView, true). [yellow]Run[white]() }` // TextView1 demonstrates the basic text view. func TextView1(nextSlide func()) (title string, content tview.Primitive) { textView := tview.NewTextView(). SetTextColor(tcell.ColorYellow). SetScrollable(false). SetDoneFunc(func(key tcell.Key) { nextSlide() }) textView.SetChangedFunc(func() { if textView.HasFocus() { app.Draw() } }) go func() { var n int for { if textView.HasFocus() { n++ if n > 512 { n = 1 textView.SetText("") } fmt.Fprintf(textView, "%d ", n) time.Sleep(200 * time.Millisecond) } else { time.Sleep(time.Second) } } }() textView.SetBorder(true).SetTitle("TextView implements io.Writer") return "Text 1", Code(textView, 36, 13, textView1) } const textView2 = `[green]package[white] main [green]import[white] ( [red]"strconv"[white] [red]"github.com/gdamore/tcell/v2"[white] [red]"github.com/rivo/tview"[white] ) [green]func[white] [yellow]main[white]() { ["0"]textView[""] := tview.[yellow]NewTextView[white]() ["1"]textView[""].[yellow]SetDynamicColors[white](true). [yellow]SetWrap[white](false). [yellow]SetRegions[white](true). [yellow]SetDoneFunc[white]([yellow]func[white](key tcell.Key) { highlights := ["2"]textView[""].[yellow]GetHighlights[white]() hasHighlights := [yellow]len[white](highlights) > [red]0 [yellow]switch[white] key { [yellow]case[white] tcell.KeyEnter: [yellow]if[white] hasHighlights { ["3"]textView[""].[yellow]Highlight[white]() } [yellow]else[white] { ["4"]textView[""].[yellow]Highlight[white]([red]"0"[white]). [yellow]ScrollToHighlight[white]() } [yellow]case[white] tcell.KeyTab: [yellow]if[white] hasHighlights { current, _ := strconv.[yellow]Atoi[white](highlights[[red]0[white]]) next := (current + [red]1[white]) % [red]9 ["5"]textView[""].[yellow]Highlight[white](strconv.[yellow]Itoa[white](next)). [yellow]ScrollToHighlight[white]() } [yellow]case[white] tcell.KeyBacktab: [yellow]if[white] hasHighlights { current, _ := strconv.[yellow]Atoi[white](highlights[[red]0[white]]) next := (current - [red]1[white] + [red]9[white]) % [red]9 ["6"]textView[""].[yellow]Highlight[white](strconv.[yellow]Itoa[white](next)). [yellow]ScrollToHighlight[white]() } } }) fmt.[yellow]Fprint[white](["7"]textView[""], content) tview.[yellow]NewApplication[white](). [yellow]SetRoot[white](["8"]textView[""], true). [yellow]Run[white]() }` // TextView2 demonstrates the extended text view. func TextView2(nextSlide func()) (title string, content tview.Primitive) { codeView := tview.NewTextView(). SetWrap(false) fmt.Fprint(codeView, textView2) codeView.SetBorder(true).SetTitle("Buffer content") textView := tview.NewTextView() textView.SetDynamicColors(true). SetWrap(false). SetRegions(true). SetDoneFunc(func(key tcell.Key) { if key == tcell.KeyEscape { nextSlide() return } highlights := textView.GetHighlights() hasHighlights := len(highlights) > 0 switch key { case tcell.KeyEnter: if hasHighlights { textView.Highlight() } else { textView.Highlight("0"). ScrollToHighlight() } case tcell.KeyTab: if hasHighlights { current, _ := strconv.Atoi(highlights[0]) next := (current + 1) % 9 textView.Highlight(strconv.Itoa(next)). ScrollToHighlight() } case tcell.KeyBacktab: if hasHighlights { current, _ := strconv.Atoi(highlights[0]) next := (current - 1 + 9) % 9 textView.Highlight(strconv.Itoa(next)). ScrollToHighlight() } } }) fmt.Fprint(textView, textView2) textView.SetBorder(true).SetTitle("TextView output") return "Text 2", tview.NewFlex(). AddItem(textView, 0, 1, true). AddItem(codeView, 0, 1, false) }
demos/presentation/textview.go
0.567697
0.449574
textview.go
starcoder
package vec import ( "log" "math" ) // Vec is a 3 dimensional vector. // It's represented as a point relative to the origin // So we also use Vec as if they were points. // But it's implementation should be considered as private type Vec struct { X float64 Y float64 Z float64 } // Origin is the point representing the zeo origin in 3D space. Treat it as a const! var Origin = Vec{0, 0, 0} // Distance returns the distance between 2 points in space func (v Vec) Distance(v2 Vec) float64 { return math.Sqrt(math.Pow(v2.X-v.X, 2) + math.Pow(v2.Y-v.Y, 2) + math.Pow(v2.Z-v.Z, 2)) } // Length returns the magnitude of a Vec, or the distance of a Vec from the Origin func (v Vec) Length() float64 { return Origin.Distance(v) } // AsSpherical returns the spherical coordinates of a Point returning length, theta, phi // where theta is the angle from the the x axis in the xy plane and // phi is the angle from the xy plane toward the z axis. func (v Vec) AsSpherical() (m float64, theta float64, phi float64) { m = v.Length() phi = math.Acos(v.Z / m) theta = math.Asin(v.Y / (m * math.Sin(phi))) return } // Minus subtracts a Vec from the receiver Vec and returns a new Vec This is also vector subtraction func (v Vec) Minus(v2 Vec) Vec { x := v.X - v2.X y := v.Y - v2.Y z := v.Z - v2.Z return Vec{x, y, z} } // Plus adds a Vec to the receiver Vec and returns a new Vec This is also vector addition func (v Vec) Plus(v2 Vec) Vec { x := v.X + v2.X y := v.Y + v2.Y z := v.Z + v2.Z return Vec{x, y, z} } // ToDegrees converts from degrees to radians // 2*pi radians = 360 degrees func ToDegrees(rad float64) float64 { return (rad * 180 / math.Pi) } // ToRadians converts from radians to degrees // 2*pi radians = 360 degrees func ToRadians(deg float64) float64 { return (deg * math.Pi / 180) } // Info prints a bunch of info for debugging purposes func (v Vec) Info(str string) { m, th, ph := v.AsSpherical() log.Printf("%s:: Vector %v length: %7.3G, theta: %7.3G, phi: %7.3G degrees", str, v, m, ToDegrees(th), ToDegrees(ph)) } // I is the unit vector on the x axis. Treat it as a const! var I = Vec{1, 0, 0} // J is the unit vector on the y axis. Treat it as a const! var J = Vec{0, 1, 0} // K is the unit vector on the z axis. Treat it as a const! var K = Vec{0, 0, 1} // Newc creates new Vec vector from a set of x, y, z coordinates func Newc(x, y, z float64) Vec { return Vec{x, y, z} } // Newv creates new Vec vector from an existing Vec func Newv(v Vec) Vec { v2 := v return v2 } // Newd creates new Vec vector from a magnitude and the direction angles // m is the magnitude of the new vector, th is theta the angle from the x axis in the xy plane // ph is phi the angle fron the xy plane toward the z axis. func Newd(m, th, ph float64) Vec { // Conversion from cylndrical to cartesian coordinates are as follows: // x = m*sin(ph)*cos(th) y = m*sin(ph)*sin(th) z= m*cos(ph) x := math.Sin(ph) * math.Cos(th) * m y := math.Sin(ph) * math.Sin(th) * m z := math.Cos(ph) * m return Vec{x, y, z} } // Newp creates a new Vec vector from 2 points. The Vec represents the distance and angle from p1 to p1 func Newp(p1, p2 Vec) Vec { return p2.Minus(p1) } // Mul performs a scaler multiplation. func (v Vec) Mul(x float64) Vec { m, theta, phi := v.AsSpherical() m *= x return Newd(m, theta, phi) } // Dot performs the dot product a.b func (v Vec) Dot(b Vec) float64 { return v.X*b.X + v.Y*b.Y + v.Z*b.Z } // Cross performs the cross product u X v func (v Vec) Cross(w Vec) Vec { x := v.Y*w.Z - v.Z*w.Y y := v.Z*w.X - v.X*w.Z z := v.X*w.Y - v.Y*w.X return Newc(x, y, z) }
vec/vec.go
0.915285
0.744285
vec.go
starcoder
package maths import "github.com/wdevore/Ranger-Go-IGE/api" type zoomTransform struct { // An optional (occasionally used) translation. position api.IVector // The zoom factor generally incremented in small steps. // For example, 0.1 scale api.IVector // The focal point where zooming occurs zoomAt api.IVector // A "running" accumulating transform accTransform api.IAffineTransform // A transform that includes position translation. transform api.IAffineTransform } // NewZoomTransform constructs an zoom transform object func NewZoomTransform() api.IZoomTransform { o := new(zoomTransform) o.position = NewVector() o.scale = NewVectorUsing(1.0, 1.0) o.zoomAt = NewVector() o.accTransform = NewTransform() o.transform = NewTransform() return o } // ---------------------------------------------------------- // Methods // ---------------------------------------------------------- func (zt *zoomTransform) GetTransform() api.IAffineTransform { zt.Update() return zt.transform } func (zt *zoomTransform) Update() { // Accumulate zoom transformations. // acc_transform is an intermediate accumulative matrix used for tracking the current zoom target. zt.accTransform.Translate(zt.zoomAt.X(), zt.zoomAt.Y()) zt.accTransform.Scale(zt.scale.X(), zt.scale.Y()) zt.accTransform.Translate(-zt.zoomAt.X(), -zt.zoomAt.Y()) // We reset Scale because acc_transform is accumulative and has "captured" the information. zt.scale.SetByComp(1.0, 1.0) // We want to leave acc_transform solely responsible for zooming. // "transform" is the final matrix. zt.transform.SetByTransform(zt.accTransform) // Tack on translation. Note: we don't append it, but concat it into a separate matrix. zt.transform.Translate(zt.position.X(), zt.position.Y()) } func (zt *zoomTransform) SetPosition(x, y float32) { zt.position.SetByComp(x, y) } func (zt *zoomTransform) ZoomBy(dx, dy float32) { zt.scale.Add(dx, dy) } func (zt *zoomTransform) TranslateBy(dx, dy float32) { zt.position.Add(dx, dy) } func (zt *zoomTransform) Scale() float32 { return zt.scale.X() } func (zt *zoomTransform) PsuedoScale() float32 { return zt.accTransform.GetPsuedoScale() } func (zt *zoomTransform) SetScale(scale float32) { zt.Update() // We use dimensional analysis to set the scale. Remember we can't // just set the scale absolutely because acc_transform is an accumulating matrix. // We have to take its current value and compute a new value based // on the passed in value. // Also, I can use acc_transform.a because I don't allow rotations for zooms, // so the diagonal components correctly represent the matrix's current scale. // And because I only perform uniform scaling I can safely use just the "a" element. scaleFactor := scale / zt.accTransform.GetPsuedoScale() zt.scale.SetByComp(scaleFactor, scaleFactor) } func (zt *zoomTransform) SetAt(x, y float32) { zt.zoomAt.SetByComp(x, y) }
engine/maths/zoom_transform.go
0.843251
0.498047
zoom_transform.go
starcoder
package cucumberexpressions import ( "errors" "fmt" "reflect" "strconv" ) // can be imported from "math/bits". Not yet supported in go 1.8 const uintSize = 32 << (^uint(0) >> 32 & 1) // 32 or 64 type ParameterByTypeTransformer interface { // toValueType accepts either reflect.Type or reflect.Kind Transform(fromValue string, toValueType interface{}) (interface{}, error) } type BuiltInParameterTransformer struct { } func (s BuiltInParameterTransformer) Transform(fromValue string, toValueType interface{}) (interface{}, error) { if toValueKind, ok := toValueType.(reflect.Kind); ok { return transformKind(fromValue, toValueKind) } if toValueTypeType, ok := toValueType.(reflect.Type); ok { return transformKind(fromValue, toValueTypeType.Kind()) } return nil, createError(fromValue, toValueType) } func transformKind(fromValue string, toValueKind reflect.Kind) (interface{}, error) { switch toValueKind { case reflect.String: return fromValue, nil case reflect.Bool: return strconv.ParseBool(fromValue) case reflect.Int: return strconv.Atoi(fromValue) case reflect.Int8: i, err := strconv.ParseInt(fromValue, 10, 8) if err == nil { return int8(i), nil } return nil, err case reflect.Int16: i, err := strconv.ParseInt(fromValue, 10, 16) if err == nil { return int16(i), nil } return nil, err case reflect.Int32: i, err := strconv.ParseInt(fromValue, 10, 32) if err == nil { return int32(i), nil } return nil, err case reflect.Int64: i, err := strconv.ParseInt(fromValue, 10, 64) if err == nil { return int64(i), nil } return nil, err case reflect.Uint: i, err := strconv.ParseUint(fromValue, 10, uintSize) if err == nil { return uint(i), nil } return nil, err case reflect.Uint8: i, err := strconv.ParseUint(fromValue, 10, 8) if err == nil { return uint8(i), nil } return nil, err case reflect.Uint16: i, err := strconv.ParseUint(fromValue, 10, 16) if err == nil { return uint16(i), nil } return nil, err case reflect.Uint32: i, err := strconv.ParseUint(fromValue, 10, 32) if err == nil { return uint32(i), nil } return nil, err case reflect.Uint64: i, err := strconv.ParseUint(fromValue, 10, 64) if err == nil { return uint64(i), nil } return nil, err case reflect.Float32: f, err := strconv.ParseFloat(fromValue, 32) if err == nil { return float32(f), nil } return nil, err case reflect.Float64: return strconv.ParseFloat(fromValue, 64) default: return nil, createError(fromValue, toValueKind.String()) } } func createError(fromValue string, toValueType interface{}) error { return errors.New(fmt.Sprintf("Can't transform '%s' to %s. "+ "BuiltInParameterTransformer only supports a limited number of types. "+ "Consider using a different object mapper or register a parameter type for %s", fromValue, toValueType, toValueType)) }
cucumber-expressions/go/parameter_by_type_transformer.go
0.595963
0.418816
parameter_by_type_transformer.go
starcoder
package ring import ( "github.com/ldsec/lattigo/utils" "math/bits" ) // GenGaloisParams generates the generators for the galois endomorphisms. func GenGaloisParams(n, gen uint64) (galElRotCol []uint64) { var m, mask uint64 m = n << 1 mask = m - 1 galElRotCol = make([]uint64, n>>1) galElRotCol[0] = 1 for i := uint64(1); i < n>>1; i++ { galElRotCol[i] = (galElRotCol[i-1] * gen) & mask } return } // PermuteNTTIndex computes the index table for PermuteNTT. func PermuteNTTIndex(gen, power, N uint64) (index []uint64) { genPow := ModExp(gen, power, 2*N) var mask, logN, tmp1, tmp2 uint64 logN = uint64(bits.Len64(N) - 1) mask = (N << 1) - 1 index = make([]uint64, N) for i := uint64(0); i < N; i++ { tmp1 = 2*utils.BitReverse64(i, logN) + 1 tmp2 = ((genPow * tmp1 & mask) - 1) >> 1 index[i] = utils.BitReverse64(tmp2, logN) } return } // PermuteNTT applies the galois transform on a polynomial in the NTT domain. // It maps the coefficients x^i to x^(gen*i) // Careful, not inplace! func PermuteNTT(polIn *Poly, gen uint64, polOut *Poly) { var N, tmp, mask, logN, tmp1, tmp2 uint64 N = uint64(len(polIn.Coeffs[0])) logN = uint64(bits.Len64(N) - 1) mask = (N << 1) - 1 index := make([]uint64, N) for i := uint64(0); i < N; i++ { tmp1 = 2*utils.BitReverse64(i, logN) + 1 tmp2 = ((gen * tmp1 & mask) - 1) >> 1 index[i] = utils.BitReverse64(tmp2, logN) } for j := uint64(0); j < N; j++ { tmp = index[j] for i := 0; i < len(polIn.Coeffs); i++ { polOut.Coeffs[i][j] = polIn.Coeffs[i][tmp] } } } // PermuteNTTWithIndex applies the galois transform on a polynomial in the NTT domain. // It maps the coefficients x^i to x^(gen*i) using the PermuteNTTIndex table. // Careful, not inplace! func PermuteNTTWithIndex(polIn *Poly, index []uint64, polOut *Poly) { var tmp uint64 for j := uint64(0); j < uint64(len(polIn.Coeffs[0])); j++ { tmp = index[j] for i := 0; i < len(polIn.Coeffs); i++ { polOut.Coeffs[i][j] = polIn.Coeffs[i][tmp] } } } // Permute applies the galois transform on a polynonial outside of the NTT domain. // It maps the coefficients x^i to x^(gen*i) // Careful, not inplace! func (context *Context) Permute(polIn *Poly, gen uint64, polOut *Poly) { var mask, index, indexRaw, logN, tmp uint64 mask = context.N - 1 logN = uint64(bits.Len64(mask)) for i := uint64(0); i < context.N; i++ { indexRaw = i * gen index = indexRaw & mask tmp = (indexRaw >> logN) & 1 for j, qi := range context.Modulus { polOut.Coeffs[j][index] = polIn.Coeffs[j][i]*(tmp^1) | (qi-polIn.Coeffs[j][i])*tmp } } }
ring/ring_galois.go
0.547464
0.47725
ring_galois.go
starcoder
package ast import ( "encoding/json" "fmt" "strings" ) // TypeAnnotation type TypeAnnotation struct { IsResource bool Type Type `json:"AnnotatedType"` StartPos Position `json:"-"` } func (t *TypeAnnotation) String() string { if t.IsResource { return fmt.Sprintf("@%s", t.Type) } return fmt.Sprint(t.Type) } func (t *TypeAnnotation) StartPosition() Position { return t.StartPos } func (t *TypeAnnotation) EndPosition() Position { return t.Type.EndPosition() } func (t *TypeAnnotation) MarshalJSON() ([]byte, error) { type Alias TypeAnnotation return json.Marshal(&struct { Range *Alias }{ Range: NewRangeFromPositioned(t), Alias: (*Alias)(t), }) } // Type type Type interface { HasPosition fmt.Stringer isType() CheckEqual(other Type, checker TypeEqualityChecker) error } // NominalType represents a named type type NominalType struct { Identifier Identifier NestedIdentifiers []Identifier `json:",omitempty"` } func (*NominalType) isType() {} func (t *NominalType) String() string { var sb strings.Builder sb.WriteString(t.Identifier.String()) for _, identifier := range t.NestedIdentifiers { sb.WriteRune('.') sb.WriteString(identifier.String()) } return sb.String() } func (t *NominalType) StartPosition() Position { return t.Identifier.StartPosition() } func (t *NominalType) EndPosition() Position { nestedCount := len(t.NestedIdentifiers) if nestedCount == 0 { return t.Identifier.EndPosition() } lastIdentifier := t.NestedIdentifiers[nestedCount-1] return lastIdentifier.EndPosition() } func (t *NominalType) MarshalJSON() ([]byte, error) { type Alias NominalType return json.Marshal(&struct { Type string Range *Alias }{ Type: "NominalType", Range: NewRangeFromPositioned(t), Alias: (*Alias)(t), }) } func (t *NominalType) IsQualifiedName() bool { return len(t.NestedIdentifiers) > 0 } func (t *NominalType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckNominalTypeEquality(t, other) } // OptionalType represents am optional variant of another type type OptionalType struct { Type Type `json:"ElementType"` EndPos Position `json:"-"` } func (*OptionalType) isType() {} func (t *OptionalType) String() string { return fmt.Sprintf("%s?", t.Type) } func (t *OptionalType) StartPosition() Position { return t.Type.StartPosition() } func (t *OptionalType) EndPosition() Position { return t.EndPos } func (t *OptionalType) MarshalJSON() ([]byte, error) { type Alias OptionalType return json.Marshal(&struct { Type string Range *Alias }{ Type: "OptionalType", Range: NewRangeFromPositioned(t), Alias: (*Alias)(t), }) } func (t *OptionalType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckOptionalTypeEquality(t, other) } // VariableSizedType is a variable sized array type type VariableSizedType struct { Type Type `json:"ElementType"` Range } func (*VariableSizedType) isType() {} func (t *VariableSizedType) String() string { return fmt.Sprintf("[%s]", t.Type) } func (t *VariableSizedType) MarshalJSON() ([]byte, error) { type Alias VariableSizedType return json.Marshal(&struct { Type string *Alias }{ Type: "VariableSizedType", Alias: (*Alias)(t), }) } func (t *VariableSizedType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckVariableSizedTypeEquality(t, other) } // ConstantSizedType is a constant sized array type type ConstantSizedType struct { Type Type `json:"ElementType"` Size *IntegerExpression Range } func (*ConstantSizedType) isType() {} func (t *ConstantSizedType) String() string { return fmt.Sprintf("[%s; %s]", t.Type, t.Size) } func (t *ConstantSizedType) MarshalJSON() ([]byte, error) { type Alias ConstantSizedType return json.Marshal(&struct { Type string *Alias }{ Type: "ConstantSizedType", Alias: (*Alias)(t), }) } func (t *ConstantSizedType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckConstantSizedTypeEquality(t, other) } // DictionaryType type DictionaryType struct { KeyType Type ValueType Type Range } func (*DictionaryType) isType() {} func (t *DictionaryType) String() string { return fmt.Sprintf("{%s: %s}", t.KeyType, t.ValueType) } func (t *DictionaryType) MarshalJSON() ([]byte, error) { type Alias DictionaryType return json.Marshal(&struct { Type string *Alias }{ Type: "DictionaryType", Alias: (*Alias)(t), }) } func (t *DictionaryType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckDictionaryTypeEquality(t, other) } // FunctionType type FunctionType struct { ParameterTypeAnnotations []*TypeAnnotation `json:",omitempty"` ReturnTypeAnnotation *TypeAnnotation Range } func (*FunctionType) isType() {} func (t *FunctionType) String() string { var parameters strings.Builder for i, parameterTypeAnnotation := range t.ParameterTypeAnnotations { if i > 0 { parameters.WriteString(", ") } parameters.WriteString(parameterTypeAnnotation.String()) } return fmt.Sprintf("((%s): %s)", parameters.String(), t.ReturnTypeAnnotation.String()) } func (t *FunctionType) MarshalJSON() ([]byte, error) { type Alias FunctionType return json.Marshal(&struct { Type string *Alias }{ Type: "FunctionType", Alias: (*Alias)(t), }) } func (t *FunctionType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckFunctionTypeEquality(t, other) } // ReferenceType type ReferenceType struct { Authorized bool Type Type `json:"ReferencedType"` StartPos Position `json:"-"` } func (*ReferenceType) isType() {} func (t *ReferenceType) String() string { var builder strings.Builder if t.Authorized { builder.WriteString("auth ") } builder.WriteRune('&') builder.WriteString(t.Type.String()) return builder.String() } func (t *ReferenceType) StartPosition() Position { return t.StartPos } func (t *ReferenceType) EndPosition() Position { return t.Type.EndPosition() } func (t *ReferenceType) MarshalJSON() ([]byte, error) { type Alias ReferenceType return json.Marshal(&struct { Type string Range *Alias }{ Type: "ReferenceType", Range: NewRangeFromPositioned(t), Alias: (*Alias)(t), }) } func (t *ReferenceType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckReferenceTypeEquality(t, other) } // RestrictedType type RestrictedType struct { Type Type `json:"RestrictedType"` Restrictions []*NominalType Range } func (*RestrictedType) isType() {} func (t *RestrictedType) String() string { var builder strings.Builder if t.Type != nil { builder.WriteString(t.Type.String()) } builder.WriteRune('{') for i, restriction := range t.Restrictions { if i > 0 { builder.WriteString(", ") } builder.WriteString(restriction.String()) } builder.WriteRune('}') return builder.String() } func (t *RestrictedType) MarshalJSON() ([]byte, error) { type Alias RestrictedType return json.Marshal(&struct { Type string *Alias }{ Type: "RestrictedType", Alias: (*Alias)(t), }) } func (t *RestrictedType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckRestrictedTypeEquality(t, other) } // InstantiationType represents an instantiation of a generic (nominal) type type InstantiationType struct { Type Type `json:"InstantiatedType"` TypeArguments []*TypeAnnotation TypeArgumentsStartPos Position EndPos Position `json:"-"` } func (*InstantiationType) isType() {} func (t *InstantiationType) String() string { var sb strings.Builder sb.WriteString(t.Type.String()) sb.WriteRune('<') for i, typeArgument := range t.TypeArguments { if i > 0 { sb.WriteString(", ") } sb.WriteString(typeArgument.String()) } sb.WriteRune('>') return sb.String() } func (t *InstantiationType) StartPosition() Position { return t.Type.StartPosition() } func (t *InstantiationType) EndPosition() Position { return t.EndPos } func (t *InstantiationType) MarshalJSON() ([]byte, error) { type Alias InstantiationType return json.Marshal(&struct { Type string Range *Alias }{ Type: "InstantiationType", Range: NewRangeFromPositioned(t), Alias: (*Alias)(t), }) } func (t *InstantiationType) CheckEqual(other Type, checker TypeEqualityChecker) error { return checker.CheckInstantiationTypeEquality(t, other) } type TypeEqualityChecker interface { CheckNominalTypeEquality(*NominalType, Type) error CheckOptionalTypeEquality(*OptionalType, Type) error CheckVariableSizedTypeEquality(*VariableSizedType, Type) error CheckConstantSizedTypeEquality(*ConstantSizedType, Type) error CheckDictionaryTypeEquality(*DictionaryType, Type) error CheckFunctionTypeEquality(*FunctionType, Type) error CheckReferenceTypeEquality(*ReferenceType, Type) error CheckRestrictedTypeEquality(*RestrictedType, Type) error CheckInstantiationTypeEquality(*InstantiationType, Type) error }
runtime/ast/type.go
0.778144
0.434881
type.go
starcoder
package main import ( "errors" "fmt" "math" "math/big" "strings" "github.com/pachisi456/sia-hostdb-profiles/types" ) var errUnableToParseSize = errors.New("unable to parse size") // filesize returns a string that displays a filesize in human-readable units. func filesizeUnits(size int64) string { if size == 0 { return "0 B" } sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} i := int(math.Log10(float64(size)) / 3) return fmt.Sprintf("%.*f %s", i, float64(size)/math.Pow10(3*i), sizes[i]) } // parseFilesize converts strings of form 10GB to a size in bytes. Fractional // sizes are truncated at the byte size. func parseFilesize(strSize string) (string, error) { units := []struct { suffix string multiplier int64 }{ {"kb", 1e3}, {"mb", 1e6}, {"gb", 1e9}, {"tb", 1e12}, {"kib", 1 << 10}, {"mib", 1 << 20}, {"gib", 1 << 30}, {"tib", 1 << 40}, {"b", 1}, // must be after others else it'll match on them all } strSize = strings.ToLower(strSize) for _, unit := range units { if strings.HasSuffix(strSize, unit.suffix) { r, ok := new(big.Rat).SetString(strings.TrimSuffix(strSize, unit.suffix)) if !ok { return "", errUnableToParseSize } r.Mul(r, new(big.Rat).SetInt(big.NewInt(unit.multiplier))) if !r.IsInt() { f, _ := r.Float64() return fmt.Sprintf("%d", int64(f)), nil } return r.RatString(), nil } } return "", errUnableToParseSize } // periodUnits turns a period in terms of blocks to a number of weeks. func periodUnits(blocks types.BlockHeight) string { return fmt.Sprint(blocks / 1008) // 1008 blocks per week } // parsePeriod converts a duration specified in blocks, hours, or weeks to a // number of blocks. func parsePeriod(period string) (string, error) { units := []struct { suffix string multiplier float64 }{ {"b", 1}, // blocks {"block", 1}, // blocks {"blocks", 1}, // blocks {"h", 6}, // hours {"hour", 6}, // hours {"hours", 6}, // hours {"d", 144}, // days {"day", 144}, // days {"days", 144}, // days {"w", 1008}, // weeks {"week", 1008}, // weeks {"weeks", 1008}, // weeks } period = strings.ToLower(period) for _, unit := range units { if strings.HasSuffix(period, unit.suffix) { var base float64 _, err := fmt.Sscan(strings.TrimSuffix(period, unit.suffix), &base) if err != nil { return "", errUnableToParseSize } blocks := int(base * unit.multiplier) return fmt.Sprint(blocks), nil } } return "", errUnableToParseSize } // currencyUnits converts a types.Currency to a string with human-readable // units. The unit used will be the largest unit that results in a value // greater than 1. The value is rounded to 4 significant digits. func currencyUnits(c types.Currency) string { pico := types.SiacoinPrecision.Div64(1e12) if c.Cmp(pico) < 0 { return c.String() + " H" } // iterate until we find a unit greater than c mag := pico unit := "" for _, unit = range []string{"pS", "nS", "uS", "mS", "SC", "KS", "MS", "GS", "TS"} { if c.Cmp(mag.Mul64(1e3)) < 0 { break } else if unit != "TS" { // don't want to perform this multiply on the last iter; that // would give us 1.235 TS instead of 1235 TS mag = mag.Mul64(1e3) } } num := new(big.Rat).SetInt(c.Big()) denom := new(big.Rat).SetInt(mag.Big()) res, _ := new(big.Rat).Mul(num, denom.Inv(denom)).Float64() return fmt.Sprintf("%.4g %s", res, unit) } // parseCurrency converts a siacoin amount to base units. func parseCurrency(amount string) (string, error) { units := []string{"pS", "nS", "uS", "mS", "SC", "KS", "MS", "GS", "TS"} for i, unit := range units { if strings.HasSuffix(amount, unit) { // scan into big.Rat r, ok := new(big.Rat).SetString(strings.TrimSuffix(amount, unit)) if !ok { return "", errors.New("malformed amount") } // convert units exp := 24 + 3*(int64(i)-4) mag := new(big.Int).Exp(big.NewInt(10), big.NewInt(exp), nil) r.Mul(r, new(big.Rat).SetInt(mag)) // r must be an integer at this point if !r.IsInt() { return "", errors.New("non-integer number of hastings") } return r.RatString(), nil } } // check for hastings separately if strings.HasSuffix(amount, "H") { return strings.TrimSuffix(amount, "H"), nil } return "", errors.New("amount is missing units; run 'wallet --help' for a list of units") } // yesNo returns "Yes" if b is true, and "No" if b is false. func yesNo(b bool) string { if b { return "Yes" } return "No" }
cmd/siac/parse.go
0.68595
0.463444
parse.go
starcoder
// Package day19 solves AoC 2021 day 19. package day19 import ( "fmt" "sort" "strconv" "strings" "github.com/fis/aoc/glue" "github.com/fis/aoc/util" ) func init() { glue.RegisterSolver(2021, 19, glue.ChunkSolver(solve)) } func solve(chunks []string) ([]string, error) { scanners, err := parseInput(chunks) if err != nil { return nil, err } scannerPos, beaconPos := scanners.buildMap() p1 := len(beaconPos) p2 := maxDist(scannerPos) return glue.Ints(p1, p2), nil } func maxDist(points []p3) (maxD int) { for i, p := range points[:len(points)-1] { for _, q := range points[i+1:] { d := int(abs(q.x-p.x) + abs(q.y-p.y) + abs(q.z-p.z)) if d > maxD { maxD = d } } } return maxD } type scannerSet struct { scanners []scanner } func (ss *scannerSet) buildMap() (scannerPos []p3, beaconPos map[p3]struct{}) { beaconPos = make(map[p3]struct{}) used := make(map[int]struct{}) scannerPos = ss.mergeToMap(scannerPos, beaconPos, 0, identityTr, used) if len(used) != len(ss.scanners) { panic("could not merge all scanners") } return scannerPos, beaconPos } func (ss *scannerSet) mergeToMap(scannerPos []p3, beaconPos map[p3]struct{}, scanner int, tr transform, used map[int]struct{}) []p3 { scannerPos = append(scannerPos, tr.apply(p3{0, 0, 0})) for _, p := range ss.scanners[scanner].beacons { beaconPos[tr.apply(p)] = struct{}{} } used[scanner] = struct{}{} for next := 0; next < len(ss.scanners); next++ { if _, ok := used[next]; ok { continue } overlap := ss.overlap(scanner, next) if len(overlap) == 0 { continue } nextTr := tr.combine(ss.align(scanner, next, overlap)) scannerPos = ss.mergeToMap(scannerPos, beaconPos, next, nextTr, used) } return scannerPos } func (ss *scannerSet) align(ref, next int, overlap [][2]int32) (tr transform) { r1 := ss.scanners[ref].beacons[overlap[0][0]] r2 := ss.scanners[ref].beacons[overlap[1][0]] rd := p3{r2.x - r1.x, r2.y - r1.y, r2.z - r1.z} n1 := ss.scanners[next].beacons[overlap[0][1]] n2 := ss.scanners[next].beacons[overlap[1][1]] nd := p3{n2.x - n1.x, n2.y - n1.y, n2.z - n1.z} for rot := 0; ; rot++ { tr = rotationTr[rot] if tr.apply(nd) == rd { break } } n1r := tr.apply(n1) tr[0][3], tr[1][3], tr[2][3] = r1.x-n1r.x, r1.y-n1r.y, r1.z-n1r.z return tr } func (ss *scannerSet) overlap(id1, id2 int) (match [][2]int32) { const ( wantPoints = 12 wantDistances = wantPoints * (wantPoints - 1) / 2 ) var distPairs [wantDistances][2]distance if !ss.matchDistances(id1, id2, distPairs[:]) { return nil } points1 := make(map[int32][][2]distance) for _, dp := range distPairs { points1[dp[0].p1] = append(points1[dp[0].p1], dp) points1[dp[0].p2] = append(points1[dp[0].p2], dp) } if len(points1) != wantPoints { panic("impossible: got right amount of distances but wrong amount of points") } match = make([][2]int32, wantPoints) at := 0 for p1, dps := range points1 { p2a, p2b := dps[0][1].p1, dps[0][1].p2 if p2a == dps[1][1].p1 || p2a == dps[1][1].p2 { match[at] = [2]int32{p1, p2a} } else if p2b == dps[1][1].p1 || p2b == dps[1][1].p2 { match[at] = [2]int32{p1, p2b} } else { panic("impossible: no match found after all") } at++ } return match } func (ss *scannerSet) matchDistances(id1, id2 int, out [][2]distance) bool { s1, s2 := &ss.scanners[id1], &ss.scanners[id2] d1, d2 := s1.dists, s2.dists at := 0 for len(d1) > 0 && len(d2) > 0 { if d1[0].d == d2[0].d { out[at] = [2]distance{d1[0], d2[0]} at++ if at == len(out) { return true } d1, d2 = d1[1:], d2[1:] } else if distLess(d1[0].d, d2[0].d) { d1 = d1[1:] } else { d2 = d2[1:] } } return false } type scanner struct { beacons []p3 // beacon positions dists []distance // pairwise distances between all beacons, in order } type distance struct { d p3 // |x2-x1|, |y2-y1|, |x2-z1| in order of magnitude p1, p2 int32 // endpoints the distance is for } func (s *scanner) calcDists() { distMap := make(map[p3][2]int32) for i := 0; i < len(s.beacons)-1; i++ { p := s.beacons[i] for j := i + 1; j < len(s.beacons); j++ { q := s.beacons[j] dx, dy, dz := abs(q.x-p.x), abs(q.y-p.y), abs(q.z-p.z) da, db, dc := sort3(dx, dy, dz) d := p3{da, db, dc} if _, seen := distMap[d]; seen { panic("non-unique distance!") // could happen in reality, doesn't happen in puzzle-land } distMap[d] = [2]int32{int32(i), int32(j)} } } for d, p := range distMap { s.dists = append(s.dists, distance{d: d, p1: p[0], p2: p[1]}) } sort.Slice(s.dists, func(i, j int) bool { return distLess(s.dists[i].d, s.dists[j].d) }) } func distLess(a, b p3) bool { if a.x < b.x { return true } if a.x == b.x && a.y < b.y { return true } if a.x == b.x && a.y == b.y && a.z < b.z { return true } return false } func parseInput(chunks []string) (ss *scannerSet, err error) { ss = &scannerSet{scanners: make([]scanner, len(chunks))} for i, chunk := range chunks { header := fmt.Sprintf("--- scanner %d ---\n", i) if len(chunk) < len(header) { return nil, fmt.Errorf("short chunk: %q", chunk) } else if !strings.HasPrefix(chunk, header) { return nil, fmt.Errorf("expected header %q, got %q", header, chunk[:len(header)]) } lines, err := util.ScanAllRegexp(strings.NewReader(chunk[len(header):]), `^(-?\d+),(-?\d+),(-?\d+)$`) if err != nil { return nil, err } ss.scanners[i].beacons = make([]p3, len(lines)) for j, line := range lines { x, _ := strconv.Atoi(line[0]) y, _ := strconv.Atoi(line[1]) z, _ := strconv.Atoi(line[2]) ss.scanners[i].beacons[j] = p3{int32(x), int32(y), int32(z)} } ss.scanners[i].calcDists() } return ss, nil } type transform [4][4]int32 func (tr transform) apply(p p3) (q p3) { q.x = tr[0][0]*p.x + tr[0][1]*p.y + tr[0][2]*p.z + tr[0][3] q.y = tr[1][0]*p.x + tr[1][1]*p.y + tr[1][2]*p.z + tr[1][3] q.z = tr[2][0]*p.x + tr[2][1]*p.y + tr[2][2]*p.z + tr[2][3] return q } func (tr transform) combine(next transform) (out transform) { for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { for k := 0; k < 4; k++ { out[i][j] += tr[i][k] * next[k][j] } } } return out } var identityTr = transform{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} var rotationTr [24]transform func init() { x, y, z, w := [4]int32{1, 0, 0, 0}, [4]int32{0, 1, 0, 0}, [4]int32{0, 0, 1, 0}, [4]int32{0, 0, 0, 1} X, Y, Z := [4]int32{-1, 0, 0, 0}, [4]int32{0, -1, 0, 0}, [4]int32{0, 0, -1, 0} rotationTr = [24]transform{ {x, y, z, w}, {y, X, z, w}, {X, Y, z, w}, {Y, x, z, w}, {Z, y, x, w}, {y, z, x, w}, {z, Y, x, w}, {Y, Z, x, w}, {X, y, Z, w}, {y, x, Z, w}, {x, Y, Z, w}, {Y, X, Z, w}, {z, y, X, w}, {y, Z, X, w}, {Z, Y, X, w}, {Y, z, X, w}, {x, Z, y, w}, {Z, X, y, w}, {X, z, y, w}, {z, x, y, w}, {x, z, Y, w}, {Z, x, Y, w}, {X, Z, Y, w}, {z, X, Y, w}, } } type p3 struct { x, y, z int32 } func sort3(x, y, z int32) (a, b, c int32) { if x <= y { // x <= y if x <= z { // x <= y, x <= z if y <= z { // x <= y, x <= z, y <= z return x, y, z } else { // x <= y, x <= z, y > z return x, z, y } } else { // x <= y, x > z return z, x, y } } else { // x > y if y <= z { // x > y, y <= z if x <= z { // x > y, y <= z, x <= z return y, x, z } else { // x > y, y <= z, x > z return y, z, x } } else { // x > y, y > z return z, y, x } } } func abs(x int32) int32 { if x < 0 { return -x } return x }
2021/day19/day19.go
0.521227
0.469399
day19.go
starcoder
package casee import ( "github.com/fatih/camelcase" "strings" "unicode" ) // Convert argument to snake_case style string. // If argument is empty, return itself. func ToSnakeCase(s string) string { if len(s) == 0 { return s } fields := splitToLowerFields(s) return strings.Join(fields, "_") } // If argument is snake_case style string, return true. func IsSnakeCase(s string) bool { if strings.Contains(s, "_") { fields := strings.Split(s, "_") for _, field := range fields { if !isMadeByLowerAndDigit(field) { return false } } return true } else { return isMadeByLowerAndDigit(s) } } // Convert argument to chain-case style string. // If argument is empty, return itself. func ToChainCase(s string) string { if len(s) == 0 { return s } fields := splitToLowerFields(s) return strings.Join(fields, "-") } // If argument is chain-case style string, return true. func IsChainCase(s string) bool { if strings.Contains(s, "-") { fields := strings.Split(s, "-") for _, field := range fields { if !isMadeByLowerAndDigit(field) { return false } } return true } else { return isMadeByLowerAndDigit(s) } } // Convert argument to camelCase style string // If argument is empty, return itself func ToCamelCase(s string) string { if len(s) == 0 { return s } fields := splitToLowerFields(s) for i, f := range fields { if i != 0 { fields[i] = toUpperFirstRune(f) } } return strings.Join(fields, "") } // If argument is camelCase style string, return true. // If first character is digit, always returns false func IsCamelCase(s string) bool { if isFirstRuneDigit(s) { return false } else { return isMadeByAlphanumeric(s) && isFirstRuneLower(s) } } // Convert argument to PascalCase style string // If argument is empty, return itself func ToPascalCase(s string) string { if len(s) == 0 { return s } fields := splitToLowerFields(s) for i, f := range fields { fields[i] = toUpperFirstRune(f) } return strings.Join(fields, "") } // If argument is PascalCase style string, return true. // If first character is digit, always returns false func IsPascalCase(s string) bool { if isFirstRuneDigit(s) { return false } else { return isMadeByAlphanumeric(s) && isFirstRuneUpper(s) } } // Convert argument to flatcase style string // If argument is empty, return itself func ToFlatCase(s string) string { if len(s) == 0 { return s } fields := splitToLowerFields(s) return strings.Join(fields, "") } // If argument is flatcase style string, return true. // If first character is digit, always returns false func IsFlatCase(s string) bool { if isFirstRuneDigit(s) { return false } else { return isMadeByLowerAndDigit(s) } } func isMadeByLowerAndDigit(s string) bool { if len(s) == 0 { return false } for _, r := range s { if !unicode.IsLower(r) && !unicode.IsDigit(r) { return false } } return true } func isMadeByAlphanumeric(s string) bool { if len(s) == 0 { return false } for _, r := range s { if !unicode.IsUpper(r) && !unicode.IsLower(r) && !unicode.IsDigit(r) { return false } } return true } func isFirstRuneUpper(s string) bool { if len(s) == 0 { return false } return unicode.IsUpper(getRuneAt(s, 0)) } func isFirstRuneLower(s string) bool { if len(s) == 0 { return false } return unicode.IsLower(getRuneAt(s, 0)) } func isFirstRuneDigit(s string) bool { if len(s) == 0 { return false } return unicode.IsDigit(getRuneAt(s, 0)) } func getRuneAt(s string, i int) rune { if len(s) == 0 { return 0 } rs := []rune(s) return rs[0] } func splitToLowerFields(s string) []string { defaultCap := len([]rune(s)) / 3 fields := make([]string, 0, defaultCap) for _, sf := range strings.Fields(s) { for _, su := range strings.Split(sf, "_") { for _, sh := range strings.Split(su, "-") { for _, sc := range camelcase.Split(sh) { fields = append(fields, strings.ToLower(sc)) } } } } return fields } func toUpperFirstRune(s string) string { rs := []rune(s) return strings.ToUpper(string(rs[0])) + string(rs[1:]) }
vendor/github.com/pinzolo/casee/casee.go
0.593374
0.441191
casee.go
starcoder
package growthbook import ( "encoding/json" "reflect" "regexp" "strings" ) // Condition represents conditions used to target features/experiments // to specific users. type Condition interface { Eval(attrs Attributes) bool } // Concrete condition representing ORing together a list of // conditions. type orCondition struct { conds []Condition } // Concrete condition representing NORing together a list of // conditions. type norCondition struct { conds []Condition } // Concrete condition representing ANDing together a list of // conditions. type andCondition struct { conds []Condition } // Concrete condition representing the complement of another // condition. type notCondition struct { cond Condition } // Concrete condition representing the base condition case of a set of // keys and values or subsidiary conditions. type baseCondition struct { // This is represented in this dynamically typed form to make lax // error handling easier. values map[string]interface{} } // Evaluate ORed list of conditions. func (cond orCondition) Eval(attrs Attributes) bool { if len(cond.conds) == 0 { return true } for i := range cond.conds { if cond.conds[i].Eval(attrs) { return true } } return false } // Evaluate NORed list of conditions. func (cond norCondition) Eval(attrs Attributes) bool { or := orCondition{cond.conds} return !or.Eval(attrs) } // Evaluate ANDed list of conditions. func (cond andCondition) Eval(attrs Attributes) bool { for i := range cond.conds { if !cond.conds[i].Eval(attrs) { return false } } return true } // Evaluate complemented condition. func (cond notCondition) Eval(attrs Attributes) bool { return !cond.cond.Eval(attrs) } // Evaluate base Condition case by iterating over keys and performing // evaluation for each one (either a simple comparison, or an operator // evaluation). func (cond baseCondition) Eval(attrs Attributes) bool { for k, v := range cond.values { if !evalConditionValue(v, getPath(attrs, k)) { return false } } return true } // ParseCondition creates a Condition value from raw JSON input. func ParseCondition(data []byte) Condition { topLevel := map[string]interface{}{} err := json.Unmarshal(data, &topLevel) if err != nil { logError(ErrJSONFailedToParse, "Condition") return nil } return BuildCondition(topLevel) } // BuildCondition creates a Condition value from a JSON object // represented as a Go map. func BuildCondition(cond map[string]interface{}) Condition { if or, ok := cond["$or"]; ok { conds := buildSeq(or) if conds == nil { return nil } return orCondition{conds} } if nor, ok := cond["$nor"]; ok { conds := buildSeq(nor) if conds == nil { return nil } return norCondition{conds} } if and, ok := cond["$and"]; ok { conds := buildSeq(and) if conds == nil { return nil } return andCondition{conds} } if not, ok := cond["$not"]; ok { subcond, ok := not.(map[string]interface{}) if !ok { logError(ErrCondJSONNot) return nil } cond := BuildCondition(subcond) if cond == nil { return nil } return notCondition{cond} } return baseCondition{cond} } //-- PRIVATE FUNCTIONS START HERE ---------------------------------------------- // Extract sub-elements of an attribute object using dot-separated // paths. func getPath(attrs Attributes, path string) interface{} { parts := strings.Split(path, ".") var current interface{} for i, p := range parts { if i == 0 { current = attrs[p] } else { m, ok := current.(map[string]interface{}) if !ok { return nil } current = m[p] } } return current } // Process a sequence of JSON values into an array of Conditions. func buildSeq(seq interface{}) []Condition { // The input should be a JSON array. conds, ok := seq.([]interface{}) if !ok { logError(ErrCondJSONSequence) return nil } retval := make([]Condition, len(conds)) for i := range conds { // Each condition in the sequence should be a JSON object. condmap, ok := conds[i].(map[string]interface{}) if !ok { logError(ErrCondJSONSequenceElement) } cond := BuildCondition(condmap) if cond == nil { return nil } retval[i] = cond } return retval } // Evaluate one element of a base condition. If the condition value is // a JSON object and each key in it is an operator name (e.g. "$eq", // "$gt", "$elemMatch", etc.), then evaluate as an operator condition. // Otherwise, just directly compare the condition value with the // attribute value. func evalConditionValue(condVal interface{}, attrVal interface{}) bool { condmap, ok := condVal.(map[string]interface{}) if ok && isOperatorObject(condmap) { for k, v := range condmap { if !evalOperatorCondition(k, attrVal, v) { return false } } return true } return reflect.DeepEqual(condVal, attrVal) } // An operator object is a JSON object all of whose keys start with a // "$" character, representing comparison operators. func isOperatorObject(obj map[string]interface{}) bool { for k := range obj { if !strings.HasPrefix(k, "$") { return false } } return true } // Evaluate operator conditions. The first parameter here is the // operator name. func evalOperatorCondition(key string, attrVal interface{}, condVal interface{}) bool { switch key { case "$eq": return reflect.DeepEqual(attrVal, condVal) case "$ne": return !reflect.DeepEqual(attrVal, condVal) case "$lt", "$lte", "$gt", "$gte": return compare(key, attrVal, condVal) case "$regex": restring, reok := condVal.(string) attrstring, attrok := attrVal.(string) if !reok || !attrok { return false } re, err := regexp.Compile(restring) if err != nil { return false } return re.MatchString(attrstring) case "$in": return elementIn(attrVal, condVal) case "$nin": return !elementIn(attrVal, condVal) case "$elemMatch": return elemMatch(attrVal, condVal) case "$size": if getType(attrVal) != "array" { return false } return evalConditionValue(condVal, float64(len(attrVal.([]interface{})))) case "$all": return evalAll(condVal, attrVal) case "$exists": return existsCheck(condVal, attrVal) case "$type": return getType(attrVal) == condVal.(string) case "$not": return !evalConditionValue(condVal, attrVal) default: return false } } // Get JSON type name for Go representation of JSON objects. func getType(v interface{}) string { if v == nil { return "null" } switch v.(type) { case string: return "string" case float64: return "number" case bool: return "boolean" case []interface{}: return "array" case map[string]interface{}: return "object" default: return "unknown" } } // Perform numeric or string ordering comparisons on polymorphic JSON // values. func compare(comp string, x interface{}, y interface{}) bool { switch x.(type) { case float64: xn := x.(float64) yn, ok := y.(float64) if !ok { logWarn(WarnCondCompareTypeMismatch) return false } switch comp { case "$lt": return xn < yn case "$lte": return xn <= yn case "$gt": return xn > yn case "$gte": return xn >= yn } case string: xs := x.(string) ys, ok := y.(string) if !ok { logWarn(WarnCondCompareTypeMismatch) return false } switch comp { case "$lt": return xs < ys case "$lte": return xs <= ys case "$gt": return xs > ys case "$gte": return xs >= ys } } return false } // Check for membership of a JSON value in a JSON array. func elementIn(v interface{}, array interface{}) bool { vals, ok := array.([]interface{}) if !ok { return false } for _, val := range vals { if reflect.DeepEqual(v, val) { return true } } return false } // Perform "element matching" operation. func elemMatch(attrVal interface{}, condVal interface{}) bool { // Check that the attribute and condition values are of the // appropriate types (an array and an object respectively). attrs, ok := attrVal.([]interface{}) if !ok { return false } condmap, ok := condVal.(map[string]interface{}) if !ok { return false } // Decide on the type of check to perform on the attribute values. check := func(v interface{}) bool { return evalConditionValue(condVal, v) } if !isOperatorObject(condmap) { cond := BuildCondition(condmap) if cond == nil { return false } check = func(v interface{}) bool { vmap, ok := v.(map[string]interface{}) if !ok { return false } as := Attributes(vmap) return cond.Eval(as) } } // Check attribute array values. for _, a := range attrs { if check(a) { return true } } return false } // Perform "exists" operation. func existsCheck(condVal interface{}, attrVal interface{}) bool { cond, ok := condVal.(bool) if !ok { return false } if !cond { return attrVal == nil } return attrVal != nil } // Perform "all" operation. func evalAll(condVal interface{}, attrVal interface{}) bool { conds, okc := condVal.([]interface{}) attrs, oka := attrVal.([]interface{}) if !okc || !oka { return false } for _, c := range conds { passed := false for _, a := range attrs { if evalConditionValue(c, a) { passed = true break } } if !passed { return false } } return true }
conditions.go
0.654122
0.456713
conditions.go
starcoder
package client // NetworkPolicySpec provides the specification of a NetworkPolicy type V1NetworkPolicySpec struct { // List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8 Egress []V1NetworkPolicyEgressRule `json:"egress,omitempty"` // List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default) Ingress []V1NetworkPolicyIngressRule `json:"ingress,omitempty"` // Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace. PodSelector V1LabelSelector `json:"podSelector"` // List of rule types that the NetworkPolicy relates to. Valid options are Ingress, Egress, or Ingress,Egress. If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ \"Egress\" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include \"Egress\" (since such a policy would not include an Egress section and would otherwise default to just [ \"Ingress\" ]). This field is beta-level in 1.8 PolicyTypes []string `json:"policyTypes,omitempty"` }
pkg/client/v1_network_policy_spec.go
0.770853
0.786213
v1_network_policy_spec.go
starcoder
package evalengine import ( "vitess.io/vitess/go/sqltypes" "vitess.io/vitess/go/vt/sqlparser" ) type ( LogicalOp interface { eval(left, right EvalResult) (boolean, error) String() } LogicalExpr struct { BinaryExpr op func(left, right boolean) boolean opname string } NotExpr struct { UnaryExpr } OpLogicalAnd struct{} boolean int8 ) const ( boolFalse boolean = 0 boolTrue boolean = 1 boolNULL boolean = -1 ) func makeboolean(b bool) boolean { if b { return boolTrue } return boolFalse } func makeboolean2(b, isNull bool) boolean { if isNull { return boolNULL } return makeboolean(b) } func (left boolean) not() boolean { switch left { case boolFalse: return boolTrue case boolTrue: return boolFalse default: return left } } func (left boolean) and(right boolean) boolean { // Logical AND. // Evaluates to 1 if all operands are nonzero and not NULL, to 0 if one or more operands are 0, otherwise NULL is returned. switch { case left == boolTrue && right == boolTrue: return boolTrue case left == boolFalse || right == boolFalse: return boolFalse default: return boolNULL } } func (left boolean) or(right boolean) boolean { // Logical OR. When both operands are non-NULL, the result is 1 if any operand is nonzero, and 0 otherwise. // With a NULL operand, the result is 1 if the other operand is nonzero, and NULL otherwise. // If both operands are NULL, the result is NULL. switch { case left == boolNULL: if right == boolTrue { return boolTrue } return boolNULL case right == boolNULL: if left == boolTrue { return boolTrue } return boolNULL default: if left == boolTrue || right == boolTrue { return boolTrue } return boolFalse } } func (left boolean) xor(right boolean) boolean { // Logical XOR. Returns NULL if either operand is NULL. // For non-NULL operands, evaluates to 1 if an odd number of operands is nonzero, otherwise 0 is returned. switch { case left == boolNULL || right == boolNULL: return boolNULL default: if left != right { return boolTrue } return boolFalse } } func (n *NotExpr) eval(env *ExpressionEnv, out *EvalResult) { var inner EvalResult inner.init(env, n.Inner) out.setBoolean(inner.truthy().not()) } func (n *NotExpr) typeof(env *ExpressionEnv) (sqltypes.Type, flag) { _, flags := n.Inner.typeof(env) return sqltypes.Uint64, flags } func (l *LogicalExpr) eval(env *ExpressionEnv, out *EvalResult) { var left, right EvalResult left.init(env, l.Left) right.init(env, l.Right) if left.typeof() == sqltypes.Tuple || right.typeof() == sqltypes.Tuple { panic("did not typecheck tuples") } out.setBoolean(l.op(left.truthy(), right.truthy())) } func (l *LogicalExpr) typeof(env *ExpressionEnv) (sqltypes.Type, flag) { _, f1 := l.Left.typeof(env) _, f2 := l.Right.typeof(env) return sqltypes.Uint64, f1 | f2 } // IsExpr represents the IS expression in MySQL. // boolean_primary IS [NOT] {TRUE | FALSE | NULL} type IsExpr struct { UnaryExpr Op sqlparser.IsExprOperator Check func(*EvalResult) bool } func (i *IsExpr) eval(env *ExpressionEnv, result *EvalResult) { var in EvalResult in.init(env, i.Inner) result.setBool(i.Check(&in)) } func (i *IsExpr) typeof(env *ExpressionEnv) (sqltypes.Type, flag) { return sqltypes.Int64, 0 }
go/vt/vtgate/evalengine/logical.go
0.678966
0.457621
logical.go
starcoder
package softwarebackend import ( "image" "image/color" "math" "github.com/tfriedel6/canvas/backend/backendbase" ) func (b *SoftwareBackend) Clear(pts [4]backendbase.Vec) { iterateTriangles(pts[:], func(tri []backendbase.Vec) { b.fillTriangleNoAA(tri, func(x, y int) { if b.clip.AlphaAt(x, y).A == 0 { return } b.Image.SetRGBA(x, y, color.RGBA{}) }) }) } func (b *SoftwareBackend) Fill(style *backendbase.FillStyle, pts []backendbase.Vec, tf backendbase.Mat, canOverlap bool) { ffn := fillFunc(style) var triBuf [500]backendbase.Vec if tf != backendbase.MatIdentity { ptsOld := pts if len(pts) < len(triBuf) { pts = triBuf[:len(pts)] } else { pts = make([]backendbase.Vec, len(pts)) } for i, pt := range ptsOld { pts[i] = pt.MulMat(tf) } } if style.Blur > 0 { b.activateBlurTarget() b.fillTriangles(pts, ffn) b.drawBlurred(style.Blur) } else { b.fillTriangles(pts, ffn) } } func (b *SoftwareBackend) FillImageMask(style *backendbase.FillStyle, mask *image.Alpha, pts [4]backendbase.Vec) { ffn := fillFunc(style) mw := float64(mask.Bounds().Dx()) mh := float64(mask.Bounds().Dy()) b.fillQuad(pts, func(x, y, sx2, sy2 float64) color.RGBA { sxi := int(mw * sx2) syi := int(mh * sy2) a := mask.AlphaAt(sxi, syi) if a.A == 0 { return color.RGBA{} } col := ffn(x, y) return alphaColor(col, a) }) } func fillFunc(style *backendbase.FillStyle) func(x, y float64) color.RGBA { if lg := style.LinearGradient; lg != nil { lg := lg.(*LinearGradient) from := backendbase.Vec{style.Gradient.X0, style.Gradient.Y0} dir := backendbase.Vec{style.Gradient.X1 - style.Gradient.X0, style.Gradient.Y1 - style.Gradient.Y0} dirlen := math.Sqrt(dir[0]*dir[0] + dir[1]*dir[1]) dir[0] /= dirlen dir[1] /= dirlen return func(x, y float64) color.RGBA { pos := backendbase.Vec{x - from[0], y - from[1]} r := (pos[0]*dir[0] + pos[1]*dir[1]) / dirlen return lg.data.ColorAt(r) } } else if rg := style.RadialGradient; rg != nil { rg := rg.(*RadialGradient) from := backendbase.Vec{style.Gradient.X0, style.Gradient.Y0} to := backendbase.Vec{style.Gradient.X1, style.Gradient.Y1} radFrom := style.Gradient.RadFrom radTo := style.Gradient.RadTo return func(x, y float64) color.RGBA { pos := backendbase.Vec{x, y} oa := 0.5 * math.Sqrt( math.Pow(-2.0*from[0]*from[0]+2.0*from[0]*to[0]+2.0*from[0]*pos[0]-2.0*to[0]*pos[0]-2.0*from[1]*from[1]+2.0*from[1]*to[1]+2.0*from[1]*pos[1]-2.0*to[1]*pos[1]+2.0*radFrom*radFrom-2.0*radFrom*radTo, 2.0)- 4.0*(from[0]*from[0]-2.0*from[0]*pos[0]+pos[0]*pos[0]+from[1]*from[1]-2.0*from[1]*pos[1]+pos[1]*pos[1]-radFrom*radFrom)* (from[0]*from[0]-2.0*from[0]*to[0]+to[0]*to[0]+from[1]*from[1]-2.0*from[1]*to[1]+to[1]*to[1]-radFrom*radFrom+2.0*radFrom*radTo-radTo*radTo)) ob := (from[0]*from[0] - from[0]*to[0] - from[0]*pos[0] + to[0]*pos[0] + from[1]*from[1] - from[1]*to[1] - from[1]*pos[1] + to[1]*pos[1] - radFrom*radFrom + radFrom*radTo) oc := (from[0]*from[0] - 2.0*from[0]*to[0] + to[0]*to[0] + from[1]*from[1] - 2.0*from[1]*to[1] + to[1]*to[1] - radFrom*radFrom + 2.0*radFrom*radTo - radTo*radTo) o1 := (-oa + ob) / oc o2 := (oa + ob) / oc if math.IsNaN(o1) && math.IsNaN(o2) { return color.RGBA{} } o := math.Max(o1, o2) return rg.data.ColorAt(o) } } else if ip := style.ImagePattern; ip != nil { ip := ip.(*ImagePattern) img := ip.data.Image.(*Image) mip := img.mips[0] // todo select the right mip size w, h := img.Size() fw, fh := float64(w), float64(h) rx := ip.data.Repeat == backendbase.Repeat || ip.data.Repeat == backendbase.RepeatX ry := ip.data.Repeat == backendbase.Repeat || ip.data.Repeat == backendbase.RepeatY return func(x, y float64) color.RGBA { pos := backendbase.Vec{x, y} tfptx := pos[0]*ip.data.Transform[0] + pos[1]*ip.data.Transform[1] + ip.data.Transform[2] tfpty := pos[0]*ip.data.Transform[3] + pos[1]*ip.data.Transform[4] + ip.data.Transform[5] if !rx && (tfptx < 0 || tfptx >= fw) { return color.RGBA{} } if !ry && (tfpty < 0 || tfpty >= fh) { return color.RGBA{} } mx := int(math.Floor(tfptx)) % w if mx < 0 { mx += w } my := int(math.Floor(tfpty)) % h if my < 0 { my += h } return toRGBA(mip.At(mx, my)) } } return func(x, y float64) color.RGBA { return style.Color } } func (b *SoftwareBackend) clearStencil() { p := b.stencil.Pix for i := range p { p[i] = 0 } } func (b *SoftwareBackend) ClearClip() { p := b.clip.Pix for i := range p { p[i] = 255 } } func (b *SoftwareBackend) Clip(pts []backendbase.Vec) { b.clearStencil() iterateTriangles(pts[:], func(tri []backendbase.Vec) { b.fillTriangleNoAA(tri, func(x, y int) { b.stencil.SetAlpha(x, y, color.Alpha{A: 255}) }) }) p := b.clip.Pix p2 := b.stencil.Pix for i := range p { if p2[i] == 0 { p[i] = 0 } } }
backend/softwarebackend/fill.go
0.510985
0.458288
fill.go
starcoder
package day_21 const input = ` move position 2 to position 1 move position 2 to position 5 move position 2 to position 4 swap position 0 with position 2 move position 6 to position 5 swap position 0 with position 4 reverse positions 1 through 6 move position 7 to position 2 rotate right 4 steps rotate left 6 steps rotate based on position of letter a rotate based on position of letter c move position 2 to position 0 swap letter d with letter a swap letter g with letter a rotate left 6 steps reverse positions 4 through 7 swap position 6 with position 5 swap letter b with letter a rotate based on position of letter d rotate right 6 steps move position 3 to position 1 swap letter g with letter a swap position 3 with position 6 rotate left 7 steps swap letter b with letter c swap position 3 with position 7 move position 2 to position 6 swap letter b with letter a rotate based on position of letter d swap letter f with letter b move position 3 to position 4 rotate left 3 steps rotate left 6 steps rotate based on position of letter c move position 1 to position 3 swap letter e with letter a swap letter a with letter c rotate left 2 steps move position 6 to position 5 swap letter a with letter g rotate left 5 steps reverse positions 3 through 6 move position 7 to position 2 swap position 6 with position 5 swap letter e with letter c reverse positions 2 through 7 rotate based on position of letter e swap position 3 with position 5 swap letter e with letter d rotate left 3 steps rotate based on position of letter c move position 4 to position 7 rotate based on position of letter e reverse positions 3 through 5 rotate based on position of letter h swap position 3 with position 0 swap position 3 with position 4 move position 7 to position 4 rotate based on position of letter a reverse positions 6 through 7 rotate based on position of letter g swap letter d with letter h reverse positions 0 through 3 rotate right 2 steps rotate right 6 steps swap letter a with letter g reverse positions 2 through 4 rotate based on position of letter e move position 6 to position 0 reverse positions 0 through 6 move position 5 to position 1 swap position 5 with position 2 rotate right 3 steps move position 3 to position 1 rotate left 1 step reverse positions 1 through 3 rotate left 4 steps reverse positions 5 through 6 rotate right 7 steps reverse positions 0 through 2 move position 0 to position 2 swap letter b with letter c rotate based on position of letter d rotate left 1 step swap position 2 with position 1 swap position 6 with position 5 swap position 5 with position 0 swap letter a with letter c move position 7 to position 3 move position 6 to position 7 rotate based on position of letter h move position 3 to position 0 move position 4 to position 5 rotate left 4 steps swap letter h with letter c swap letter f with letter e swap position 1 with position 3 swap letter e with letter b rotate based on position of letter e `
adventofcode_2016/day_21/input.go
0.871324
0.996604
input.go
starcoder
package main import ( "time" ) // ReportFactory generates data structures that define reports about the comments made between two dates, // and provides method to deal with week numbers, so as to easily generate reports for a specific week. type ReportFactory struct { cutOff int64 // Max acceptable comment score for inclusion in the report leeway time.Duration // Shift of the report's start and end date nbTop uint // Number of items to summarize the weeks with statistics Timezone *time.Location // Timezone used to compute weeks, years and corresponding start/end dates } // NewReportFactory returns a ReportFactory. func NewReportFactory(conf ReportConf) ReportFactory { return ReportFactory{ leeway: conf.Leeway.Value, Timezone: conf.Timezone.Value, cutOff: conf.CutOff, nbTop: conf.NbTop, } } // ReportWeek generates a Report for an ISO week number and a year. func (rf ReportFactory) ReportWeek(conn StorageConn, weekNum uint8, year int) (Report, error) { start, end := rf.WeekYearToDates(weekNum, year) report, err := rf.Report(conn, start.Add(-rf.leeway), end.Add(-rf.leeway)) if err != nil { return report, err } report.Week = weekNum report.Year = year return report, nil } // StatsWeek generates a statistical summary of the activity for an ISO week number and year. func (rf ReportFactory) StatsWeek(conn StorageConn, weekNum uint8, year int) (ReportHeader, error) { start, end := rf.WeekYearToDates(weekNum, year) header, err := rf.Stats(conn, start.Add(-rf.leeway), end.Add(-rf.leeway)) if err != nil { return header, err } header.Week = weekNum header.Year = year return header, nil } // Report generates a Report between two arbitrary dates. func (rf ReportFactory) Report(conn StorageConn, start, end time.Time) (Report, error) { var comments []Comment var stats StatsCollection err := conn.WithTx(func() error { var err error comments, err = conn.GetCommentsBelowBetween(rf.cutOff, start, end) if err != nil { return err } stats, err = conn.StatsBetween(start, end) return err }) report := Report{ ReportInfo: ReportInfo{ CutOff: rf.cutOff, End: end, Start: start, Timezone: rf.Timezone, Version: Version, }, comments: comments, nbTop: rf.nbTop, stats: stats.Filter(func(s Stats) bool { return s.Sum < rf.cutOff }), } return report, err } // Stats generates a statistical summary of the activity between two arbitrary dates. func (rf ReportFactory) Stats(conn StorageConn, start, end time.Time) (ReportHeader, error) { stats, err := conn.StatsBetween(start, end) global := stats.Stats() report := ReportHeader{ ReportInfo: ReportInfo{ CutOff: rf.cutOff, End: end, Start: start, Timezone: rf.Timezone, Version: Version, }, Average: stats.OrderBy(func(a, b Stats) bool { return a.Average < b.Average }).ToView(rf.Timezone), Delta: stats.ToView(rf.Timezone), Global: global.ToView(0, rf.Timezone), Len: global.Count, } return report, err } // CurrentWeekCoordinates returns the week number and year of the current week according to the ReportFactory's time zone. func (rf ReportFactory) CurrentWeekCoordinates() (uint8, int) { year, week := rf.Now().ISOWeek() return uint8(week), year } // LastWeekCoordinates returns the week number and year of the previous week according to the ReportFactory's time zone. func (rf ReportFactory) LastWeekCoordinates() (uint8, int) { year, week := rf.Now().AddDate(0, 0, -7).ISOWeek() return uint8(week), year } // WeekYearToDates converts a week number and year to start/end dates according to the ReportFactory's time zone. func (rf ReportFactory) WeekYearToDates(weekNum uint8, year int) (time.Time, time.Time) { weekStart := rf.WeekNumToStartDate(weekNum, year) weekEnd := weekStart.AddDate(0, 0, 7) return weekStart, weekEnd } // WeekNumToStartDate converts a week number and year to the week's start date according to the ReportFactory's time zone. func (rf ReportFactory) WeekNumToStartDate(weekNum uint8, year int) time.Time { return rf.StartOfFirstWeek(year).AddDate(0, 0, int(weekNum-1)*7) } // StartOfFirstWeek returns the date at which the first ISO week of the given year starts according to the ReportFactory's time zone. func (rf ReportFactory) StartOfFirstWeek(year int) time.Time { inFirstWeek := time.Date(year, 1, 4, 0, 0, 0, 0, rf.Timezone) dayPosition := (inFirstWeek.Weekday() + 6) % 7 return inFirstWeek.AddDate(0, 0, -int(dayPosition)) } // Now returns the current date according to the ReportFactory's time zone. func (rf ReportFactory) Now() time.Time { return time.Now().In(rf.Timezone) } // ReportInfo describes the metadata of a report. type ReportInfo struct { CutOff int64 // Max score of the comments included in the report End time.Time // End date of the report Start time.Time // Start date of the report Timezone *time.Location // Timezone of dates Version SemVer // Version of the software with which the report was made Week uint8 // ISO Week number of the report Year int // Year of the report } // ReportHeader describes a summary of a Report suitable for a use in a template. type ReportHeader struct { ReportInfo Global StatsView Average []StatsView // List of users with the lowest average karma Delta []StatsView // List of users with the biggest loss of karma Len uint64 // Number of comments in the report } // ReportComment is a specialized version of CommentView for use in Report. type ReportComment struct { CommentView Stats StatsView // Stats for that user } // Report describes the commenting activity between two dates that may correspond to a week number. // It is suitable for use in a template. type Report struct { ReportInfo nbTop uint // Max number of statistics to put in the report's headers to summarize the week stats StatsCollection // Statistics for all users comments []Comment CommentBodyConverter CommentBodyConverter } // Header returns a data structure that describes a summary of the Report. func (r Report) Header() ReportHeader { return ReportHeader{ ReportInfo: r.ReportInfo, Average: r.stats.OrderBy(func(a, b Stats) bool { return a.Average < b.Average }).Limit(r.nbTop).ToView(r.Timezone), Delta: r.stats.Limit(r.nbTop).ToView(r.Timezone), Global: r.stats.Stats().ToView(0, r.Timezone), Len: r.Len(), } } // Comments returns a slice of data structures describing comments that are suitable for use in templates. func (r Report) Comments() []ReportComment { n := r.Len() byName := r.stats.ToMap() views := make([]ReportComment, 0, n) for i := uint64(0); i < n; i++ { comment := r.comments[i] number := i + 1 views = append(views, ReportComment{ CommentView: comment.ToView(number, r.Timezone, r.CommentBodyConverter), Stats: byName[comment.Author].ToView(number, r.Timezone), }) } return views } // Len returns the number of comments without having to run Comments. func (r Report) Len() uint64 { return uint64(len(r.comments)) }
report.go
0.76999
0.529263
report.go
starcoder
package sweetiebot import ( "fmt" "sort" "strconv" "strings" "github.com/bwmarrin/discordgo" ) type HelpCommand struct { } func (c *HelpCommand) Name() string { return "Help" } func (c *HelpCommand) Process(args []string, msg *discordgo.Message, info *GuildInfo) (string, bool) { if len(args) == 0 { s := []string{"Sweetie Bot knows the following commands. For more information on a specific command, type !help [command].\n"} commands := GetCommandsInOrder(info.commands) for _, v := range commands { s = append(s, v+": "+info.commands[v].UsageShort()) } return "```" + strings.Join(s, "\n") + "```", true } v, ok := info.commands[strings.ToLower(args[0])] if !ok { return "``` Sweetie Bot doesn't recognize that command. You can check what commands Sweetie Bot knows by typing !help.```", false } return "```> !" + v.Name() + " " + v.Usage(info) + "```", true } func (c *HelpCommand) Usage(info *GuildInfo) string { return info.FormatUsage(c, "[command]", "Lists all available commands Sweetie Bot knows, or gives information about the given command. Of course, you should have figured this out by now, since you just typed !help help for some reason.") } func (c *HelpCommand) UsageShort() string { return "[PM Only] Generates the list you are looking at right now." } type AboutCommand struct { } func (c *AboutCommand) Name() string { return "About" } func (c *AboutCommand) Process(args []string, msg *discordgo.Message, info *GuildInfo) (string, bool) { s := "```Sweetie Bot version " + sb.version.String() if sb.Debug { return s + " [debug]```", false } return s + " [release]```", false } func (c *AboutCommand) Usage(info *GuildInfo) string { return info.FormatUsage(c, "", "Displays information about Sweetie Bot. What, did you think it would do something else?") } func (c *AboutCommand) UsageShort() string { return "Displays information about Sweetie Bot." } type RulesCommand struct { } func (c *RulesCommand) Name() string { return "Rules" } func (c *RulesCommand) Process(args []string, msg *discordgo.Message, info *GuildInfo) (string, bool) { if len(info.config.Rules) == 0 { return "```I don't know what the rules are in this server... ¯\\_(ツ)_/¯```", false } if len(args) < 1 { rules := make([]string, 0, len(info.config.Rules)+1) rules = append(rules, "Official rules of "+info.Guild.Name+":") keys := MapIntToSlice(info.config.Rules) sort.Ints(keys) for _, v := range keys { rules = append(rules, fmt.Sprintf("%v. %s", v, info.config.Rules[v])) } return strings.Join(rules, "\n"), len(rules) > 4 } arg, err := strconv.Atoi(args[0]) if err != nil { return "```Rule index must be a number!```", false } rule, ok := info.config.Rules[arg] if !ok { return "```That's not a rule! Stop making things up!```", false } return fmt.Sprintf("%v. %s", arg, rule), false } func (c *RulesCommand) Usage(info *GuildInfo) string { return info.FormatUsage(c, "[index]", "Lists all the rules in this server, or displays the specific rule requested, if it exists. Rules can be set using \"!setconfig rules 1 this is a rule\"") } func (c *RulesCommand) UsageShort() string { return "Lists the rules of the server." } type ChangelogCommand struct { } func (c *ChangelogCommand) Name() string { return "Changelog" } func (c *ChangelogCommand) Process(args []string, msg *discordgo.Message, info *GuildInfo) (string, bool) { v := Version{0, 0, 0, 0} if len(args) == 0 { versions := make([]string, 0, len(sb.changelog)+1) versions = append(versions, "All versions of Sweetie Bot with a changelog:") keys := MapIntToSlice(sb.changelog) sort.Ints(keys) for i := len(keys) - 1; i >= 0; i-- { k := keys[i] version := Version{byte(k >> 24), byte((k >> 16) & 0xFF), byte((k >> 8) & 0xFF), byte(k & 0xFF)} versions = append(versions, version.String()) } return "```" + strings.Join(versions, "\n") + "```", len(versions) > 6 } if strings.ToLower(args[0]) == "current" { v = sb.version } else { s := strings.Split(args[0], ".") if len(s) > 0 { i, _ := strconv.Atoi(s[0]) v.major = byte(i) } if len(s) > 1 { i, _ := strconv.Atoi(s[1]) v.minor = byte(i) } if len(s) > 2 { i, _ := strconv.Atoi(s[2]) v.revision = byte(i) } if len(s) > 3 { i, _ := strconv.Atoi(s[3]) v.build = byte(i) } } log, ok := sb.changelog[v.Integer()] if !ok { return "```That's not a valid version of Sweetie Bot! Use this command with no arguments to list all valid versions, or use \"current\" to get the most recent changelog.```", false } return fmt.Sprintf("```%s\n--------\n%s```", v.String(), log), false } func (c *ChangelogCommand) Usage(info *GuildInfo) string { return info.FormatUsage(c, "[version]", "Displays the given changelog for Sweetie Bot. If no version is given, lists all versions with an associated changelog. Use \"current\" to get the changelog for the most recent version.") } func (c *ChangelogCommand) UsageShort() string { return "Retrieves the changelog for Sweetie Bot." }
sweetiebot/help_command.go
0.596903
0.481637
help_command.go
starcoder
// Package pl provides holiday definitions for Poland. package pl import ( "time" "github.com/devechelon/cal/v2" "github.com/devechelon/cal/v2/aa" ) var ( // NewYear represents New Year's Day on 1-Jan NewYear = aa.NewYear.Clone(&cal.Holiday{Name: "Nowy Rok", Type: cal.ObservancePublic}) // ThreeKings represents Epiphany on 6-Jan ThreeKings = aa.Epiphany.Clone(&cal.Holiday{Name: "Święto Trzech Króli", Type: cal.ObservancePublic}) // EasterMonday represents Easter Monday on the day after Easter EasterMonday = aa.EasterMonday.Clone(&cal.Holiday{Name: "drugi dzień Wielkiej Nocy", Type: cal.ObservancePublic}) // LabourDay represents Labor Day on 1-May LabourDay = aa.WorkersDay.Clone(&cal.Holiday{Name: "Święto Państwowe", Type: cal.ObservancePublic}) // ConstitutionDay represents Constitution Day on 3-May ConstitutionDay = &cal.Holiday{ Name: "<NAME>", Type: cal.ObservancePublic, Month: time.May, Day: 3, Func: cal.CalcDayOfMonth, } // CorpusChristi represents Corpus Christi on the 60th day after Easter CorpusChristi = aa.CorpusChristi.Clone(&cal.Holiday{Name: "dzień Bożego Ciała", Type: cal.ObservancePublic}) // AssumptionBlessedVirginMary represents Assumption of Mary on 15-Aug AssumptionBlessedVirginMary = aa.AssumptionOfMary.Clone(&cal.Holiday{Name: "Wniebowzięcie Najświętsze<NAME>", Type: cal.ObservancePublic}) // AllSaints represents All Saints' Day on 1-Nov AllSaints = aa.AllSaintsDay.Clone(&cal.Holiday{Name: "Wszystkich Świętych", Type: cal.ObservancePublic}) // NationalIndependenceDay represents National Independence Day on 11-Nov NationalIndependenceDay = aa.ArmisticeDay.Clone(&cal.Holiday{Name: "Narodowe Święto Niepodległości", Type: cal.ObservancePublic}) // ChristmasDayOne represents Christmas Day on 25-Dec ChristmasDayOne = aa.ChristmasDay.Clone(&cal.Holiday{Name: "pierwszy dzień Bożego Narodzenia", Type: cal.ObservancePublic}) // ChristmasDayTwo represents the second day of Christmas on 26-Dec ChristmasDayTwo = aa.ChristmasDay2.Clone(&cal.Holiday{Name: "drugi dzień Bożego Narodzenia", Type: cal.ObservancePublic}) // Holidays provides a list of the standard national holidays Holidays = []*cal.Holiday{ NewYear, ThreeKings, EasterMonday, LabourDay, ConstitutionDay, CorpusChristi, AssumptionBlessedVirginMary, AllSaints, NationalIndependenceDay, ChristmasDayOne, ChristmasDayTwo, } )
v2/pl/pl_holidays.go
0.514644
0.523238
pl_holidays.go
starcoder
package explain import ( "fmt" "github.com/crillab/gophersat/solver" ) // MUSMaxSat returns a Minimal Unsatisfiable Subset for the problem using the MaxSat strategy. // A MUS is an unsatisfiable subset such that, if any of its clause is removed, // the problem becomes satisfiable. // A MUS can be useful to understand why a problem is UNSAT, but MUSes are expensive to compute since // a SAT solver must be called several times on parts of the original problem to find them. // With the MaxSat strategy, the function computes the MUS through several calls to MaxSat. func (pb *Problem) MUSMaxSat() (mus *Problem, err error) { pb2 := pb.clone() nbVars := pb2.NbVars NbClauses := pb2.NbClauses weights := make([]int, NbClauses) // Weights of each clause relaxLits := make([]solver.Lit, NbClauses) // Set of all relax lits relaxLit := nbVars + 1 // Index of last used relax lit for i, clause := range pb2.Clauses { pb2.Clauses[i] = append(clause, relaxLit) relaxLits[i] = solver.IntToLit(int32(relaxLit)) weights[i] = 1 relaxLit++ } prob := solver.ParseSlice(pb2.Clauses) prob.SetCostFunc(relaxLits, weights) s := solver.New(prob) s.Verbose = pb.Options.Verbose var musClauses [][]int done := make([]bool, NbClauses) // Indicates whether a clause is already part of MUS or not yet for { cost := s.Minimize() if cost == -1 { return makeMus(nbVars, musClauses), nil } if cost == 0 { return nil, fmt.Errorf("cannot extract MUS from satisfiable problem") } model := s.Model() for i, clause := range pb.Clauses { if !done[i] && !satClause(clause, model) { // The clause is part of the MUS pb2.Clauses = append(pb2.Clauses, []int{-(nbVars + i + 1)}) // Now, relax lit has to be false pb2.NbClauses++ musClauses = append(musClauses, clause) done[i] = true // Make it a hard clause before restarting solver lits := make([]solver.Lit, len(clause)) for j, lit := range clause { lits[j] = solver.IntToLit(int32(lit)) } s.AppendClause(solver.NewClause(lits)) } } if pb.Options.Verbose { fmt.Printf("c Currently %d/%d clauses in MUS\n", len(musClauses), NbClauses) } prob = solver.ParseSlice(pb2.Clauses) prob.SetCostFunc(relaxLits, weights) s = solver.New(prob) s.Verbose = pb.Options.Verbose } } // true iff the clause is satisfied by the model func satClause(clause []int, model []bool) bool { for _, lit := range clause { if (lit > 0 && model[lit-1]) || (lit < 0 && !model[-lit-1]) { return true } } return false } func makeMus(nbVars int, clauses [][]int) *Problem { mus := &Problem{ Clauses: clauses, NbVars: nbVars, NbClauses: len(clauses), units: make([]int, nbVars), } for _, clause := range clauses { if len(clause) == 1 { lit := clause[0] if lit > 0 { mus.units[lit-1] = 1 } else { mus.units[-lit-1] = -1 } } } return mus } // MUSInsertion returns a Minimal Unsatisfiable Subset for the problem using the insertion method. // A MUS is an unsatisfiable subset such that, if any of its clause is removed, // the problem becomes satisfiable. // A MUS can be useful to understand why a problem is UNSAT, but MUSes are expensive to compute since // a SAT solver must be called several times on parts of the original problem to find them. // The insertion algorithm is efficient is many cases, as it calls the same solver several times in a row. // However, in some cases, the number of calls will be higher than using other methods. // For instance, if called on a formula that is already a MUS, it will perform n*(n-1) calls to SAT, where // n is the number of clauses of the problem. func (pb *Problem) MUSInsertion() (mus *Problem, err error) { pb2, err := pb.UnsatSubset() if err != nil { return nil, fmt.Errorf("could not extract MUS: %v", err) } mus = &Problem{NbVars: pb2.NbVars} clauses := pb2.Clauses for { if pb.Options.Verbose { fmt.Printf("c mus currently contains %d clauses\n", mus.NbClauses) } s := solver.New(solver.ParseSliceNb(mus.Clauses, mus.NbVars)) s.Verbose = pb.Options.Verbose st := s.Solve() if st == solver.Unsat { // Found the MUS return mus, nil } // Add clauses until the problem becomes UNSAT idx := 0 for st == solver.Sat { clause := clauses[idx] lits := make([]solver.Lit, len(clause)) for i, lit := range clause { lits[i] = solver.IntToLit(int32(lit)) } cl := solver.NewClause(lits) s.AppendClause(cl) idx++ st = s.Solve() } idx-- // We went one step too far, go back mus.Clauses = append(mus.Clauses, clauses[idx]) // Last clause is part of the MUS mus.NbClauses++ if pb.Options.Verbose { fmt.Printf("c removing %d/%d clause(s)\n", len(clauses)-idx, len(clauses)) } clauses = clauses[:idx] // Remaining clauses are not part of the MUS } } // MUSDeletion returns a Minimal Unsatisfiable Subset for the problem using the insertion method. // A MUS is an unsatisfiable subset such that, if any of its clause is removed, // the problem becomes satisfiable. // A MUS can be useful to understand why a problem is UNSAT, but MUSes are expensive to compute since // a SAT solver must be called several times on parts of the original problem to find them. // The deletion algorithm is guaranteed to call exactly n SAT solvers, where n is the number of clauses in the problem. // It can be quite efficient, but each time the solver is called, it is starting from scratch. // Other methods keep the solver "hot", so despite requiring more calls, these methods can be more efficient in practice. func (pb *Problem) MUSDeletion() (mus *Problem, err error) { pb2, err := pb.UnsatSubset() if err != nil { return nil, fmt.Errorf("could not extract MUS: %v", err) } pb2.NbVars += pb2.NbClauses // Add one relax var for each clause for i, clause := range pb2.Clauses { // Add relax lit to each clause newClause := make([]int, len(clause)+1) copy(newClause, clause) newClause[len(clause)] = pb.NbVars + i + 1 // Add relax lit to the clause pb2.Clauses[i] = newClause } s := solver.New(solver.ParseSlice(pb2.Clauses)) asumptions := make([]solver.Lit, pb2.NbClauses) for i := 0; i < pb2.NbClauses; i++ { asumptions[i] = solver.IntToLit(int32(-(pb.NbVars + i + 1))) // At first, all asumptions are false } for i := range pb2.Clauses { // Relax current clause asumptions[i] = asumptions[i].Negation() s.Assume(asumptions) if s.Solve() == solver.Sat { // It is now sat; reinsert the clause, i.e re-falsify the relax lit asumptions[i] = asumptions[i].Negation() if pb.Options.Verbose { fmt.Printf("c clause %d/%d: kept\n", i+1, pb2.NbClauses) } } else if pb.Options.Verbose { fmt.Printf("c clause %d/%d: removed\n", i+1, pb2.NbClauses) } } mus = &Problem{ NbVars: pb.NbVars, } for i, val := range asumptions { if !val.IsPositive() { // Lit is not relaxed, meaning the clause is part of the MUS clause := pb2.Clauses[i] clause = clause[:len(clause)-1] // Remove relax lit mus.Clauses = append(mus.Clauses, clause) } mus.NbClauses = len(mus.Clauses) } return mus, nil } // MUS returns a Minimal Unsatisfiable Subset for the problem. // A MUS is an unsatisfiable subset such that, if any of its clause is removed, // the problem becomes satisfiable. // A MUS can be useful to understand why a problem is UNSAT, but MUSes are expensive to compute since // a SAT solver must be called several times on parts of the original problem to find them. // The exact algorithm used to compute the MUS is not guaranteed. If you want to use a given algorithm, // use the relevant functions. func (pb *Problem) MUS() (mus *Problem, err error) { return pb.MUSDeletion() }
explain/mus.go
0.699254
0.446736
mus.go
starcoder
package suture /* Service is the interface that describes a service to a Supervisor. Serve Method The Serve method is called by a Supervisor to start the service. The service should execute within the goroutine that this is called in. If this function either returns or panics, the Supervisor will call it again. A Serve method SHOULD do as much cleanup of the state as possible, to prevent any corruption in the previous state from crashing the service again. Stop Method This method is used by the supervisor to stop the service. Calling this directly on a Service given to a Supervisor will simply result in the Service being restarted; use the Supervisor's .Remove(ServiceToken) method to stop a service. A supervisor will call .Stop() only once. Thus, it may be as destructive as it likes to get the service to stop. Once Stop has been called on a Service, the Service SHOULD NOT be reused in any other supervisor! Because of the impossibility of guaranteeing that the service has actually stopped in Go, you can't prove that you won't be starting two goroutines using the exact same memory to store state, causing completely unpredictable behavior. Stop should not return until the service has actually stopped. "Stopped" here is defined as "the service will stop servicing any further requests in the future". For instance, a common implementation is to receive a message on a dedicated "stop" channel and immediately returning. Once the stop command has been processed, the service is stopped. Another common Stop implementation is to forcibly close an open socket or other resource, which will cause detectable errors to manifest in the service code. Bear in mind that to perfectly correctly use this approach requires a bit more work to handle the chance of a Stop command coming in before the resource has been created. If a service does not Stop within the supervisor's timeout duration, a log entry will be made with a descriptive string to that effect. This does not guarantee that the service is hung; it may still get around to being properly stopped in the future. Until the service is fully stopped, both the service and the spawned goroutine trying to stop it will be "leaked". Stringer Interface When a Service is added to a Supervisor, the Supervisor will create a string representation of that service used for logging. If you implement the fmt.Stringer interface, that will be used. If you do not implement the fmt.Stringer interface, a default fmt.Sprintf("%#v") will be used. */ type Service interface { Serve() Stop() }
vendor/github.com/thejerf/suture/service.go
0.609989
0.435601
service.go
starcoder
// Package cursor defines the oswin cursor interface and standard system // cursors that are supported across platforms package cursor import ( "fmt" "log" "github.com/goki/ki/kit" ) // todo: apps can add new named shapes starting at ShapesN // Shapes are the standard cursor shapes available on all platforms type Shapes int32 const ( // Arrow is the standard arrow pointer Arrow Shapes = iota // Cross is a crosshair plus-like cursor -- typically used for precise actions. Cross // DragCopy indicates that the current drag operation will copy the dragged items DragCopy // DragMove indicates that the current drag operation will move the dragged items DragMove // DragLink indicates that the current drag operation will link the dragged items DragLink // HandPointing is a hand with a pointing index finger -- typically used // to indicate a link is clickable. HandPointing // HandOpen is an open hand -- typically used to indicate ability to click // and drag to move something. HandOpen // HandClosed is a closed hand -- typically used to indicate a dragging // operation involving scrolling. HandClosed // Help is an arrow and question mark indicating help is available. Help // IBeam is the standard text-entry symbol like a capital I. IBeam // Not is a slashed circle indicating operation not allowed (NO). Not // UpDown is Double-pointed arrow pointing up and down (SIZENS). UpDown // LeftRight is a Double-pointed arrow pointing west and east (SIZEWE). LeftRight // UpRight is a Double-pointed arrow pointing up-right and down-left (SIZEWE). UpRight // UpLeft is a Double-pointed arrow pointing up-left and down-right (SIZEWE). UpLeft // AllArrows is all four directions of arrow pointing. AllArrows // Wait is a system-dependent busy / wait cursor (typically an hourglass). Wait // ShapesN is number of standard cursor shapes ShapesN ) //go:generate stringer -type=Shapes var KiT_Shapes = kit.Enums.AddEnum(ShapesN, kit.NotBitFlag, nil) // Drags is a map-set of cursors used for signaling dragging events. var Drags = map[Shapes]struct{}{ DragCopy: {}, DragMove: {}, DragLink: {}, } // Cursor manages the mouse cursor / pointer appearance. Currently only a // fixed set of standard cursors are supported, but in the future it will be // possible to set the cursor from an image / svg. type Cursor interface { // Current returns the current shape of the cursor. Current() Shapes // Push pushes a new active cursor. Push(sh Shapes) // PushIfNot pushes a new active cursor if it is not already set to given shape. PushIfNot(sh Shapes) bool // Pop pops cursor off the stack and restores the previous cursor -- an // error message is emitted if no more cursors on the stack (programming // error). Pop() // PopIf pops cursor off the stack and restores the previous cursor if the // current cursor is the given shape. PopIf(sh Shapes) bool // Set sets the active cursor, without reference to the cursor stack -- // generally not recommended for direct use -- prefer Push / Pop. Set(sh Shapes) // IsVisible returns whether cursor is currently visible (according to Hide / show actions) IsVisible() bool // Hide hides the cursor if it is not already hidden. Hide() // Show shows the cursor after a hide if it is hidden. Show() // IsDrag returns true if the current cursor is used for signaling dragging events. IsDrag() bool } // CursorBase provides the common infrastructure for Cursor interface. type CursorBase struct { // Stack is the stack of shapes from push / pop actions. Stack []Shapes // Cur is current shape -- maintained by std methods. Cur Shapes // Vis is visibility: be sure to initialize to true! Vis bool } func (c *CursorBase) Current() Shapes { return c.Cur } func (c *CursorBase) IsVisible() bool { return c.Vis } func (c *CursorBase) IsDrag() bool { _, has := Drags[c.Cur] return has } // PushStack pushes item on the stack func (c *CursorBase) PushStack(sh Shapes) { c.Cur = sh c.Stack = append(c.Stack, sh) } // PopStack pops item off the stack, returning 2nd-to-last item on stack func (c *CursorBase) PopStack() (Shapes, error) { sz := len(c.Stack) if len(c.Stack) == 0 { err := fmt.Errorf("gi.oswin.cursor PopStack: stack is empty -- programmer error\n") log.Print(err) return Arrow, err } c.Stack = c.Stack[:sz-1] c.Cur = c.PeekStack() return c.Cur, nil } // PeekStack returns top item on the stack (default Arrow if nothing on stack) func (c *CursorBase) PeekStack() Shapes { sz := len(c.Stack) if len(c.Stack) == 0 { return Arrow } return c.Stack[sz-1] }
oswin/cursor/cursor.go
0.530236
0.441673
cursor.go
starcoder
package algorithms import ( "math" ) func unDef(f float64) bool { if math.IsNaN(f) { return true } if math.IsInf(f, 1) { return true } if math.IsInf(f, -1) { return true } return false } func Ewma(series []float64, com float64) []float64 { var cur float64 var prev float64 var oldw float64 var adj float64 N := len(series) ret := make([]float64, N) if N == 0 { return ret } oldw = com / (1 + com) adj = oldw ret[0] = series[0] / (1 + com) for i := 1; i < N; i++ { cur = series[i] prev = ret[i-1] if unDef(cur) { ret[i] = prev } else { if unDef(prev) { ret[i] = cur / (1 + com) } else { ret[i] = (com*prev + cur) / (1 + com) } } } for i := 0; i < N; i++ { cur = ret[i] if !math.IsNaN(cur) { ret[i] = ret[i] / (1. - adj) adj *= oldw } else { if i > 0 { ret[i] = ret[i-1] } } } return ret } func EwmStdLast(series []float64, com float64) float64 { m1st := Ewma(series, com) var series2 []float64 for _, val := range series { series2 = append(series2, val*val) } m2nd := Ewma(series2, com) i := len(m1st) - 1 t := m2nd[i] - math.Pow(m1st[i], 2) t *= (1.0 + 2.0*com) / (2.0 * com) if t < 0 { return 0 } return math.Sqrt(t) } func copyLast(series []int64, N int) []float64 { var start = len(series) - N if start < 0 { start = 0 } var end = len(series) ret := make([]float64, end-start) for i := start; i < end; i++ { ret[i-start] = float64(series[i]) } return ret } func sum(numbers []float64) (total float64) { for _, x := range numbers { total += x } return total } func mean(series []float64) float64 { return float64(sum(series)) / float64(len(series)) } func stdDev(numbers []float64, mean float64) float64 { total := 0.0 for _, number := range numbers { total += math.Pow(float64(number)-mean, 2) } variance := total / float64(len(numbers)-1) return math.Sqrt(variance) } func removeOutliers(series []float64, m float64) []float64 { u := mean(series) s := stdDev(series, u) var ret []float64 for _, e := range series { if u-m*s < e && e < u+m*s { ret = append(ret, e) } } if len(ret) == 0 { return series } return ret } func autoAlgEwmaStdRemoveOutliers(series []int64, factor float64) int64 { var last20 = copyLast(series, 20) last20 = removeOutliers(last20, 3) if len(last20) == 0 { return 1000 } var medians = Ewma(last20, 10) var median = medians[len(medians)-1] var stdev = EwmStdLast(last20, 10) var ret = median + factor*stdev + 1000 if math.IsNaN(ret) { return 0 } return int64(ret + 0.5) } func AutoAlg(series []int64) int64 { return autoAlgEwmaStdRemoveOutliers(series, 3) }
algorithms/auto1.go
0.611614
0.414662
auto1.go
starcoder
package dns // NameUsed sets the RRs in the prereq section to // "Name is in use" RRs. RFC 2136 section 2.4.4. func (u *Msg) NameUsed(rr []RR) { u.Answer = make([]RR, len(rr)) for i, r := range rr { u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}} } } // NameNotUsed sets the RRs in the prereq section to // "Name is in not use" RRs. RFC 2136 section 2.4.5. func (u *Msg) NameNotUsed(rr []RR) { u.Answer = make([]RR, len(rr)) for i, r := range rr { u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassNONE}} } } // Used sets the RRs in the prereq section to // "RRset exists (value dependent -- with rdata)" RRs. RFC 2136 section 2.4.2. func (u *Msg) Used(rr []RR) { if len(u.Question) == 0 { panic("dns: empty question section") } u.Answer = make([]RR, len(rr)) for i, r := range rr { u.Answer[i] = r u.Answer[i].Header().Class = u.Question[0].Qclass } } // RRsetUsed sets the RRs in the prereq section to // "RRset exists (value independent -- no rdata)" RRs. RFC 2136 section 2.4.1. func (u *Msg) RRsetUsed(rr []RR) { u.Answer = make([]RR, len(rr)) for i, r := range rr { u.Answer[i] = r u.Answer[i].Header().Class = ClassANY u.Answer[i].Header().Ttl = 0 u.Answer[i].Header().Rdlength = 0 } } // RRsetNotUsed sets the RRs in the prereq section to // "RRset does not exist" RRs. RFC 2136 section 2.4.3. func (u *Msg) RRsetNotUsed(rr []RR) { u.Answer = make([]RR, len(rr)) for i, r := range rr { u.Answer[i] = r u.Answer[i].Header().Class = ClassNONE u.Answer[i].Header().Rdlength = 0 u.Answer[i].Header().Ttl = 0 } } // Insert creates a dynamic update packet that adds an complete RRset, see RFC 2136 section 2.5.1. func (u *Msg) Insert(rr []RR) { if len(u.Question) == 0 { panic("dns: empty question section") } u.Ns = make([]RR, len(rr)) for i, r := range rr { u.Ns[i] = r u.Ns[i].Header().Class = u.Question[0].Qclass } } // RemoveRRset creates a dynamic update packet that deletes an RRset, see RFC 2136 section 2.5.2. func (u *Msg) RemoveRRset(rr []RR) { u.Ns = make([]RR, len(rr)) for i, r := range rr { u.Ns[i] = r u.Ns[i].Header().Class = ClassANY u.Ns[i].Header().Rdlength = 0 u.Ns[i].Header().Ttl = 0 } } // RemoveName creates a dynamic update packet that deletes all RRsets of a name, see RFC 2136 section 2.5.3 func (u *Msg) RemoveName(rr []RR) { u.Ns = make([]RR, len(rr)) for i, r := range rr { u.Ns[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}} } } // Remove creates a dynamic update packet deletes RR from the RRSset, see RFC 2136 section 2.5.4 func (u *Msg) Remove(rr []RR) { u.Ns = make([]RR, len(rr)) for i, r := range rr { u.Ns[i] = r u.Ns[i].Header().Class = ClassNONE u.Ns[i].Header().Ttl = 0 } }
github.com/miekg/dns/update.go
0.544559
0.419648
update.go
starcoder
package log import "time" // Interface represents the API of both Logger and Entry and exposes 3 types of // functions: // - functions named like WithXX and Watch return entries that can be used in chained call // - xxf are in printf style with message format and arguments // - logging functions - like Info - log a message and optional kv arguments that // are expected to be key/value pairs exception made of error values that can // be passed alone and will automatically be assigned to a key 'error'. type Interface interface { // WithFields returns a new entry with the given Fields appended WithFields(Fielder) *Entry // WithField returns a new entry with the given name and value appended to fields WithField(name string, value interface{}) *Entry // WithDuration returns a new entry with the given duration appended as a 'duration' field WithDuration(time.Duration) *Entry // WithError returns a new entry with the given error appended as an 'error' field WithError(error) *Entry Trace(msg string, kv ...interface{}) // Trace is a Trace level message with KV values. Debug(msg string, kv ...interface{}) // Debug is a Debug level message with KV values. Info(msg string, kv ...interface{}) // Info is a Info level message with KV values. Warn(msg string, kv ...interface{}) // Warn is a Warn level message with KV values. Error(msg string, kv ...interface{}) // Error is a Error level message with KV values. Fatal(msg string, kv ...interface{}) // Fatal is a Fatal level message with KV values. Tracef(string, ...interface{}) // Tracef is a Trace level formatted message. Debugf(string, ...interface{}) // Debugf is a Debug level formatted message. Infof(string, ...interface{}) // Infof is a Info level formatted message. Warnf(string, ...interface{}) // Warnf is a Warn level formatted message. Errorf(string, ...interface{}) // Errorf is a Error level formatted message. Fatalf(string, ...interface{}) // Tracef is a Fatal level formatted message. // Watch returns a new entry whose Stop method can be used to fire off a // corresponding log that will include the duration taken for completion: // useful with defer. Watch(string) *Entry }
interface.go
0.522689
0.470919
interface.go
starcoder
package dualshock import ( "encoding/binary" "io" ) // Controller describes the reference to the hardware device type Controller struct { reader io.Reader queue chan []byte errors chan error interrupt chan int } // DPad is the data structure describing the joysticks on the controller type DPad struct { X, Y int } // TrackPad is the touch surface in the middle of the controller type TrackPad struct { ID int Active bool X, Y int } // Motion contains information about acceleration in x, y and z axis type Motion struct { X, Y, Z int16 } // Orientation describes roll, yaw and pith of the controller type Orientation struct { Roll, Yaw, Pitch int16 } // State is the overall state of the controller, the controller will output 254 // states within a second. type State struct { L1, L2, L3 bool R1, R2, R3 bool Up, Down, Left, Right bool Cross, Circle, Square, Triangle bool Share, Options, PSHome bool Timestamp, BatteryLevel int LeftDPad DPad RightDPad DPad Motion Motion Orientation Orientation // TrackPad is true if its pressed TrackPad bool // TrackPad0 contains info relating to a touch event TrackPad0 TrackPad // TrackPad1 only register touches if TrackPad0 also does, this enables // multi touch functionality TrackPad1 TrackPad // Analog describes the analog position of buttons, on the PS4 controller its // only L2 and R2 which has analog output as well as digital. Analog struct{ L2, R2 int } } // transform reads a slice of bytes and turns them into a valid state for the // controller func transform(b []byte) State { return State{ L1: (b[6] & 0x01) != 0, L2: (b[6] & 0x04) != 0, L3: (b[6] & 0x40) != 0, R1: (b[6] & 0x02) != 0, R2: (b[6] & 0x08) != 0, R3: (b[6] & 0x80) != 0, Up: (b[5]&15) == 0 || (b[5]&15) == 1 || (b[5]&15) == 7, Down: (b[5]&15) == 3 || (b[5]&15) == 4 || (b[5]&15) == 5, Left: (b[5]&15) == 5 || (b[5]&15) == 6 || (b[5]&15) == 7, Right: (b[5]&15) == 1 || (b[5]&15) == 2 || (b[5]&15) == 3, Cross: (b[5] & 32) != 0, Circle: (b[5] & 64) != 0, Square: (b[5] & 16) != 0, Triangle: (b[5] & 128) != 0, Share: (b[6] & 0x10) != 0, Options: (b[6] & 0x20) != 0, PSHome: (b[7] & 1) != 0, TrackPad: (b[7] & 2) != 0, TrackPad0: TrackPad{ ID: int(b[35] & 0x7f), Active: (b[35] >> 7) == 0, X: int(((b[37] & 0x0f) << 4) | b[36]), Y: int(b[38]<<4 | ((b[37] & 0xf0) >> 4)), }, TrackPad1: TrackPad{ ID: int(b[39] & 0x7f), Active: (b[39] >> 7) == 0, X: int(((b[41] & 0x0f) << 4) | b[40]), Y: int(b[42]<<4 | ((b[41] & 0xf0) >> 4)), }, LeftDPad: DPad{ X: int(b[1]), Y: int(b[2]), }, RightDPad: DPad{ X: int(b[3]), Y: int(b[4]), }, Motion: Motion{ Y: int16(binary.LittleEndian.Uint16(b[13:])), X: -int16(binary.LittleEndian.Uint16(b[15:])), Z: -int16(binary.LittleEndian.Uint16(b[17:])), }, Orientation: Orientation{ Roll: -int16(binary.LittleEndian.Uint16(b[19:])), Yaw: int16(binary.LittleEndian.Uint16(b[21:])), Pitch: int16(binary.LittleEndian.Uint16(b[23:])), }, Analog: struct{ L2, R2 int }{ L2: int(b[8]), R2: int(b[9]), }, Timestamp: int(b[7] >> 2), BatteryLevel: int(b[12]), } } // New returns a new controller which transforms input from the device to a valid // controller state func New(reader io.Reader) *Controller { c := &Controller{ reader, make(chan []byte), make(chan error), make(chan int), } go c.read() return c } // read transforms data from the io.Reader and pushes it to the queue of // states func (c *Controller) read() { for { select { case <-c.interrupt: close(c.errors) close(c.queue) return default: b := make([]byte, 64) n, err := c.reader.Read(b) if err != nil { c.errors <- err continue } c.queue <- b[:n] } } } // Listen for controller state changes func (c *Controller) Listen(handle func(State)) { for { select { case <-c.interrupt: return default: handle(transform(<-c.queue)) } } } // Errors returns a channel of reader errors func (c *Controller) Errors() <-chan error { return c.errors } // Close the listener func (c *Controller) Close() { close(c.interrupt) }
dualshock.go
0.631253
0.568296
dualshock.go
starcoder
package wikifier // A collection of elements. type elements struct { elements []element metas map[string]bool cachedHTML HTML parentElement element shouldHide bool } // Creates a collection of elements. func newElements(els []element) *elements { return &elements{elements: els, metas: make(map[string]bool)} } func (els *elements) id() string { return "elements" } func (els *elements) hide() { els.shouldHide = true } func (els *elements) hidden() bool { return els.shouldHide } // If els is empty, returns an empty string. // Otherwise, returns the first element's tag. func (els *elements) tag() string { if len(els.elements) == 0 { return "" } return els.elements[0].tag() } // Sets the tag on all underlying elements. func (els *elements) setTag(tag string) { for _, el := range els.elements { el.setTag(tag) } } // Returns "elements" as the type of element. func (els *elements) elementType() string { return "elements" } // Fetches a value from the collection's metadata. func (els *elements) meta(name string) bool { return els.metas[name] } // Sets a value in the collection's metadata. func (els *elements) setMeta(name string, value bool) { if value == false { delete(els.metas, name) return } els.metas[name] = value } // Always returns false, as an element collection has no attributes. func (els *elements) hasAttr(name string) bool { return false } // Panics. Cannot fetch attribute from an element collection. func (els *elements) attr(name string) string { panic("unimplemented") } // Panics. Cannot fetch attribute from an element collection. func (els *elements) boolAttr(name string) bool { panic("unimplemented") } // Sets a string attribute on all underlying elements. func (els *elements) setAttr(name, value string) { for _, el := range els.elements { el.setAttr(name, value) } } // Sets a boolean attribute on all underlying elements. func (els *elements) setBoolAttr(name string, value bool) { for _, el := range els.elements { el.setBoolAttr(name, value) } } // Panics. Cannot fetch styles from an element collection. func (els *elements) hasStyle(name string) bool { panic("unimplemented") } // Panics. Cannot fetch styles from an element collection. func (els *elements) style(name string) string { panic("unimplemented") } // Sets a style on all underlying elements. func (els *elements) setStyle(name, value string) { for _, el := range els.elements { el.setStyle(name, value) } } // Adds another element. If i is not an element, panics. func (els *elements) add(i interface{}) { if child, ok := i.(element); ok { els.addChild(child) } panic("can't add() non-element to element collection") } // Panics. Cannot add text node to a collection of elements. func (els *elements) addText(s string) { panic("unimplemented") } // Panics. Cannot add raw HTML to a collection of elements. func (els *elements) addHTML(h HTML) { panic("unimplemented") } // Adds another element. func (els *elements) addChild(child element) { els.elements = append(els.elements, child) } // Creates an element and adds it. func (els *elements) createChild(tag, typ string) element { child := newElement(tag, typ) els.addChild(child) return child } // Fetches the parent of this element collection. func (els *elements) parent() element { return els.parentElement } // Sets the parent of this element collection. func (els *elements) setParent(parent element) { els.parentElement = parent // recursive!! } // Adds one or more classes to all underlying elements. func (els *elements) addClass(class ...string) { for _, el := range els.elements { el.addClass(class...) } } // Removes a class from all underlying elements. func (els *elements) removeClass(class string) bool { oneTrue := false for _, el := range els.elements { if el.removeClass(class) { oneTrue = true } } return oneTrue } // Generates and returns HTML for the elements. func (els *elements) generate() HTML { // cached version if els.cachedHTML != "" { return els.cachedHTML } els.cachedHTML = generateIndentedLines(els.generateIndented(0)) return els.cachedHTML } // Generates and returns HTML for the elements with an indent applied. func (els *elements) generateIndented(indent int) []indentedLine { var lines []indentedLine if els.hidden() { return nil } // add each for _, el := range els.elements { theirLines := el.generateIndented(indent) lines = append(lines, theirLines...) } return lines }
wikifier/elements.go
0.831314
0.421254
elements.go
starcoder
package toolbox import ( "fmt" "strings" "unicode" ) //Matcher represents a matcher, that matches input from offset position, it returns number of characters matched. type Matcher interface { //Match matches input starting from offset, it return number of characters matched Match(input string, offset int) (matched int) } //Token a matchable input type Token struct { Token int Matched string } //Tokenizer represents a token scanner. type Tokenizer struct { matchers map[int]Matcher Input string Index int InvalidToken int EndOfFileToken int } //Nexts matches the first of the candidates func (t *Tokenizer) Nexts(candidates ...int) *Token { for _, candidate := range candidates { result := t.Next(candidate) if result.Token != t.InvalidToken { return result } } return &Token{t.InvalidToken, ""} } //Next tries to match a candidate, it returns token if imatching is successful. func (t *Tokenizer) Next(candidate int) *Token { offset := t.Index if !(offset < len(t.Input)) { return &Token{t.EndOfFileToken, ""} } if candidate == t.EndOfFileToken { return &Token{t.InvalidToken, ""} } if matcher, ok := t.matchers[candidate]; ok { matchedSize := matcher.Match(t.Input, offset) if matchedSize > 0 { t.Index = t.Index + matchedSize return &Token{candidate, t.Input[offset : offset+matchedSize]} } } else { panic(fmt.Sprintf("failed to lookup matcher for %v", candidate)) } return &Token{t.InvalidToken, ""} } //NewTokenizer creates a new NewTokenizer, it takes input, invalidToken, endOfFileToeken, and matchers. func NewTokenizer(input string, invalidToken int, endOfFileToken int, matcher map[int]Matcher) *Tokenizer { return &Tokenizer{ matchers: matcher, Input: input, Index: 0, InvalidToken: invalidToken, EndOfFileToken: endOfFileToken, } } //CharactersMatcher represents a matcher, that matches any of Chars. type CharactersMatcher struct { Chars string //characters to be matched } //Match matches any characters defined in Chars in the input, returns 1 if character has been matched func (m CharactersMatcher) Match(input string, offset int) int { var matched = 0 if offset >= len(input) { return matched } outer: for _, r := range input[offset:] { for _, candidate := range m.Chars { if candidate == r { matched++ continue outer } } break } return matched } //NewCharactersMatcher creates a new character matcher func NewCharactersMatcher(chars string) Matcher { return &CharactersMatcher{Chars: chars} } //EOFMatcher represents end of input matcher type EOFMatcher struct { } //Match returns 1 if end of input has been reached otherwise 0 func (m EOFMatcher) Match(input string, offset int) int { if offset+1 == len(input) { return 1 } return 0 } //IntMatcher represents a matcher that finds any int in the input type IntMatcher struct{} //Match matches a literal in the input, it returns number of character matched. func (m IntMatcher) Match(input string, offset int) int { var matched = 0 if offset >= len(input) { return matched } for _, r := range input[offset:] { if !unicode.IsDigit(r) { break } matched++ } return matched } //NewIntMatcher returns a new integer matcher func NewIntMatcher() Matcher { return &IntMatcher{} } var dotRune = rune('.') var underscoreRune = rune('_') //LiteralMatcher represents a matcher that finds any literals in the input type LiteralMatcher struct{} //Match matches a literal in the input, it returns number of character matched. func (m LiteralMatcher) Match(input string, offset int) int { var matched = 0 if offset >= len(input) { return matched } for i, r := range input[offset:] { if i == 0 { if !unicode.IsLetter(r) { break } } else if !(unicode.IsLetter(r) || unicode.IsDigit(r) || r == dotRune || r == underscoreRune) { break } matched++ } return matched } //LiteralMatcher represents a matcher that finds any literals in the input type IdMatcher struct{} //Match matches a literal in the input, it returns number of character matched. func (m IdMatcher) Match(input string, offset int) int { var matched = 0 if offset >= len(input) { return matched } for i, r := range input[offset:] { if i == 0 { if !(unicode.IsLetter(r) || unicode.IsDigit(r)) { break } } else if !(unicode.IsLetter(r) || unicode.IsDigit(r) || r == dotRune || r == underscoreRune) { break } matched++ } return matched } //SequenceMatcher represents a matcher that finds any sequence until find provided terminators type SequenceMatcher struct { Terminators []string CaseSensitive bool matchAllIfNoTerminator bool runeTerminators []rune } func (m *SequenceMatcher) hasTerminator(candidate string) bool { var candidateLength = len(candidate) for _, terminator := range m.Terminators { terminatorLength := len(terminator) if len(terminator) > candidateLength { continue } if !m.CaseSensitive { if strings.ToLower(terminator) == strings.ToLower(string(candidate[:terminatorLength])) { return true } } if terminator == string(candidate[:terminatorLength]) { return true } } return false } //Match matches a literal in the input, it returns number of character matched. func (m *SequenceMatcher) Match(input string, offset int) int { var matched = 0 hasTerminator := false if offset >= len(input) { return matched } if len(m.runeTerminators) > 0 { return m.matchSingleTerminator(input, offset) } var i = 0 for ; i < len(input)-offset; i++ { if m.hasTerminator(string(input[offset+i:])) { hasTerminator = true break } } if !hasTerminator && !m.matchAllIfNoTerminator { return 0 } return i } func (m *SequenceMatcher) matchSingleTerminator(input string, offset int) int { matched := 0 hasTerminator := false outer: for i, r := range input[offset:] { for _, terminator := range m.runeTerminators { terminator = unicode.ToLower(terminator) if m.CaseSensitive { r = unicode.ToLower(r) terminator = unicode.ToLower(terminator) } if r == terminator { hasTerminator = true matched = i break outer } } } if !hasTerminator && !m.matchAllIfNoTerminator { return 0 } return matched } //NewSequenceMatcher creates a new matcher that finds all sequence until find at least one of the provided terminators func NewSequenceMatcher(terminators ...string) Matcher { result := &SequenceMatcher{ matchAllIfNoTerminator: true, Terminators: terminators, runeTerminators: []rune{}, } for _, terminator := range terminators { if len(terminator) != 1 { result.runeTerminators = []rune{} break } result.runeTerminators = append(result.runeTerminators, rune(terminator[0])) } return result } //NewTerminatorMatcher creates a new matcher that finds any sequence until find at least one of the provided terminators func NewTerminatorMatcher(terminators ...string) Matcher { result := &SequenceMatcher{ Terminators: terminators, runeTerminators: []rune{}, } for _, terminator := range terminators { if len(terminator) != 1 { result.runeTerminators = []rune{} break } result.runeTerminators = append(result.runeTerminators, rune(terminator[0])) } return result } //remainingSequenceMatcher represents a matcher that matches all reamining input type remainingSequenceMatcher struct{} //Match matches a literal in the input, it returns number of character matched. func (m *remainingSequenceMatcher) Match(input string, offset int) (matched int) { return len(input) - offset } //Creates a matcher that matches all remaining input func NewRemainingSequenceMatcher() Matcher { return &remainingSequenceMatcher{} } //CustomIdMatcher represents a matcher that finds any literals with additional custom set of characters in the input type customIdMatcher struct { Allowed map[rune]bool } func (m *customIdMatcher) isValid(r rune) bool { if unicode.IsLetter(r) || unicode.IsDigit(r) { return true } return m.Allowed[r] } //Match matches a literal in the input, it returns number of character matched. func (m *customIdMatcher) Match(input string, offset int) int { var matched = 0 if offset >= len(input) { return matched } for _, r := range input[offset:] { if !m.isValid(r) { break } matched++ } return matched } //NewCustomIdMatcher creates new custom matcher func NewCustomIdMatcher(allowedChars ...string) Matcher { var result = &customIdMatcher{ Allowed: make(map[rune]bool), } if len(allowedChars) == 1 && len(allowedChars[0]) > 0 { for _, allowed := range allowedChars[0] { result.Allowed[rune(allowed)] = true } } for _, allowed := range allowedChars { result.Allowed[rune(allowed[0])] = true } return result } //LiteralMatcher represents a matcher that finds any literals in the input type BodyMatcher struct { Begin string End string } //Match matches a literal in the input, it returns number of character matched. func (m *BodyMatcher) Match(input string, offset int) (matched int) { beginLen := len(m.Begin) endLen := len(m.End) uniEnclosed := m.Begin == m.End if offset+beginLen >= len(input) { return 0 } if input[offset:offset+beginLen] != m.Begin { return 0 } var depth = 1 var i = 1 for ; i < len(input)-offset; i++ { canCheckEnd := offset+i+endLen <= len(input) if !canCheckEnd { return 0 } if !uniEnclosed { canCheckBegin := offset+i+beginLen <= len(input) if canCheckBegin { if string(input[offset+i:offset+i+beginLen]) == m.Begin { depth++ } } } if string(input[offset+i:offset+i+endLen]) == m.End { depth-- } if depth == 0 { i += endLen break } } return i } //NewBodyMatcher creates a new body matcher func NewBodyMatcher(begin, end string) Matcher { return &BodyMatcher{Begin: begin, End: end} } // Parses SQL Begin End blocks func NewBlockMatcher(caseSensitive bool, sequenceStart string, sequenceTerminator string, nestedSequences []string, ignoredTerminators []string) Matcher { return &BlockMatcher{ CaseSensitive: caseSensitive, SequenceStart: sequenceStart, SequenceTerminator: sequenceTerminator, NestedSequences: nestedSequences, IgnoredTerminators: ignoredTerminators, } } type BlockMatcher struct { CaseSensitive bool SequenceStart string SequenceTerminator string NestedSequences []string IgnoredTerminators []string } func (m *BlockMatcher) Match(input string, offset int) (matched int) { sequenceStart := m.SequenceStart terminator := m.SequenceTerminator nestedSequences := m.NestedSequences ignoredTerminators := m.IgnoredTerminators in := input starterLen := len(sequenceStart) terminatorLen := len(terminator) if !m.CaseSensitive { sequenceStart = strings.ToLower(sequenceStart) terminator = strings.ToLower(terminator) for i, seq := range nestedSequences { nestedSequences[i] = strings.ToLower(seq) } for i, term := range ignoredTerminators { ignoredTerminators[i] = strings.ToLower(term) } in = strings.ToLower(input) } if offset+starterLen >= len(in) { return 0 } if in[offset:offset+starterLen] != sequenceStart { return 0 } var depth = 1 var i = 1 for ; i < len(in)-offset; i++ { canCheckEnd := offset+i+terminatorLen <= len(in) if !canCheckEnd { return 0 } canCheckBegin := offset+i+starterLen <= len(in) if canCheckBegin { beginning := in[offset+i : offset+i+starterLen] if beginning == sequenceStart { depth++ } else { for _, nestedSeq := range nestedSequences { nestedLen := len(nestedSeq) if offset+i+nestedLen >= len(in) { continue } beginning := in[offset+i : offset+i+nestedLen] if beginning == nestedSeq { depth++ break } } } } ignored := false for _, ignoredTerm := range ignoredTerminators { termLen := len(ignoredTerm) if offset+i+termLen >= len(in) { continue } ending := in[offset+i : offset+i+termLen] if ending == ignoredTerm { ignored = true break } } if !ignored && in[offset+i:offset+i+terminatorLen] == terminator && unicode.IsSpace(rune(in[offset+i-1])) { depth-- } if depth == 0 { i += terminatorLen break } } return i } //KeywordMatcher represents a keyword matcher type KeywordMatcher struct { Keyword string CaseSensitive bool } //Match matches keyword in the input, it returns number of character matched. func (m KeywordMatcher) Match(input string, offset int) (matched int) { if !(offset+len(m.Keyword)-1 < len(input)) { return 0 } if m.CaseSensitive { if input[offset:offset+len(m.Keyword)] == m.Keyword { return len(m.Keyword) } } else { if strings.ToLower(input[offset:offset+len(m.Keyword)]) == strings.ToLower(m.Keyword) { return len(m.Keyword) } } return 0 } //KeywordsMatcher represents a matcher that finds any of specified keywords in the input type KeywordsMatcher struct { Keywords []string CaseSensitive bool } //Match matches any specified keyword, it returns number of character matched. func (m KeywordsMatcher) Match(input string, offset int) (matched int) { for _, keyword := range m.Keywords { if len(input)-offset < len(keyword) { continue } if m.CaseSensitive { if input[offset:offset+len(keyword)] == keyword { return len(keyword) } } else { if strings.ToLower(input[offset:offset+len(keyword)]) == strings.ToLower(keyword) { return len(keyword) } } } return 0 } //NewKeywordsMatcher returns a matcher for supplied keywords func NewKeywordsMatcher(caseSensitive bool, keywords ...string) Matcher { return &KeywordsMatcher{CaseSensitive: caseSensitive, Keywords: keywords} } //IllegalTokenError represents illegal token error type IllegalTokenError struct { Illegal *Token Message string Expected []int Position int } func (e *IllegalTokenError) Error() string { return fmt.Sprintf("%v; illegal token at %v [%v], expected %v, but had: %v", e.Message, e.Position, e.Illegal.Matched, e.Expected, e.Illegal.Token) } //NewIllegalTokenError create a new illegal token error func NewIllegalTokenError(message string, expected []int, position int, found *Token) error { return &IllegalTokenError{ Message: message, Illegal: found, Expected: expected, Position: position, } } //ExpectTokenOptionallyFollowedBy returns second matched token or error if first and second group was not matched func ExpectTokenOptionallyFollowedBy(tokenizer *Tokenizer, first int, errorMessage string, second ...int) (*Token, error) { _, _ = ExpectToken(tokenizer, "", first) return ExpectToken(tokenizer, errorMessage, second...) } //ExpectToken returns the matched token or error func ExpectToken(tokenizer *Tokenizer, errorMessage string, candidates ...int) (*Token, error) { token := tokenizer.Nexts(candidates...) hasMatch := HasSliceAnyElements(candidates, token.Token) if !hasMatch { return nil, NewIllegalTokenError(errorMessage, candidates, tokenizer.Index, token) } return token, nil }
tokenizer.go
0.7478
0.437223
tokenizer.go
starcoder
package iso20022 // Set of elements providing information specific to the individual transaction(s) included in the message. type CreditTransferTransactionInformation2 struct { // Set of elements to reference a payment instruction. PaymentIdentification *PaymentIdentification2 `xml:"PmtId"` // Set of elements used to further specify the type of transaction. PaymentTypeInformation *PaymentTypeInformation3 `xml:"PmtTpInf,omitempty"` // Amount of money moved between the instructing agent and the instructed agent. InterbankSettlementAmount *CurrencyAndAmount `xml:"IntrBkSttlmAmt"` // Date on which the amount of money ceases to be available to the agent that owes it and when the amount of money becomes available to the agent to which it is due. InterbankSettlementDate *ISODate `xml:"IntrBkSttlmDt,omitempty"` // Provides information on the occurred settlement time(s) of the payment transaction. SettlementTimeIndication *SettlementDateTimeIndication1 `xml:"SttlmTmIndctn,omitempty"` // Provides information on the requested settlement time of the payment instruction. SettlementTimeRequest *SettlementTimeRequest1 `xml:"SttlmTmReq,omitempty"` // Point in time when the payment order from the initiating party meets the processing conditions of the account servicing agent (debtor's agent in case of a credit transfer, creditor's agent in case of a direct debit). This means - amongst others - that the account servicing agent has received the payment order and has applied checks as eg, authorisation, availability of funds. AcceptanceDateTime *ISODateTime `xml:"AccptncDtTm,omitempty"` // Date used for the correction of the value date of a cash pool movement that has been posted with a different value date. PoolingAdjustmentDate *ISODate `xml:"PoolgAdjstmntDt,omitempty"` // Amount of money to be moved between the debtor and creditor, before deduction of charges, expressed in the currency as ordered by the initiating party. InstructedAmount *CurrencyAndAmount `xml:"InstdAmt,omitempty"` // The factor used for conversion of an amount from one currency to another. This reflects the price at which one currency was bought with another currency. ExchangeRate *BaseOneRate `xml:"XchgRate,omitempty"` // Specifies which party/parties will bear the charges associated with the processing of the payment transaction. ChargeBearer *ChargeBearerType1Code `xml:"ChrgBr"` // Provides information on the charges related to the payment transaction. ChargesInformation []*ChargesInformation1 `xml:"ChrgsInf,omitempty"` // Agent immediately prior to the instructing agent. PreviousInstructingAgent *BranchAndFinancialInstitutionIdentification3 `xml:"PrvsInstgAgt,omitempty"` // Unambiguous identification of the account of the previous instructing agent at its servicing agent in the payment chain. PreviousInstructingAgentAccount *CashAccount7 `xml:"PrvsInstgAgtAcct,omitempty"` // Agent that instructs the next party in the chain to carry out the (set of) instruction(s). InstructingAgent *BranchAndFinancialInstitutionIdentification3 `xml:"InstgAgt,omitempty"` // Agent that is instructed by the previous party in the chain to carry out the (set of) instruction(s). InstructedAgent *BranchAndFinancialInstitutionIdentification3 `xml:"InstdAgt,omitempty"` // Agent between the debtor agent and creditor agent. // // Usage: If more than one intermediary agent is present, then IntermediaryAgent1 identifies the agent between the debtor agent and the intermediary agent 2. IntermediaryAgent1 *BranchAndFinancialInstitutionIdentification3 `xml:"IntrmyAgt1,omitempty"` // Unambiguous identification of the account of the intermediary agent 1 at its servicing agent in the payment chain. IntermediaryAgent1Account *CashAccount7 `xml:"IntrmyAgt1Acct,omitempty"` // Agent between the debtor agent and creditor agent. // // Usage: If more than two intermediary agents are present, then IntermediaryAgent2 identifies the agent between the intermediary agent 1 and the intermediary agent 3. IntermediaryAgent2 *BranchAndFinancialInstitutionIdentification3 `xml:"IntrmyAgt2,omitempty"` // Unambiguous identification of the account of the intermediary agent 2 at its servicing agent in the payment chain. IntermediaryAgent2Account *CashAccount7 `xml:"IntrmyAgt2Acct,omitempty"` // Agent between the debtor agent and creditor agent. // // Usage: If IntermediaryAgent3 is present, then it identifies the agent between the intermediary agent 2 and the creditor agent. IntermediaryAgent3 *BranchAndFinancialInstitutionIdentification3 `xml:"IntrmyAgt3,omitempty"` // Unambiguous identification of the account of the intermediary agent 3 at its servicing agent in the payment chain. IntermediaryAgent3Account *CashAccount7 `xml:"IntrmyAgt3Acct,omitempty"` // Ultimate party that owes an amount of money to the (ultimate) creditor. UltimateDebtor *PartyIdentification8 `xml:"UltmtDbtr,omitempty"` // Party that initiates the payment. In the payment context, this can either be the debtor (in a credit transfer), the creditor (in a direct debit), or a party that initiates the payment on behalf of the debtor or creditor. InitiatingParty *PartyIdentification8 `xml:"InitgPty,omitempty"` // Party that owes an amount of money to the (ultimate) creditor. Debtor *PartyIdentification8 `xml:"Dbtr"` // Unambiguous identification of the account of the debtor to which a debit entry will be made as a result of the transaction. DebtorAccount *CashAccount7 `xml:"DbtrAcct,omitempty"` // Financial institution servicing an account for the debtor. DebtorAgent *BranchAndFinancialInstitutionIdentification3 `xml:"DbtrAgt"` // Unambiguous identification of the account of the debtor agent at its servicing agent in the payment chain. DebtorAgentAccount *CashAccount7 `xml:"DbtrAgtAcct,omitempty"` // Financial institution servicing an account for the creditor. CreditorAgent *BranchAndFinancialInstitutionIdentification3 `xml:"CdtrAgt"` // Unambiguous identification of the account of the creditor agent at its servicing agent to which a credit entry will be made as a result of the payment transaction. CreditorAgentAccount *CashAccount7 `xml:"CdtrAgtAcct,omitempty"` // Party to which an amount of money is due. Creditor *PartyIdentification8 `xml:"Cdtr"` // Unambiguous identification of the account of the creditor to which a credit entry will be posted as a result of the payment transaction. CreditorAccount *CashAccount7 `xml:"CdtrAcct,omitempty"` // Ultimate party to which an amount of money is due. UltimateCreditor *PartyIdentification8 `xml:"UltmtCdtr,omitempty"` // Further information related to the processing of the payment instruction that may need to be acted upon by the creditor agent. // // Usage: The instruction can relate to a level of service, can be an instruction to be executed by the creditor's agent, or can be information required by the creditor's agent to process the instruction. InstructionForCreditorAgent []*InstructionForCreditorAgent1 `xml:"InstrForCdtrAgt,omitempty"` // Further information related to the processing of the payment instruction that may need to be acted upon by the next agent. // // Usage: The next agent may not be the creditor agent. // The instruction can relate to a level of service, can be an instruction that has to be executed by the agent, or can be information required by the next agent. InstructionForNextAgent []*InstructionForNextAgent1 `xml:"InstrForNxtAgt,omitempty"` // Underlying reason for the payment transaction. // // Usage: Purpose is used by the end-customers, i.e. initiating party, (ultimate) debtor, (ultimate) creditor to provide information concerning the nature of the payment. Purpose is a content element, which is not used for processing by any of the agents involved in the payment chain. Purpose *Purpose1Choice `xml:"Purp,omitempty"` // Information needed due to regulatory and statutory requirements. RegulatoryReporting []*RegulatoryReporting2 `xml:"RgltryRptg,omitempty"` // Information related to the handling of the remittance information by any of the agents in the transaction processing chain. RelatedRemittanceInformation []*RemittanceLocation1 `xml:"RltdRmtInf,omitempty"` // Information supplied to enable the matching of an entry with the items that the transfer is intended to settle, such as commercial invoices in an accounts' receivable system. RemittanceInformation *RemittanceInformation1 `xml:"RmtInf,omitempty"` } func (c *CreditTransferTransactionInformation2) AddPaymentIdentification() *PaymentIdentification2 { c.PaymentIdentification = new(PaymentIdentification2) return c.PaymentIdentification } func (c *CreditTransferTransactionInformation2) AddPaymentTypeInformation() *PaymentTypeInformation3 { c.PaymentTypeInformation = new(PaymentTypeInformation3) return c.PaymentTypeInformation } func (c *CreditTransferTransactionInformation2) SetInterbankSettlementAmount(value, currency string) { c.InterbankSettlementAmount = NewCurrencyAndAmount(value, currency) } func (c *CreditTransferTransactionInformation2) SetInterbankSettlementDate(value string) { c.InterbankSettlementDate = (*ISODate)(&value) } func (c *CreditTransferTransactionInformation2) AddSettlementTimeIndication() *SettlementDateTimeIndication1 { c.SettlementTimeIndication = new(SettlementDateTimeIndication1) return c.SettlementTimeIndication } func (c *CreditTransferTransactionInformation2) AddSettlementTimeRequest() *SettlementTimeRequest1 { c.SettlementTimeRequest = new(SettlementTimeRequest1) return c.SettlementTimeRequest } func (c *CreditTransferTransactionInformation2) SetAcceptanceDateTime(value string) { c.AcceptanceDateTime = (*ISODateTime)(&value) } func (c *CreditTransferTransactionInformation2) SetPoolingAdjustmentDate(value string) { c.PoolingAdjustmentDate = (*ISODate)(&value) } func (c *CreditTransferTransactionInformation2) SetInstructedAmount(value, currency string) { c.InstructedAmount = NewCurrencyAndAmount(value, currency) } func (c *CreditTransferTransactionInformation2) SetExchangeRate(value string) { c.ExchangeRate = (*BaseOneRate)(&value) } func (c *CreditTransferTransactionInformation2) SetChargeBearer(value string) { c.ChargeBearer = (*ChargeBearerType1Code)(&value) } func (c *CreditTransferTransactionInformation2) AddChargesInformation() *ChargesInformation1 { newValue := new (ChargesInformation1) c.ChargesInformation = append(c.ChargesInformation, newValue) return newValue } func (c *CreditTransferTransactionInformation2) AddPreviousInstructingAgent() *BranchAndFinancialInstitutionIdentification3 { c.PreviousInstructingAgent = new(BranchAndFinancialInstitutionIdentification3) return c.PreviousInstructingAgent } func (c *CreditTransferTransactionInformation2) AddPreviousInstructingAgentAccount() *CashAccount7 { c.PreviousInstructingAgentAccount = new(CashAccount7) return c.PreviousInstructingAgentAccount } func (c *CreditTransferTransactionInformation2) AddInstructingAgent() *BranchAndFinancialInstitutionIdentification3 { c.InstructingAgent = new(BranchAndFinancialInstitutionIdentification3) return c.InstructingAgent } func (c *CreditTransferTransactionInformation2) AddInstructedAgent() *BranchAndFinancialInstitutionIdentification3 { c.InstructedAgent = new(BranchAndFinancialInstitutionIdentification3) return c.InstructedAgent } func (c *CreditTransferTransactionInformation2) AddIntermediaryAgent1() *BranchAndFinancialInstitutionIdentification3 { c.IntermediaryAgent1 = new(BranchAndFinancialInstitutionIdentification3) return c.IntermediaryAgent1 } func (c *CreditTransferTransactionInformation2) AddIntermediaryAgent1Account() *CashAccount7 { c.IntermediaryAgent1Account = new(CashAccount7) return c.IntermediaryAgent1Account } func (c *CreditTransferTransactionInformation2) AddIntermediaryAgent2() *BranchAndFinancialInstitutionIdentification3 { c.IntermediaryAgent2 = new(BranchAndFinancialInstitutionIdentification3) return c.IntermediaryAgent2 } func (c *CreditTransferTransactionInformation2) AddIntermediaryAgent2Account() *CashAccount7 { c.IntermediaryAgent2Account = new(CashAccount7) return c.IntermediaryAgent2Account } func (c *CreditTransferTransactionInformation2) AddIntermediaryAgent3() *BranchAndFinancialInstitutionIdentification3 { c.IntermediaryAgent3 = new(BranchAndFinancialInstitutionIdentification3) return c.IntermediaryAgent3 } func (c *CreditTransferTransactionInformation2) AddIntermediaryAgent3Account() *CashAccount7 { c.IntermediaryAgent3Account = new(CashAccount7) return c.IntermediaryAgent3Account } func (c *CreditTransferTransactionInformation2) AddUltimateDebtor() *PartyIdentification8 { c.UltimateDebtor = new(PartyIdentification8) return c.UltimateDebtor } func (c *CreditTransferTransactionInformation2) AddInitiatingParty() *PartyIdentification8 { c.InitiatingParty = new(PartyIdentification8) return c.InitiatingParty } func (c *CreditTransferTransactionInformation2) AddDebtor() *PartyIdentification8 { c.Debtor = new(PartyIdentification8) return c.Debtor } func (c *CreditTransferTransactionInformation2) AddDebtorAccount() *CashAccount7 { c.DebtorAccount = new(CashAccount7) return c.DebtorAccount } func (c *CreditTransferTransactionInformation2) AddDebtorAgent() *BranchAndFinancialInstitutionIdentification3 { c.DebtorAgent = new(BranchAndFinancialInstitutionIdentification3) return c.DebtorAgent } func (c *CreditTransferTransactionInformation2) AddDebtorAgentAccount() *CashAccount7 { c.DebtorAgentAccount = new(CashAccount7) return c.DebtorAgentAccount } func (c *CreditTransferTransactionInformation2) AddCreditorAgent() *BranchAndFinancialInstitutionIdentification3 { c.CreditorAgent = new(BranchAndFinancialInstitutionIdentification3) return c.CreditorAgent } func (c *CreditTransferTransactionInformation2) AddCreditorAgentAccount() *CashAccount7 { c.CreditorAgentAccount = new(CashAccount7) return c.CreditorAgentAccount } func (c *CreditTransferTransactionInformation2) AddCreditor() *PartyIdentification8 { c.Creditor = new(PartyIdentification8) return c.Creditor } func (c *CreditTransferTransactionInformation2) AddCreditorAccount() *CashAccount7 { c.CreditorAccount = new(CashAccount7) return c.CreditorAccount } func (c *CreditTransferTransactionInformation2) AddUltimateCreditor() *PartyIdentification8 { c.UltimateCreditor = new(PartyIdentification8) return c.UltimateCreditor } func (c *CreditTransferTransactionInformation2) AddInstructionForCreditorAgent() *InstructionForCreditorAgent1 { newValue := new (InstructionForCreditorAgent1) c.InstructionForCreditorAgent = append(c.InstructionForCreditorAgent, newValue) return newValue } func (c *CreditTransferTransactionInformation2) AddInstructionForNextAgent() *InstructionForNextAgent1 { newValue := new (InstructionForNextAgent1) c.InstructionForNextAgent = append(c.InstructionForNextAgent, newValue) return newValue } func (c *CreditTransferTransactionInformation2) AddPurpose() *Purpose1Choice { c.Purpose = new(Purpose1Choice) return c.Purpose } func (c *CreditTransferTransactionInformation2) AddRegulatoryReporting() *RegulatoryReporting2 { newValue := new (RegulatoryReporting2) c.RegulatoryReporting = append(c.RegulatoryReporting, newValue) return newValue } func (c *CreditTransferTransactionInformation2) AddRelatedRemittanceInformation() *RemittanceLocation1 { newValue := new (RemittanceLocation1) c.RelatedRemittanceInformation = append(c.RelatedRemittanceInformation, newValue) return newValue } func (c *CreditTransferTransactionInformation2) AddRemittanceInformation() *RemittanceInformation1 { c.RemittanceInformation = new(RemittanceInformation1) return c.RemittanceInformation }
CreditTransferTransactionInformation2.go
0.761006
0.583055
CreditTransferTransactionInformation2.go
starcoder
package integration import ( "errors" "testing" "github.com/devhossamali/ari" ) func TestLoggingList(t *testing.T, s Server) { runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { expected := []*ari.Key{ ari.NewKey(ari.LoggingKey, "n1"), } m.Logging.On("List", (*ari.Key)(nil)).Return(expected, nil) ld, err := cl.Asterisk().Logging().List(nil) if err != nil { t.Errorf("Unexpected error in logging list: %s", err) } if len(ld) != len(expected) { t.Errorf("Expected return of length %d, got %d", len(expected), len(ld)) } else { for idx := range ld { failed := false failed = failed || ld[idx].ID != expected[idx].ID if failed { t.Errorf("Expected item '%d' to be '%v', got '%v", idx, expected[idx], ld[idx]) } } } m.Logging.AssertCalled(t, "List", (*ari.Key)(nil)) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { var expected []*ari.Key m.Logging.On("List", (*ari.Key)(nil)).Return(expected, errors.New("error")) ld, err := cl.Asterisk().Logging().List(nil) if err == nil { t.Errorf("Expected error in logging list") } if len(ld) != len(expected) { t.Errorf("Expected return of length %d, got %d", len(expected), len(ld)) } else { for idx := range ld { failed := false failed = failed || ld[idx].ID != expected[idx].ID // nolint if failed { t.Errorf("Expected item '%d' to be '%v', got '%v", idx, expected[idx], ld[idx]) // nolint } } } m.Logging.AssertCalled(t, "List", (*ari.Key)(nil)) }) } func TestLoggingCreate(t *testing.T, s Server) { key := ari.NewKey(ari.LoggingKey, "n1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Logging.On("Create", key, "l1").Return(ari.NewLogHandle(key, m.Logging), nil) _, err := cl.Asterisk().Logging().Create(key, "l1") if err != nil { t.Errorf("Unexpected error in logging create: %s", err) } m.Logging.AssertCalled(t, "Create", key, "l1") }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Logging.On("Create", key, "l1").Return(nil, errors.New("error")) _, err := cl.Asterisk().Logging().Create(key, "l1") if err == nil { t.Errorf("Expected error in logging create") } m.Logging.AssertCalled(t, "Create", key, "l1") }) } func TestLoggingDelete(t *testing.T, s Server) { key := ari.NewKey(ari.LoggingKey, "n1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Logging.On("Delete", key).Return(nil) err := cl.Asterisk().Logging().Delete(key) if err != nil { t.Errorf("Unexpected error in logging Delete: %s", err) } m.Logging.AssertCalled(t, "Delete", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Logging.On("Delete", key).Return(errors.New("error")) err := cl.Asterisk().Logging().Delete(key) if err == nil { t.Errorf("Expected error in logging Delete") } m.Logging.AssertCalled(t, "Delete", key) }) } func TestLoggingRotate(t *testing.T, s Server) { key := ari.NewKey(ari.LoggingKey, "n1") runTest("ok", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Logging.On("Rotate", key).Return(nil) err := cl.Asterisk().Logging().Rotate(key) if err != nil { t.Errorf("Unexpected error in logging Rotate: %s", err) } m.Logging.AssertCalled(t, "Rotate", key) }) runTest("err", t, s, func(t *testing.T, m *mock, cl ari.Client) { m.Logging.On("Rotate", key).Return(errors.New("error")) err := cl.Asterisk().Logging().Rotate(key) if err == nil { t.Errorf("Expected error in logging Rotate") } m.Logging.AssertCalled(t, "Rotate", key) }) }
internal/integration/logging.go
0.581184
0.533823
logging.go
starcoder
package gorhsm import ( "encoding/json" ) // ImageInContentSet Image Details in a content set image listing. type ImageInContentSet struct { Arch *string `json:"arch,omitempty"` Checksum *string `json:"checksum,omitempty"` // Date represents the date format used for API returns DatePublished *string `json:"datePublished,omitempty"` DownloadHref *string `json:"downloadHref,omitempty"` Filename *string `json:"filename,omitempty"` ImageName *string `json:"imageName,omitempty"` } // NewImageInContentSet instantiates a new ImageInContentSet 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 NewImageInContentSet() *ImageInContentSet { this := ImageInContentSet{} return &this } // NewImageInContentSetWithDefaults instantiates a new ImageInContentSet 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 NewImageInContentSetWithDefaults() *ImageInContentSet { this := ImageInContentSet{} return &this } // GetArch returns the Arch field value if set, zero value otherwise. func (o *ImageInContentSet) GetArch() string { if o == nil || o.Arch == nil { var ret string return ret } return *o.Arch } // GetArchOk returns a tuple with the Arch field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ImageInContentSet) GetArchOk() (*string, bool) { if o == nil || o.Arch == nil { return nil, false } return o.Arch, true } // HasArch returns a boolean if a field has been set. func (o *ImageInContentSet) HasArch() bool { if o != nil && o.Arch != nil { return true } return false } // SetArch gets a reference to the given string and assigns it to the Arch field. func (o *ImageInContentSet) SetArch(v string) { o.Arch = &v } // GetChecksum returns the Checksum field value if set, zero value otherwise. func (o *ImageInContentSet) GetChecksum() string { if o == nil || o.Checksum == nil { var ret string return ret } return *o.Checksum } // GetChecksumOk returns a tuple with the Checksum field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ImageInContentSet) GetChecksumOk() (*string, bool) { if o == nil || o.Checksum == nil { return nil, false } return o.Checksum, true } // HasChecksum returns a boolean if a field has been set. func (o *ImageInContentSet) HasChecksum() bool { if o != nil && o.Checksum != nil { return true } return false } // SetChecksum gets a reference to the given string and assigns it to the Checksum field. func (o *ImageInContentSet) SetChecksum(v string) { o.Checksum = &v } // GetDatePublished returns the DatePublished field value if set, zero value otherwise. func (o *ImageInContentSet) GetDatePublished() string { if o == nil || o.DatePublished == nil { var ret string return ret } return *o.DatePublished } // GetDatePublishedOk returns a tuple with the DatePublished field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ImageInContentSet) GetDatePublishedOk() (*string, bool) { if o == nil || o.DatePublished == nil { return nil, false } return o.DatePublished, true } // HasDatePublished returns a boolean if a field has been set. func (o *ImageInContentSet) HasDatePublished() bool { if o != nil && o.DatePublished != nil { return true } return false } // SetDatePublished gets a reference to the given string and assigns it to the DatePublished field. func (o *ImageInContentSet) SetDatePublished(v string) { o.DatePublished = &v } // GetDownloadHref returns the DownloadHref field value if set, zero value otherwise. func (o *ImageInContentSet) GetDownloadHref() string { if o == nil || o.DownloadHref == nil { var ret string return ret } return *o.DownloadHref } // GetDownloadHrefOk returns a tuple with the DownloadHref field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ImageInContentSet) GetDownloadHrefOk() (*string, bool) { if o == nil || o.DownloadHref == nil { return nil, false } return o.DownloadHref, true } // HasDownloadHref returns a boolean if a field has been set. func (o *ImageInContentSet) HasDownloadHref() bool { if o != nil && o.DownloadHref != nil { return true } return false } // SetDownloadHref gets a reference to the given string and assigns it to the DownloadHref field. func (o *ImageInContentSet) SetDownloadHref(v string) { o.DownloadHref = &v } // GetFilename returns the Filename field value if set, zero value otherwise. func (o *ImageInContentSet) GetFilename() string { if o == nil || o.Filename == nil { var ret string return ret } return *o.Filename } // GetFilenameOk returns a tuple with the Filename field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ImageInContentSet) GetFilenameOk() (*string, bool) { if o == nil || o.Filename == nil { return nil, false } return o.Filename, true } // HasFilename returns a boolean if a field has been set. func (o *ImageInContentSet) HasFilename() bool { if o != nil && o.Filename != nil { return true } return false } // SetFilename gets a reference to the given string and assigns it to the Filename field. func (o *ImageInContentSet) SetFilename(v string) { o.Filename = &v } // GetImageName returns the ImageName field value if set, zero value otherwise. func (o *ImageInContentSet) GetImageName() string { if o == nil || o.ImageName == nil { var ret string return ret } return *o.ImageName } // GetImageNameOk returns a tuple with the ImageName field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ImageInContentSet) GetImageNameOk() (*string, bool) { if o == nil || o.ImageName == nil { return nil, false } return o.ImageName, true } // HasImageName returns a boolean if a field has been set. func (o *ImageInContentSet) HasImageName() bool { if o != nil && o.ImageName != nil { return true } return false } // SetImageName gets a reference to the given string and assigns it to the ImageName field. func (o *ImageInContentSet) SetImageName(v string) { o.ImageName = &v } func (o ImageInContentSet) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Arch != nil { toSerialize["arch"] = o.Arch } if o.Checksum != nil { toSerialize["checksum"] = o.Checksum } if o.DatePublished != nil { toSerialize["datePublished"] = o.DatePublished } if o.DownloadHref != nil { toSerialize["downloadHref"] = o.DownloadHref } if o.Filename != nil { toSerialize["filename"] = o.Filename } if o.ImageName != nil { toSerialize["imageName"] = o.ImageName } return json.Marshal(toSerialize) } type NullableImageInContentSet struct { value *ImageInContentSet isSet bool } func (v NullableImageInContentSet) Get() *ImageInContentSet { return v.value } func (v *NullableImageInContentSet) Set(val *ImageInContentSet) { v.value = val v.isSet = true } func (v NullableImageInContentSet) IsSet() bool { return v.isSet } func (v *NullableImageInContentSet) Unset() { v.value = nil v.isSet = false } func NewNullableImageInContentSet(val *ImageInContentSet) *NullableImageInContentSet { return &NullableImageInContentSet{value: val, isSet: true} } func (v NullableImageInContentSet) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableImageInContentSet) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_image_in_content_set.go
0.807347
0.404743
model_image_in_content_set.go
starcoder
// Package at provides holiday definitions for Austria. package at import ( "time" "github.com/devechelon/cal/v2" "github.com/devechelon/cal/v2/aa" ) var ( // Neujahr represents New Year's Day on 1-Jan Neujahr = aa.NewYear.Clone(&cal.Holiday{Name: "Neujahrstag", Type: cal.ObservancePublic}) // HeiligeDreiKoenige represents Epiphany on 6-Jan HeiligeDreiKoenige = aa.Epiphany.Clone(&cal.Holiday{Name: "Heilige Drei Könige", Type: cal.ObservancePublic}) // Ostermontag represents Easter Monday on the day after Easter Ostermontag = aa.EasterMonday.Clone(&cal.Holiday{Name: "Ostermontag", Type: cal.ObservancePublic}) // TagderArbeit represents Labor Day on the first Monday in May TagderArbeit = aa.WorkersDay.Clone(&cal.Holiday{Name: "Tag der Arbeit", Type: cal.ObservancePublic}) // ChristiHimmelfahrt represents Ascension Day on the 39th day after Easter ChristiHimmelfahrt = aa.AscensionDay.Clone(&cal.Holiday{Name: "Christi Himmelfahrt", Type: cal.ObservancePublic}) // Pfingstmontag represents Pentecost Monday on the day after Pentecost (50 days after Easter) Pfingstmontag = aa.PentecostMonday.Clone(&cal.Holiday{Name: "Pfingstmontag", Type: cal.ObservancePublic}) // Fronleichnam represents Corpus Christi on the 60th day after Easter Fronleichnam = aa.CorpusChristi.Clone(&cal.Holiday{Name: "Fronleichnam", Type: cal.ObservancePublic}) // MariaHimmelfahrt represents Assumption of Mary on 15-Aug MariaHimmelfahrt = aa.AssumptionOfMary.Clone(&cal.Holiday{Name: "Mariä Himmelfahrt", Type: cal.ObservancePublic}) // Nationalfeiertag represents National Day on 26-Oct Nationalfeiertag = &cal.Holiday{ Name: "Nationalfeiertag", Type: cal.ObservancePublic, Month: time.October, Day: 26, Func: cal.CalcDayOfMonth, } // Allerheiligen represents All Saints' Day on 1-Nov Allerheiligen = aa.AllSaintsDay.Clone(&cal.Holiday{Name: "Allerheiligen", Type: cal.ObservancePublic}) // MariaEmpfaengnis represents Immaculate Conception on 8-Dec MariaEmpfaengnis = aa.ImmaculateConception.Clone(&cal.Holiday{Name: "<NAME>", Type: cal.ObservancePublic}) // Christtag represents Christmas Day on 25-Dec Christtag = aa.ChristmasDay.Clone(&cal.Holiday{Name: "Christtag", Type: cal.ObservancePublic}) // Stefanitag represents St. Stephen's Day on 26-Dec Stefanitag = aa.ChristmasDay2.Clone(&cal.Holiday{Name: "Stefanitag", Type: cal.ObservancePublic}) // Holidays provides a list of the standard national holidays Holidays = []*cal.Holiday{ Neujahr, HeiligeDreiKoenige, Ostermontag, TagderArbeit, ChristiHimmelfahrt, Pfingstmontag, Fronleichnam, MariaHimmelfahrt, Nationalfeiertag, Allerheiligen, MariaEmpfaengnis, Christtag, Stefanitag, } )
v2/at/at_holidays.go
0.535827
0.41947
at_holidays.go
starcoder
package models type HasPrices interface { MinPrice() int GuaranteedPrice() int MaxPrice() int } type pricesVal struct { // Price info minPrice int guaranteedPrice int maxPrice int // chance info minChance float64 maxChance float64 midChance float64 } // The absolute minimum price that may occur. func (prices *pricesVal) MinPrice() int { return prices.minPrice } // The highest guaranteed to happen minimum price that may occur. On // PotentialPricePeriod objects, this is the *lowest possible price* for the given // period, but on Week, Pattern, and Prediction object this is the minimum guaranteed // price, or the highest price we can guarantee will occur this week. func (prices *pricesVal) GuaranteedPrice() int { return prices.guaranteedPrice } // The potential maximum price for this period / week / pattern / prediction. func (prices *pricesVal) MaxPrice() int { return prices.maxPrice } // Returns the chance of this price range resulting in this price. func (prices *pricesVal) PriceChance(price int) float64 { switch { case price == prices.maxPrice: return prices.maxChance case price == prices.guaranteedPrice: return prices.minChance default: return prices.midChance } } func (prices *pricesVal) updateMin(value int) (updated bool) { updated = (prices.minPrice == 0 || value < prices.minPrice) && value != 0 if updated { prices.minPrice = value } return updated } func (prices *pricesVal) updateGuaranteed(value int, useHigher bool) (updated bool) { updated = ((useHigher && value > prices.guaranteedPrice) || (!useHigher && value < prices.guaranteedPrice) || prices.guaranteedPrice == 0) && value != 0 if updated { prices.guaranteedPrice = value } return updated } func (prices *pricesVal) updateMax(value int) (updated bool) { updated = value > prices.maxPrice if updated { prices.maxPrice = value } return updated } func (prices *pricesVal) updatePrices( otherPrices HasPrices, useHigherGuaranteed bool, ) (guaranteedUpdated bool, maxUpdated bool, minUpdated bool) { minUpdated = prices.updateMin(otherPrices.MinPrice()) guaranteedUpdated = prices.updateGuaranteed( otherPrices.GuaranteedPrice(), useHigherGuaranteed, ) maxUpdated = prices.updateMax(otherPrices.MaxPrice()) return guaranteedUpdated, maxUpdated, minUpdated }
models/analysisPrices.go
0.798029
0.447219
analysisPrices.go
starcoder
package main /* Helper method fills a singly-even order matrix. Key: - Fill each quarter of a singly-even order matrix to make each an odd-order magic square. - Calculate the number of columns we need to shift, then exchange values of top quarters with bottom quarters. Note: the middle rows of the left quarters need to be shifted 1 to the right. Time = O(n^2) because we visit all cells. Space = O(1) because we don't use extra space, just fill the matrix. */ func fillSinglyEvenOrder(magicSquare [][]int, n int) { // Build odd order magic square for each quarter: // Top left: fillQuarterOfSinglyEvenOrder(magicSquare, 0, n/2, 0, n/2, 1, (n/2)*(n/2)) // Bottom right: fillQuarterOfSinglyEvenOrder(magicSquare, n/2, n, n/2, n, (n/2)*(n/2)+1, n*n/2) // Top right: fillQuarterOfSinglyEvenOrder(magicSquare, 0, n/2, n/2, n, n*n/2+1, 3*(n/2)*(n/2)) // Bottom left: fillQuarterOfSinglyEvenOrder(magicSquare, n/2, n, 0, n/2, 3*(n/2)*(n/2)+1, n*n) shiftCol := (n/2 - 1) / 2 // Exchange columns in left quarters: for i := 0; i < n/2; i++ { for j := 0; j < shiftCol; j++ { // If we're at middle row of top left quarter, shift 1 to the right: if i == n/4 { exchangeCell(i, j+shiftCol, magicSquare) } else { exchangeCell(i, j, magicSquare) } } } // Exchange columns right quarters if n > 6: for i := 0; i < n/2; i++ { for j := n - 1; j > n-shiftCol; j-- { exchangeCell(i, j, magicSquare) } } } /* Helper method fills a quarter of a singly-even order magic square to make an odd order magic square. */ func fillQuarterOfSinglyEvenOrder(magicSquare [][]int, firstRow int, lastRow int, firstCol int, lastCol int, num int, lastNum int) { // Initialize position for 1st number: i := firstRow j := (lastCol + firstCol) / 2 // One by one put all values in magic square for num <= lastNum { // 4th condition: if i < firstRow && j >= lastCol { i += 2 j-- } // 2nd condition: // If next number goes to out of square's right side if j >= lastCol { j = firstCol } // 1st condition: // If next number goes to out of square's upper side if i < firstRow { i = lastRow - 1 } // 3rd condition: if magicSquare[i][j] != 0 { i += 2 j-- continue } else { // Add num to cell: magicSquare[i][j] = num // Increment num to next one: num++ } i-- j++ } } /* Helper method exchanges cell i,j with n/2+i,j */ func exchangeCell(i int, j int, matrix [][]int) { r := len(matrix)/2 + i matrix[i][j], matrix[r][j] = matrix[r][j], matrix[i][j] }
golang/singly-even-order.go
0.640523
0.601008
singly-even-order.go
starcoder
package redel import ( "bufio" "bytes" "crypto/rand" "io" ) type ( // Redel provides an interface (around Scanner) for replace string occurrences // between two string delimiters. Redel struct { Reader io.Reader Delimiters []Delimiter eof []byte } // Delimiter defines a replacement delimiters structure Delimiter struct { Start []byte End []byte } // replacementData interface contains intern replacing info. replacementData struct { delimiter Delimiter value []byte } // earlyDelimiter defines a found delimiter earlyDelimiter struct { value []byte delimiter Delimiter startIndex int endIndex int } // ReplacementMapFunc defines a map function that will be called for every scan splitted token. ReplacementMapFunc func(data []byte, atEOF bool) // FilterValueFunc defines a filter function that will be called per replacement // which supports a return `bool` value to apply the replacement or not. FilterValueFunc func(matchValue []byte) bool // FilterValueReplaceFunc defines a filter function that will be called per replacement // which supports a return `[]byte` value to customize the replacement value. FilterValueReplaceFunc func(matchValue []byte) []byte ) // getEOFToken generates a random EOF bytes token. func getEOFToken() []byte { eof := make([]byte, 7) _, err := rand.Read(eof) if err != nil { panic(err) } return eof } // New creates a new Redel instance. func New(reader io.Reader, delimiters []Delimiter) *Redel { eof := getEOFToken() return &Redel{ Reader: reader, Delimiters: delimiters, eof: eof, } } // replaceFilterFunc is the API function which scans and replace bytes supporting different options. // It's used by API's replace functions. func (rd *Redel) replaceFilterFunc( replacementMapFunc ReplacementMapFunc, filterFunc FilterValueReplaceFunc, preserveDelimiters bool, replaceWith bool, replacement []byte, ) { scanner := bufio.NewScanner(rd.Reader) delimiters := rd.Delimiters var valuesData []replacementData ScanByDelimiters := func(data []byte, atEOF bool) (advance int, token []byte, err error) { var earlyDelimiters []earlyDelimiter var closerDelimiter earlyDelimiter if atEOF && len(data) == 0 { return 0, nil, nil } // iterate array of delimiters for _, del := range delimiters { startLen := len(del.Start) endLen := len(del.End) if startLen <= 0 || endLen <= 0 { continue } // store every found delimiter if from := bytes.Index(data, del.Start); from >= 0 { if to := bytes.Index(data[from:], del.End); to >= 0 { x1 := from + startLen x2 := from + endLen + (to - endLen) val := data[x1:x2] earlyDelimiters = append(earlyDelimiters, earlyDelimiter{ value: val, delimiter: del, startIndex: x1, endIndex: x2, }) } } } if len(earlyDelimiters) > 0 { // Determine the closer delimiter for i, del := range earlyDelimiters { if i == 0 || del.startIndex < closerDelimiter.startIndex { closerDelimiter = del } } // Assign and check the closer delimiter delimiter := closerDelimiter.delimiter delimiterVal := closerDelimiter.value if len(delimiterVal) > 0 { valuesData = append(valuesData, replacementData{ delimiter: delimiter, value: delimiterVal, }) } endIndex := closerDelimiter.endIndex startIndex := closerDelimiter.startIndex return endIndex, data[0:startIndex], nil } if atEOF && len(data) > 0 { last := append(data[0:], rd.eof...) return len(data), last, nil } return 0, nil, nil } scanner.Split(ScanByDelimiters) // Variables to control delimiters checking hasStartPrevDelimiter := false var previousDelimiter Delimiter // Scan every token based on current split function for scanner.Scan() { bytesO := scanner.Bytes() bytesR := make([]byte, len(bytesO)) copy(bytesR, bytesO) atEOF := bytes.HasSuffix(bytesR, rd.eof) valueCurrent := []byte(nil) valueCurrentLen := len(valuesData) - 1 valueToReplace := []byte(nil) var replacementData replacementData if valueCurrentLen >= 0 { replacementData = valuesData[valueCurrentLen] valueCurrent = append(valueCurrent, replacementData.value...) valueToReplace = filterFunc(valueCurrent) } delimiterData := replacementData.delimiter // Remove delimiters only if `preserveDelimiters` is `false` if !preserveDelimiters { // 1. Check for the first start delimiter (once) if !hasStartPrevDelimiter && bytes.HasSuffix(bytesR, delimiterData.Start) { bytesR = bytes.Replace(bytesR, delimiterData.Start, []byte(nil), 1) previousDelimiter = delimiterData hasStartPrevDelimiter = true } // 2. Next check for start and end delimiters (many times) if hasStartPrevDelimiter { hasPrevEndDelimiter := false // 2.1. Check for a previous end delimiter (in current data) if bytes.HasPrefix(bytesR, previousDelimiter.End) { bytesR = bytes.Replace(bytesR, previousDelimiter.End, []byte(nil), 1) previousDelimiter = delimiterData hasPrevEndDelimiter = true } // 2.2. Check for a new start delimiter (in current data) if hasPrevEndDelimiter && bytes.HasSuffix(bytesR, delimiterData.Start) { bytesR = bytes.Replace(bytesR, delimiterData.Start, []byte(nil), 1) } } } // Last process to append or not values or replacements if atEOF { bytesR = bytes.Split(bytesR, rd.eof)[0] } else { if replaceWith { // takes the callback value instead bytesR = append(bytesR, valueToReplace...) } else { // don't replace and use the value instead if len(valueToReplace) == 0 { // takes the array value instead bytesR = append(bytesR, valueCurrent...) } else { // otherwise use the replacement value bytesR = append(bytesR, replacement...) } } } replacementMapFunc(bytesR, atEOF) } } // Replace function replaces every occurrence with a custom replacement token. func (rd *Redel) Replace(replacement []byte, mapFunc ReplacementMapFunc) { rd.replaceFilterFunc(mapFunc, func(value []byte) []byte { return value }, false, false, replacement) } // ReplaceFilter function scans and replaces byte occurrences filtering every replacement value via a bool callback. func (rd *Redel) ReplaceFilter( replacement []byte, mapFunc ReplacementMapFunc, filterFunc FilterValueFunc, preserveDelimiters bool, ) { rd.replaceFilterFunc(mapFunc, func(matchValue []byte) []byte { result := []byte(nil) ok := filterFunc(matchValue) if ok { result = []byte("1") } return result }, preserveDelimiters, false, replacement) } // ReplaceFilterWith function scans and replaces byte occurrences via a custom replacement callback. func (rd *Redel) ReplaceFilterWith( mapFunc ReplacementMapFunc, filterReplaceFunc FilterValueReplaceFunc, preserveDelimiters bool, ) { rd.replaceFilterFunc(mapFunc, filterReplaceFunc, preserveDelimiters, true, []byte(nil)) }
redel.go
0.651244
0.408336
redel.go
starcoder
package ipv4 import ( "math/bits" ) // setNode is currently the same data structure as trieNode. However, // its purpose is to implement a set of keys. Hence, values in the underlying // data structure are completely ignored. Aliasing it in this way allows me to // provide a completely different API on top of the same data structure and // benefit from the trieNode API where needed by casting. type setNode trieNode func setNodeFromPrefix(p Prefix) *setNode { return &setNode{ isActive: true, Prefix: p, size: 1, h: 1, } } func setNodeFromRange(r Range) *setNode { // xor shows the bits that are different between first and last xor := r.first.ui ^ r.last.ui // The number of leading zeroes in the xor is the number of bits the two addresses have in common numCommonBits := bits.LeadingZeros32(xor) if numCommonBits == bits.OnesCount32(^xor) { // This range is exactly one prefix, return a node with it. prefix := Prefix{r.first, uint32(numCommonBits)} return setNodeFromPrefix(prefix) } // "pivot" is the address within the range with the most trailing zeroes. // Dividing and conquering on it recursively teases out all of the largest // prefixes in the range. The result is the smallest set of prefixes that // covers it. It takes Log(p) time where p is the number of prefixes in the // result -- bounded by 32 x 2 in the worst case pivot := r.first.ui & (uint32(0xffffffff) << (32 - numCommonBits)) pivot |= uint32(0x80000000) >> numCommonBits a := setNodeFromRange(Range{r.first, Address{pivot - 1}}) b := setNodeFromRange(Range{Address{pivot}, r.last}) return a.Union(b) } // Insert inserts the key / value if the key didn't previously exist and then // flattens the structure (without regard to any values) to remove nested // prefixes resulting in a flat list of disjoint prefixes. func (me *setNode) Insert(key Prefix) *setNode { newHead, _ := (*trieNode)(me).insert(&trieNode{Prefix: key, Data: nil}, insertOpts{insert: true, update: true, flatten: true}) return (*setNode)(newHead) } // Delete removes a prefix from the trie and returns the new root of the trie. // It is important to note that the root of the trie can change. Like Insert, // this is designed for using trie as a set of keys, completely ignoring // values. All stored prefixes that match the given prefix with LPM will be // removed, not just exact matches. func (me *setNode) Remove(key Prefix) *setNode { newHead, _ := (*trieNode)(me).del(key, deleteOpts{flatten: true}) return (*setNode)(newHead) } func (me *setNode) Left() *setNode { return (*setNode)(me.children[0]) } func (me *setNode) Right() *setNode { return (*setNode)(me.children[1]) } // so much casting! func (me *setNode) mutate(mutator func(*setNode)) *setNode { n := (*trieNode)(me) n = n.mutate(func(node *trieNode) { mutator((*setNode)(node)) }) return (*setNode)(n) } func (me *setNode) flatten() { (*trieNode)(me).flatten() } // Union returns the flattened union of prefixes. func (me *setNode) Union(other *setNode) (rc *setNode) { if me == other { return me } if other == nil { return me } if me == nil { return other } // Test containership both ways result, reversed, common, child := compare(me.Prefix, other.Prefix) switch result { case compareSame: if me.isActive { return me } if other.isActive { return other } left := me.Left().Union(other.Left()) right := me.Right().Union(other.Right()) if left == me.Left() && right == me.Right() { return me } newHead := &setNode{ Prefix: Prefix{ addr: Address{ ui: me.Prefix.addr.ui, }, length: me.Prefix.length, }, children: [2]*trieNode{ (*trieNode)(left), (*trieNode)(right), }, } return newHead.mutate(func(n *setNode) { n.flatten() }) case compareContains, compareIsContained: super, sub := me, other if reversed { super, sub = sub, super } if super.isActive { return super } var left, right *setNode if child == 1 { left, right = super.Left(), super.Right().Union(sub) } else { left, right = super.Left().Union(sub), super.Right() } newHead := &setNode{ Prefix: Prefix{ addr: Address{ ui: super.Prefix.addr.ui, }, length: super.Prefix.length, }, children: [2]*trieNode{ (*trieNode)(left), (*trieNode)(right), }, } return newHead.mutate(func(n *setNode) { n.flatten() }) default: var left, right *setNode if (child == 1) != reversed { // (child == 1) XOR reversed left, right = me, other } else { left, right = other, me } newHead := &setNode{ Prefix: Prefix{ addr: Address{ ui: me.Prefix.addr.ui & ^(uint32(0xffffffff) >> common), // zero out bits not in common }, length: common, }, children: [2]*trieNode{ (*trieNode)(left), (*trieNode)(right), }, } return newHead.mutate(func(n *setNode) { n.flatten() }) } } func (me *setNode) Match(searchKey Prefix) *setNode { return (*setNode)((*trieNode)(me).Match(searchKey)) } func (me *setNode) isValid() bool { return (*trieNode)(me).isValid() } // Difference returns the flattened difference of prefixes. func (me *setNode) Difference(other *setNode) (rc *setNode) { if me == nil || other == nil { return me } result, _, _, child := compare(me.Prefix, other.Prefix) switch result { case compareIsContained: if other.isActive { return nil } return me.Difference((*setNode)(other.children[child])) case compareDisjoint: return me } if !me.isActive { left := me.Left().Difference(other) right := me.Right().Difference(other) if left == me.Left() && right == me.Right() { return me } return left.Union(right) } // Assumes `me` is active as checked above halves := func() (a, b *setNode) { aPrefix, bPrefix := me.Prefix.Halves() return setNodeFromPrefix(aPrefix), setNodeFromPrefix(bPrefix) } switch result { case compareSame: if other.isActive { return nil } a, b := halves() return a.Difference(other.Left()).Union( b.Difference(other.Right()), ) case compareContains: a, b := halves() halves := [2]*setNode{a, b} whole := halves[(child+1)%2] partial := halves[child].Difference(other) return whole.Union(partial) } panic("unreachable") } // Intersect returns the flattened intersection of prefixes func (me *setNode) Intersect(other *setNode) *setNode { if me == nil || other == nil { return nil } result, reversed, _, _ := compare(me.Prefix, other.Prefix) if result == compareDisjoint { return nil } if !me.isActive { return other.Intersect(me.Left()).Union( other.Intersect(me.Right()), ) } if !other.isActive { return me.Intersect(other.Left()).Union( me.Intersect(other.Right()), ) } // Return the smaller prefix if reversed { return me } return other } func (me *setNode) Equal(other *setNode) bool { return (*trieNode)(me).Equal((*trieNode)(other), func(a, b interface{}) bool { return true }) } // NumAddresses calls trieNode NumAddresses func (me *setNode) NumAddresses() int64 { return (*trieNode)(me).NumAddresses() } // NumNodes returns the number of entries in the trie func (me *setNode) NumNodes() int64 { return (*trieNode)(me).NumNodes() } func (me *setNode) height() int { return (*trieNode)(me).height() } func (me *setNode) Walk(callback func(Prefix, interface{}) bool) bool { return (*trieNode)(me).Walk(callback) }
ipv4/setnode.go
0.724481
0.558086
setnode.go
starcoder
package iso20022 // Calculation of the current situation of a baseline as a result of the submission of a commercial data set. type LineItem14 struct { // Calculated information about the goods of the underlying transaction. LineItemDetails []*LineItemDetails12 `xml:"LineItmDtls"` // Line items total amount as indicated in the baseline. OrderedLineItemsTotalAmount *CurrencyAndAmount `xml:"OrdrdLineItmsTtlAmt"` // Line items total amount accepted by a data set submission(s). AcceptedLineItemsTotalAmount *CurrencyAndAmount `xml:"AccptdLineItmsTtlAmt"` // Difference between the ordered and the accepted line items total amount. OutstandingLineItemsTotalAmount *CurrencyAndAmount `xml:"OutsdngLineItmsTtlAmt"` // Line item total amount for which a mismatched data set has been submitted and has not yet been accepted or rejected. PendingLineItemsTotalAmount *CurrencyAndAmount `xml:"PdgLineItmsTtlAmt"` // Total net amount as indicated in the baseline. OrderedTotalNetAmount *CurrencyAndAmount `xml:"OrdrdTtlNetAmt"` // Total net amount accepted by a data set submission. AcceptedTotalNetAmount *CurrencyAndAmount `xml:"AccptdTtlNetAmt"` // Total net amount for which a mismatched data set has been submitted and has not yet been accepted or rejected. OutstandingTotalNetAmount *CurrencyAndAmount `xml:"OutsdngTtlNetAmt"` // Difference between the ordered and the accepted total net amount. PendingTotalNetAmount *CurrencyAndAmount `xml:"PdgTtlNetAmt"` } func (l *LineItem14) AddLineItemDetails() *LineItemDetails12 { newValue := new (LineItemDetails12) l.LineItemDetails = append(l.LineItemDetails, newValue) return newValue } func (l *LineItem14) SetOrderedLineItemsTotalAmount(value, currency string) { l.OrderedLineItemsTotalAmount = NewCurrencyAndAmount(value, currency) } func (l *LineItem14) SetAcceptedLineItemsTotalAmount(value, currency string) { l.AcceptedLineItemsTotalAmount = NewCurrencyAndAmount(value, currency) } func (l *LineItem14) SetOutstandingLineItemsTotalAmount(value, currency string) { l.OutstandingLineItemsTotalAmount = NewCurrencyAndAmount(value, currency) } func (l *LineItem14) SetPendingLineItemsTotalAmount(value, currency string) { l.PendingLineItemsTotalAmount = NewCurrencyAndAmount(value, currency) } func (l *LineItem14) SetOrderedTotalNetAmount(value, currency string) { l.OrderedTotalNetAmount = NewCurrencyAndAmount(value, currency) } func (l *LineItem14) SetAcceptedTotalNetAmount(value, currency string) { l.AcceptedTotalNetAmount = NewCurrencyAndAmount(value, currency) } func (l *LineItem14) SetOutstandingTotalNetAmount(value, currency string) { l.OutstandingTotalNetAmount = NewCurrencyAndAmount(value, currency) } func (l *LineItem14) SetPendingTotalNetAmount(value, currency string) { l.PendingTotalNetAmount = NewCurrencyAndAmount(value, currency) }
LineItem14.go
0.794185
0.415907
LineItem14.go
starcoder
package giso import ( "fmt" "math" ) // Point is a position in a 3D space. type Point struct { x float64 y float64 z float64 } // At returns a point. func At(x, y, z float64) *Point { return &Point{x, y, z} } func (p *Point) X() float64 { return p.x } func (p *Point) Y() float64 { return p.y } func (p *Point) Z() float64 { return p.z } // Translate translates the point by a given dx, dy, and dz. func (p *Point) Translate(dx, dy, dz float64) *Point { return &Point{ x: p.x + dx, y: p.y + dy, z: p.z + dz, } } // Scale scales the point about a given origin. func (p *Point) Scale(origin *Point, dx, dy, dz float64) *Point { t := p.Translate(-origin.x, -origin.y, -origin.z) t.x = t.x * dx t.y = t.y * dy t.z = t.z * dz return t.Translate(origin.x, origin.y, origin.z) } // RotateX rotates the point about origin on the X axis. func (p *Point) RotateX(origin *Point, angle float64) *Point { cos := math.Cos(angle) sin := math.Sin(angle) t := p.Translate(-origin.x, -origin.y, -origin.z) z := t.z*cos - t.y*sin y := t.z*sin + t.y*cos t.z, t.y = z, y return t.Translate(origin.x, origin.y, origin.z) } // RotateY rotates the point about origin on the Y axis. func (p *Point) RotateY(origin *Point, angle float64) *Point { cos := math.Cos(angle) sin := math.Sin(angle) t := p.Translate(-origin.x, -origin.y, -origin.z) x := t.x*cos - t.z*sin z := t.x*sin + t.z*cos t.x, t.z = x, z return t.Translate(origin.x, origin.y, origin.z) } // RotateZ rotates the point about origin on the Z axis. func (p *Point) RotateZ(origin *Point, angle float64) *Point { cos := math.Cos(angle) sin := math.Sin(angle) t := p.Translate(-origin.x, -origin.y, -origin.z) x := t.x*cos - t.y*sin y := t.x*sin + t.y*cos t.x, t.y = x, y return t.Translate(origin.x, origin.y, origin.z) } // Depth computes the depth of a point in the isometric plane. func (p *Point) Depth() float64 { // z is weighted slightly to accomodate |_ arrangements return p.x + p.y - 2*p.z } func (p *Point) String() string { return fmt.Sprintf("(%v, %v, %v)", p.x, p.y, p.z) } /* NOT USED TBD remove it! // Distance returns the distance between two points. func Distance(p1, p2 *Point) float64 { dx := p2.x - p1.x dy := p2.y - p1.y dz := p2.z - p1.z return math.Sqrt(dx*dx + dy*dy + dz*dz) } */
point.go
0.924713
0.692993
point.go
starcoder
package aoc type Matrix3x3 struct { // 0 1 2 // 3 4 5 // 6 7 8 v [9]int } func NewMatrix3x3(values [9]int) Matrix3x3 { return Matrix3x3{v: values} } func NewIdentityMatrix3x3() Matrix3x3 { return NewMatrix3x3([9]int{1, 0, 0, 0, 1, 0, 0, 0, 1}) } func (m Matrix3x3) MulVector3(v Vector3) Vector3 { return Vector3{ X: m.v[0]*v.X + m.v[1]*v.Y + m.v[2]*v.Z, Y: m.v[3]*v.X + m.v[4]*v.Y + m.v[5]*v.Z, Z: m.v[6]*v.X + m.v[7]*v.Y + m.v[8]*v.Z, } } func (m Matrix3x3) Mul(am Matrix3x3) Matrix3x3 { return NewMatrix3x3([9]int{ // 0 1 2 // 3 4 5 // 6 7 8 m.v[0]*am.v[0] + m.v[1]*am.v[3] + m.v[2]*am.v[6], // 0 m.v[0]*am.v[1] + m.v[1]*am.v[4] + m.v[2]*am.v[7], // 1 m.v[0]*am.v[2] + m.v[1]*am.v[5] + m.v[2]*am.v[8], // 2 m.v[3]*am.v[0] + m.v[4]*am.v[3] + m.v[5]*am.v[6], // 3 m.v[3]*am.v[1] + m.v[4]*am.v[4] + m.v[5]*am.v[7], // 4 m.v[3]*am.v[2] + m.v[4]*am.v[5] + m.v[5]*am.v[8], // 5 m.v[6]*am.v[0] + m.v[7]*am.v[3] + m.v[8]*am.v[6], // 6 m.v[6]*am.v[1] + m.v[7]*am.v[4] + m.v[8]*am.v[7], // 7 m.v[6]*am.v[2] + m.v[7]*am.v[5] + m.v[8]*am.v[8], // 8 }) } var rotationMatrixXY map[int]Matrix3x3 var rotationMatrixXZ map[int]Matrix3x3 var rotationMatrixYZ map[int]Matrix3x3 func init() { cos90 := 0 sin90 := 1 cos180 := -1 sin180 := 0 cos270 := 0 sin270 := -1 rotMatrixes := func(f func(c, s int) Matrix3x3) map[int]Matrix3x3 { return map[int]Matrix3x3{ 0: NewIdentityMatrix3x3(), 90: f(cos90, sin90), 180: f(cos180, sin180), 270: f(cos270, sin270), } } rotationMatrixXY = rotMatrixes(func(c, s int) Matrix3x3 { return NewMatrix3x3([9]int{c, -s, 0, s, c, 0, 0, 0, 1}) }) rotationMatrixXZ = rotMatrixes(func(c, s int) Matrix3x3 { return NewMatrix3x3([9]int{c, 0, s, 0, 1, 0, -s, 0, c}) }) rotationMatrixYZ = rotMatrixes(func(c, s int) Matrix3x3 { return NewMatrix3x3([9]int{1, 0, 0, 0, c, -s, 0, s, c}) }) } func RotationMatrixXY(angle int) Matrix3x3 { return rotationMatrixXY[normAngle(angle)] } func RotationMatrixXZ(angle int) Matrix3x3 { return rotationMatrixXZ[normAngle(angle)] } func RotationMatrixYZ(angle int) Matrix3x3 { return rotationMatrixYZ[normAngle(angle)] } func normAngle(angle int) int { angle = angle % 360 if angle < 0 { angle += 360 } return angle }
aoc/matrix3x3.go
0.741487
0.72911
matrix3x3.go
starcoder
package iter type mapIterableForInt struct { iter IterableForInt mapper func(item int) int } func (m *mapIterableForInt) Next() OptionForInt { item := m.iter.Next() if item.IsNone() { return NoneInt() } return SomeInt(m.mapper(item.Unwrap())) } var _ IterableForInt = &mapIterableForInt{} type chainForInt struct { first IterableForInt second IterableForInt flag bool } func (c *chainForInt) Next() OptionForInt { if c.flag { return c.second.Next() } item := c.first.Next() if item.IsNone() { c.flag = true return c.second.Next() } return item } var _ IterableForInt = &chainForInt{} // PairForInt is a 2-tuple. type PairForInt struct { First int Second int } type takeWhileForInt struct { iter IterableForInt predicate func(item int) bool flag bool } func (t *takeWhileForInt) Next() OptionForInt { if t.flag { return NoneInt() } item := t.iter.Next() if item.IsNone() { t.flag = true return NoneInt() } if !t.predicate(item.Unwrap()) { t.flag = true return NoneInt() } return item } var _ IterableForInt = &takeWhileForInt{} type takeForInt struct { iter IterableForInt max uint count uint flag bool } func (t *takeForInt) Next() OptionForInt { if t.flag { return NoneInt() } item := t.iter.Next() if item.IsNone() { t.flag = true return NoneInt() } if t.count >= t.max { t.flag = true return NoneInt() } t.count++ return item } var _ IterableForInt = &takeForInt{} type filterForInt struct { iter IteratorForInt predicate func(item int) bool } func (f *filterForInt) Next() OptionForInt { return f.iter.Find(f.predicate) } var _ IterableForInt = &filterForInt{} type mapIterableForString struct { iter IterableForString mapper func(item string) string } func (m *mapIterableForString) Next() OptionForString { item := m.iter.Next() if item.IsNone() { return NoneString() } return SomeString(m.mapper(item.Unwrap())) } var _ IterableForString = &mapIterableForString{} type chainForString struct { first IterableForString second IterableForString flag bool } func (c *chainForString) Next() OptionForString { if c.flag { return c.second.Next() } item := c.first.Next() if item.IsNone() { c.flag = true return c.second.Next() } return item } var _ IterableForString = &chainForString{} // PairForString is a 2-tuple. type PairForString struct { First string Second string } type takeWhileForString struct { iter IterableForString predicate func(item string) bool flag bool } func (t *takeWhileForString) Next() OptionForString { if t.flag { return NoneString() } item := t.iter.Next() if item.IsNone() { t.flag = true return NoneString() } if !t.predicate(item.Unwrap()) { t.flag = true return NoneString() } return item } var _ IterableForString = &takeWhileForString{} type takeForString struct { iter IterableForString max uint count uint flag bool } func (t *takeForString) Next() OptionForString { if t.flag { return NoneString() } item := t.iter.Next() if item.IsNone() { t.flag = true return NoneString() } if t.count >= t.max { t.flag = true return NoneString() } t.count++ return item } var _ IterableForString = &takeForString{} type filterForString struct { iter IteratorForString predicate func(item string) bool } func (f *filterForString) Next() OptionForString { return f.iter.Find(f.predicate) } var _ IterableForString = &filterForString{}
examples/iterators.go
0.5769
0.441071
iterators.go
starcoder
package conditions import ( "fmt" "github.com/zimmski/tavor/log" "github.com/zimmski/tavor/token" "github.com/zimmski/tavor/token/lists" "github.com/zimmski/tavor/token/primitives" ) // BooleanExpression defines a boolean expression type BooleanExpression interface { token.Token // Evaluate evaluates the boolean expression and returns its result Evaluate() bool } // BooleanTrue implements a boolean expression which evaluates to always true type BooleanTrue struct{} // NewBooleanTrue returns a new instance of a BooleanTrue token func NewBooleanTrue() *BooleanTrue { return &BooleanTrue{} } // Evaluate evaluates the boolean expression and returns its result func (c *BooleanTrue) Evaluate() bool { return true } // Token interface methods // Clone returns a copy of the token and all its children func (c *BooleanTrue) Clone() token.Token { return &BooleanTrue{} } // Parse tries to parse the token beginning from the current position in the parser data. // If the parsing is successful the error argument is nil and the next current position after the token is returned. func (c *BooleanTrue) Parse(pars *token.InternalParser, cur int) (int, []error) { panic("This should never happen") } // Permutation sets a specific permutation for this token func (c *BooleanTrue) Permutation(i uint) error { // do nothing return nil } // Permutations returns the number of permutations for this token func (c *BooleanTrue) Permutations() uint { return 1 } // PermutationsAll returns the number of all possible permutations for this token including its children func (c *BooleanTrue) PermutationsAll() uint { return 1 } func (c *BooleanTrue) String() string { return "true" } // List interface methods // Get returns the current referenced token at the given index. The error return argument is not nil, if the index is out of bound. func (c *BooleanTrue) Get(i int) (token.Token, error) { return nil, &lists.ListError{ Type: lists.ListErrorOutOfBound, } } // Len returns the number of the current referenced tokens func (c *BooleanTrue) Len() int { return 0 } // InternalGet returns the current referenced internal token at the given index. The error return argument is not nil, if the index is out of bound. func (c *BooleanTrue) InternalGet(i int) (token.Token, error) { return nil, &lists.ListError{ Type: lists.ListErrorOutOfBound, } } // InternalLen returns the number of referenced internal tokens func (c *BooleanTrue) InternalLen() int { return 0 } // InternalLogicalRemove removes the referenced internal token and returns the replacement for the current token or nil if the current token should be removed. func (c *BooleanTrue) InternalLogicalRemove(tok token.Token) token.Token { panic("This should never happen") } // InternalReplace replaces an old with a new internal token if it is referenced by this token. The error return argument is not nil, if the replacement is not suitable. func (c *BooleanTrue) InternalReplace(oldToken, newToken token.Token) error { panic("This should never happen") } // BooleanEqual implements a boolean expression which compares the value of two tokens type BooleanEqual struct { a, b token.Token } // NewBooleanEqual returns a new instance of a BooleanEqual token referencing two tokens func NewBooleanEqual(a, b token.Token) *BooleanEqual { return &BooleanEqual{ a: a, b: b, } } // Evaluate evaluates the boolean expression and returns its result func (c *BooleanEqual) Evaluate() bool { return c.a.String() == c.b.String() } // Token interface methods // Clone returns a copy of the token and all its children func (c *BooleanEqual) Clone() token.Token { return &BooleanEqual{ a: c.a, b: c.b, } } // Parse tries to parse the token beginning from the current position in the parser data. // If the parsing is successful the error argument is nil and the next current position after the token is returned. func (c *BooleanEqual) Parse(pars *token.InternalParser, cur int) (int, []error) { panic("This should never happen") } // Permutation sets a specific permutation for this token func (c *BooleanEqual) Permutation(i uint) error { // do nothing return nil } // Permutations returns the number of permutations for this token func (c *BooleanEqual) Permutations() uint { return 1 } // PermutationsAll returns the number of all possible permutations for this token including its children func (c *BooleanEqual) PermutationsAll() uint { return 1 } func (c *BooleanEqual) String() string { return fmt.Sprintf("(%p)%#v == (%p)%#v", c.a, c.a, c.b, c.b) } // List interface methods // Get returns the current referenced token at the given index. The error return argument is not nil, if the index is out of bound. func (c *BooleanEqual) Get(i int) (token.Token, error) { return nil, &lists.ListError{ Type: lists.ListErrorOutOfBound, } } // Len returns the number of the current referenced tokens func (c *BooleanEqual) Len() int { return 0 } // InternalGet returns the current referenced internal token at the given index. The error return argument is not nil, if the index is out of bound. func (c *BooleanEqual) InternalGet(i int) (token.Token, error) { switch i { case 0: return c.a, nil case 1: return c.b, nil default: return nil, &lists.ListError{ Type: lists.ListErrorOutOfBound, } } } // InternalLen returns the number of referenced internal tokens func (c *BooleanEqual) InternalLen() int { return 2 } // InternalLogicalRemove removes the referenced internal token and returns the replacement for the current token or nil if the current token should be removed. func (c *BooleanEqual) InternalLogicalRemove(tok token.Token) token.Token { if tok == c.a || tok == c.b { return nil } return c } // InternalReplace replaces an old with a new internal token if it is referenced by this token. The error return argument is not nil, if the replacement is not suitable. func (c *BooleanEqual) InternalReplace(oldToken, newToken token.Token) error { if oldToken == c.a { c.a = newToken } if oldToken == c.b { c.b = newToken } return nil } // VariableDefined implements a boolean expression which evaluates if a variable is defined in a given scope type VariableDefined struct { name string variableScope *token.VariableScope } // NewVariableDefined returns a new instance of a VariableDefined token initialzed with the given name and scope func NewVariableDefined(name string, variableScope *token.VariableScope) *VariableDefined { return &VariableDefined{ name: name, variableScope: variableScope, } } // Evaluate evaluates the boolean expression and returns its result func (c *VariableDefined) Evaluate() bool { return c.variableScope.Get(c.name) != nil } // Token interface methods // Clone returns a copy of the token and all its children func (c *VariableDefined) Clone() token.Token { return &VariableDefined{ name: c.name, variableScope: c.variableScope, } } // Parse tries to parse the token beginning from the current position in the parser data. // If the parsing is successful the error argument is nil and the next current position after the token is returned. func (c *VariableDefined) Parse(pars *token.InternalParser, cur int) (int, []error) { panic("This should never happen") } // Permutation sets a specific permutation for this token func (c *VariableDefined) Permutation(i uint) error { // do nothing return nil } // Permutations returns the number of permutations for this token func (c *VariableDefined) Permutations() uint { return 1 } // PermutationsAll returns the number of all possible permutations for this token including its children func (c *VariableDefined) PermutationsAll() uint { return 1 } func (c *VariableDefined) String() string { return fmt.Sprintf("defined(%q)", c.name) } // ScopeToken interface methods // SetScope sets the scope of the token func (c *VariableDefined) SetScope(variableScope *token.VariableScope) { c.variableScope = variableScope } // ExpressionPointer implements a token pointer to an expression token type ExpressionPointer struct { token token.Token } // NewExpressionPointer returns a new instance of a ExpressionPointer token referencing the given token func NewExpressionPointer(token token.Token) *ExpressionPointer { return &ExpressionPointer{ token: token, } } // Evaluate evaluates the boolean expression and returns its result func (c *ExpressionPointer) Evaluate() bool { tok := c.token if po, ok := tok.(*primitives.Pointer); ok { log.Debugf("Found pointer in ExpressionPointer %p(%#v)", c, c) for { c := po.InternalGet() c = c.Clone() _ = po.Set(c) po, ok = c.(*primitives.Pointer) if !ok { log.Debugf("Replaced pointer %p(%#v) with %p(%#v)", tok, tok, c, c) tok = c break } } } if t, ok := tok.(BooleanExpression); ok { return t.Evaluate() } panic(fmt.Sprintf("token %p(%#v) does not implement BooleanExpression interface", c.token, c.token)) } // Token interface methods // Clone returns a copy of the token and all its children func (c *ExpressionPointer) Clone() token.Token { return &ExpressionPointer{ token: c.token.Clone(), } } // Parse tries to parse the token beginning from the current position in the parser data. // If the parsing is successful the error argument is nil and the next current position after the token is returned. func (c *ExpressionPointer) Parse(pars *token.InternalParser, cur int) (int, []error) { panic("This should never happen") } // Permutation sets a specific permutation for this token func (c *ExpressionPointer) Permutation(i uint) error { // do nothing return nil } // Permutations returns the number of permutations for this token func (c *ExpressionPointer) Permutations() uint { return 1 } // PermutationsAll returns the number of all possible permutations for this token including its children func (c *ExpressionPointer) PermutationsAll() uint { return 1 } func (c *ExpressionPointer) String() string { return c.token.String() } // ForwardToken interface methods // Get returns the current referenced token func (c *ExpressionPointer) Get() token.Token { return nil } // InternalGet returns the current referenced internal token func (c *ExpressionPointer) InternalGet() token.Token { return c.token } // InternalLogicalRemove removes the referenced internal token and returns the replacement for the current token or nil if the current token should be removed. func (c *ExpressionPointer) InternalLogicalRemove(tok token.Token) token.Token { if c.token == tok { return nil } return c } // InternalReplace replaces an old with a new internal token if it is referenced by this token. The error return argument is not nil, if the replacement is not suitable. func (c *ExpressionPointer) InternalReplace(oldToken, newToken token.Token) error { if c.token == oldToken { c.token = newToken } return nil } // ScopeToken interface methods // SetScope sets the scope of the token func (c *ExpressionPointer) SetScope(variableScope *token.VariableScope) { tok := c.token if po, ok := tok.(*primitives.Pointer); ok { log.Debugf("Found pointer in ExpressionPointer %p(%#v)", c, c) for { c := po.InternalGet() c = c.Clone() _ = po.Set(c) po, ok = c.(*primitives.Pointer) if !ok { log.Debugf("Replaced pointer %p(%#v) with %p(%#v)", tok, tok, c, c) tok = c break } } } if t, ok := tok.(token.ScopeToken); ok { t.SetScope(variableScope) } }
token/conditions/expressions.go
0.830525
0.537163
expressions.go
starcoder
package fields import ( "errors" "reflect" ) // AreEqual is comparing two given Fields using DefaultEquality. func AreEqual(left, right Fields) (bool, error) { if v := DefaultEquality; v != nil { return v.AreFieldsEqual(left, right) } return false, nil } // DefaultEquality is the default instance of a Equality. The initial // initialization of this global variable should be able to deal with the // majority of the cases. There is also a shortcut function: // AreEqual(left,right) var DefaultEquality Equality = &privateEqualityImpl{&EqualityImpl{ ValueEquality: NewValueEqualityFacade(func() ValueEquality { return DefaultValueEquality }), }} // Equality is comparing two Fields with each other and check if both are equal. type Equality interface { // AreFieldsEqual compares the two given Fields for their equality. AreFieldsEqual(left, right Fields) (bool, error) } // EqualityFunc is wrapping a given func into Equality. type EqualityFunc func(left, right Fields) (bool, error) // AreFieldsEqual implements Equality.AreFieldsEqual(). func (instance EqualityFunc) AreFieldsEqual(left, right Fields) (bool, error) { return instance(left, right) } // EqualityImpl is a default implementation of Equality which compares all its // values using the configured ValueEquality. type EqualityImpl struct { // ValueEquality is used to compare the values of the given fields. If nil // DefaultValueEquality is used. If this is nil too, there is always false // returned. ValueEquality ValueEquality } // AreFieldsEqual implements Equality.AreFieldsEqual(). func (instance *EqualityImpl) AreFieldsEqual(left, right Fields) (bool, error) { if instance == nil { return false, nil } ve := instance.ValueEquality if left == nil && right == nil { return true, nil } if left == nil { left = Empty() } if right == nil { right = Empty() } if left.Len() != right.Len() { return false, nil } if ve != nil { if err := left.ForEach(func(key string, lValue interface{}) error { rValue, rExists := right.Get(key) if !rExists { return entriesNotEqualV } if equal, err := ve.AreValuesEqual(key, lValue, rValue); err != nil { return err } else if !equal { return entriesNotEqualV } return nil }); err == entriesNotEqualV { return false, nil } else if err != nil { return false, err } } return true, nil } // NewEqualityFacade creates a re-implementation of Equality which uses the // given provider to retrieve the actual instance of Equality in the moment when // it is used. This is useful especially in cases where you want to deal with // concurrency while creation of objects that need to hold a reference to an // Equality. func NewEqualityFacade(provider func() Equality) Equality { return equalityFacade(provider) } type equalityFacade func() Equality func (instance equalityFacade) AreFieldsEqual(left, right Fields) (bool, error) { return instance.Unwrap().AreFieldsEqual(left, right) } func (instance equalityFacade) Unwrap() Equality { return instance() } type privateEqualityImpl struct { inner *EqualityImpl } func (instance *privateEqualityImpl) AreFieldsEqual(left, right Fields) (bool, error) { return instance.inner.AreFieldsEqual(left, right) } var ( entriesNotEqualV = errors.New(reflect.TypeOf((*Equality)(nil)).PkgPath() + "/both entries are not equal") )
fields/equality.go
0.896311
0.557665
equality.go
starcoder
package validationparams import "github.com/calvine/simplevalidation/validator" // ValidationParams is a struct that represents the parameters for validating a value. type ValidationParams struct { /* ArrayDepth tells the validator how many layers deep an array is. So for instance: [][]int would have an ArrayDepth of 2 []int would have an ArrayDepth of 1 int would have an ArrayDepth of 0 When utilizing tag based validation for struct fields, the array depth is computed by reading the validator type and counting the square bracket pairs before the validator name. While being validated the validation function will recursivly go through each arra level and validate each value. For any failed validation, the resulting error label will be in the format of "type[index1][index2][index3]" for as may nested arrays you may have. */ ArrayDepth uint8 /* FieldValidator is the validator used to validate a value. If the validation is being performed based on struct tags, this is populated by the validation tag parser. */ FieldValidator validator.Validator /* Name is the name of the field being validated if it can be determined and if not, for instance if ou are validating a non struct field, you can populate it, or */ Name string /* Required is a special validation cruteria that is technically valid for any validator. If the Validator does not directly use the required flag, it is still used in the event that the value being validated is a pointer. If the value being validated is a pointer and that pointer is nil then that will result in a validation error when required is true. */ Required bool /* This is a counter that keeps track of how many structs deep validation is being performed. For instance: type s2 struct { C int `validation:"int"` } type s1 struct { A int `validation:"int,min=3,max=15"` B s2 `validation:"struct"` } When validating A StructDepth is 1 and when validating C StructDepth is 2. When StructDepth is greater than 1 the resulting error label will be the "path" to the field within the top level struct. So if C in the example above did have an issue the error label would be "B.C". */ StructDepth uint8 /* Value is the raw value being validated. */ Value interface{} } func New() ValidationParams { return ValidationParams{ ArrayDepth: 0, Name: "", Required: false, StructDepth: 0, } }
validation/validationparams/validationparams.go
0.719186
0.670709
validationparams.go
starcoder
package main import ( "flag" "image" "image/png" "math" "math/rand" "os" "sync" "github.com/Sirupsen/logrus" "github.com/karlek/bygget/plane" "github.com/karlek/bygget/ray" "github.com/karlek/bygget/sphere" "github.com/karlek/bygget/vector" "github.com/karlek/bygget/world" "github.com/pkg/profile" ) func main() { flag.Parse() defer profile.Start(profile.CPUProfile).Stop() if err := render(); err != nil { logrus.Println(err) } } type Camera struct { origin vector.Vector horizontal vector.Vector vertical vector.Vector lowerLeft vector.Vector lensRadius float64 } func NewCamera(lookFrom, lookAt vector.Vector, vFov, aspect, aperture float64) Camera { // Convert vertical fov to radians. theta := vFov * math.Pi / 180 // Vertical field of view, where 180 degrees is rays with (close to) // infinite ascent and decent. And 0.1 degrees is really narrow. halfHeight := math.Tan(theta / 2) // Aspect ratio of height and width to produce the width. halfWidth := aspect * halfHeight // Our skewed reference system. // w is our "forward" vector // u our "right" vector. // v our "upwards" vector. w := lookFrom.Sub(lookAt).Norm() u := vector.Vector{0, 1, 0}.Cross(w).Norm() v := w.Cross(u) focusDist := lookFrom.Sub(lookAt).Length() x := u.MultiplyScalar(halfWidth * focusDist) y := v.MultiplyScalar(halfHeight * focusDist) z := w.MultiplyScalar(focusDist) lowerLeft := lookFrom.Sub(x).Sub(y).Sub(z) horizontal := x.MultiplyScalar(2) vertical := y.MultiplyScalar(2) return Camera{ origin: lookFrom, horizontal: horizontal, vertical: vertical, lowerLeft: lowerLeft, lensRadius: aperture / 2, } } func (c Camera) RayAt(xscale, yscale float64, width, height int) ray.Ray { position := c.horizontal.MultiplyScalar(xscale).Add(c.vertical.MultiplyScalar(yscale)) direction := c.lowerLeft.Add(position) return ray.Ray{ Origin: c.origin, Direction: direction} } func render() (err error) { var ( width, height = 1280, 720 samples = 10 ) img := image.NewRGBA(image.Rect(0, 0, width, height)) h := -2.0 cam := NewCamera(vector.Origo, vector.Vector{0, h, -5.5}, 70, float64(width)/float64(height), 5.4) s1 := &sphere.Sphere{vector.Vector{0, h, -6}, 0.5, world.Lambertian{vector.Vector{0.8, 0.7, 0.2}}} // s2 := &sphere.Sphere{vector.Vector{-1, h, -6}, 0.5, world.Dielectric{0.5}} // s3 := &sphere.Sphere{vector.Vector{-.2, h, -4}, 0.5, world.Lambertian{vector.Vector{0.88, 0.0, 0.5}}} // s4 := &sphere.Sphere{vector.Vector{-0.4, h, -3}, 0.5, world.Dielectric{0.8}} // s5 := &sphere.Sphere{vector.Vector{1, h, -6}, 0.5, world.Metal{vector.Vector{.7, .7, .9}, 0.3}} floor := &plane.Plane{P: vector.Vector{0, h - 0.5, 0}, N: vector.Vector{0, -1, 0}, Material: world.Lambertian{vector.Vector{.1, .1, .1}}} // roof := &plane.Plane{P: vector.Vector{0, 1, 0}, N: vector.Vector{0, 1, 0}, Material: world.Lambertian{vector.Vector{.9, .9, .9}}} wall1 := &plane.Plane{P: vector.Vector{0, h, -9}, N: vector.Vector{0, 0, -1}, Material: world.Lambertian{vector.Vector{.9, .9, .9}}} wall2 := &plane.Plane{P: vector.Vector{-3, h, 0}, N: vector.Vector{-1, -1, 0}, Material: world.Lambertian{vector.Vector{.9, .9, .9}}} wall3 := &plane.Plane{P: vector.Vector{3, h, 0}, N: vector.Vector{1, 0, 0}, Material: world.Lambertian{vector.Vector{.9, .9, .9}}} // wall4 := &plane.Plane{P: vector.Vector{0, 0, 1}, N: vector.Vector{0, 0, 1}, Material: world.Lambertian{vector.Vector{1, 1, 1}}} disc := &plane.Disc{P: vector.Vector{0, 3, 0}, N: vector.Vector{0, 1, 0}, R: 3, Material: world.Light{vector.Vector{1.0, 1.0, 1.0}}} world.Bulb = disc // world.Bulb = &sphere.Sphere{Center: vector.Vector{0, 0, 0}, Radius: 3, Material: world.Light{vector.Vector{1.0, 1.0, 1.0}}} w := &world.World{Elements: []world.Hitable{}} w.Add(floor) // w.Add(roof) w.Add(wall1) w.Add(wall2) w.Add(wall3) // w.Add(wall4) w.Add(s1) // w.Add(s2) // w.Add(s3) // w.Add(s4) // w.Add(s5) wg := new(sync.WaitGroup) wg.Add(height) for y := 0; y < height; y++ { go func(y int, wg *sync.WaitGroup) { defer wg.Done() r := ray.Ray{} rnd := rand.New(rand.NewSource(int64(y))) for x := 0; x < width; x++ { xscale := (float64(x) + rand.Float64()) / float64(width) yscale := (float64(y) + rand.Float64()) / float64(height) rgb := vector.Vector{} for i := 0; i < samples; i++ { r = cam.RayAt(xscale, yscale, width, height) col := world.ColorVector(&r, w, 0, rnd) rgb = rgb.Add(col) } c := rgb.DivideScalar(float64(samples)).Color() img.Set(int(x), int(height-y), c) } }(y, wg) } wg.Wait() f, err := os.Create("a.png") if err != nil { return err } err = png.Encode(f, img) if err != nil { return err } f.Close() // } return nil }
cmd/bygget/bygget.go
0.52342
0.418727
bygget.go
starcoder
package main import ( "math" ) type meanVarianceCouple struct { mean float64 variance float64 } type caracteristicsStats struct { noiseLevel meanVarianceCouple brakeDistance meanVarianceCouple vibrations meanVarianceCouple } type caracteristicsStatsByPlaneType map[PlaneType]caracteristicsStats func calculateStats(measurementsByPlaneTypeLocal measurementsByPlaneType) caracteristicsStatsByPlaneType { var caracteristicsStatsByPlaneTypeLocal caracteristicsStatsByPlaneType = make(caracteristicsStatsByPlaneType, len(measurementsByPlaneTypeLocal)) for planeType, measurements := range measurementsByPlaneTypeLocal { // Calculate the means for each caracteristic noiseLevelMean, brakeDistanceMean, vibrationsMean := calculateMeans(measurements) // Calculate the variance noiseLevelVariance, brakeDistanceVariance, vibrationsVariance := calculateVariance(measurements, noiseLevelMean, brakeDistanceMean, vibrationsMean) // Add the caracteristic stats var ( noiseLevelCouple meanVarianceCouple = meanVarianceCouple{noiseLevelMean, noiseLevelVariance} brakeDistanceCouple meanVarianceCouple = meanVarianceCouple{brakeDistanceMean, brakeDistanceVariance} vibrationsCouple meanVarianceCouple = meanVarianceCouple{vibrationsMean, vibrationsVariance} caracteristicsStatsLocal caracteristicsStats = caracteristicsStats{noiseLevelCouple, brakeDistanceCouple, vibrationsCouple} ) logger.Printf("We got for plane %s:\n\tNoise Level mean:\t%f\n\tNoise Level variance:\t%f\n\tBrake Distance mean:\t%f\n\tBrake Distance variance:\t%f\n\tVibrations mean:\t%f\n\tVibrations variance:\t%f\n", planeType, noiseLevelMean, noiseLevelVariance, brakeDistanceMean, brakeDistanceVariance, vibrationsMean, vibrationsVariance) // Add it to the map caracteristicsStatsByPlaneTypeLocal[planeType] = caracteristicsStatsLocal } return caracteristicsStatsByPlaneTypeLocal } func calculateMeans(measurementList []Measurement) (noiseLevelMean, brakeDistanceMean, vibrationsMean float64) { measurementsNumber := float64(len(measurementList)) var ( noiseLevelSum float64 brakeDistanceSum float64 vibrationsSum float64 ) // Sum it all for _, m := range measurementList { noiseLevelSum += m.NoiseLevel brakeDistanceSum += m.BrakeDistance vibrationsSum += m.Vibrations } // Divide it noiseLevelMean = noiseLevelSum / measurementsNumber brakeDistanceMean = brakeDistanceSum / measurementsNumber vibrationsMean = vibrationsSum / measurementsNumber // Return return } func calculateVariance(measurementList []Measurement, noiseLevelMean, brakeDistanceMean, vibrationsMean float64) (noiseLevelVariance, brakeDistanceVariance, vibrationsVariance float64) { measurementsNumber := float64(len(measurementList)) var ( noiseLevelTmp float64 brakeDistanceTmp float64 vibrationsTmp float64 ) // Intermediary calculation for _, m := range measurementList { noiseLevelTmp += math.Pow(m.NoiseLevel-noiseLevelMean, 2) brakeDistanceTmp += math.Pow(m.BrakeDistance-brakeDistanceMean, 2) vibrationsTmp += math.Pow(m.Vibrations-vibrationsMean, 2) } // Divide it noiseLevelVariance = noiseLevelTmp / measurementsNumber brakeDistanceVariance = brakeDistanceTmp / measurementsNumber vibrationsVariance = vibrationsTmp / measurementsNumber // Return return }
caracteristics.go
0.84607
0.525856
caracteristics.go
starcoder
package grapher import ( "fmt" "io/ioutil" "gopkg.in/yaml.v2" ) // NodeSpec defines the structure expected from the yaml file to define each nodes. type NodeSpec struct { Name string `yaml:"name"` // unique name assigned to this node Category string `yaml:"category"` // "job", "sequence", or "conditional" NodeType string `yaml:"type"` // the type of job or sequence to create Each []string `yaml:"each"` // arguments to repeat over Args []*NodeArg `yaml:"args"` // expected arguments Sets []string `yaml:"sets"` // expected job args to be set Dependencies []string `yaml:"deps"` // nodes with out-edges leading to this node Retry uint `yaml:"retry"` // the number of times to retry a "job" that fails RetryWait string `yaml:"retryWait"` // the time, in seconds, to sleep between "job" retries If string `yaml:"if"` // the name of the jobArg to check for a conditional value Eq map[string]string `yaml:"eq"` // conditional values mapping to appropriate sequence names } // NodeArg defines the structure expected from the yaml file to define a job's args. type NodeArg struct { Expected string `yaml:"expected"` // the name of the argument that this job expects Given string `yaml:"given"` // the name of the argument that will be given to this job } // SequenceSpec defines the structure expected from the config yaml file to // define each sequence type SequenceSpec struct { Name string `yaml:"name"` // name of the sequence Args SequenceArgs `yaml:"args"` // arguments to the sequence Nodes map[string]*NodeSpec `yaml:"nodes"` // list of nodes that are a part of the sequence Retry uint `yaml:"retry"` // the number of times to retry the sequence if it fails Request bool `yaml:"request"` // whether or not the sequence spec is a user request ACL []ACL `yaml:"acl"` // allowed caller roles (optional) } // SequenceArgs defines the structure expected from the config file to define // a sequence's arguments. A sequence can have required arguments; any arguments // on this list that are missing will result in an error from Grapher. // A sequence can also have optional arguemnts; arguments on this list that are // missing will not result in an error. Additionally optional arguments can // have default values that will be used if not explicitly given. type SequenceArgs struct { Required []*ArgSpec `yaml:"required"` Optional []*ArgSpec `yaml:"optional"` Static []*ArgSpec `yaml:"static"` } // ArgSpec defines the structure expected from the config to define sequence args. type ArgSpec struct { Name string `yaml:"name"` Desc string `yaml:"desc"` Default string `yaml:"default"` } // ACL represents one role-based ACL entry. Every auth.Caller (from the // user-provided auth plugin Authenticate method) is authorized with a matching // ACL, else the request is denied with HTTP 401 unauthorized. Roles are // user-defined. If Admin is true, Ops cannot be set. type ACL struct { Role string `yaml:"role"` // user-defined role Admin bool `yaml:"admin"` // all ops allowed if true Ops []string `yaml:"ops"` // proto.REQUEST_OP_* } // All Sequences in the yaml. Also contains the user defined no-op job. type Config struct { Sequences map[string]*SequenceSpec `yaml:"sequences"` } // ReadConfig will read from configFile and return a Config that the user // can then use for NewGrapher(). configFile is expected to be in the yaml // format specified. func ReadConfig(configFile string) (Config, error) { var cfg Config sequenceData, err := ioutil.ReadFile(configFile) if err != nil { return cfg, err } err = yaml.Unmarshal(sequenceData, &cfg) if err != nil { return cfg, err } for sequenceName, sequence := range cfg.Sequences { sequence.Name = sequenceName for nodeName, node := range sequence.Nodes { node.Name = nodeName } // Validate ACLs, if any seen := map[string]bool{} for _, acl := range sequence.ACL { if acl.Admin && len(acl.Ops) != 0 { return cfg, fmt.Errorf("invalid user ACL for %s in %s: admin=true and ops are mutually exclusive; set admin=false or remove ops", sequenceName, configFile) } if acl.Role == "" { return cfg, fmt.Errorf("invalid user ACL for %s in %s: role is not set (empty string); it must be set", sequenceName, configFile) } if seen[acl.Role] { return cfg, fmt.Errorf("duplicate user ACL for %s in %s: role=%s", sequenceName, configFile, acl.Role) } seen[acl.Role] = true } } return cfg, nil } // isSequence will return true if j is a Sequence, and false otherwise. func (j *NodeSpec) isSequence() bool { return j.Category == "sequence" } // isSequence will return true if j is a Sequence, and false otherwise. func (j *NodeSpec) isConditional() bool { return j.Category == "conditional" }
request-manager/grapher/spec.go
0.72331
0.484685
spec.go
starcoder
package spatial import ( "golina/matrix" "math" ) func PointToPointDistance(p1, p2 *matrix.Vector) float64 { return p1.Sub(p2).Norm() } func PointToLineDistance(pt, linePt, lineDir *matrix.Vector) float64 { return pt.Sub(linePt).Sub(lineDir.MulNum(lineDir.Dot(pt.Sub(linePt)))).Norm() } func PointToPlaneDistance(pt, planeCenter, planeNormal *matrix.Vector) float64 { return math.Abs(planeNormal.Dot(pt.Sub(planeCenter))) } // https://en.wikipedia.org/wiki/Hausdorff_distance type HausdorffDistance struct { Distance float64 LIndex, RIndex int } func DirectedHausdorffDistance(pts1, pts2 *matrix.Matrix) *HausdorffDistance { r1, c1 := pts1.Dims() r2, c2 := pts2.Dims() if c1 != c2 { panic("points should have same coordinates") } cMax, cMin, d := 0., 0., 0. i, j, k := 0, 0, 0 iStore, jStore, iRet, jRet := 0, 0, 0, 0 noBreakOccurred := false hd := HausdorffDistance{0., 0, 0} for i = 0; i < r1; i++ { noBreakOccurred = true cMin = math.Inf(1) for j = 0; j < r2; j++ { d = 0. for k = 0; k < c1; k++ { d += (pts1.At(i, k) - pts2.At(j, k)) * (pts1.At(i, k) - pts2.At(j, k)) } if d < cMax { noBreakOccurred = false break } if d < cMin { cMin = d iStore, jStore = i, j } } if cMin != math.Inf(1) && cMin > cMax && noBreakOccurred { cMax = cMin iRet = iStore jRet = jStore } } hd.Distance = math.Sqrt(cMax) hd.LIndex = iRet hd.RIndex = jRet return &hd } func DirectedHausdorffDistanceBasedOnKNN(pts1, pts2 *matrix.Matrix) *HausdorffDistance { // TODO: tile first then convert to matrix operations? r1, c1 := pts1.Dims() _, c2 := pts2.Dims() if c1 != c2 { panic("points should have same coordinates") } ch := make(chan matrix.Vector, r1) for i, p := range pts1.Data { go func(i int, p matrix.Vector) { res := KNearestNeighborsWithDistance(matrix.Copy(pts2), &p, 1, SquaredEuclideanDistance).Row(0) ch <- matrix.Vector{float64(i), res.At(-2), res.At(-1)} // idx, idx, distance }(i, p) } lidx, ridx, dist := 0, 0, 0. for i := 0; i < r1; i++ { res := <-ch if res.At(-1) > dist { dist = res.At(-1) lidx = int(res.At(0)) ridx = int(res.At(1)) } } return &HausdorffDistance{LIndex: lidx, RIndex: ridx, Distance: math.Sqrt(dist)} } // https://people.revoledu.com/kardi/tutorial/Similarity/ // Taxicab Distance or Manhattan Distance (== p1 MinkowskiDistance) // https://en.wikipedia.org/wiki/Taxicab_geometry func TaxicabDistance(v1, v2 *matrix.Vector) float64 { return v1.Sub(v2).AbsSum() } // EuclideanDistance (== p2 MinkowskiDistance) func EuclideanDistance(v1, v2 *matrix.Vector) float64 { return v1.Sub(v2).Norm() } func SquaredEuclideanDistance(v1, v2 *matrix.Vector) float64 { return v1.Sub(v2).SquareSum() } // p norm // https://en.wikipedia.org/wiki/Minkowski_distance func MinkowskiDistance(v1, v2 *matrix.Vector, p float64) float64 { d := 0. for i := range *v1 { d += math.Pow(math.Abs((*v1)[i]-(*v2)[i]), p) } return math.Pow(d, 1./p) } // L∞ distance (infinity norm distance, p -> ∞); Chessboard Distance; Chebyshev Distance // https://en.wikipedia.org/wiki/Chebyshev_distance func ChebyshevDistance(v1, v2 *matrix.Vector) float64 { d := 0. tmp := 0. for i := range *v1 { tmp = math.Abs((*v1)[i] - (*v2)[i]) if tmp >= d { d = tmp } } return d } // HammingDistance (bitwise difference) // https://en.wikipedia.org/wiki/Hamming_distance func HammingDistance(v1, v2 *matrix.Vector) float64 { d := 0. for i := range *v1 { if (*v1)[i] != (*v2)[i] { d++ } } return d } // CanberraDistance // https://en.wikipedia.org/wiki/Canberra_distance func CanberraDistance(v1, v2 *matrix.Vector) float64 { d := 0. for i := range *v1 { d += math.Abs((*v1)[i]-(*v2)[i]) / (math.Abs((*v1)[i]) + math.Abs((*v2)[i])) } return d }
spatial/distance.go
0.643441
0.602237
distance.go
starcoder
package math import ( "unsafe" "math/rand" "math" "korok.io/korok/math/f32" ) const MaxFloat32 float32 = 3.40282346638528859811704183484516925440e+38 const Pi = math.Pi /// This is A approximate yet fast inverse square-root. func InvSqrt(x float32) float32 { xhalf := float32(0.5) * x i := *(*int32)(unsafe.Pointer(&x)) i = int32(0x5f3759df) - int32(i>>1) x = *(*float32)(unsafe.Pointer(&i)) x = x * (1.5 - (xhalf * x * x)) return x } func InvLength(x, y , fail float32) float32 { return 1/float32(math.Sqrt(float64(x*x + y*y))) } /// a faster way ? func Random(low, high float32) float32 { return low + (high - low) * rand.Float32() } func ABS(a float32) float32 { if a < 0 { return -a } return a } func Max(a, b float32) float32 { if a < b { return b } return a } func Min(a, b float32) float32 { if a < b { return a } return b } func Clamp(v, left, right float32) float32{ if v > right { return right } if v < left { return left } return v } func Sin(r float32) float32 { return float32(math.Sin(float64(r))) } func Cos(r float32) float32 { return float32(math.Cos(float64(r))) } func Atan2(y, x float32) float32 { return float32(math.Atan2(float64(y), float64(x))) } func Floor(v float32) float32 { return float32(math.Floor(float64(v))) } func Ceil(v float32) float32 { return float32(math.Ceil(float64(v))) } // Radian converts degree to radian. func Radian(d float32) float32 { return d * Pi / 180 } // Degree converts radian to degree. func Degree(r float32) float32 { return r * 180 / Pi } func AngleTo(v1, v2 f32.Vec2) (dot float32) { l1 := InvLength(v1[0], v1[1], 1) l2 := InvLength(v2[0], v2[1], 1) x1, y1 := v1[0]*l1, v1[1]*l1 x2, y2 := v2[0]*l2, v2[1]*l2 dot = x1 * x2 + y1 * y2 return } func Direction(v1, v2 f32.Vec2) float32 { return v1[0]*v2[1] - v1[1]*v2[0] } func Angle(v f32.Vec2) float32 { return float32(math.Atan2(float64(v[1]), float64(v[0]))) } func Vector(a float32) f32.Vec2 { return f32.Vec2{Cos(a), Sin(a)} }
math/f32.go
0.835718
0.48054
f32.go
starcoder
package fractal import ( "bytes" "github.com/nfnt/resize" "image" "image/color" "io" "math" ) const ( GAMMA = 0.75 DECODE_ITERATIONS = 16 ) type imagePanel struct { x, y, mean int pixels []uint16 } type image8 struct { xPanels, yPanels, panelSize int bounds image.Rectangle pixels []uint8 panels []imagePanel } func splitImage(input image.Image) (r, g, b image.Image) { width, height := input.Bounds().Max.X, input.Bounds().Max.Y size := width * height rpixels, gpixels, bpixels := make([]uint8, size), make([]uint8, size), make([]uint8, size) for y := 0; y < height; y++ { offset := y * width for x := 0; x < width; x++ { r, g, b, _ := input.At(x, y).RGBA() i := x + offset rpixels[i], gpixels[i], bpixels[i] = uint8(r >> 8), uint8(g >> 8), uint8(b >> 8) } } r = &image8{ bounds: image.Rectangle{ Max: image.Point{ X: width, Y: height}}, pixels: rpixels} g = &image8{ bounds: image.Rectangle{ Max: image.Point{ X: width, Y: height}}, pixels: gpixels} b = &image8{ bounds: image.Rectangle{ Max: image.Point{ X: width, Y: height}}, pixels: bpixels} return } func newImage(input image.Image, scale, panelSize int, gamma float64) *image8 { width, height := input.Bounds().Max.X, input.Bounds().Max.Y if scale > 1 { width, height = width/scale, height/scale input = resize.Resize(uint(width), uint(height), input, resize.NearestNeighbor) } for (width%panelSize) != 0 || (width%2) != 0 { width-- } for (height%panelSize) != 0 || (height%2) != 0 { height-- } pixels := make([]uint8, width*height) for y := 0; y < height; y++ { offset := y * width for x := 0; x < width; x++ { c, _, _, _ := input.At(x, y).RGBA() pixels[offset+x] = uint8(uint32(round(float64(c)*gamma/256.0))) } } xPanels, yPanels := width/panelSize, height/panelSize panels, size := make([]imagePanel, xPanels*yPanels), panelSize*panelSize for i := range panels { panels[i].pixels = make([]uint16, size) } paneled := &image8{ xPanels: xPanels, yPanels: yPanels, panelSize: panelSize, bounds: image.Rectangle{ Max: image.Point{ X: width, Y: height}}, pixels: pixels, panels: panels} paneled.updatePanels() return paneled } func (i *image8) updatePanels() { width, height := i.Bounds().Max.X, i.Bounds().Max.Y pixels, panels, panelSize := i.pixels, i.panels, i.panelSize p, size := 0, panelSize*panelSize for y := 0; y < height; y += panelSize { for x := 0; x < width; x += panelSize { pix, q, sum := panels[p].pixels, 0, 0 for j := 0; j < panelSize; j++ { for i := 0; i < panelSize; i++ { pix[q] = uint16(pixels[(y+j)*width+x+i]) sum, q = sum+int(pix[q]), q+1 } } panels[p] = imagePanel{ x: x, y: y, mean: sum / size, pixels: pix} p++ } } } func (i *image8) ColorModel() color.Model { return color.GrayModel } func (i *image8) Bounds() image.Rectangle { return i.bounds } func (i *image8) At(x, y int) color.Color { return color.Gray{Y: i.pixels[y*i.bounds.Max.X+x]} } func (i *image8) Set(x, y int, c color.Color) { gray, _, _, _ := c.RGBA() i.pixels[y*i.bounds.Max.X+x] = uint8(gray) } func FractalCoder(in image.Image, panelSize int, out io.Writer) { destination := newImage(in, 1, panelSize, 1) reference := newImage(in, 2, panelSize, GAMMA) maps := newPixelMap(panelSize) buffer, count := &bytes.Buffer{}, 0 write16 := func(s uint16) { b := [...]byte{ byte(s >> 8), byte(s & 0xFF)} buffer.Write(b[:]) } for _, dPanel := range destination.panels { var best imagePanel bestError, bestForm, bestBeta := uint64(math.MaxUint64), 0, 0 for _, rPanel := range reference.panels { beta := dPanel.mean - rPanel.mean search: for f, pmap := range maps { error := uint64(0) for i, j := range pmap { delta := int(dPanel.pixels[i]) - int(rPanel.pixels[j]) - beta error += uint64(delta * delta) if error >= bestError { continue search } } if error < bestError { best = rPanel bestBeta = beta bestForm = f bestError = error } } if bestError == 0 { break } } write16(uint16(bestForm)) write16(uint16(best.x)) write16(uint16(best.y)) write16(uint16(bestBeta)) count++ } write32 := func(i uint32) { b := [...]byte{ byte(i >> 24), byte((i >> 16) & 0xFF), byte((i >> 8) & 0xFF), byte(i & 0xFF)} out.Write(b[:]) } write32(uint32(destination.xPanels)) write32(uint32(destination.yPanels)) write32(uint32(destination.panelSize)) write32(uint32(count)) out.Write(buffer.Bytes()) } func FractalDecoder(in io.Reader, _panelSize int) image.Image { read32 := func() uint32 { var p [4]byte in.Read(p[:]) return (uint32(p[0]) << 24) | (uint32(p[1]) << 16) | (uint32(p[2]) << 8) | uint32(p[3]) } xPanels := read32() yPanels := read32() panelSize := read32() count := read32() read16 := func() uint16 { var p [2]byte in.Read(p[:]) return (uint16(p[0]) << 8) | uint16(p[1]) } codes := make([]struct{ form, x, y, beta uint16 }, count) for i := range codes { codes[i].form = read16() codes[i].x = read16() codes[i].y = read16() codes[i].beta = read16() } width, height := xPanels*uint32(_panelSize), yPanels*uint32(_panelSize) pixels := make([]uint8, width*height) for y := uint32(0); y < height; y++ { offset := y * width for x := uint32(0); x < width; x++ { pixels[offset+x] = uint8(0x80) } } panels, size := make([]imagePanel, xPanels*yPanels), _panelSize*_panelSize for i := range panels { panels[i].pixels = make([]uint16, size) } destination := &image8{ xPanels: int(xPanels), yPanels: int(yPanels), panelSize: _panelSize, bounds: image.Rectangle{ Max: image.Point{ X: int(width), Y: int(height)}}, pixels: pixels, panels: panels} destination.updatePanels() newReference := func() *image8 { width, height := destination.Bounds().Max.X, destination.Bounds().Max.Y width, height = width/2, height/2 reference := resize.Resize(uint(width), uint(height), destination, resize.NearestNeighbor) pixels := make([]uint8, width*height) for y := 0; y < height; y++ { offset := y * width for x := 0; x < width; x++ { r, _, _, _ := reference.At(x, y).RGBA() pixels[offset+x] = uint8(uint32(round(float64(r)*GAMMA/256))) } } xPanels, yPanels := width/_panelSize, height/_panelSize panels, size := make([]imagePanel, xPanels*yPanels), _panelSize*_panelSize for i := range panels { panels[i].pixels = make([]uint16, size) } paneled := &image8{ xPanels: xPanels, yPanels: yPanels, panelSize: _panelSize, bounds: image.Rectangle{ Max: image.Point{ X: width, Y: height}}, pixels: pixels, panels: panels} paneled.updatePanels() return paneled } maps := newPixelMap(_panelSize) for i := 0; i < DECODE_ITERATIONS; i++ { reference := newReference() for j, d := range panels { code := codes[j] //x, y := int(uint64(_panelSize)*uint64(code.x)/(2*uint64(panelSize))), // int(uint64(_panelSize)*uint64(code.y)/(2*uint64(panelSize))) x, y := int(uint32(code.x)/panelSize), int(uint32(code.y)/panelSize) if x >= reference.xPanels { x = reference.xPanels - 1 } if y >= reference.yPanels { y = reference.yPanels - 1 } r := reference.panels[x+y*reference.xPanels] pmap, f := maps[code.form], 0 for y := 0; y < _panelSize; y++ { for x := 0; x < _panelSize; x++ { z, e := int(r.pixels[pmap[f]])+int(int16(code.beta)), d.x+x+int(width)*(d.y+y) if z < 0 { pixels[e] = uint8(0) } else if z > 255 { pixels[e] = uint8(0xFF) } else { pixels[e] = uint8(z) } f++ } } } } return destination }
_vendor/src/github.com/pointlander/compress/fractal/fractal.go
0.613584
0.465995
fractal.go
starcoder
package day09 import ( "errors" "advent2021.com/util" ) type FloorMap struct { values []int columnLength int } func ParseFloorMap(lines []string) (*FloorMap, error) { columnLength := -1 size := 0 for _, line := range lines { size += len(line) if columnLength == -1 { columnLength = len(line) } else if columnLength != len(line) { return nil, errors.New("invalid row length") } } if size == 0 { return nil, errors.New("no data") } values := make([]int, size) i := 0 for _, line := range lines { for _, r := range line { value, err := util.RuneToInt(r) if err != nil { return nil, err } values[i] = value i++ } } return &FloorMap{values: values, columnLength: columnLength}, nil } func convertToIndex(row, column, columnLength int) int { return (row * columnLength) + column } func (f *FloorMap) Rows() int { return len(f.values) / f.columnLength } func (f *FloorMap) Columns() int { return f.columnLength } func (f *FloorMap) Value(row, column int) int { index := convertToIndex(row, column, f.columnLength) return f.values[index] } func Part1(f *FloorMap) int { isHigherThan := func(value, row, column int) bool { if row < 0 || row >= f.Rows() || column < 0 || column >= f.Columns() { return true } return f.Value(row, column) > value } isLowPoint := func(row, column int) bool { value := f.Value(row, column) return isHigherThan(value, row-1, column) && isHigherThan(value, row+1, column) && isHigherThan(value, row, column+1) && isHigherThan(value, row, column-1) } sum := 0 for r := 0; r < f.Rows(); r++ { for c := 0; c < f.Columns(); c++ { if isLowPoint(r, c) { risk := f.Value(r, c) + 1 sum += risk } } } return sum } func Part2(f *FloorMap) int { found := make([]bool, len(f.values)) var calcBasinSize func(row, column int) int calcBasinSize = func(row, column int) int { if row < 0 || row >= f.Rows() || column < 0 || column >= f.Columns() { return 0 } index := convertToIndex(row, column, f.columnLength) if found[index] { return 0 } found[index] = true value := f.values[index] if value == 9 { return 0 } return 1 + calcBasinSize(row-1, column) + calcBasinSize(row+1, column) + calcBasinSize(row, column+1) + calcBasinSize(row, column-1) } maxes := make([]int, 3) updateMaxes := func(size int) { if size == 0 { return } for i := 0; i < len(maxes); i++ { if size > maxes[i] { temp := maxes[i] maxes[i] = size size = temp } } } for r := 0; r < f.Rows(); r++ { for c := 0; c < f.Columns(); c++ { size := calcBasinSize(r, c) updateMaxes(size) } } result := 1 for _, size := range maxes { result *= size } return result }
day09/day09.go
0.554953
0.498291
day09.go
starcoder
package master import ( "encoding/json" "fmt" "github.com/chubaofs/cfs/proto" "github.com/chubaofs/cfs/util/log" "github.com/juju/errors" "runtime" "sync" "time" ) // DataPartitionMap stores all the data partitionMap type DataPartitionMap struct { sync.RWMutex partitionMap map[uint64]*DataPartition readableAndWritableCnt int // number of readable and writable partitionMap lastLoadedIndex uint64 // last loaded partition index lastReleasedIndex uint64 // last released partition index partitions []*DataPartition responseCache []byte volName string } func newDataPartitionMap(volName string) (dpMap *DataPartitionMap) { dpMap = new(DataPartitionMap) dpMap.partitionMap = make(map[uint64]*DataPartition, 0) dpMap.partitions = make([]*DataPartition, 0) dpMap.volName = volName return } func (dpMap *DataPartitionMap) get(ID uint64) (*DataPartition, error) { dpMap.RLock() defer dpMap.RUnlock() if v, ok := dpMap.partitionMap[ID]; ok { return v, nil } return nil, errors.Annotatef(dataPartitionNotFound(ID), "[%v] not found in [%v]", ID, dpMap.volName) } func (dpMap *DataPartitionMap) put(dp *DataPartition) { dpMap.Lock() defer dpMap.Unlock() _, ok := dpMap.partitionMap[dp.PartitionID] if !ok { dpMap.partitions = append(dpMap.partitions, dp) dpMap.partitionMap[dp.PartitionID] = dp return } // replace the old partition with dp in the map and array dpMap.partitionMap[dp.PartitionID] = dp dataPartitions := make([]*DataPartition, 0) for index, partition := range dpMap.partitions { if partition.PartitionID == dp.PartitionID { dataPartitions = append(dataPartitions, dpMap.partitions[:index]...) dataPartitions = append(dataPartitions, dp) dataPartitions = append(dataPartitions, dpMap.partitions[index+1:]...) dpMap.partitions = dataPartitions break } } } func (dpMap *DataPartitionMap) setReadWriteDataPartitions(readWrites int, clusterName string) { dpMap.Lock() defer dpMap.Unlock() dpMap.readableAndWritableCnt = readWrites } func (dpMap *DataPartitionMap) updateResponseCache(needsUpdate bool, minPartitionID uint64) (body []byte, err error) { dpMap.Lock() defer dpMap.Unlock() if dpMap.responseCache == nil || needsUpdate || len(dpMap.responseCache) == 0 { dpMap.responseCache = make([]byte, 0) dpResps := dpMap.getDataPartitionsView(minPartitionID) if len(dpResps) == 0 { log.LogError(fmt.Sprintf("action[updateDpResponseCache],volName[%v] minPartitionID:%v,err:%v", dpMap.volName, minPartitionID, proto.ErrNoAvailDataPartition)) return nil, proto.ErrNoAvailDataPartition } cv := proto.NewDataPartitionsView() cv.DataPartitions = dpResps if body, err = json.Marshal(cv); err != nil { log.LogError(fmt.Sprintf("action[updateDpResponseCache],minPartitionID:%v,err:%v", minPartitionID, err.Error())) return nil, proto.ErrMarshalData } dpMap.responseCache = body return } body = make([]byte, len(dpMap.responseCache)) copy(body, dpMap.responseCache) return } func (dpMap *DataPartitionMap) getDataPartitionsView(minPartitionID uint64) (dpResps []*proto.DataPartitionResponse) { dpResps = make([]*proto.DataPartitionResponse, 0) log.LogDebugf("volName[%v] DataPartitionMapLen[%v],DataPartitionsLen[%v],minPartitionID[%v]", dpMap.volName, len(dpMap.partitionMap), len(dpMap.partitions), minPartitionID) for _, dp := range dpMap.partitionMap { if dp.PartitionID <= minPartitionID { continue } dpResp := dp.convertToDataPartitionResponse() dpResps = append(dpResps, dpResp) } return } func (dpMap *DataPartitionMap) getDataPartitionsToBeReleased(numberOfDataPartitionsToFree int, secondsToFreeDataPartitionAfterLoad int64) (partitions []*DataPartition, startIndex uint64) { partitions = make([]*DataPartition, 0) dpMap.RLock() defer dpMap.RUnlock() dpLen := len(dpMap.partitions) if dpLen == 0 { return } startIndex = dpMap.lastReleasedIndex count := numberOfDataPartitionsToFree if dpLen < numberOfDataPartitionsToFree { count = dpLen } for i := 0; i < count; i++ { if dpMap.lastReleasedIndex >= uint64(dpLen) { dpMap.lastReleasedIndex = 0 } dp := dpMap.partitions[dpMap.lastReleasedIndex] dpMap.lastReleasedIndex++ if time.Now().Unix()-dp.LastLoadedTime >= secondsToFreeDataPartitionAfterLoad { partitions = append(partitions, dp) } } return } func (dpMap *DataPartitionMap) freeMemOccupiedByDataPartitions(partitions []*DataPartition) { var wg sync.WaitGroup for _, dp := range partitions { wg.Add(1) go func(dp *DataPartition) { defer func() { wg.Done() if err := recover(); err != nil { const size = runtimeStackBufSize buf := make([]byte, size) buf = buf[:runtime.Stack(buf, false)] log.LogError(fmt.Sprintf("[%v] freeMemOccupiedByDataPartitions panic %v: %s\n", dpMap.volName, err, buf)) } }() dp.releaseDataPartition() }(dp) } wg.Wait() } func (dpMap *DataPartitionMap) getDataPartitionsToBeChecked(loadFrequencyTime int64) (partitions []*DataPartition, startIndex uint64) { partitions = make([]*DataPartition, 0) dpMap.RLock() defer dpMap.RUnlock() dpLen := len(dpMap.partitions) if dpLen == 0 { return } startIndex = dpMap.lastLoadedIndex // determine the number of data partitions to load count := dpLen / intervalToLoadDataPartition if count == 0 { count = 1 } for i := 0; i < count; i++ { if dpMap.lastLoadedIndex >= (uint64)(len(dpMap.partitions)) { dpMap.lastLoadedIndex = 0 } dp := dpMap.partitions[dpMap.lastLoadedIndex] dpMap.lastLoadedIndex++ if time.Now().Unix()-dp.LastLoadedTime >= loadFrequencyTime { partitions = append(partitions, dp) } } return } func (dpMap *DataPartitionMap) totalUsedSpace() (totalUsed uint64) { dpMap.RLock() defer dpMap.RUnlock() for _, dp := range dpMap.partitions { totalUsed = totalUsed + dp.getMaxUsedSpace() } return } func (dpMap *DataPartitionMap) setAllDataPartitionsToReadOnly() { dpMap.Lock() defer dpMap.Unlock() for _, dp := range dpMap.partitions { dp.Status = proto.ReadOnly } }
master/data_partition_map.go
0.544075
0.402803
data_partition_map.go
starcoder
package set import "github.com/rickb777/golist/internal/collection" const Set = collection.Collection + ` //------------------------------------------------------------------------------------------------- // {{.TName}}Set is a typesafe set of {{.TName}} items. {{if .Has.Tag.Mutate}} // The implementation is based on an underlying Go map, which can be manipulated directly. // Also methods *Add* and *Remove* mutate the current set. {{else}} // The implementation is based on an underyling Go map, which can be manipulated directly, // but otherwise instances are essentially immutable. {{end}} // The set-agebra functions *Union*, *Intersection* and *Difference* allow new variants to be constructed // easily; these methods do not modify the input sets. type {{.TName}}Set map[{{.TName}}]struct{} //------------------------------------------------------------------------------------------------- // New{{.TName}}Set constructs a new set containing the supplied values, if any. func New{{.TName}}Set(values ...{{.PName}}) {{.TName}}Set { set := make(map[{{.TName}}]struct{}) for _, v := range values { set[v] = struct{}{} } return {{.TName}}Set(set) } {{if .Type.IsBasic}} // New{{.TName}}SetFrom{{.Type.Underlying.LongName}}s constructs a new {{.TName}}Set from a []{{.Type.Underlying}}. func New{{.TName}}SetFrom{{.Type.Underlying.LongName}}s(values []{{.Type.Underlying}}) {{.TName}}Set { set := make(map[{{.TName}}]struct{}) for _, v := range values { set[{{.TName}}(v)] = struct{}{} } return {{.TName}}Set(set) } {{end}} // Build{{.TName}}SetFrom constructs a new {{.TName}}Set from a channel that supplies a stream of values // until it is closed. The function returns all these values in a set (i.e. without any duplicates). func Build{{.TName}}SetFrom(source <-chan {{.PName}}) {{.TName}}Set { set := make(map[{{.TName}}]struct{}) for v := range source { set[v] = struct{}{} } return {{.TName}}Set(set) } //------------------------------------------------------------------------------------------------- // IsSequence returns false for sets. func (set {{.TName}}Set) IsSequence() bool { return false } // IsSet returns true for sets. func (set {{.TName}}Set) IsSet() bool { return true } func (set {{.TName}}Set) Size() int { return len(set) } func (set {{.TName}}Set) IsEmpty() bool { return len(set) == 0 } func (set {{.TName}}Set) NonEmpty() bool { return len(set) > 0 } // Head gets an arbitrary element. func (set {{.TName}}Set) Head() {{.PName}} { for v := range set { return v } panic("Set is empty") } // ToSlice gets all the set's elements in a plain slice. func (set {{.TName}}Set) ToSlice() []{{.PName}} { slice := make([]{{.PName}}, set.Size()) i := 0 for v := range set { slice[i] = v i++ } return slice } {{if .Type.Underlying.IsBasic}} // To{{.Type.Underlying.LongName}}s gets all the elements in a []{{.Type.Underlying}}. func (set {{.TName}}Set) To{{.Type.Underlying.LongName}}s() []{{.Type.Underlying}} { slice := make([]{{.Type.Underlying}}, len(set)) i := 0 for v := range set { slice[i] = {{.Type.Underlying}}(v) i++ } return slice } {{end}} {{if .Has.List}} // ToList gets all the set's elements in a in {{.Name}}List. func (set {{.TName}}Set) ToList() {{.TName}}List { return {{.TName}}List(set.ToSlice()) } {{end}} // ToSet gets the current set, which requires no further conversion. func (set {{.TName}}Set) ToSet() {{.TName}}Set { return set } ` + setAlgebra + addRemoveFunctions + iterationFunctions + predicatedFunctions + numericFunctions + orderedFunctions + mkstringFunctions
internal/set/set.go
0.648578
0.541591
set.go
starcoder
package assert import ( "fmt" "reflect" "testing" ) func equal(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } if reflect.DeepEqual(expected, actual) { return true } actualType := reflect.TypeOf(actual) if actualType == nil { return false } expectedValue := reflect.ValueOf(expected) if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) } return false } func fail(t *testing.T, message string, errorMessage ...string) { t.Helper() if len(errorMessage) != 0 { message = fmt.Sprintf("%s\n%s", message, errorMessage) } t.Errorf(message) t.FailNow() } // Equal asserts that two objects are equal. func Equal(t *testing.T, expected, actual interface{}, errorMessage ...string) { t.Helper() if equal(expected, actual) { return } msg := fmt.Sprintf("Not equal: \nexpected: %v\nactual : %v", expected, actual) fail(t, msg, errorMessage...) } // NoError asserts that a function returned no error. func NoError(t *testing.T, err error, errorMessage ...string) { t.Helper() if err == nil { return } msg := fmt.Sprintf("Unexpected error:\n%+v", err) fail(t, msg, errorMessage...) } // Error asserts that a function returned an error. func Error(t *testing.T, err error, expectedError string, errorMessage ...string) { t.Helper() if err == nil { msg := fmt.Sprintf("Error message not equal: \nexpected: %v\nactual : nil", expectedError) fail(t, msg, errorMessage...) return } actual := err.Error() if actual == expectedError { return } msg := fmt.Sprintf("Error message not equal: \nexpected: %v\nactual : %v", expectedError, actual) fail(t, msg, errorMessage...) } // True asserts that the specified value is true. func True(t *testing.T, value bool, errorMessage ...string) { t.Helper() if value { return } fail(t, "Unexpected false", errorMessage...) } // False asserts that the specified value is false. func False(t *testing.T, value bool, errorMessage ...string) { t.Helper() if !value { return } fail(t, "Unexpected true", errorMessage...) }
internal/assert/assert.go
0.718693
0.552117
assert.go
starcoder
package util import ( "fmt" "math" "reflect" "time" ) // Define the Type enum const ( // bool TypeBooleanField = 1 << iota // string TypeStringField // time.Time TypeDateTimeField // int8 TypeBitField // int16 TypeSmallIntegerField // int32 TypeInteger32Field // int TypeIntegerField // int64 TypeBigIntegerField // uint8 TypePositiveBitField // uint16 TypePositiveSmallIntegerField // uint32 TypePositiveInteger32Field // uint TypePositiveIntegerField // uint64 TypePositiveBigIntegerField // float32 TypeFloatField // float64 TypeDoubleField // struct TypeStructField // slice TypeSliceField ) func IsInteger(tType reflect.Type) bool { switch tType.Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64: return true } return false } func IsUInteger(tType reflect.Type) bool { switch tType.Kind() { case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64: return true } return false } func IsFloat(tType reflect.Type) bool { switch tType.Kind() { case reflect.Float32, reflect.Float64: return true } return false } func IsBool(tType reflect.Type) bool { return tType.Kind() == reflect.Bool } func IsString(tType reflect.Type) bool { return tType.Kind() == reflect.String } func IsDateTime(tType reflect.Type) bool { return tType.String() == "time.Time" } func IsSlice(tType reflect.Type) bool { return tType.Kind() == reflect.Slice } func IsStruct(tType reflect.Type) bool { return tType.Kind() == reflect.Struct } // IsBasicType IsBasicType func IsBasicType(typeValue int) bool { return typeValue < TypeStructField } // IsStructType IsStructType func IsStructType(typeValue int) bool { return typeValue == TypeStructField } // IsSliceType IsSliceType func IsSliceType(typeValue int) bool { return typeValue == TypeSliceField } // GetTypeEnum return field type as type constant from reflect.Value func GetTypeEnum(val reflect.Type) (ret int, err error) { switch val.Kind() { case reflect.Int8: ret = TypeBitField case reflect.Uint8: ret = TypePositiveBitField case reflect.Int16: ret = TypeSmallIntegerField case reflect.Uint16: ret = TypePositiveSmallIntegerField case reflect.Int32: ret = TypeInteger32Field case reflect.Uint32: ret = TypePositiveInteger32Field case reflect.Int64: ret = TypeBigIntegerField case reflect.Uint64: ret = TypePositiveBigIntegerField case reflect.Int: ret = TypeIntegerField case reflect.Uint: ret = TypePositiveIntegerField case reflect.Float32: ret = TypeFloatField case reflect.Float64: ret = TypeDoubleField case reflect.Bool: ret = TypeBooleanField case reflect.String: ret = TypeStringField case reflect.Struct: switch val.String() { case "time.Time": ret = TypeDateTimeField default: ret = TypeStructField } case reflect.Slice: ret = TypeSliceField default: err = fmt.Errorf("unsupport field type:%v", val.String()) } return } // IsNil check value if nil func IsNil(val reflect.Value) (ret bool) { val = reflect.Indirect(val) if val.Kind() == reflect.Interface { val = reflect.Indirect(val.Elem()) } switch val.Kind() { case reflect.Interface: ret = val.IsNil() case reflect.Slice, reflect.Map: ret = false case reflect.Invalid: ret = true default: ret = false } return } //isSameStruct check if same func isSameStruct(firstVal, secondVal reflect.Value) (ret bool, err error) { firstNum := firstVal.NumField() secondNum := secondVal.NumField() if firstNum != secondNum { ret = false return } for idx := 0; idx < firstNum; idx++ { firstField := firstVal.Field(idx) secondField := secondVal.Field(idx) ret, err = IsSameVal(firstField, secondField) if !ret || err != nil { ret = false return } } ret = true return } // IsSameVal is same value func IsSameVal(firstVal, secondVal reflect.Value) (ret bool, err error) { ret = firstVal.Type().String() == secondVal.Type().String() if !ret { return } firstIsNil := IsNil(firstVal) secondIsNil := IsNil(secondVal) if firstIsNil != secondIsNil { ret = false return } if firstIsNil { ret = true return } firstVal = reflect.Indirect(firstVal) secondVal = reflect.Indirect(secondVal) typeVal, typeErr := GetTypeEnum(firstVal.Type()) if typeErr != nil { err = typeErr ret = false return } if IsStructType(typeVal) { ret, err = isSameStruct(firstVal, secondVal) return } if IsBasicType(typeVal) { switch typeVal { case TypeBooleanField: ret = firstVal.Bool() == secondVal.Bool() case TypeStringField: ret = firstVal.String() == secondVal.String() case TypeBitField, TypeSmallIntegerField, TypeInteger32Field, TypeIntegerField, TypeBigIntegerField: ret = firstVal.Int() == secondVal.Int() case TypePositiveBitField, TypePositiveSmallIntegerField, TypePositiveInteger32Field, TypePositiveIntegerField, TypePositiveBigIntegerField: ret = firstVal.Uint() == secondVal.Uint() case TypeFloatField, TypeDoubleField: ret = math.Abs(firstVal.Float()-secondVal.Float()) <= 0.0001 case TypeDateTimeField: ret = firstVal.Interface().(time.Time).Sub(secondVal.Interface().(time.Time)) == 0 default: ret = false err = fmt.Errorf("illegal value, is a struct value") } return } ret = firstVal.Len() == secondVal.Len() if !ret { return } for idx := 0; idx < firstVal.Len(); idx++ { firstItem := firstVal.Index(idx) secondItem := secondVal.Index(idx) ret, err = IsSameVal(firstItem, secondItem) if !ret || err != nil { ret = false return } } return } // AddSlashes() 函数返回在预定义字符之前添加反斜杠的字符串。 // 预定义字符是: // 单引号(') // 双引号(") // 反斜杠(\) func AddSlashes(str string) string { tmpRune := []rune{} strRune := []rune(str) for _, ch := range strRune { switch ch { case []rune{'\\'}[0], []rune{'"'}[0], []rune{'\''}[0]: tmpRune = append(tmpRune, []rune{'\\'}[0]) tmpRune = append(tmpRune, ch) default: tmpRune = append(tmpRune, ch) } } return string(tmpRune) } // StripSlashes() 函数删除由 AddSlashes() 函数添加的反斜杠。 func StripSlashes(str string) string { dstRune := []rune{} strRune := []rune(str) strLength := len(strRune) for i := 0; i < strLength; i++ { if strRune[i] == []rune{'\\'}[0] { i++ } dstRune = append(dstRune, strRune[i]) } return string(dstRune) }
util/const.go
0.582016
0.472623
const.go
starcoder