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
// Copyright 2017 Microsoft Corporation. All rights reserved. // Use of this source code is governed by an MIT // license that can be found in the LICENSE file. /* Package azblob can access an Azure Blob Storage. The azblob package is capable of :- - Creating, deleting, and querying containers in an account - Creating, deleting, and querying blobs in a container - Creating Shared Access Signature for authentication Types of Resources The azblob package allows you to interact with three types of resources :- * Azure storage accounts. * Containers within those storage accounts. * Blobs (block blobs/ page blobs/ append blobs) within those containers. The Azure Blob Storage (azblob) client library for Go allows you to interact with each of these components through the use of a dedicated client object. To create a client object, you will need the account's blob service endpoint URL and a credential that allows you to access the account. Types of Credentials The clients support different forms of authentication. The azblob library supports any of the `azcore.TokenCredential` interfaces, authorization via a Connection String, or authorization with a Shared Access Signature token. Using a Shared Key To use an account shared key (aka account key or access key), provide the key as a string. This can be found in your storage account in the Azure Portal under the "Access Keys" section. Use the key as the credential parameter to authenticate the client: accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME") if !ok { panic("AZURE_STORAGE_ACCOUNT_NAME could not be found") } accountKey, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_KEY") if !ok { panic("AZURE_STORAGE_ACCOUNT_KEY could not be found") } serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName) cred, err := azblob.NewSharedKeyCredential(accountName, accountKey) handle(err) serviceClient, err := azblob.NewServiceClientWithSharedKey(serviceURL, cred, nil) handle(err) fmt.Println(serviceClient.URL()) Using a Connection String Depending on your use case and authorization method, you may prefer to initialize a client instance with a connection string instead of providing the account URL and credential separately. To do this, pass the connection string to the service client's `NewServiceClientFromConnectionString` method. The connection string can be found in your storage account in the Azure Portal under the "Access Keys" section. connStr := "DefaultEndpointsProtocol=https;AccountName=<my_account_name>;AccountKey=<my_account_key>;EndpointSuffix=core.windows.net" serviceClient, err := azblob.NewServiceClientFromConnectionString(connStr, nil) Using a Shared Access Signature (SAS) Token To use a shared access signature (SAS) token, provide the token at the end of your service URL. You can generate a SAS token from the Azure Portal under Shared Access Signature or use the ServiceClient.GetSASToken() functions. accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME") if !ok { panic("AZURE_STORAGE_ACCOUNT_NAME could not be found") } accountKey, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_KEY") if !ok { panic("AZURE_STORAGE_ACCOUNT_KEY could not be found") } serviceURL := fmt.Sprintf("https://%s.blob.core.windows.net/", accountName) cred, err := azblob.NewSharedKeyCredential(accountName, accountKey) handle(err) serviceClient, err := azblob.NewServiceClientWithSharedKey(serviceURL, cred, nil) handle(err) fmt.Println(serviceClient.URL()) // Alternatively, you can create SAS on the fly resources := azblob.AccountSASResourceTypes{Service: true} permission := azblob.AccountSASPermissions{Read: true} start := time.Now() expiry := start.AddDate(0, 0, 1) serviceURLWithSAS, err := serviceClient.GetSASURL(resources, permission, start, expiry) handle(err) serviceClientWithSAS, err := azblob.NewServiceClientWithNoCredential(serviceURLWithSAS, nil) handle(err) fmt.Println(serviceClientWithSAS.URL()) Types of Clients There are three different clients provided to interact with the various components of the Blob Service: 1. **`ServiceClient`** * Get and set account settings. * Query, create, and delete containers within the account. 2. **`ContainerClient`** * Get and set container access settings, properties, and metadata. * Create, delete, and query blobs within the container. * `ContainerLeaseClient` to support container lease management. 3. **`BlobClient`** * `AppendBlobClient`, `BlockBlobClient`, and `PageBlobClient` * Get and set blob properties. * Perform CRUD operations on a given blob. * `BlobLeaseClient` to support blob lease management. Examples // Your account name and key can be obtained from the Azure Portal. accountName, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_NAME") if !ok { panic("AZURE_STORAGE_ACCOUNT_NAME could not be found") } accountKey, ok := os.LookupEnv("AZURE_STORAGE_ACCOUNT_KEY") if !ok { panic("AZURE_STORAGE_ACCOUNT_KEY could not be found") } cred, err := azblob.NewSharedKeyCredential(accountName, accountKey) handle(err) // The service URL for blob endpoints is usually in the form: http(s)://<account>.blob.core.windows.net/ serviceClient, err := azblob.NewServiceClientWithSharedKey(fmt.Sprintf("https://%s.blob.core.windows.net/", accountName), cred, nil) handle(err) // ===== 1. Create a container ===== // First, create a container client, and use the Create method to create a new container in your account containerClient, err := serviceClient.NewContainerClient("testcontainer") handle(err) // All APIs have an options' bag struct as a parameter. // The options' bag struct allows you to specify optional parameters such as metadata, public access types, etc. // If you want to use the default options, pass in nil. _, err = containerClient.Create(context.TODO(), nil) handle(err) // ===== 2. Upload and Download a block blob ===== uploadData := "Hello world!" // Create a new blockBlobClient from the containerClient blockBlobClient, err := containerClient.NewBlockBlobClient("HelloWorld.txt") handle(err) // Upload data to the block blob blockBlobUploadOptions := azblob.BlockBlobUploadOptions{ Metadata: map[string]string{"Foo": "Bar"}, TagsMap: map[string]string{"Year": "2022"}, } _, err = blockBlobClient.Upload(context.TODO(), streaming.NopCloser(strings.NewReader(uploadData)), &blockBlobUploadOptions) handle(err) // Download the blob's contents and ensure that the download worked properly blobDownloadResponse, err := blockBlobClient.Download(context.TODO(), nil) handle(err) // Use the bytes.Buffer object to read the downloaded data. // RetryReaderOptions has a lot of in-depth tuning abilities, but for the sake of simplicity, we'll omit those here. reader := blobDownloadResponse.Body(nil) downloadData, err := ioutil.ReadAll(reader) handle(err) if string(downloadData) != uploadData { handle(errors.New("Uploaded data should be same as downloaded data")) } if err = reader.Close(); err != nil { handle(err) return } // ===== 3. List blobs ===== // List methods returns a pager object which can be used to iterate over the results of a paging operation. // To iterate over a page use the NextPage(context.Context) to fetch the next page of results. // PageResponse() can be used to iterate over the results of the specific page. // Always check the Err() method after paging to see if an error was returned by the pager. A pager will return either an error or the page of results. pager := containerClient.ListBlobsFlat(nil) for pager.NextPage(context.TODO()) { resp := pager.PageResponse() for _, v := range resp.Segment.BlobItems { fmt.Println(*v.Name) } } if err = pager.Err(); err != nil { handle(err) } // Delete the blob. _, err = blockBlobClient.Delete(context.TODO(), nil) handle(err) // Delete the container. _, err = containerClient.Delete(context.TODO(), nil) handle(err) */ package azblob
sdk/storage/azblob/doc.go
0.694406
0.440108
doc.go
starcoder
package linkedlist import "github.com/clipperhouse/typewriter" var templates = typewriter.TemplateSlice{ list, } var list = &typewriter.Template{ Name: "bigratalias", Text: ` type {{.Name}}Time struct { rat *big.Rat } func New{{.Name}}Time(rat *big.Rat) *{{.Name}}Time { return &{{.Name}}Time{rat: rat} } // Le returns true if x is less than y func (x *{{.Name}}Time) Le(y *{{.Name}}Time) bool { return x.rat.Cmp(y.rat) < 0 } // Leq returns true if x is less than or equal to y func (x *{{.Name}}Time) Leq(y *{{.Name}}Time) bool { return x.rat.Cmp(y.rat) <= 0 } // Ge returns true if x is greater than y func (x *{{.Name}}Time) Ge(y *{{.Name}}Time) bool { return x.rat.Cmp(y.rat) > 0 } // Geq returns true if x is greater than or equal to y func (x *{{.Name}}Time) Geq(y *{{.Name}}Time) bool { return x.rat.Cmp(y.rat) >= 0 } // Eq returns true if x is equal to y func (x *{{.Name}}Time) Eq(y *{{.Name}}Time) bool { return x.rat.Cmp(y.rat) == 0 } // Neq returns true if x is not equal to y func (x *{{.Name}}Time) Neq(y *{{.Name}}Time) bool { return x.rat.Cmp(y.rat) != 0 } func (x *{{.Name}}Time) Add(y *{{.Name}}Duration) *{{.Name}}Time { return New{{.Name}}Time(new(big.Rat).Add(x.rat, y.rat)) } func (x *{{.Name}}Time) Sub(y *{{.Name}}Time) *{{.Name}}Duration { return New{{.Name}}Duration(new(big.Rat).Sub(x.rat, y.rat)) } func Max{{.Name}}Time(x *{{.Name}}Time, y *{{.Name}}Time) *{{.Name}}Time { if x.Ge(y) { return x } return y } func Min{{.Name}}Time(x *{{.Name}}Time, y *{{.Name}}Time) *{{.Name}}Time { if x.Le(y) { return x } return y } func (x *{{.Name}}Time) Inv() *{{.Name}}Time { return New{{.Name}}Time(new(big.Rat).Inv(x.rat)) } func (x *{{.Name}}Time) Rat() *big.Rat { if x == nil { return nil } return x.rat } type {{.Name}}Duration struct { rat *big.Rat } func New{{.Name}}Duration(rat *big.Rat) *{{.Name}}Duration { return &{{.Name}}Duration{rat: rat} } func (x *{{.Name}}Duration) Mul(y *big.Rat) *{{.Name}}Duration { return New{{.Name}}Duration(new(big.Rat).Mul(x.rat, y)) } // Le returns true if x is less than y func (x *{{.Name}}Duration) Le(y *{{.Name}}Duration) bool { return x.rat.Cmp(y.rat) < 0 } // Leq returns true if x is less than or equal to y func (x *{{.Name}}Duration) Leq(y *{{.Name}}Duration) bool { return x.rat.Cmp(y.rat) <= 0 } // Ge returns true if x is greater than y func (x *{{.Name}}Duration) Ge(y *{{.Name}}Duration) bool { return x.rat.Cmp(y.rat) > 0 } // Geq returns true if x is greater than or equal to y func (x *{{.Name}}Duration) Geq(y *{{.Name}}Duration) bool { return x.rat.Cmp(y.rat) >= 0 } // Eq returns true if x is equal to y func (x *{{.Name}}Duration) Eq(y *{{.Name}}Duration) bool { return x.rat.Cmp(y.rat) == 0 } // Neq returns true if x is not equal to y func (x *{{.Name}}Duration) Neq(y *{{.Name}}Duration) bool { return x.rat.Cmp(y.rat) != 0 } func (x *{{.Name}}Duration) Neg() *{{.Name}}Duration { return New{{.Name}}Duration(new(big.Rat).Neg(x.rat)) } func (x *{{.Name}}Duration) Div(y *big.Rat) *{{.Name}}Duration { return New{{.Name}}Duration(new(big.Rat).Mul(x.rat, new(big.Rat).Inv(y))) } func Max{{.Name}}Duration(x *{{.Name}}Duration, y *{{.Name}}Duration) *{{.Name}}Duration { if x.Ge(y) { return x } return y } func Min{{.Name}}Duration(x *{{.Name}}Duration, y *{{.Name}}Duration) *{{.Name}}Duration { if x.Le(y) { return x } return y } func (x *{{.Name}}Duration) Abs() *{{.Name}}Duration { return Max{{.Name}}Duration(x, x.Neg()) } func (x *{{.Name}}Duration) Add(y *{{.Name}}Duration) *{{.Name}}Duration { return New{{.Name}}Duration(new(big.Rat).Add(x.rat, y.rat)) } func (x *{{.Name}}Duration) Sub(y *{{.Name}}Duration) *{{.Name}}Duration { return New{{.Name}}Duration(new(big.Rat).Sub(x.rat, y.rat)) } func (x *{{.Name}}Duration) Rat() *big.Rat { if x == nil { return nil } return x.rat } func (x *{{.Name}}Duration) Positive() bool { return x.Ge(New{{.Name}}Duration(new(big.Rat))) } func (x *{{.Name}}Duration) Negative() bool { return x.Le(New{{.Name}}Duration(new(big.Rat))) } `}
templates.go
0.796965
0.591133
templates.go
starcoder
package language import ( "bytes" "fmt" "reflect" ) // Eval runs the expression in the environment func Eval(n Node, env *Environment) Object { switch node := n.(type) { case *DynamoExpression: return Eval(node.Statement, env) case *ExpressionStatement: return Eval(node.Expression, env) case *PrefixExpression: return evalPrefixExpression(node, env) case *InfixExpression: return evalInfixParts(node, env) case *BetweenExpression: return evalBetween(node, env) case *CallExpression: return evalFunctionCall(node, env) case *Identifier: return evalIdentifier(node, env) } return newError("unsupported expression: %s", n.String()) } func newError(format string, a ...interface{}) *Error { return &Error{Message: fmt.Sprintf(format, a...)} } func isError(obj Object) bool { if obj != nil { return obj.Type() == ObjectTypeError } return false } func isNumber(obj Object) bool { if obj != nil { return obj.Type() == ObjectTypeNumber } return false } func isString(obj Object) bool { if obj != nil { return obj.Type() == ObjectTypeString } return false } func isUndefined(obj Object) bool { return obj == nil || obj == NULL } func isComparable(obj Object) bool { return comparableTypes[obj.Type()] || isUndefined(obj) } func matchTypes(typ ObjectType, objs ...Object) bool { for _, o := range objs { if typ != o.Type() { return false } } return true } func evalPrefixExpression(node *PrefixExpression, env *Environment) Object { right := Eval(node.Right, env) if isError(right) { return right } if node.Operator == NOT { return evalBangOperatorExpression(right) } return newError("unknown operator: %s %s", node.Operator, right.Type()) } func evalBangOperatorExpression(right Object) Object { switch right { case TRUE: return FALSE case FALSE: return TRUE default: return newError("unknown operator: NOT %s", right.Type()) } } func evalInfixParts(node *InfixExpression, env *Environment) Object { left := Eval(node.Left, env) if isError(left) { return left } right := Eval(node.Right, env) if isError(right) { return right } return evalInfixExpression(node.Operator, left, right) } func evalInfixExpression(operator string, left, right Object) Object { switch { case isComparable(left) && isComparable(right): return evalComparableInfixExpression(operator, left, right) case matchTypes(ObjectTypeBoolean, left, right): return evalBooleanInfixExpression(operator, left, right) case matchTypes(ObjectTypeNull, left, right): return evalNullInfixExpression(operator, left, right) case operator == "=": return nativeBoolToBooleanObject(equalObject(left, right)) case operator == "<>": return nativeBoolToBooleanObject(!equalObject(left, right)) case !matchTypes(left.Type(), left, right): return newError("type mismatch: %s %s %s", left.Type(), operator, right.Type()) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalNullInfixExpression(operator string, left, right Object) Object { switch operator { case "=": if isUndefined(left) || isUndefined(right) { return FALSE } return TRUE case "<>": if isUndefined(left) || isUndefined(right) { return TRUE } return FALSE } return FALSE } func evalComparableInfixExpression(operator string, left, right Object) Object { if isUndefined(left) || isUndefined(right) { return FALSE } switch left.Type() { case ObjectTypeNumber: return evalNumberInfixExpression(operator, left, right) case ObjectTypeString: return evalStringInfixExpression(operator, left, right) case ObjectTypeBinary: return evalBinaryInfixExpression(operator, left, right) } return newError("comparing types are not supported: %s %s %s", left.Type(), operator, right.Type()) } func evalNumberInfixExpression(operator string, left, right Object) Object { leftVal := left.(*Number).Value rightVal := right.(*Number).Value switch operator { case "<": return nativeBoolToBooleanObject(leftVal < rightVal) case "<=": return nativeBoolToBooleanObject(leftVal <= rightVal) case ">": return nativeBoolToBooleanObject(leftVal > rightVal) case ">=": return nativeBoolToBooleanObject(leftVal >= rightVal) case "=": return nativeBoolToBooleanObject(leftVal == rightVal) case "<>": return nativeBoolToBooleanObject(leftVal != rightVal) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalStringInfixExpression(operator string, left, right Object) Object { leftVal := left.(*String).Value rightVal := right.(*String).Value switch operator { case "<": return nativeBoolToBooleanObject(leftVal < rightVal) case "<=": return nativeBoolToBooleanObject(leftVal <= rightVal) case ">": return nativeBoolToBooleanObject(leftVal > rightVal) case ">=": return nativeBoolToBooleanObject(leftVal >= rightVal) case "=": return nativeBoolToBooleanObject(leftVal == rightVal) case "<>": return nativeBoolToBooleanObject(leftVal != rightVal) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalBinaryInfixExpression(operator string, left, right Object) Object { leftVal := left.(*Binary).Value rightVal := right.(*Binary).Value switch operator { case "<": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) < 0) case "<=": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) <= 0) case ">": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) > 0) case ">=": return nativeBoolToBooleanObject(bytes.Compare(leftVal, rightVal) >= 0) case "=": return nativeBoolToBooleanObject(bytes.Equal(leftVal, rightVal)) case "<>": return nativeBoolToBooleanObject(!bytes.Equal(leftVal, rightVal)) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func evalBooleanInfixExpression(operator string, left, right Object) Object { if isUndefined(left) || isUndefined(right) { return FALSE } leftVal := left.(*Boolean).Value rightVal := right.(*Boolean).Value switch operator { case "AND": return nativeBoolToBooleanObject(leftVal && rightVal) case "OR": return nativeBoolToBooleanObject(leftVal || rightVal) case "=": return nativeBoolToBooleanObject(left == right) case "<>": return nativeBoolToBooleanObject(left != right) default: return newError("unknown operator: %s %s %s", left.Type(), operator, right.Type()) } } func equalObject(left, right Object) bool { if !matchTypes(left.Type(), left, right) { return false } return reflect.DeepEqual(left, right) } func evalIdentifier(node *Identifier, env *Environment) Object { val, ok := env.Get(node.Value) if !ok { return NULL } return val } func evalBetween(node *BetweenExpression, env *Environment) Object { val := evalBetweenOperand(node.Left, env) if isError(val) { return val } min := evalBetweenOperand(node.Range[0], env) if isError(min) { return min } max := evalBetweenOperand(node.Range[1], env) if isError(max) { return max } if isUndefined(val) || isUndefined(min) || isUndefined(max) { return FALSE } if !matchTypes(val.Type(), val, min, max) { return newError("mismatch type: BETWEEN operands must have the same type") } b := compareRange(val, min, max) return b } func compareRange(value, min, max Object) Object { switch val := value.(type) { case *Number: left := evalNumberInfixExpression("<=", min, val) right := evalNumberInfixExpression("<=", val, max) return evalBooleanInfixExpression("AND", left, right) case *String: left := evalStringInfixExpression("<=", min, val) right := evalStringInfixExpression("<=", val, max) return evalBooleanInfixExpression("AND", left, right) case *Binary: left := evalBinaryInfixExpression("<=", min, val) right := evalBinaryInfixExpression("<=", val, max) return evalBooleanInfixExpression("AND", left, right) } return newError("unsupported type: between do not support comparing %s", value.Type()) } func evalBetweenOperand(exp Expression, env *Environment) Object { identifier, ok := exp.(*Identifier) if !ok { return newError("identifier expected: got %q", exp.String()) } val := evalIdentifier(identifier, env) if !comparableTypes[val.Type()] && !isUndefined(val) { return newError("unexpected type: %q should be a comparable type(N,S,B) got %q", exp.String(), val.Type()) } return val } func evalFunctionCall(node *CallExpression, env *Environment) Object { fn := evalFunctionCallIdentifer(node, env) if isError(fn) { return fn } args := evalExpressions(node.Arguments, env) if len(args) == 1 && isError(args[0]) { return args[0] } return fn.(*Function).Value(args...) } func evalFunctionCallIdentifer(node *CallExpression, env *Environment) Object { functionIdentifier, ok := node.Function.(*Identifier) if !ok { return newError("bad function syntax") } name := functionIdentifier.Value fn, ok := functions[name] if !ok { return newError("function not found: " + name) } return fn } func evalExpressions(exps []Expression, env *Environment) []Object { var result []Object for _, e := range exps { evaluated := Eval(e, env) if isError(evaluated) { return []Object{evaluated} } result = append(result, evaluated) } return result }
interpreter/language/evaluator.go
0.747708
0.414543
evaluator.go
starcoder
package diagnostic import "github.com/hashicorp/hcl/v2" // DedupDiagnostics allows the accumulation of hcl.Diagnostic while avoiding // duplicate entries. It implements a subset of the methods of hcl.Diagnostics. type DedupDiagnostics struct { diags hcl.Diagnostics // An index of the diagnostic entries present in the diags list. index map[diagIndex]struct{} } // diagIndex is a reduced version of a hcl.Diagnostic which uniquely identifies // a given instance of a particular diagnostic. // It is meant to be used as the key to an index of diagnostics. type diagIndex struct { summary string detail string subject hcl.Range } // indexableDiag takes a hcl.Diagnostic and returns a corresponding diagIndex. func indexableDiag(diag *hcl.Diagnostic) diagIndex { dIdx := diagIndex{ summary: diag.Summary, detail: diag.Detail, } if subj := diag.Subject; subj != nil { dIdx.subject = *subj } return dIdx } // NewDedupDiagnostics returns an initialized DedupDiagnostics. func NewDedupDiagnostics() *DedupDiagnostics { return &DedupDiagnostics{ index: make(map[diagIndex]struct{}), } } // Append appends a new hcl.Diagnostic to the receiver and returns the whole // DedupDiagnostics. func (d *DedupDiagnostics) Append(diag *hcl.Diagnostic) *DedupDiagnostics { diagIdx := indexableDiag(diag) if _, exists := d.index[diagIdx]; exists { return d } d.index[diagIdx] = struct{}{} d.diags = append(d.diags, diag) return d } // Extend concatenates the given hcl.Diagnostics with the receiver after // filtering the diagnostics that already exist, and returns the whole // DedupDiagnostics. func (d *DedupDiagnostics) Extend(diags hcl.Diagnostics) *DedupDiagnostics { filteredDiags := diags[:0] for _, diag := range diags { diagIdx := indexableDiag(diag) if _, exists := d.index[diagIdx]; exists { continue } d.index[diagIdx] = struct{}{} filteredDiags = append(filteredDiags, diag) } d.diags = append(d.diags, filteredDiags...) return d } // Diagnostics returns the hcl.Diagnostics accumulated in the receiver. func (d *DedupDiagnostics) Diagnostics() hcl.Diagnostics { return d.diags }
core/diagnostic/diagnostic.go
0.806052
0.440409
diagnostic.go
starcoder
package numberer import ( "fmt" "strconv" ) var ( // MinuteFactory is a factory to produce valid minute values MinuteFactory = Must(NewFactory("minute", 0, 59)) // HourFactory is a factory to produce valid hour values HourFactory = Must(NewFactory("hour", 0, 23)) // DayOfMonthFactory is a factory to produce valid day of month values DayOfMonthFactory = Must(NewFactory("dayOfMonth", 1, 31)) // MonthFactory is a factory to produce valid month values MonthFactory = Must(NewFactory("month", 1, 12)) // DayOfWeekFactory is a factory that can produce valid day of week values DayOfWeekFactory = Must(NewFactory("dayOfWeek", 0, 6)) ) // Must will panic if an error is passed to it, used for factory variables func Must(factory Factory, err error) Factory { if err != nil { panic(err) } return factory } // NewFactory will create a new factory for a given range, with a // name, the name is used for errors. func NewFactory(name string, start, end int) (Factory, error) { rnge, err := NewRange(start, end) if err != nil { return Factory{}, fmt.Errorf("(%s) %w", name, err) } return Factory{ rnge: rnge, name: name, }, nil } // Factory is a type that can create Numberers for different strings type Factory struct { rnge Range name string } // Number will create a Number Numberer from a string, and validate that // it is within the range of the factory (along with validating that the // input is an int) func (f Factory) Number(numstr string) (Number, error) { num, err := strconv.ParseInt(numstr, 10, 32) if err != nil { return 0, fmt.Errorf("(%s) failed to parse (%s) as int got (%w)", f.name, numstr, err) } if int(num) < f.rnge.Start || int(num) > f.rnge.End { return 0, fmt.Errorf("(%s) number (%d) must be in range (%d-%d)", f.name, num, f.rnge.Start, f.rnge.End) } return Number(num), nil } // Range will create a range from the given strings, validating that the // range that they within the range of the factory (along with validating // that the inputs is an int) func (f Factory) Range(startString, endString string) (Range, error) { start, err := strconv.ParseInt(startString, 10, 32) if err != nil { return Range{}, fmt.Errorf("(%s) failed to parse (%s) as int got (%w)", f.name, startString, err) } end, err := strconv.ParseInt(endString, 10, 32) if err != nil { return Range{}, fmt.Errorf("(%s) failed to parse (%s) as int got (%w)", f.name, endString, err) } if int(start) < f.rnge.Start || int(end) > f.rnge.End { return Range{}, fmt.Errorf("(%s) range (%d - %d) must be in range (%d - %d)", f.name, start, end, f.rnge.Start, f.rnge.End) } return NewRange(int(start), int(end)) } // Any will return a Numberer that will return the entire range of numbers func (f Factory) Any() Any { return f.rnge.Numbers() } // Number is a Numberer that will return a single number type Number int // Numbers implements Numberer and will return the number as an array of // numbers func (n Number) Numbers() []int { return []int{int(n)} } // NewRange will create a new Range, validating that the end is greater // than the end func NewRange(start, end int) (Range, error) { if start > end { return Range{}, fmt.Errorf("start (%d), cannot be greater than end (%d)", start, end) } return Range{ Start: start, End: end, }, nil } // Range is a Numberer that will return all of the numbers in a given range type Range struct { Start, End int } // Numbers implements Numberer that will return all of the numbers between // the start and end values func (r Range) Numbers() []int { numbers := make([]int, 0, r.End-r.Start) for i := r.Start; i <= r.End; i++ { numbers = append(numbers, i) } return numbers } // Any is a type that can be filled with all the numbers from a range type Any []int // Numbers implements Numberer and will return all of the values it // contains func (a Any) Numbers() []int { return a } // Provider is an interface to abstract the Factory type Provider interface { Number(numstr string) (Number, error) Range(startString, endString string) (Range, error) Any() Any }
internal/numberer/number.go
0.681727
0.417865
number.go
starcoder
package main import ( "encoding/json" "fmt" . "github.com/eywa/configs" . "github.com/eywa/models" . "github.com/eywa/utils" ) var messages = ` { "messages": { "_all": { "enabled": false }, "_size" : {"enabled" : true}, "dynamic_templates": [ { "string_to_doc_values": { "match_mapping_type": "string", "mapping": { "type": "string", "index": "not_analyzed", "doc_values": true, "norms": { "enabled": false } } } }, { "boolean_to_doc_values": { "match_mapping_type": "boolean", "mapping": { "type": "boolean", "doc_values": true } } }, { "date_to_doc_values": { "match_mapping_type": "date", "mapping": { "type": "date", "format": "dateOptionalTime", "doc_values": true } } }, { "integer_to_doc_values": { "match_mapping_type": "integer", "mapping": { "type": "integer", "doc_values": true } } }, { "long_to_doc_values": { "match_mapping_type": "long", "mapping": { "type": "long", "doc_values": true } } }, { "float_to_doc_values": { "match_mapping_type": "float", "mapping": { "type": "float", "doc_values": true } } }, { "double_to_doc_values": { "match_mapping_type": "double", "mapping": { "type": "double", "doc_values": true } } } ], "properties": { "timestamp": { "type": "date", "format": "epoch_millis", "doc_values": true } } } } ` var activities = ` { "activities": { "_all": { "enabled": false }, "_size" : {"enabled" : false}, "dynamic_templates": [ { "string_to_doc_values": { "match_mapping_type": "string", "mapping": { "type": "string", "index": "not_analyzed", "doc_values": true, "norms": { "enabled": false } } } }, { "boolean_to_doc_values": { "match_mapping_type": "boolean", "mapping": { "type": "boolean", "doc_values": true } } }, { "date_to_doc_values": { "match_mapping_type": "date", "mapping": { "type": "date", "format": "dateOptionalTime", "doc_values": true } } }, { "integer_to_doc_values": { "match_mapping_type": "integer", "mapping": { "type": "integer", "doc_values": true } } }, { "long_to_doc_values": { "match_mapping_type": "long", "mapping": { "type": "long", "doc_values": true } } }, { "float_to_doc_values": { "match_mapping_type": "float", "mapping": { "type": "float", "doc_values": true } } }, { "double_to_doc_values": { "match_mapping_type": "double", "mapping": { "type": "double", "doc_values": true } } } ], "properties": { "timestamp": { "type": "date", "format": "epoch_millis", "doc_values": true } } } } ` func setupES() { settings := map[string]interface{}{ "index.cache.query.enable": true, "number_of_shards": Config().Indices.NumberOfShards, "number_of_replicas": Config().Indices.NumberOfReplicas, } mappings := map[string]interface{}{} FatalIfErr(json.Unmarshal([]byte(messages), &mappings)) FatalIfErr(json.Unmarshal([]byte(activities), &mappings)) if Config().Indices.TTLEnabled { m := mappings["messages"].(map[string]interface{}) m["_ttl"] = map[string]interface{}{ "enabled": true, "default": fmt.Sprintf("%.0fs", Config().Indices.TTL.Seconds()), } m = mappings["activities"].(map[string]interface{}) m["_ttl"] = map[string]interface{}{ "enabled": true, "default": fmt.Sprintf("%.0fs", Config().Indices.TTL.Seconds()), } } body := map[string]interface{}{ "template": "channels*", "order": 0, "settings": settings, "mappings": mappings, } _, err := IndexClient.IndexPutTemplate("channels_template").BodyJson(body).Do() FatalIfErr(err) }
setup_es.go
0.523664
0.461502
setup_es.go
starcoder
package entries import ( "bufio" "encoding/binary" "errors" "fmt" "os" ) const ( // TombstoneValue is the value given to deleted key-value pairs. TombstoneValue string = "\x00" ) // Entry represents a database entry that is written into disk type Entry struct { Key string Value string } // EntryScanner contains the logic and settings for parsing database entries from files. type EntryScanner struct { // this is embedded since this allows cleaner code *bufio.Scanner } // KeyValueToBytes makes it so we don't need to convert key-value pairs into entries // before writing them to bytes. This just skips a step and makes some of the code more // elegant. func KeyValueToBytes(key, value string) []byte { data := make([]byte, 1) data = append(data, getStringBinaryLength(key)...) data = append(data, getStringBinaryLength(value)...) data = append(data, []byte(key)...) data = append(data, []byte(value)...) return data } // EntryFromBytes takes in a some byte data and tries to encode a database entry from that data. // The byte encoding is as followed: each entry is seperated by a 0-byte; then the following 8 // bytes contain the lengths of the key and value. Then the following entries are of the specified // length. func EntryFromBytes(bytes []byte) (*Entry, error) { // the bytes dont have the encoded values // the first byte is empty which is why we need 9 bytes overall for the beginning if len(bytes) < 9 { return nil, fmt.Errorf("data is too short. got=%d", len(bytes)) } klen := binary.BigEndian.Uint32(bytes[1:5]) vlen := binary.BigEndian.Uint32(bytes[5:9]) if uint32(9+klen+vlen) > uint32(len(bytes)) { return nil, errors.New("the key and value lengths are invalid") } return &Entry{ Key: string(bytes[9 : 9+klen]), Value: string(bytes[9+klen : 9+klen+vlen]), }, nil } func getStringBinaryLength(str string) []byte { buffer := make([]byte, 4) binary.BigEndian.PutUint32(buffer, uint32(len([]byte(str)))) return buffer } // ToBinary converts the keys into the binary representation in bytes func (e *Entry) ToBinary() []byte { data := make([]byte, 1) data = append(data, getStringBinaryLength(e.Key)...) data = append(data, getStringBinaryLength(e.Value)...) data = append(data, []byte(e.Key)...) data = append(data, []byte(e.Value)...) return data } // WriteEntriesToBinary takes in a a list of entries and returns a complete byte buffer that contains // all of the entries in the binary format. func WriteEntriesToBinary(entries []*Entry) []byte { var res []byte for _, entry := range entries { res = append(res, entry.ToBinary()...) } return res } // AppendToFile adds the given entry to the end of a specified file func (e *Entry) AppendToFile(filename string) error { file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600) if err != nil { return err } defer file.Close() if _, err := file.Write(e.ToBinary()); err != nil { return err } return nil } // ReadNext finds the next entry and returns the error and bytes func (e *EntryScanner) ReadNext() (*Entry, error) { e.Scanner.Scan() return EntryFromBytes(e.Scanner.Bytes()) } // ReadAll scans until a error is found meaning that all entries have been read. func (e *EntryScanner) ReadAll() []*Entry { var entries []*Entry for e.Scan() { entry, err := EntryFromBytes(e.Bytes()) if err != nil { return entries } entries = append(entries, entry) } return entries } // InitScanner reads the file while splitting the data using a custom bufio split function. func InitScanner(file *os.File, readSize int) *EntryScanner { s := bufio.NewScanner(file) buffer := make([]byte, readSize) s.Buffer(buffer, bufio.MaxScanTokenSize) s.Split(func(data []byte, atEOF bool) (int, []byte, error) { entry, err := EntryFromBytes(data) if err == nil { return len(entry.ToBinary()), data[:len(entry.ToBinary())], nil } return 0, nil, nil }) return &EntryScanner{s} }
entries/entries.go
0.678433
0.401541
entries.go
starcoder
package loader import ( "errors" "io" "time" "github.com/lestrrat/go-xslate/vm" ) // Mask... set of constants are used as flags to denote Debug modes. // If you're using these you should be reading the source code const ( MaskDumpByteCode = 1 << iota MaskDumpAST ) // Flags holds the flags to indicate if certain debug operations should be // performed during load time type Flags struct{ flags int32 } // NewFlags creates a new Flags struct initialized to 0 func NewFlags() *Flags { return &Flags{0} } // DumpAST sets the bitmask for DumpAST debug flag func (f *Flags) DumpAST(b bool) { if b { f.flags |= MaskDumpAST } else { f.flags &= ^MaskDumpAST } } // DumpByteCode sets the bitmask for DumpByteCode debug flag func (f *Flags) DumpByteCode(b bool) { if b { f.flags |= MaskDumpByteCode } else { f.flags &= ^MaskDumpByteCode } } // ShouldDumpAST returns true if the DumpAST debug flag is set func (f *Flags) ShouldDumpAST() bool { return f.flags&MaskDumpAST == MaskDumpAST } // ShouldDumpByteCode returns true if the DumpByteCode debug flag is set func (f Flags) ShouldDumpByteCode() bool { return f.flags&MaskDumpByteCode == 1 } // DebugDumper defines interface that an object able to dump debug informatin // during load time must fulfill type DebugDumper interface { DumpAST(bool) DumpByteCode(bool) ShouldDumpAST() bool ShouldDumpByteCode() bool } // ByteCodeLoader defines the interface for objects that can load // ByteCode specified by a key type ByteCodeLoader interface { DebugDumper LoadString(string, string) (*vm.ByteCode, error) Load(string) (*vm.ByteCode, error) } // TemplateFetcher defines the interface for objects that can load // TemplateSource specified by a key type TemplateFetcher interface { FetchTemplate(string) (TemplateSource, error) } // TemplateSource is an abstraction over the actual template, which may live // on a file system, cache, database, whatever. // It needs to be able to give us the actual template string AND its // last modified time type TemplateSource interface { LastModified() (time.Time, error) Bytes() ([]byte, error) Reader() (io.Reader, error) } // ErrTemplateNotFound is returned whenever one of the loaders failed to // find a suitable template var ErrTemplateNotFound = errors.New("error: Specified template was not found")
loader/loader.go
0.766031
0.424591
loader.go
starcoder
package cache import ( "sync" "github.com/disgoorg/snowflake/v2" ) // FilterFunc is used to filter cached entities. type FilterFunc[T any] func(T) bool // Cache is a simple key value store. They key is always a snowflake.ID. // The cache provides a simple way to store and retrieve entities. But is not guaranteed to be thread safe as this depends on the underlying implementation. type Cache[T any] interface { // Get returns a copy of the entity with the given snowflake and a bool wheaten it was found or not. Get(id snowflake.ID) (T, bool) // Put stores the given entity with the given snowflake as key. If the entity is already present, it will be overwritten. Put(id snowflake.ID, entity T) // Remove removes the entity with the given snowflake as key and returns a copy of the entity and a bool whether it was removed or not. Remove(id snowflake.ID) (T, bool) // RemoveIf removes all entities that pass the given FilterFunc RemoveIf(filterFunc FilterFunc[T]) // Len returns the number of entities in the cache. Len() int // All returns a copy of all entities in this cache as a slice. All() []T // MapAll returns a copy of all entities in this cache as a map. MapAll() map[snowflake.ID]T // FindFirst returns the first entity that passes the given FilterFunc and a bool whether it was found or not. FindFirst(cacheFindFunc FilterFunc[T]) (T, bool) // FindAll returns all entities that pass the given FilterFunc as a slice. FindAll(cacheFindFunc FilterFunc[T]) []T // ForEach calls the given function for each entity in the cache. ForEach(func(entity T)) } var _ Cache[any] = (*DefaultCache[any])(nil) // NewCache returns a new DefaultCache implementation which filter the entities after the gives Flags and Policy. // This cache implementation is thread safe and can be used in multiple goroutines without any issues. // It also only hands out copies to the entities. Regardless these entities should be handles as immutable. func NewCache[T any](flags Flags, neededFlags Flags, policy Policy[T]) Cache[T] { return &DefaultCache[T]{ flags: flags, neededFlags: neededFlags, policy: policy, cache: make(map[snowflake.ID]T), } } // DefaultCache is a simple thread safe cache key value store. type DefaultCache[T any] struct { mu sync.RWMutex flags Flags neededFlags Flags policy Policy[T] cache map[snowflake.ID]T } func (c *DefaultCache[T]) Get(id snowflake.ID) (T, bool) { c.mu.RLock() defer c.mu.RUnlock() entity, ok := c.cache[id] return entity, ok } func (c *DefaultCache[T]) Put(id snowflake.ID, entity T) { if c.neededFlags != FlagsNone && c.flags.Missing(c.neededFlags) { return } if c.policy != nil && !c.policy(entity) { return } c.mu.Lock() defer c.mu.Unlock() c.cache[id] = entity } func (c *DefaultCache[T]) Remove(id snowflake.ID) (T, bool) { c.mu.Lock() defer c.mu.Unlock() entity, ok := c.cache[id] if ok { delete(c.cache, id) } return entity, ok } func (c *DefaultCache[T]) RemoveIf(filterFunc FilterFunc[T]) { c.mu.Lock() defer c.mu.Unlock() for id, entity := range c.cache { if filterFunc(entity) { delete(c.cache, id) } } } func (c *DefaultCache[T]) Len() int { c.mu.RLock() defer c.mu.RUnlock() return len(c.cache) } func (c *DefaultCache[T]) All() []T { c.mu.RLock() defer c.mu.RUnlock() entities := make([]T, len(c.cache)) i := 0 for _, entity := range c.cache { entities[i] = entity i++ } return entities } func (c *DefaultCache[T]) MapAll() map[snowflake.ID]T { c.mu.RLock() defer c.mu.RUnlock() entities := make(map[snowflake.ID]T, len(c.cache)) for entityID, entity := range c.cache { entities[entityID] = entity } return entities } func (c *DefaultCache[T]) FindFirst(cacheFindFunc FilterFunc[T]) (T, bool) { c.mu.RLock() defer c.mu.RUnlock() for _, entity := range c.cache { if cacheFindFunc(entity) { return entity, true } } var entity T return entity, false } func (c *DefaultCache[T]) FindAll(cacheFindFunc FilterFunc[T]) []T { c.mu.RLock() defer c.mu.RUnlock() var entities []T for _, entity := range c.cache { if cacheFindFunc(entity) { entities = append(entities, entity) } } return entities } func (c *DefaultCache[T]) ForEach(forEachFunc func(entity T)) { c.mu.RLock() defer c.mu.RUnlock() for _, entity := range c.cache { forEachFunc(entity) } }
cache/cache.go
0.665737
0.433082
cache.go
starcoder
package rke import ( "github.com/hashicorp/terraform-plugin-sdk/helper/schema" ) const ( rkeClusterCloudProviderAwsName = "aws" ) //Schemas func rkeClusterCloudProviderAwsGlobalFields() map[string]*schema.Schema { s := map[string]*schema.Schema{ "disable_security_group_ingress": { Type: schema.TypeBool, Optional: true, Default: false, Description: "Disables the automatic ingress creation", }, "disable_strict_zone_check": { Type: schema.TypeBool, Optional: true, Default: false, Description: "Setting this to true will disable the check and provide a warning that the check was skipped", }, "elb_security_group": { Type: schema.TypeString, Optional: true, Description: "Use these ELB security groups instead create new", }, "kubernetes_cluster_id": { Type: schema.TypeString, Optional: true, Description: "The cluster id we'll use to identify our cluster resources", }, "kubernetes_cluster_tag": { Type: schema.TypeString, Optional: true, Description: "Legacy cluster id we'll use to identify our cluster resources", }, "role_arn": { Type: schema.TypeString, Optional: true, Description: "IAM role to assume when interaction with AWS APIs", }, "route_table_id": { Type: schema.TypeString, Optional: true, Description: "Enables using a specific RouteTable", }, "subnet_id": { Type: schema.TypeString, Optional: true, Description: "Enables using a specific subnet to use for ELB's", }, "vpc": { Type: schema.TypeString, Optional: true, Description: "The AWS VPC flag enables the possibility to run the master components on a different aws account, on a different cloud provider or on-premises. If the flag is set also the KubernetesClusterTag must be provided", }, "zone": { Type: schema.TypeString, Optional: true, Description: "The AWS zone", }, } return s } func rkeClusterCloudProviderAwsServiceOverrideFields() map[string]*schema.Schema { s := map[string]*schema.Schema{ "service": { Type: schema.TypeString, Required: true, }, "key": { Type: schema.TypeString, Optional: true, Deprecated: "Use service instead", }, "region": { Type: schema.TypeString, Optional: true, }, "signing_method": { Type: schema.TypeString, Optional: true, Computed: true, }, "signing_name": { Type: schema.TypeString, Optional: true, }, "signing_region": { Type: schema.TypeString, Optional: true, }, "url": { Type: schema.TypeString, Optional: true, }, } return s } func rkeClusterCloudProviderAwsFields() map[string]*schema.Schema { s := map[string]*schema.Schema{ "global": { Type: schema.TypeList, MaxItems: 1, Optional: true, Elem: &schema.Resource{ Schema: rkeClusterCloudProviderAwsGlobalFields(), }, }, "service_override": { Type: schema.TypeList, Optional: true, Elem: &schema.Resource{ Schema: rkeClusterCloudProviderAwsServiceOverrideFields(), }, }, } return s }
rke/schema_rke_cluster_cloud_provider_aws.go
0.579519
0.411939
schema_rke_cluster_cloud_provider_aws.go
starcoder
package spline import ( "math" ) type Bspline struct { points [][]float64 degree int copy bool } var ( pts [][]float64 degree int dimension int baseFunc func(x float64) float64 baseFuncRangeInt int ) func NewBspline(points [][]float64, degree int, copy bool) *Bspline { return &Bspline{ points, degree, copy, } } func (self *Bspline) Init() { if self.copy { pts = make([][]float64, len(self.points)) for i := 0; i < len(self.points); i++ { pts = append(pts, self.points[i]) } } else { pts = self.points } degree = self.degree dimension = len(self.points[0]) if degree == 2 { baseFunc = self.baseDeg2 baseFuncRangeInt = 2 } else if degree == 3 { baseFunc = self.baseDeg3 baseFuncRangeInt = 2 } else if degree == 4 { baseFunc = self.baseDeg4 baseFuncRangeInt = 3 } else if degree == 5 { baseFunc = self.baseDeg5 baseFuncRangeInt = 3 } } func (self *Bspline) seqAt(dim int) func(int) float64 { margin := self.degree + 1 return func(n int) float64 { if n < margin { return pts[0][dim] } else if len(pts)+margin <= n { return pts[len(pts)-1][dim] } else { return pts[n-margin][dim] } } } func (self *Bspline) baseDeg2(x float64) float64 { if x >= -0.5 && x < 0.5 { return 0.75 - x*x } else if x >= 0.5 && x <= 1.5 { return 1.125 + (-1.5+x/2.0)*x } else if x >= -1.5 && x < -0.5 { return 1.125 + (1.5+x/2.0)*x } else { return 0.0 } } func (self *Bspline) baseDeg3(x float64) float64 { if x >= -1.0 && x < 0 { return 2.0/3.0 + (-1.0-x/2.0)*x*x } else if x >= 1 && x <= 2 { return 4.0/3.0 + x*(-2.0+(1.0-x/6.0)*x) } else if x >= -2.0 && x < -1 { return 4.0/3.0 + x*(2.0+(1.0+x/6.0)*x) } else if x >= 0 && x < 1 { return 2.0/3.0 + (-1.0+x/2.0)*x*x } else { return 0.0 } } func (self *Bspline) baseDeg4(x float64) float64 { if x >= -1.5 && x < -0.5 { return 55.0/96.0 + x*(-(5.0/24.0)+x*(-(5.0/4.0)+(-(5.0/6.0)-x/6.0)*x)) } else if x >= 0.5 && x < 1.5 { return 55.0/96.0 + x*(5.0/24.0+x*(-(5.0/4.0)+(5.0/6.0-x/6.0)*x)) } else if x >= 1.5 && x <= 2.5 { return 625.0/384.0 + x*(-(125.0/48.0)+x*(25.0/16.0+(-(5.0/12.0)+x/24.0)*x)) } else if x >= -2.5 && x <= -1.5 { return 625.0/384.0 + x*(125.0/48.0+x*(25.0/16.0+(5.0/12.0+x/24.0)*x)) } else if x >= -1.5 && x < 1.5 { return 115.0/192.0 + x*x*(-(5.0/8.0)+x*x/4.0) } else { return 0.0 } } func (self *Bspline) baseDeg5(x float64) float64 { if x >= -2.0 && x < -1 { return 17.0/40.0 + x*(-(5.0/8.0)+x*(-(7.0/4.0)+x*(-(5.0/4.0)+(-(3.0/8.0)-x/24.0)*x))) } else if x >= 0 && x < 1 { return 11.0/20.0 + x*x*(-(1.0/2.0)+(1.0/4.0-x/12.0)*x*x) } else if x >= 2 && x <= 3 { return 81.0/40.0 + x*(-(27.0/8.0)+x*(9.0/4.0+x*(-(3.0/4.0)+(1.0/8.0-x/120.0)*x))) } else if x >= -3 && x < -2 { return 81.0/40.0 + x*(27.0/8.0+x*(9.0/4.0+x*(3.0/4.0+(1.0/8.0+x/120.0)*x))) } else if x >= 1 && x < 2 { return 17.0/40.0 + x*(5.0/8.0+x*(-(7.0/4.0)+x*(5.0/4.0+(-(3.0/8.0)+x/24.0)*x))) } else if x >= -1 && x < 0 { return 11.0/20.0 + x*x*(-(1.0/2.0)+(1.0/4.0+x/12.0)*x*x) } else { return 0.0 } } func (self *Bspline) getInterpol(seq func(int) float64, t float64) float64 { tInt := int(math.Floor(t)) var result float64 for i := tInt - baseFuncRangeInt; i <= tInt+baseFuncRangeInt; i++ { result += seq(i) * baseFunc(t-float64(i)) } return result } func (self *Bspline) Interpolate(t float64) []float64 { t = t * ((float64(degree)+1.0)*2.0 + float64(len(pts))) // t must be between 0...1 result := []float64{} for i := 0; i < dimension; i++ { result = append(result, self.getInterpol(self.seqAt(i), t)) } return result }
app/service/comparing/spline/bspline.go
0.505859
0.416263
bspline.go
starcoder
package sql // Code based on https://github.com/emirpasic/gods/tree/master/trees/redblacktree // Referenced https://en.wikipedia.org/wiki/Interval_tree#Augmented_tree import ( "fmt" "strings" ) // rangeTreeColor is a node's color for balancing a RangeColumnExprTree. type rangeTreeColor uint8 const ( black rangeTreeColor = iota red ) // rangeTreeIterPos is the iterator's position for a RangeColumnExprTree. type rangeTreeIterPos uint8 const ( begin rangeTreeIterPos = iota between end ) // RangeColumnExprTree represents a red-black tree over a range column expression. To represent an entire range, each // node has both an upper bound and lower bound that represents a single column expression. If the Range has another // dimension, then the node will have an inner tree representing the nested dimension ad infinitum. This implicitly // means that all column expressions on the lower dimension share the same column expression in the higher dimensions. // This way, a Range is deconstructed and sorted by its column expressions, but may easily be retrieved by walking down // a tree and all of its inner trees. type RangeColumnExprTree struct { root *rangeColumnExprTreeNode size int typ Type } // rangeColumnExprTreeNode is a node within a RangeColumnExprTree. type rangeColumnExprTreeNode struct { color rangeTreeColor LowerBound RangeCut UpperBound RangeCut MaxUpperbound RangeCut Inner *RangeColumnExprTree Left *rangeColumnExprTreeNode Right *rangeColumnExprTreeNode Parent *rangeColumnExprTreeNode } // GetColExprTypes returns a list of RangeColumnExpr // type fields, defaulting to Null types if all // columns expressions are Null. func GetColExprTypes(ranges []Range) []Type { if len(ranges) == 0 { return []Type{} } colExprTypes := make([]Type, len(ranges[0])) var colTypesSet int for _, rang := range ranges { for i, e := range rang { if e.Type() != RangeType_Null && colExprTypes[i] == nil { colExprTypes[i] = e.Typ colTypesSet++ } if colTypesSet == len(ranges[0]) { return colExprTypes } } } for i, t := range colExprTypes { if t == nil { colExprTypes[i] = Null } } return colExprTypes } // NewRangeColumnExprTree creates a new RangeColumnExprTree constructed from an initial range. As the initial Range may // contain column expressions that have a NULL type, the expected non-NULL type for each column expression is given // separately. If all column expressions for a specific column will be NULL, then it is valid to use the NULL type. // Returns an error if the number of column expressions do not equal the number of types, or if the Range has a length // of zero. func NewRangeColumnExprTree(initialRange Range, columnExprTypes []Type) (*RangeColumnExprTree, error) { if len(initialRange) != len(columnExprTypes) { return nil, fmt.Errorf("number of types given do not correspond to the number of column expressions") } if len(initialRange) == 0 { return nil, fmt.Errorf("a RangeColumnExprTree cannot be created from a Range of length 0") } var tree *RangeColumnExprTree var parent *RangeColumnExprTree for i, colExpr := range initialRange { innerTree := &RangeColumnExprTree{ typ: columnExprTypes[i], size: 1, root: nil, } innerTree.root = &rangeColumnExprTreeNode{ color: black, LowerBound: colExpr.LowerBound, UpperBound: colExpr.UpperBound, MaxUpperbound: colExpr.UpperBound, Inner: nil, Left: nil, Right: nil, Parent: nil, } if tree == nil { tree = innerTree parent = innerTree } else { parent.root.Inner = innerTree parent = innerTree } } return tree, nil } // FindConnections returns all connecting Ranges found in the tree. They may or may not be mergeable or overlap. func (tree *RangeColumnExprTree) FindConnections(rang Range, colExprIdx int) (RangeCollection, error) { // Some potential optimizations that may significantly reduce the number of comparisons in a worst-case scenario: // 1) Rewrite this function to return a single Range that is guaranteed to either merge or overlap, rather than // a slice of ranges that are all connected (either overlapping or adjacent) but may not be mergeable. // 2) Move the overlap logic into this function, which would remove many redundant checks as the state would be local. // 3) Pre-construct the Ranges (RangeColumnExpr slice) and assign to different index positions based on the index // that is passed down. This is basically fixed by #1, however it can also be done separately. if tree.root == nil { return nil, nil } var rangeCollection RangeCollection colExpr := rang[colExprIdx] stack := []*rangeColumnExprTreeNode{tree.root} for len(stack) > 0 { node := stack[len(stack)-1] stack = stack[:len(stack)-1] cmp1, err := colExpr.LowerBound.Compare(node.UpperBound, tree.typ) if err != nil { return nil, err } cmp2, err := node.LowerBound.Compare(colExpr.UpperBound, tree.typ) if err != nil { return nil, err } if cmp1 <= 0 && cmp2 <= 0 { // We have a connection here, so we need to see if any inner column expressions also have a connection typ := tree.typ if typ == Null { typ = colExpr.Typ } connectedColExpr := RangeColumnExpr{ LowerBound: node.LowerBound, UpperBound: node.UpperBound, Typ: typ, } if node.Inner == nil { rangeCollection = append(rangeCollection, Range{connectedColExpr}) } else if connectedRanges, err := node.Inner.FindConnections(rang, colExprIdx+1); err != nil { return nil, err } else if connectedRanges != nil { for _, connectedRange := range connectedRanges { rang := append(Range{connectedColExpr}, connectedRange...) rangeCollection = append(rangeCollection, rang) } } } // If the node's lowerbound is less than the search column's upperbound, we need to search the right subtree if cmp2 <= 0 && node.Right != nil { stack = append(stack, node.Right) } // If the left child's max upperbound is greater than the search column's lowerbound, we need to search the left subtree if node.Left != nil { cmp, err := colExpr.LowerBound.Compare(node.Left.MaxUpperbound, tree.typ) if err != nil { return nil, err } if cmp <= 0 { stack = append(stack, node.Left) } } } return rangeCollection, nil } // Insert adds the given Range into the tree. func (tree *RangeColumnExprTree) Insert(rang Range) error { return tree.insert(rang, 0) } // insert is the internal implementation of Insert. func (tree *RangeColumnExprTree) insert(rang Range, colExprIdx int) error { colExpr := rang[colExprIdx] var insertedNode *rangeColumnExprTreeNode var inner *RangeColumnExprTree var err error if tree.root == nil { if len(rang)-colExprIdx > 1 { inner, err = NewRangeColumnExprTree(rang[colExprIdx+1:], GetColExprTypes([]Range{rang[colExprIdx+1:]})) if err != nil { return err } } tree.root = &rangeColumnExprTreeNode{ color: black, LowerBound: colExpr.LowerBound, UpperBound: colExpr.UpperBound, MaxUpperbound: colExpr.UpperBound, Inner: inner, Left: nil, Right: nil, Parent: nil, } insertedNode = tree.root } else { node := tree.root loop := true for loop { cmp, err := colExpr.LowerBound.Compare(node.LowerBound, tree.typ) if err != nil { return err } if cmp == 0 { cmp, err = colExpr.UpperBound.Compare(node.UpperBound, tree.typ) if err != nil { return err } } if cmp < 0 { if node.Left == nil { var inner *RangeColumnExprTree if len(rang)-colExprIdx > 1 { inner, err = NewRangeColumnExprTree(rang[colExprIdx+1:], GetColExprTypes([]Range{rang[colExprIdx+1:]})) if err != nil { return err } } node.Left = &rangeColumnExprTreeNode{ color: red, LowerBound: colExpr.LowerBound, UpperBound: colExpr.UpperBound, MaxUpperbound: colExpr.UpperBound, Inner: inner, Left: nil, Right: nil, Parent: nil, } insertedNode = node.Left loop = false } else { node = node.Left } } else if cmp > 0 { if node.Right == nil { var inner *RangeColumnExprTree if len(rang)-colExprIdx > 1 { inner, err = NewRangeColumnExprTree(rang[colExprIdx+1:], GetColExprTypes([]Range{rang[colExprIdx+1:]})) if err != nil { return err } } node.Right = &rangeColumnExprTreeNode{ color: red, LowerBound: colExpr.LowerBound, UpperBound: colExpr.UpperBound, MaxUpperbound: colExpr.UpperBound, Inner: inner, Left: nil, Right: nil, Parent: nil, } insertedNode = node.Right loop = false } else { node = node.Right } } else /* cmp == 0 */ { if node.Inner != nil { return node.Inner.insert(rang, colExprIdx+1) } return nil } } insertedNode.Parent = node } tree.insertBalance(insertedNode) tree.size++ return nil } // Remove removes the given Range from the tree (and subtrees if applicable). func (tree *RangeColumnExprTree) Remove(rang Range) error { return tree.remove(rang, 0) } // remove is the internal implementation of Remove. func (tree *RangeColumnExprTree) remove(rang Range, colExprIdx int) error { colExpr := rang[colExprIdx] var child *rangeColumnExprTreeNode node, err := tree.getNode(colExpr) if err != nil || node == nil { return err } if node.Inner != nil { err = node.Inner.remove(rang, colExprIdx+1) if err != nil { return err } if node.Inner.size > 0 { return nil } node.Inner = nil } if node.Left != nil && node.Right != nil { pred := node.Left.maximumNode() node.LowerBound = pred.LowerBound node.UpperBound = pred.UpperBound node.MaxUpperbound = pred.MaxUpperbound if pred.Inner != nil && pred.Inner.size > 0 { node.Inner = pred.Inner } else { node.Inner = nil } node = pred } if node.Left == nil || node.Right == nil { if node.Right == nil { child = node.Left } else { child = node.Right } if node.color == black { node.color = child.nodeColor() tree.removeBalance(node) } tree.replaceNode(node, child) if child != nil { if node.Parent == nil { child.color = black } else { parentMax, err := GetRangeCutMax(tree.typ, child.Parent.Left.maxUpperBound(), child.Parent.Right.maxUpperBound(), child.Parent.UpperBound) if err != nil { panic(err) } child.Parent.MaxUpperbound = parentMax } } } tree.size-- return nil } // GetRangeCollection returns every Range that this tree contains. func (tree *RangeColumnExprTree) GetRangeCollection() (RangeCollection, error) { var rangeCollection RangeCollection iterStack := []*rangeTreeIter{tree.Iterator()} rangeStack := Range{RangeColumnExpr{}} for len(iterStack) > 0 { iter := iterStack[len(iterStack)-1] node, err := iter.Next() if err != nil { return nil, err } if node != nil { rangeStack[len(rangeStack)-1] = RangeColumnExpr{ LowerBound: node.LowerBound, UpperBound: node.UpperBound, Typ: iter.tree.typ, } if node.Inner != nil { iterStack = append(iterStack, node.Inner.Iterator()) rangeStack = append(rangeStack, RangeColumnExpr{}) } else { rang := make(Range, len(rangeStack)) copy(rang, rangeStack) rangeCollection = append(rangeCollection, rang) } } else { iterStack = iterStack[:len(iterStack)-1] rangeStack = rangeStack[:len(rangeStack)-1] } } return rangeCollection, nil } // String returns the tree as a formatted string. Does not display the inner trees. func (tree *RangeColumnExprTree) String() string { sb := strings.Builder{} sb.WriteString("RangeColumnExprTree\n") if tree.size > 0 { tree.root.string("", true, &sb, tree.typ) } return sb.String() } // strings returns this node as a formatted string. func (node *rangeColumnExprTreeNode) string(prefix string, isTail bool, sb *strings.Builder, typ Type) { if node == nil { return } if node.Right != nil { newPrefix := prefix if isTail { newPrefix += "│ " } else { newPrefix += " " } node.Right.string(newPrefix, false, sb, typ) } sb.WriteString(prefix) if isTail { sb.WriteString("└── ") } else { sb.WriteString("┌── ") } sb.WriteString(RangeColumnExpr{ LowerBound: node.LowerBound, UpperBound: node.UpperBound, Typ: typ, }.DebugString()) sb.WriteRune('\n') if node.Left != nil { newPrefix := prefix if isTail { newPrefix += " " } else { newPrefix += "│ " } node.Left.string(newPrefix, true, sb, typ) } } // getNode returns the node that matches the given column expression, if it exists. Returns nil otherwise. func (tree *RangeColumnExprTree) getNode(colExpr RangeColumnExpr) (*rangeColumnExprTreeNode, error) { node := tree.root for node != nil { cmp, err := colExpr.LowerBound.Compare(node.LowerBound, tree.typ) if err != nil { return nil, err } if cmp == 0 { cmp, err = colExpr.UpperBound.Compare(node.UpperBound, tree.typ) if err != nil { return nil, err } } if cmp < 0 { node = node.Left } else if cmp > 0 { node = node.Right } else /* cmp == 0 */ { return node, nil } } return nil, nil } // left returns the node with the smallest lowerbound. func (tree *RangeColumnExprTree) left() *rangeColumnExprTreeNode { var parent *rangeColumnExprTreeNode current := tree.root for current != nil { parent = current current = current.Left } return parent } // rotateLeft performs a left rotation. This also updates the max upperbounds of each affected node. func (tree *RangeColumnExprTree) rotateLeft(node *rangeColumnExprTreeNode) { right := node.Right tree.replaceNode(node, right) node.Right = right.Left if right.Left != nil { right.Left.Parent = node } right.Left = node node.Parent = right nodeMax, err := GetRangeCutMax(tree.typ, node.Left.maxUpperBound(), node.Right.maxUpperBound(), node.UpperBound) if err != nil { panic(err) } node.MaxUpperbound = nodeMax rightMax, err := GetRangeCutMax(tree.typ, node.UpperBound, right.UpperBound, right.Right.upperBound()) if err != nil { panic(err) } right.MaxUpperbound = rightMax } // rotateRight performs a right rotation. This also updates the max upperbounds of each affected node. func (tree *RangeColumnExprTree) rotateRight(node *rangeColumnExprTreeNode) { left := node.Left tree.replaceNode(node, left) node.Left = left.Right if left.Right != nil { left.Right.Parent = node } left.Right = node node.Parent = left nodeMax, err := GetRangeCutMax(tree.typ, node.Left.maxUpperBound(), node.Right.maxUpperBound(), node.upperBound()) if err != nil { panic(err) } node.MaxUpperbound = nodeMax leftMax, err := GetRangeCutMax(tree.typ, node.UpperBound, left.UpperBound, left.Left.upperBound()) if err != nil { panic(err) } left.MaxUpperbound = leftMax } // replaceNode replaces the old node with the new node. func (tree *RangeColumnExprTree) replaceNode(old *rangeColumnExprTreeNode, new *rangeColumnExprTreeNode) { if old.Parent == nil { tree.root = new } else { if old == old.Parent.Left { old.Parent.Left = new } else { old.Parent.Right = new } } if new != nil { new.Parent = old.Parent } } // insertBalance handles the balancing of the nodes after an insertion. func (tree *RangeColumnExprTree) insertBalance(node *rangeColumnExprTreeNode) { if node.Parent == nil { node.color = black return } else if node.Parent.nodeColor() == black { return } uncle := node.uncle() if uncle.nodeColor() == red { node.Parent.color = black uncle.color = black node.grandparent().color = red tree.insertBalance(node.grandparent()) } else { grandparent := node.grandparent() if node == node.Parent.Right && node.Parent == grandparent.Left { tree.rotateLeft(node.Parent) node = node.Left } else if node == node.Parent.Left && node.Parent == grandparent.Right { tree.rotateRight(node.Parent) node = node.Right } node.Parent.color = black grandparent = node.grandparent() grandparent.color = red if node == node.Parent.Left && node.Parent == grandparent.Left { tree.rotateRight(grandparent) } else if node == node.Parent.Right && node.Parent == grandparent.Right { tree.rotateLeft(grandparent) } } } // removeBalance handles the balancing of the nodes after a removal. func (tree *RangeColumnExprTree) removeBalance(node *rangeColumnExprTreeNode) { if node.Parent == nil { return } sibling := node.sibling() if sibling.nodeColor() == red { node.Parent.color = red sibling.color = black if node == node.Parent.Left { tree.rotateLeft(node.Parent) } else { tree.rotateRight(node.Parent) } } sibling = node.sibling() if node.Parent.nodeColor() == black && sibling.nodeColor() == black && sibling.Left.nodeColor() == black && sibling.Right.nodeColor() == black { sibling.color = red tree.removeBalance(node.Parent) } else { sibling = node.sibling() if node.Parent.nodeColor() == red && sibling.nodeColor() == black && sibling.Left.nodeColor() == black && sibling.Right.nodeColor() == black { sibling.color = red node.Parent.color = black } else { sibling := node.sibling() if node == node.Parent.Left && sibling.nodeColor() == black && sibling.Left.nodeColor() == red && sibling.Right.nodeColor() == black { sibling.color = red sibling.Left.color = black tree.rotateRight(sibling) } else if node == node.Parent.Right && sibling.nodeColor() == black && sibling.Right.nodeColor() == red && sibling.Left.nodeColor() == black { sibling.color = red sibling.Right.color = black tree.rotateLeft(sibling) } sibling = node.sibling() sibling.color = node.Parent.nodeColor() node.Parent.color = black if node == node.Parent.Left && sibling.Right.nodeColor() == red { sibling.Right.color = black tree.rotateLeft(node.Parent) } else if sibling.Left.nodeColor() == red { sibling.Left.color = black tree.rotateRight(node.Parent) } } } } // grandparent returns the parent's parent. func (node *rangeColumnExprTreeNode) grandparent() *rangeColumnExprTreeNode { if node != nil && node.Parent != nil { return node.Parent.Parent } return nil } // uncle returns the parent's parent's other child. func (node *rangeColumnExprTreeNode) uncle() *rangeColumnExprTreeNode { if node == nil || node.Parent == nil || node.Parent.Parent == nil { return nil } return node.Parent.sibling() } // sibling returns the parent's other child. func (node *rangeColumnExprTreeNode) sibling() *rangeColumnExprTreeNode { if node == nil || node.Parent == nil { return nil } if node == node.Parent.Left { return node.Parent.Right } return node.Parent.Left } // maximumNode returns the furthest-right node in the tree. func (node *rangeColumnExprTreeNode) maximumNode() *rangeColumnExprTreeNode { if node == nil { return nil } for node.Right != nil { node = node.Right } return node } // nodeColor is a nil-safe way to return this node's color. func (node *rangeColumnExprTreeNode) nodeColor() rangeTreeColor { if node == nil { return black } return node.color } // maxUpperBound is a nil-safe way to return this node's maximum upper bound. func (node *rangeColumnExprTreeNode) maxUpperBound() RangeCut { if node == nil { return nil } return node.MaxUpperbound } // upperBound is a nil-safe way to return this node's upper bound. func (node *rangeColumnExprTreeNode) upperBound() RangeCut { if node == nil { return nil } return node.UpperBound } // rangeTreeIter is an iterator for accessing a RangeColumnExprTree's column expression nodes in order. type rangeTreeIter struct { tree *RangeColumnExprTree node *rangeColumnExprTreeNode position rangeTreeIterPos } // Iterator returns an iterator over the calling tree. Does not handle any inner trees. func (tree *RangeColumnExprTree) Iterator() *rangeTreeIter { return &rangeTreeIter{tree: tree, node: nil, position: begin} } // Next returns the next node, or nil if no more nodes are available. func (iterator *rangeTreeIter) Next() (*rangeColumnExprTreeNode, error) { if iterator.position == end { return nil, nil } if iterator.position == begin { left := iterator.tree.left() if left == nil { iterator.node = nil iterator.position = end return nil, nil } iterator.node = left iterator.position = between return iterator.node, nil } if iterator.node.Right != nil { iterator.node = iterator.node.Right for iterator.node.Left != nil { iterator.node = iterator.node.Left } iterator.position = between return iterator.node, nil } if iterator.node.Parent != nil { node := iterator.node for iterator.node.Parent != nil { iterator.node = iterator.node.Parent if cmp, err := node.LowerBound.Compare(iterator.node.LowerBound, iterator.tree.typ); err != nil { return nil, err } else if cmp < 0 { iterator.position = between return iterator.node, nil } else if cmp == 0 { cmp, err = node.UpperBound.Compare(iterator.node.UpperBound, iterator.tree.typ) if err != nil { return nil, err } if cmp <= 0 { iterator.position = between return iterator.node, nil } } } } iterator.node = nil iterator.position = end return nil, nil }
sql/range_tree.go
0.806815
0.65922
range_tree.go
starcoder
package currency var currenciesByCode = map[string]currency{ `AFN`: { countries: Countries{`AFGHANISTAN`}, currency: `Afghani`, code: `AFN`, number: `971`, }, `EUR`: { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, `ALL`: { countries: Countries{`ALBANIA`}, currency: `Lek`, code: `ALL`, number: `008`, }, `DZD`: { countries: Countries{`ALGERIA`}, currency: `Algerian Dinar`, code: `DZD`, number: `012`, }, `USD`: { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, `AOA`: { countries: Countries{`ANGOLA`}, currency: `Kwanza`, code: `AOA`, number: `973`, }, `XCD`: { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, `ARS`: { countries: Countries{`ARGENTINA`}, currency: `Argentine Peso`, code: `ARS`, number: `032`, }, `AMD`: { countries: Countries{`ARMENIA`}, currency: `Armenian Dram`, code: `AMD`, number: `051`, }, `AWG`: { countries: Countries{`ARUBA`}, currency: `Aruban Florin`, code: `AWG`, number: `533`, }, `AUD`: { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, `AZN`: { countries: Countries{`AZERBAIJAN`}, currency: `Azerbaijan Manat`, code: `AZN`, number: `944`, }, `BSD`: { countries: Countries{`BAHAMAS (THE)`, `BAHAMAS`}, currency: `Bahamian Dollar`, code: `BSD`, number: `044`, }, `BHD`: { countries: Countries{`BAHRAIN`}, currency: `Bahraini Dinar`, code: `BHD`, number: `048`, }, `BDT`: { countries: Countries{`BANGLADESH`}, currency: `Taka`, code: `BDT`, number: `050`, }, `BBD`: { countries: Countries{`BARBADOS`}, currency: `Barbados Dollar`, code: `BBD`, number: `052`, }, `BYN`: { countries: Countries{`BELARUS`}, currency: `Belarusian Ruble`, code: `BYN`, number: `933`, }, `BZD`: { countries: Countries{`BELIZE`}, currency: `Belize Dollar`, code: `BZD`, number: `084`, }, `XOF`: { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, `BMD`: { countries: Countries{`BERMUDA`}, currency: `Bermudian Dollar`, code: `BMD`, number: `060`, }, `INR`: { countries: Countries{`BHUTAN`, `INDIA`}, currency: `Indian Rupee`, code: `INR`, number: `356`, }, `BTN`: { countries: Countries{`BHUTAN`}, currency: `Ngultrum`, code: `BTN`, number: `064`, }, `BOB`: { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Boliviano`, code: `BOB`, number: `068`, }, `BOV`: { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Mvdol`, code: `BOV`, number: `984`, }, `BAM`: { countries: Countries{`BOSNIA AND HERZEGOVINA`}, currency: `Convertible Mark`, code: `BAM`, number: `977`, }, `BWP`: { countries: Countries{`BOTSWANA`}, currency: `Pula`, code: `BWP`, number: `072`, }, `NOK`: { countries: Countries{`BOUVET ISLAND`, `NORWAY`, `SVALBARD AND JAN MAYEN`}, currency: `Norwegian Krone`, code: `NOK`, number: `578`, }, `BRL`: { countries: Countries{`BRAZIL`}, currency: `Brazilian Real`, code: `BRL`, number: `986`, }, `BND`: { countries: Countries{`BRUNEI DARUSSALAM`}, currency: `Brunei Dollar`, code: `BND`, number: `096`, }, `BGN`: { countries: Countries{`BULGARIA`}, currency: `Bulgarian Lev`, code: `BGN`, number: `975`, }, `BIF`: { countries: Countries{`BURUNDI`}, currency: `Burundi Franc`, code: `BIF`, number: `108`, }, `CVE`: { countries: Countries{`CABO VERDE`}, currency: `Cabo Verde Escudo`, code: `CVE`, number: `132`, }, `KHR`: { countries: Countries{`CAMBODIA`}, currency: `Riel`, code: `KHR`, number: `116`, }, `XAF`: { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, `CAD`: { countries: Countries{`CANADA`}, currency: `Canadian Dollar`, code: `CAD`, number: `124`, }, `KYD`: { countries: Countries{`CAYMAN ISLANDS (THE)`, `CAYMAN ISLANDS`}, currency: `Cayman Islands Dollar`, code: `KYD`, number: `136`, }, `CLP`: { countries: Countries{`CHILE`}, currency: `Chilean Peso`, code: `CLP`, number: `152`, }, `CLF`: { countries: Countries{`CHILE`}, currency: `Unidad de Fomento`, code: `CLF`, number: `990`, }, `CNY`: { countries: Countries{`CHINA`}, currency: `Yuan Renminbi`, code: `CNY`, number: `156`, }, `COP`: { countries: Countries{`COLOMBIA`}, currency: `Colombian Peso`, code: `COP`, number: `170`, }, `COU`: { countries: Countries{`COLOMBIA`}, currency: `Unidad de Valor Real`, code: `COU`, number: `970`, }, `KMF`: { countries: Countries{`COMOROS (THE)`, `COMOROS`}, currency: `Comorian Franc `, code: `KMF`, number: `174`, }, `CDF`: { countries: Countries{`CONGO (THE DEMOCRATIC REPUBLIC OF THE)`, `CONGO`}, currency: `Congolese Franc`, code: `CDF`, number: `976`, }, `NZD`: { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, `CRC`: { countries: Countries{`COSTA RICA`}, currency: `Costa Rican Colon`, code: `CRC`, number: `188`, }, `HRK`: { countries: Countries{`CROATIA`}, currency: `Kuna`, code: `HRK`, number: `191`, }, `CUP`: { countries: Countries{`CUBA`}, currency: `Cuban Peso`, code: `CUP`, number: `192`, }, `CUC`: { countries: Countries{`CUBA`}, currency: `Peso Convertible`, code: `CUC`, number: `931`, }, `ANG`: { countries: Countries{`CURAÇAO`, `SINT MAARTEN (DUTCH PART)`, `SINT MAARTEN`}, currency: `Netherlands Antillean Guilder`, code: `ANG`, number: `532`, }, `CZK`: { countries: Countries{`CZECHIA`}, currency: `Czech Koruna`, code: `CZK`, number: `203`, }, `DKK`: { countries: Countries{`DENMARK`, `FAROE ISLANDS (THE)`, `GREENLAND`, `FAROE ISLANDS`}, currency: `Danish Krone`, code: `DKK`, number: `208`, }, `DJF`: { countries: Countries{`DJIBOUTI`}, currency: `Djibouti Franc`, code: `DJF`, number: `262`, }, `DOP`: { countries: Countries{`DOMINICAN REPUBLIC (THE)`, `DOMINICAN REPUBLIC`}, currency: `Dominican Peso`, code: `DOP`, number: `214`, }, `EGP`: { countries: Countries{`EGYPT`}, currency: `Egyptian Pound`, code: `EGP`, number: `818`, }, `SVC`: { countries: Countries{`EL SALVADOR`}, currency: `El Salvador Colon`, code: `SVC`, number: `222`, }, `ERN`: { countries: Countries{`ERITREA`}, currency: `Nakfa`, code: `ERN`, number: `232`, }, `SZL`: { countries: Countries{`ESWATINI`}, currency: `Lilangeni`, code: `SZL`, number: `748`, }, `ETB`: { countries: Countries{`ETHIOPIA`}, currency: `Ethiopian Birr`, code: `ETB`, number: `230`, }, `FKP`: { countries: Countries{`FALKLAND ISLANDS (THE) [MALVINAS]`, `FALKLAND ISLANDS [MALVINAS]`}, currency: `Falkland Islands Pound`, code: `FKP`, number: `238`, }, `FJD`: { countries: Countries{`FIJI`}, currency: `Fiji Dollar`, code: `FJD`, number: `242`, }, `XPF`: { countries: Countries{`FRENCH POLYNESIA`, `NEW CALEDONIA`, `WALLIS AND FUTUNA`}, currency: `CFP Franc`, code: `XPF`, number: `953`, }, `GMD`: { countries: Countries{`GAMBIA (THE)`, `GAMBIA`}, currency: `Dalasi`, code: `GMD`, number: `270`, }, `GEL`: { countries: Countries{`GEORGIA`}, currency: `Lari`, code: `GEL`, number: `981`, }, `GHS`: { countries: Countries{`GHANA`}, currency: `Ghana Cedi`, code: `GHS`, number: `936`, }, `GIP`: { countries: Countries{`GIBRALTAR`}, currency: `Gibraltar Pound`, code: `GIP`, number: `292`, }, `GTQ`: { countries: Countries{`GUATEMALA`}, currency: `Quetzal`, code: `GTQ`, number: `320`, }, `GBP`: { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, `GNF`: { countries: Countries{`GUINEA`}, currency: `Guinean Franc`, code: `GNF`, number: `324`, }, `GYD`: { countries: Countries{`GUYANA`}, currency: `Guyana Dollar`, code: `GYD`, number: `328`, }, `HTG`: { countries: Countries{`HAITI`}, currency: `Gourde`, code: `HTG`, number: `332`, }, `HNL`: { countries: Countries{`HONDURAS`}, currency: `Lempira`, code: `HNL`, number: `340`, }, `HKD`: { countries: Countries{`HONG KONG`}, currency: `Hong Kong Dollar`, code: `HKD`, number: `344`, }, `HUF`: { countries: Countries{`HUNGARY`}, currency: `Forint`, code: `HUF`, number: `348`, }, `ISK`: { countries: Countries{`ICELAND`}, currency: `Iceland Krona`, code: `ISK`, number: `352`, }, `IDR`: { countries: Countries{`INDONESIA`}, currency: `Rupiah`, code: `IDR`, number: `360`, }, `XDR`: { countries: Countries{`INTERNATIONAL MONETARY FUND (IMF) `, `INTERNATIONAL MONETARY FUND `}, currency: `SDR (Special Drawing Right)`, code: `XDR`, number: `960`, }, `IRR`: { countries: Countries{`IRAN (ISLAMIC REPUBLIC OF)`, `IRAN`}, currency: `Iranian Rial`, code: `IRR`, number: `364`, }, `IQD`: { countries: Countries{`IRAQ`}, currency: `Iraqi Dinar`, code: `IQD`, number: `368`, }, `ILS`: { countries: Countries{`ISRAEL`}, currency: `New Israeli Sheqel`, code: `ILS`, number: `376`, }, `JMD`: { countries: Countries{`JAMAICA`}, currency: `Jamaican Dollar`, code: `JMD`, number: `388`, }, `JPY`: { countries: Countries{`JAPAN`}, currency: `Yen`, code: `JPY`, number: `392`, }, `JOD`: { countries: Countries{`JORDAN`}, currency: `Jordanian Dinar`, code: `JOD`, number: `400`, }, `KZT`: { countries: Countries{`KAZAKHSTAN`}, currency: `Tenge`, code: `KZT`, number: `398`, }, `KES`: { countries: Countries{`KENYA`}, currency: `Kenyan Shilling`, code: `KES`, number: `404`, }, `KPW`: { countries: Countries{`KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)`, `KOREA`}, currency: `North Korean Won`, code: `KPW`, number: `408`, }, `KRW`: { countries: Countries{`KOREA (THE REPUBLIC OF)`, `KOREA`}, currency: `Won`, code: `KRW`, number: `410`, }, `KWD`: { countries: Countries{`KUWAIT`}, currency: `Kuwaiti Dinar`, code: `KWD`, number: `414`, }, `KGS`: { countries: Countries{`KYRGYZSTAN`}, currency: `Som`, code: `KGS`, number: `417`, }, `LAK`: { countries: Countries{`LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)`, `LAO PEOPLE’S DEMOCRATIC REPUBLIC`}, currency: `Lao Kip`, code: `LAK`, number: `418`, }, `LBP`: { countries: Countries{`LEBANON`}, currency: `Lebanese Pound`, code: `LBP`, number: `422`, }, `LSL`: { countries: Countries{`LESOTHO`}, currency: `Loti`, code: `LSL`, number: `426`, }, `ZAR`: { countries: Countries{`LESOTHO`, `NAMIBIA`, `SOUTH AFRICA`}, currency: `Rand`, code: `ZAR`, number: `710`, }, `LRD`: { countries: Countries{`LIBERIA`}, currency: `Liberian Dollar`, code: `LRD`, number: `430`, }, `LYD`: { countries: Countries{`LIBYA`}, currency: `Libyan Dinar`, code: `LYD`, number: `434`, }, `CHF`: { countries: Countries{`LIECHTENSTEIN`, `SWITZERLAND`}, currency: `Swiss Franc`, code: `CHF`, number: `756`, }, `MOP`: { countries: Countries{`MACAO`}, currency: `Pataca`, code: `MOP`, number: `446`, }, `MKD`: { countries: Countries{`NORTH MACEDONIA`}, currency: `Denar`, code: `MKD`, number: `807`, }, `MGA`: { countries: Countries{`MADAGASCAR`}, currency: `Malagasy Ariary`, code: `MGA`, number: `969`, }, `MWK`: { countries: Countries{`MALAWI`}, currency: `Malawi Kwacha`, code: `MWK`, number: `454`, }, `MYR`: { countries: Countries{`MALAYSIA`}, currency: `Malaysian Ringgit`, code: `MYR`, number: `458`, }, `MVR`: { countries: Countries{`MALDIVES`}, currency: `Rufiyaa`, code: `MVR`, number: `462`, }, `MRU`: { countries: Countries{`MAURITANIA`}, currency: `Ouguiya`, code: `MRU`, number: `929`, }, `MUR`: { countries: Countries{`MAURITIUS`}, currency: `Mauritius Rupee`, code: `MUR`, number: `480`, }, `XUA`: { countries: Countries{`MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP`}, currency: `ADB Unit of Account`, code: `XUA`, number: `965`, }, `MXN`: { countries: Countries{`MEXICO`}, currency: `Mexican Peso`, code: `MXN`, number: `484`, }, `MXV`: { countries: Countries{`MEXICO`}, currency: `Mexican Unidad de Inversion (UDI)`, code: `MXV`, number: `979`, }, `MDL`: { countries: Countries{`MOLDOVA (THE REPUBLIC OF)`, `MOLDOVA`}, currency: `Moldovan Leu`, code: `MDL`, number: `498`, }, `MNT`: { countries: Countries{`MONGOLIA`}, currency: `Tugrik`, code: `MNT`, number: `496`, }, `MAD`: { countries: Countries{`MOROCCO`, `WESTERN SAHARA`}, currency: `Moroccan Dirham`, code: `MAD`, number: `504`, }, `MZN`: { countries: Countries{`MOZAMBIQUE`}, currency: `Mozambique Metical`, code: `MZN`, number: `943`, }, `MMK`: { countries: Countries{`MYANMAR`}, currency: `Kyat`, code: `MMK`, number: `104`, }, `NAD`: { countries: Countries{`NAMIBIA`}, currency: `Namibia Dollar`, code: `NAD`, number: `516`, }, `NPR`: { countries: Countries{`NEPAL`}, currency: `Nepalese Rupee`, code: `NPR`, number: `524`, }, `NIO`: { countries: Countries{`NICARAGUA`}, currency: `Cordoba Oro`, code: `NIO`, number: `558`, }, `NGN`: { countries: Countries{`NIGERIA`}, currency: `Naira`, code: `NGN`, number: `566`, }, `OMR`: { countries: Countries{`OMAN`}, currency: `Rial Omani`, code: `OMR`, number: `512`, }, `PKR`: { countries: Countries{`PAKISTAN`}, currency: `Pakistan Rupee`, code: `PKR`, number: `586`, }, `PAB`: { countries: Countries{`PANAMA`}, currency: `Balboa`, code: `PAB`, number: `590`, }, `PGK`: { countries: Countries{`PAPUA NEW GUINEA`}, currency: `Kina`, code: `PGK`, number: `598`, }, `PYG`: { countries: Countries{`PARAGUAY`}, currency: `Guarani`, code: `PYG`, number: `600`, }, `PEN`: { countries: Countries{`PERU`}, currency: `Sol`, code: `PEN`, number: `604`, }, `PHP`: { countries: Countries{`PHILIPPINES (THE)`, `PHILIPPINES`}, currency: `Philippine Peso`, code: `PHP`, number: `608`, }, `PLN`: { countries: Countries{`POLAND`}, currency: `Zloty`, code: `PLN`, number: `985`, }, `QAR`: { countries: Countries{`QATAR`}, currency: `Qatari Rial`, code: `QAR`, number: `634`, }, `RON`: { countries: Countries{`ROMANIA`}, currency: `Romanian Leu`, code: `RON`, number: `946`, }, `RUB`: { countries: Countries{`RUSSIAN FEDERATION (THE)`, `RUSSIAN FEDERATION`}, currency: `Russian Ruble`, code: `RUB`, number: `643`, }, `RWF`: { countries: Countries{`RWANDA`}, currency: `Rwanda Franc`, code: `RWF`, number: `646`, }, `SHP`: { countries: Countries{`SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA`}, currency: `Saint Helena Pound`, code: `SHP`, number: `654`, }, `WST`: { countries: Countries{`SAMOA`}, currency: `Tala`, code: `WST`, number: `882`, }, `STN`: { countries: Countries{`SAO TOME AND PRINCIPE`}, currency: `Dobra`, code: `STN`, number: `930`, }, `SAR`: { countries: Countries{`SAUDI ARABIA`}, currency: `Saudi Riyal`, code: `SAR`, number: `682`, }, `RSD`: { countries: Countries{`SERBIA`}, currency: `Serbian Dinar`, code: `RSD`, number: `941`, }, `SCR`: { countries: Countries{`SEYCHELLES`}, currency: `Seychelles Rupee`, code: `SCR`, number: `690`, }, `SLL`: { countries: Countries{`SIERRA LEONE`}, currency: `Leone`, code: `SLL`, number: `694`, }, `SGD`: { countries: Countries{`SINGAPORE`}, currency: `Singapore Dollar`, code: `SGD`, number: `702`, }, `XSU`: { countries: Countries{`SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"`}, currency: `Sucre`, code: `XSU`, number: `994`, }, `SBD`: { countries: Countries{`SOLOMON ISLANDS`}, currency: `Solomon Islands Dollar`, code: `SBD`, number: `090`, }, `SOS`: { countries: Countries{`SOMALIA`}, currency: `Somali Shilling`, code: `SOS`, number: `706`, }, `SSP`: { countries: Countries{`SOUTH SUDAN`}, currency: `South Sudanese Pound`, code: `SSP`, number: `728`, }, `LKR`: { countries: Countries{`SRI LANKA`}, currency: `Sri Lanka Rupee`, code: `LKR`, number: `144`, }, `SDG`: { countries: Countries{`SUDAN (THE)`, `SUDAN`}, currency: `Sudanese Pound`, code: `SDG`, number: `938`, }, `SRD`: { countries: Countries{`SURINAME`}, currency: `Surinam Dollar`, code: `SRD`, number: `968`, }, `SEK`: { countries: Countries{`SWEDEN`}, currency: `Swedish Krona`, code: `SEK`, number: `752`, }, `CHE`: { countries: Countries{`SWITZERLAND`}, currency: `WIR Euro`, code: `CHE`, number: `947`, }, `CHW`: { countries: Countries{`SWITZERLAND`}, currency: `WIR Franc`, code: `CHW`, number: `948`, }, `SYP`: { countries: Countries{`SYRIAN ARAB REPUBLIC`}, currency: `Syrian Pound`, code: `SYP`, number: `760`, }, `TWD`: { countries: Countries{`TAIWAN (PROVINCE OF CHINA)`, `TAIWAN`}, currency: `New Taiwan Dollar`, code: `TWD`, number: `901`, }, `TJS`: { countries: Countries{`TAJIKISTAN`}, currency: `Somoni`, code: `TJS`, number: `972`, }, `TZS`: { countries: Countries{`TANZANIA, UNITED REPUBLIC OF`}, currency: `Tanzanian Shilling`, code: `TZS`, number: `834`, }, `THB`: { countries: Countries{`THAILAND`}, currency: `Baht`, code: `THB`, number: `764`, }, `TOP`: { countries: Countries{`TONGA`}, currency: `Pa’anga`, code: `TOP`, number: `776`, }, `TTD`: { countries: Countries{`TRINIDAD AND TOBAGO`}, currency: `Trinidad and Tobago Dollar`, code: `TTD`, number: `780`, }, `TND`: { countries: Countries{`TUNISIA`}, currency: `Tunisian Dinar`, code: `TND`, number: `788`, }, `TRY`: { countries: Countries{`TURKEY`}, currency: `Turkish Lira`, code: `TRY`, number: `949`, }, `TMT`: { countries: Countries{`TURKMENISTAN`}, currency: `Turkmenistan New Manat`, code: `TMT`, number: `934`, }, `UGX`: { countries: Countries{`UGANDA`}, currency: `Uganda Shilling`, code: `UGX`, number: `800`, }, `UAH`: { countries: Countries{`UKRAINE`}, currency: `Hryvnia`, code: `UAH`, number: `980`, }, `AED`: { countries: Countries{`UNITED ARAB EMIRATES (THE)`, `UNITED ARAB EMIRATES`}, currency: `UAE Dirham`, code: `AED`, number: `784`, }, `USN`: { countries: Countries{`UNITED STATES OF AMERICA (THE)`, `UNITED STATES OF AMERICA`}, currency: `US Dollar (Next day)`, code: `USN`, number: `997`, }, `UYU`: { countries: Countries{`URUGUAY`}, currency: `Peso Uruguayo`, code: `UYU`, number: `858`, }, `UYI`: { countries: Countries{`URUGUAY`}, currency: `Uruguay Peso en Unidades Indexadas (UI)`, code: `UYI`, number: `940`, }, `UYW`: { countries: Countries{`URUGUAY`}, currency: `Unidad Previsional`, code: `UYW`, number: `927`, }, `UZS`: { countries: Countries{`UZBEKISTAN`}, currency: `Uzbekistan Sum`, code: `UZS`, number: `860`, }, `VUV`: { countries: Countries{`VANUATU`}, currency: `Vatu`, code: `VUV`, number: `548`, }, `VES`: { countries: Countries{`VENEZUELA (BOLIVARIAN REPUBLIC OF)`, `VENEZUELA`}, currency: `Bolívar Soberano`, code: `VES`, number: `928`, }, `VND`: { countries: Countries{`VIET NAM`}, currency: `Dong`, code: `VND`, number: `704`, }, `YER`: { countries: Countries{`YEMEN`}, currency: `Yemeni Rial`, code: `YER`, number: `886`, }, `ZMW`: { countries: Countries{`ZAMBIA`}, currency: `Zambian Kwacha`, code: `ZMW`, number: `967`, }, `ZWL`: { countries: Countries{`ZIMBABWE`}, currency: `Zimbabwe Dollar`, code: `ZWL`, number: `932`, }, } var currenciesByNumber = map[string]currency{ `104`: { countries: Countries{`MYANMAR`}, currency: `Kyat`, code: `MMK`, number: `104`, }, `108`: { countries: Countries{`BURUNDI`}, currency: `Burundi Franc`, code: `BIF`, number: `108`, }, `116`: { countries: Countries{`CAMBODIA`}, currency: `Riel`, code: `KHR`, number: `116`, }, `124`: { countries: Countries{`CANADA`}, currency: `Canadian Dollar`, code: `CAD`, number: `124`, }, `132`: { countries: Countries{`CABO VERDE`}, currency: `Cabo Verde Escudo`, code: `CVE`, number: `132`, }, `136`: { countries: Countries{`CAYMAN ISLANDS (THE)`, `CAYMAN ISLANDS`}, currency: `Cayman Islands Dollar`, code: `KYD`, number: `136`, }, `144`: { countries: Countries{`SRI LANKA`}, currency: `Sri Lanka Rupee`, code: `LKR`, number: `144`, }, `152`: { countries: Countries{`CHILE`}, currency: `Chilean Peso`, code: `CLP`, number: `152`, }, `156`: { countries: Countries{`CHINA`}, currency: `Yuan Renminbi`, code: `CNY`, number: `156`, }, `170`: { countries: Countries{`COLOMBIA`}, currency: `Colombian Peso`, code: `COP`, number: `170`, }, `174`: { countries: Countries{`COMOROS (THE)`, `COMOROS`}, currency: `Comorian Franc `, code: `KMF`, number: `174`, }, `188`: { countries: Countries{`COSTA RICA`}, currency: `Costa Rican Colon`, code: `CRC`, number: `188`, }, `191`: { countries: Countries{`CROATIA`}, currency: `Kuna`, code: `HRK`, number: `191`, }, `192`: { countries: Countries{`CUBA`}, currency: `Cuban Peso`, code: `CUP`, number: `192`, }, `203`: { countries: Countries{`CZECHIA`}, currency: `Czech Koruna`, code: `CZK`, number: `203`, }, `208`: { countries: Countries{`DENMARK`, `FAROE ISLANDS (THE)`, `GREENLAND`, `FAROE ISLANDS`}, currency: `Danish Krone`, code: `DKK`, number: `208`, }, `214`: { countries: Countries{`DOMINICAN REPUBLIC (THE)`, `DOMINICAN REPUBLIC`}, currency: `Dominican Peso`, code: `DOP`, number: `214`, }, `222`: { countries: Countries{`EL SALVADOR`}, currency: `El Salvador Colon`, code: `SVC`, number: `222`, }, `230`: { countries: Countries{`ETHIOPIA`}, currency: `Ethiopian Birr`, code: `ETB`, number: `230`, }, `232`: { countries: Countries{`ERITREA`}, currency: `Nakfa`, code: `ERN`, number: `232`, }, `238`: { countries: Countries{`FALKLAND ISLANDS (THE) [MALVINAS]`, `FALKLAND ISLANDS [MALVINAS]`}, currency: `Falkland Islands Pound`, code: `FKP`, number: `238`, }, `242`: { countries: Countries{`FIJI`}, currency: `Fiji Dollar`, code: `FJD`, number: `242`, }, `262`: { countries: Countries{`DJIBOUTI`}, currency: `Djibouti Franc`, code: `DJF`, number: `262`, }, `270`: { countries: Countries{`GAMBIA (THE)`, `GAMBIA`}, currency: `Dalasi`, code: `GMD`, number: `270`, }, `292`: { countries: Countries{`GIBRALTAR`}, currency: `Gibraltar Pound`, code: `GIP`, number: `292`, }, `320`: { countries: Countries{`GUATEMALA`}, currency: `Quetzal`, code: `GTQ`, number: `320`, }, `324`: { countries: Countries{`GUINEA`}, currency: `Guinean Franc`, code: `GNF`, number: `324`, }, `328`: { countries: Countries{`GUYANA`}, currency: `Guyana Dollar`, code: `GYD`, number: `328`, }, `332`: { countries: Countries{`HAITI`}, currency: `Gourde`, code: `HTG`, number: `332`, }, `340`: { countries: Countries{`HONDURAS`}, currency: `Lempira`, code: `HNL`, number: `340`, }, `344`: { countries: Countries{`HONG KONG`}, currency: `Hong Kong Dollar`, code: `HKD`, number: `344`, }, `348`: { countries: Countries{`HUNGARY`}, currency: `Forint`, code: `HUF`, number: `348`, }, `352`: { countries: Countries{`ICELAND`}, currency: `Iceland Krona`, code: `ISK`, number: `352`, }, `356`: { countries: Countries{`BHUTAN`, `INDIA`}, currency: `Indian Rupee`, code: `INR`, number: `356`, }, `360`: { countries: Countries{`INDONESIA`}, currency: `Rupiah`, code: `IDR`, number: `360`, }, `364`: { countries: Countries{`IRAN (ISLAMIC REPUBLIC OF)`, `IRAN`}, currency: `Iranian Rial`, code: `IRR`, number: `364`, }, `368`: { countries: Countries{`IRAQ`}, currency: `Iraqi Dinar`, code: `IQD`, number: `368`, }, `376`: { countries: Countries{`ISRAEL`}, currency: `New Israeli Sheqel`, code: `ILS`, number: `376`, }, `388`: { countries: Countries{`JAMAICA`}, currency: `Jamaican Dollar`, code: `JMD`, number: `388`, }, `392`: { countries: Countries{`JAPAN`}, currency: `Yen`, code: `JPY`, number: `392`, }, `398`: { countries: Countries{`KAZAKHSTAN`}, currency: `Tenge`, code: `KZT`, number: `398`, }, `400`: { countries: Countries{`JORDAN`}, currency: `Jordanian Dinar`, code: `JOD`, number: `400`, }, `404`: { countries: Countries{`KENYA`}, currency: `Kenyan Shilling`, code: `KES`, number: `404`, }, `408`: { countries: Countries{`KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)`, `KOREA`}, currency: `North Korean Won`, code: `KPW`, number: `408`, }, `410`: { countries: Countries{`KOREA (THE REPUBLIC OF)`, `KOREA`}, currency: `Won`, code: `KRW`, number: `410`, }, `414`: { countries: Countries{`KUWAIT`}, currency: `Kuwaiti Dinar`, code: `KWD`, number: `414`, }, `417`: { countries: Countries{`KYRGYZSTAN`}, currency: `Som`, code: `KGS`, number: `417`, }, `418`: { countries: Countries{`LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)`, `LAO PEOPLE’S DEMOCRATIC REPUBLIC`}, currency: `Lao Kip`, code: `LAK`, number: `418`, }, `422`: { countries: Countries{`LEBANON`}, currency: `Lebanese Pound`, code: `LBP`, number: `422`, }, `426`: { countries: Countries{`LESOTHO`}, currency: `Loti`, code: `LSL`, number: `426`, }, `430`: { countries: Countries{`LIBERIA`}, currency: `Liberian Dollar`, code: `LRD`, number: `430`, }, `434`: { countries: Countries{`LIBYA`}, currency: `Libyan Dinar`, code: `LYD`, number: `434`, }, `446`: { countries: Countries{`MACAO`}, currency: `Pataca`, code: `MOP`, number: `446`, }, `454`: { countries: Countries{`MALAWI`}, currency: `Malawi Kwacha`, code: `MWK`, number: `454`, }, `458`: { countries: Countries{`MALAYSIA`}, currency: `Malaysian Ringgit`, code: `MYR`, number: `458`, }, `462`: { countries: Countries{`MALDIVES`}, currency: `Rufiyaa`, code: `MVR`, number: `462`, }, `480`: { countries: Countries{`MAURITIUS`}, currency: `Mauritius Rupee`, code: `MUR`, number: `480`, }, `484`: { countries: Countries{`MEXICO`}, currency: `Mexican Peso`, code: `MXN`, number: `484`, }, `496`: { countries: Countries{`MONGOLIA`}, currency: `Tugrik`, code: `MNT`, number: `496`, }, `498`: { countries: Countries{`MOLDOVA (THE REPUBLIC OF)`, `MOLDOVA`}, currency: `Moldovan Leu`, code: `MDL`, number: `498`, }, `504`: { countries: Countries{`MOROCCO`, `WESTERN SAHARA`}, currency: `Moroccan Dirham`, code: `MAD`, number: `504`, }, `512`: { countries: Countries{`OMAN`}, currency: `Rial Omani`, code: `OMR`, number: `512`, }, `516`: { countries: Countries{`NAMIBIA`}, currency: `Namibia Dollar`, code: `NAD`, number: `516`, }, `524`: { countries: Countries{`NEPAL`}, currency: `Nepalese Rupee`, code: `NPR`, number: `524`, }, `532`: { countries: Countries{`CURAÇAO`, `SINT MAARTEN (DUTCH PART)`, `SINT MAARTEN`}, currency: `Netherlands Antillean Guilder`, code: `ANG`, number: `532`, }, `533`: { countries: Countries{`ARUBA`}, currency: `Aruban Florin`, code: `AWG`, number: `533`, }, `548`: { countries: Countries{`VANUATU`}, currency: `Vatu`, code: `VUV`, number: `548`, }, `554`: { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, `558`: { countries: Countries{`NICARAGUA`}, currency: `Cordoba Oro`, code: `NIO`, number: `558`, }, `566`: { countries: Countries{`NIGERIA`}, currency: `Naira`, code: `NGN`, number: `566`, }, `578`: { countries: Countries{`BOUVET ISLAND`, `NORWAY`, `SVALBARD AND J<NAME>`}, currency: `Norwegian Krone`, code: `NOK`, number: `578`, }, `586`: { countries: Countries{`PAKISTAN`}, currency: `Pakistan Rupee`, code: `PKR`, number: `586`, }, `590`: { countries: Countries{`PANAMA`}, currency: `Balboa`, code: `PAB`, number: `590`, }, `598`: { countries: Countries{`PAPUA NEW GUINEA`}, currency: `Kina`, code: `PGK`, number: `598`, }, `600`: { countries: Countries{`PARAGUAY`}, currency: `Guarani`, code: `PYG`, number: `600`, }, `604`: { countries: Countries{`PERU`}, currency: `Sol`, code: `PEN`, number: `604`, }, `608`: { countries: Countries{`PHILIPPINES (THE)`, `PHILIPPINES`}, currency: `Philippine Peso`, code: `PHP`, number: `608`, }, `634`: { countries: Countries{`QATAR`}, currency: `Qatari Rial`, code: `QAR`, number: `634`, }, `643`: { countries: Countries{`RUSSIAN FEDERATION (THE)`, `RUSSIAN FEDERATION`}, currency: `Russian Ruble`, code: `RUB`, number: `643`, }, `646`: { countries: Countries{`RWANDA`}, currency: `Rwanda Franc`, code: `RWF`, number: `646`, }, `654`: { countries: Countries{`SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA`}, currency: `Saint Helena Pound`, code: `SHP`, number: `654`, }, `682`: { countries: Countries{`SAUDI ARABIA`}, currency: `Saudi Riyal`, code: `SAR`, number: `682`, }, `690`: { countries: Countries{`SEYCHELLES`}, currency: `Seychelles Rupee`, code: `SCR`, number: `690`, }, `694`: { countries: Countries{`SIERRA LEONE`}, currency: `Leone`, code: `SLL`, number: `694`, }, `702`: { countries: Countries{`SINGAPORE`}, currency: `Singapore Dollar`, code: `SGD`, number: `702`, }, `704`: { countries: Countries{`VIET NAM`}, currency: `Dong`, code: `VND`, number: `704`, }, `706`: { countries: Countries{`SOMALIA`}, currency: `Somali Shilling`, code: `SOS`, number: `706`, }, `710`: { countries: Countries{`LESOTHO`, `NAMIBIA`, `SOUTH AFRICA`}, currency: `Rand`, code: `ZAR`, number: `710`, }, `728`: { countries: Countries{`SOUTH SUDAN`}, currency: `South Sudanese Pound`, code: `SSP`, number: `728`, }, `748`: { countries: Countries{`ESWATINI`}, currency: `Lilangeni`, code: `SZL`, number: `748`, }, `752`: { countries: Countries{`SWEDEN`}, currency: `Swedish Krona`, code: `SEK`, number: `752`, }, `756`: { countries: Countries{`LIECHTENSTEIN`, `SWITZERLAND`}, currency: `Swiss Franc`, code: `CHF`, number: `756`, }, `760`: { countries: Countries{`SYRIAN ARAB REPUBLIC`}, currency: `Syrian Pound`, code: `SYP`, number: `760`, }, `764`: { countries: Countries{`THAILAND`}, currency: `Baht`, code: `THB`, number: `764`, }, `776`: { countries: Countries{`TONGA`}, currency: `Pa’anga`, code: `TOP`, number: `776`, }, `780`: { countries: Countries{`TRINIDAD AND TOBAGO`}, currency: `Trinidad and Tobago Dollar`, code: `TTD`, number: `780`, }, `784`: { countries: Countries{`UNITED ARAB EMIRATES (THE)`, `UNITED ARAB EMIRATES`}, currency: `UAE Dirham`, code: `AED`, number: `784`, }, `788`: { countries: Countries{`TUNISIA`}, currency: `Tunisian Dinar`, code: `TND`, number: `788`, }, `800`: { countries: Countries{`UGANDA`}, currency: `Uganda Shilling`, code: `UGX`, number: `800`, }, `807`: { countries: Countries{`NORTH MACEDONIA`}, currency: `Denar`, code: `MKD`, number: `807`, }, `818`: { countries: Countries{`EGYPT`}, currency: `Egyptian Pound`, code: `EGP`, number: `818`, }, `826`: { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, `834`: { countries: Countries{`TANZANIA, UNITED REPUBLIC OF`}, currency: `Tanzanian Shilling`, code: `TZS`, number: `834`, }, `840`: { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, `858`: { countries: Countries{`URUGUAY`}, currency: `Peso Uruguayo`, code: `UYU`, number: `858`, }, `860`: { countries: Countries{`UZBEKISTAN`}, currency: `Uzbekistan Sum`, code: `UZS`, number: `860`, }, `882`: { countries: Countries{`SAMOA`}, currency: `Tala`, code: `WST`, number: `882`, }, `886`: { countries: Countries{`YEMEN`}, currency: `Yemeni Rial`, code: `YER`, number: `886`, }, `901`: { countries: Countries{`TAIWAN (PROVINCE OF CHINA)`, `TAIWAN`}, currency: `New Taiwan Dollar`, code: `TWD`, number: `901`, }, `927`: { countries: Countries{`URUGUAY`}, currency: `Unidad Previsional`, code: `UYW`, number: `927`, }, `928`: { countries: Countries{`VENEZUELA (BOLIVARIAN REPUBLIC OF)`, `VENEZUELA`}, currency: `Bolívar Soberano`, code: `VES`, number: `928`, }, `929`: { countries: Countries{`MAURITANIA`}, currency: `Ouguiya`, code: `MRU`, number: `929`, }, `930`: { countries: Countries{`SAO TOME AND PRINCIPE`}, currency: `Dobra`, code: `STN`, number: `930`, }, `931`: { countries: Countries{`CUBA`}, currency: `Peso Convertible`, code: `CUC`, number: `931`, }, `932`: { countries: Countries{`ZIMBABWE`}, currency: `Zimbabwe Dollar`, code: `ZWL`, number: `932`, }, `933`: { countries: Countries{`BELARUS`}, currency: `Belarusian Ruble`, code: `BYN`, number: `933`, }, `934`: { countries: Countries{`TURKMENISTAN`}, currency: `Turkmenistan New Manat`, code: `TMT`, number: `934`, }, `936`: { countries: Countries{`GHANA`}, currency: `Ghana Cedi`, code: `GHS`, number: `936`, }, `938`: { countries: Countries{`SUDAN (THE)`, `SUDAN`}, currency: `Sudanese Pound`, code: `SDG`, number: `938`, }, `940`: { countries: Countries{`URUGUAY`}, currency: `Uruguay Peso en Unidades Indexadas (UI)`, code: `UYI`, number: `940`, }, `941`: { countries: Countries{`SERBIA`}, currency: `Serbian Dinar`, code: `RSD`, number: `941`, }, `943`: { countries: Countries{`MOZAMBIQUE`}, currency: `Mozambique Metical`, code: `MZN`, number: `943`, }, `944`: { countries: Countries{`AZERBAIJAN`}, currency: `Azerbaijan Manat`, code: `AZN`, number: `944`, }, `946`: { countries: Countries{`ROMANIA`}, currency: `Romanian Leu`, code: `RON`, number: `946`, }, `947`: { countries: Countries{`SWITZERLAND`}, currency: `WIR Euro`, code: `CHE`, number: `947`, }, `948`: { countries: Countries{`SWITZERLAND`}, currency: `WIR Franc`, code: `CHW`, number: `948`, }, `949`: { countries: Countries{`TURKEY`}, currency: `Turkish Lira`, code: `TRY`, number: `949`, }, `950`: { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, `951`: { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, `952`: { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, `953`: { countries: Countries{`FRENCH POLYNESIA`, `NEW CALEDONIA`, `WALLIS AND FUTUNA`}, currency: `CFP Franc`, code: `XPF`, number: `953`, }, `960`: { countries: Countries{`INTERNATIONAL MONETARY FUND (IMF) `, `INTERNATIONAL MONETARY FUND `}, currency: `SDR (Special Drawing Right)`, code: `XDR`, number: `960`, }, `965`: { countries: Countries{`MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP`}, currency: `ADB Unit of Account`, code: `XUA`, number: `965`, }, `967`: { countries: Countries{`ZAMBIA`}, currency: `Zambian Kwacha`, code: `ZMW`, number: `967`, }, `968`: { countries: Countries{`SURINAME`}, currency: `Surinam Dollar`, code: `SRD`, number: `968`, }, `969`: { countries: Countries{`MADAGASCAR`}, currency: `Malagasy Ariary`, code: `MGA`, number: `969`, }, `970`: { countries: Countries{`COLOMBIA`}, currency: `Unidad de Valor Real`, code: `COU`, number: `970`, }, `971`: { countries: Countries{`AFGHANISTAN`}, currency: `Afghani`, code: `AFN`, number: `971`, }, `972`: { countries: Countries{`TAJIKISTAN`}, currency: `Somoni`, code: `TJS`, number: `972`, }, `973`: { countries: Countries{`ANGOLA`}, currency: `Kwanza`, code: `AOA`, number: `973`, }, `975`: { countries: Countries{`BULGARIA`}, currency: `Bulgarian Lev`, code: `BGN`, number: `975`, }, `976`: { countries: Countries{`CONGO (THE DEMOCRATIC REPUBLIC OF THE)`, `CONGO`}, currency: `Congolese Franc`, code: `CDF`, number: `976`, }, `977`: { countries: Countries{`BOSNIA AND HERZEGOVINA`}, currency: `Convertible Mark`, code: `BAM`, number: `977`, }, `978`: { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, `979`: { countries: Countries{`MEXICO`}, currency: `Mexican Unidad de Inversion (UDI)`, code: `MXV`, number: `979`, }, `980`: { countries: Countries{`UKRAINE`}, currency: `Hryvnia`, code: `UAH`, number: `980`, }, `981`: { countries: Countries{`GEORGIA`}, currency: `Lari`, code: `GEL`, number: `981`, }, `984`: { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Mvdol`, code: `BOV`, number: `984`, }, `985`: { countries: Countries{`POLAND`}, currency: `Zloty`, code: `PLN`, number: `985`, }, `986`: { countries: Countries{`BRAZIL`}, currency: `Brazilian Real`, code: `BRL`, number: `986`, }, `990`: { countries: Countries{`CHILE`}, currency: `Unidad de Fomento`, code: `CLF`, number: `990`, }, `994`: { countries: Countries{`SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"`}, currency: `Sucre`, code: `XSU`, number: `994`, }, `997`: { countries: Countries{`UNITED STATES OF AMERICA (THE)`, `UNITED STATES OF AMERICA`}, currency: `US Dollar (Next day)`, code: `USN`, number: `997`, }, `008`: { countries: Countries{`ALBANIA`}, currency: `Lek`, code: `ALL`, number: `008`, }, `012`: { countries: Countries{`ALGERIA`}, currency: `Algerian Dinar`, code: `DZD`, number: `012`, }, `032`: { countries: Countries{`ARGENTINA`}, currency: `Argentine Peso`, code: `ARS`, number: `032`, }, `051`: { countries: Countries{`ARMENIA`}, currency: `Armenian Dram`, code: `AMD`, number: `051`, }, `036`: { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, `044`: { countries: Countries{`BAHAMAS (THE)`, `BAHAMAS`}, currency: `Bahamian Dollar`, code: `BSD`, number: `044`, }, `048`: { countries: Countries{`BAHRAIN`}, currency: `Bahraini Dinar`, code: `BHD`, number: `048`, }, `050`: { countries: Countries{`BANGLADESH`}, currency: `Taka`, code: `BDT`, number: `050`, }, `052`: { countries: Countries{`BARBADOS`}, currency: `Barbados Dollar`, code: `BBD`, number: `052`, }, `084`: { countries: Countries{`BELIZE`}, currency: `Belize Dollar`, code: `BZD`, number: `084`, }, `060`: { countries: Countries{`BERMUDA`}, currency: `Bermudian Dollar`, code: `BMD`, number: `060`, }, `064`: { countries: Countries{`BHUTAN`}, currency: `Ngultrum`, code: `BTN`, number: `064`, }, `068`: { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Boliviano`, code: `BOB`, number: `068`, }, `072`: { countries: Countries{`BOTSWANA`}, currency: `Pula`, code: `BWP`, number: `072`, }, `096`: { countries: Countries{`BRUNEI DARUSSALAM`}, currency: `Brunei Dollar`, code: `BND`, number: `096`, }, `090`: { countries: Countries{`SOLOMON ISLANDS`}, currency: `Solomon Islands Dollar`, code: `SBD`, number: `090`, }, } var currenciesByCountry = map[string]currencies{ `AFGHANISTAN`: { { countries: Countries{`AFGHANISTAN`}, currency: `Afghani`, code: `AFN`, number: `971`, }, }, `ÅLAND ISLANDS`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `ALBANIA`: { { countries: Countries{`ALBANIA`}, currency: `Lek`, code: `ALL`, number: `008`, }, }, `ALGERIA`: { { countries: Countries{`ALGERIA`}, currency: `Algerian Dinar`, code: `DZD`, number: `012`, }, }, `AMERICAN SAMOA`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `ANDORRA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `ANGOLA`: { { countries: Countries{`ANGOLA`}, currency: `Kwanza`, code: `AOA`, number: `973`, }, }, `ANGUILLA`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `ANTIGUA AND BARBUDA`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `ARGENTINA`: { { countries: Countries{`ARGENTINA`}, currency: `Argentine Peso`, code: `ARS`, number: `032`, }, }, `ARMENIA`: { { countries: Countries{`ARMENIA`}, currency: `Armenian Dram`, code: `AMD`, number: `051`, }, }, `ARUBA`: { { countries: Countries{`ARUBA`}, currency: `Aruban Florin`, code: `AWG`, number: `533`, }, }, `AUSTRALIA`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `AUSTRIA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `<NAME>`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `AZERBAIJAN`: { { countries: Countries{`AZERBAIJAN`}, currency: `Azerbaijan Manat`, code: `AZN`, number: `944`, }, }, `BAHAMAS (THE)`: { { countries: Countries{`BAHAMAS (THE)`, `BAHAMAS`}, currency: `Bahamian Dollar`, code: `BSD`, number: `044`, }, }, `BAHRAIN`: { { countries: Countries{`BAHRAIN`}, currency: `Bahraini Dinar`, code: `BHD`, number: `048`, }, }, `BANGLADESH`: { { countries: Countries{`BANGLADESH`}, currency: `Taka`, code: `BDT`, number: `050`, }, }, `BARBADOS`: { { countries: Countries{`BARBADOS`}, currency: `Barbados Dollar`, code: `BBD`, number: `052`, }, }, `BELARUS`: { { countries: Countries{`BELARUS`}, currency: `Belarusian Ruble`, code: `BYN`, number: `933`, }, }, `BELGIUM`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `BELIZE`: { { countries: Countries{`BELIZE`}, currency: `Belize Dollar`, code: `BZD`, number: `084`, }, }, `BENIN`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `BERMUDA`: { { countries: Countries{`BERMUDA`}, currency: `Bermudian Dollar`, code: `BMD`, number: `060`, }, }, `BHUTAN`: { { countries: Countries{`BHUTAN`, `INDIA`}, currency: `Indian Rupee`, code: `INR`, number: `356`, }, { countries: Countries{`BHUTAN`}, currency: `Ngultrum`, code: `BTN`, number: `064`, }, }, `BOLIVIA (PLURINATIONAL STATE OF)`: { { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Boliviano`, code: `BOB`, number: `068`, }, { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Mvdol`, code: `BOV`, number: `984`, }, }, `BONAIRE, SINT EUSTATIUS AND SABA`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `BOSNIA AND HERZEGOVINA`: { { countries: Countries{`BOSNIA AND HERZEGOVINA`}, currency: `Convertible Mark`, code: `BAM`, number: `977`, }, }, `BOTSWANA`: { { countries: Countries{`BOTSWANA`}, currency: `Pula`, code: `BWP`, number: `072`, }, }, `BOUVET ISLAND`: { { countries: Countries{`BOUVET ISLAND`, `NORWAY`, `SVALBARD AND JAN MAYEN`}, currency: `Norwegian Krone`, code: `NOK`, number: `578`, }, }, `BRAZIL`: { { countries: Countries{`BRAZIL`}, currency: `Brazilian Real`, code: `BRL`, number: `986`, }, }, `BRITISH INDIAN OCEAN TERRITORY (THE)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `BRUNEI DARUSSALAM`: { { countries: Countries{`BRUNEI DARUSSALAM`}, currency: `Brunei Dollar`, code: `BND`, number: `096`, }, }, `BULGARIA`: { { countries: Countries{`BULGARIA`}, currency: `Bulgarian Lev`, code: `BGN`, number: `975`, }, }, `BURKINA FASO`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `BURUNDI`: { { countries: Countries{`BURUNDI`}, currency: `Burundi Franc`, code: `BIF`, number: `108`, }, }, `CABO VERDE`: { { countries: Countries{`CABO VERDE`}, currency: `Cabo Verde Escudo`, code: `CVE`, number: `132`, }, }, `CAMBODIA`: { { countries: Countries{`CAMBODIA`}, currency: `Riel`, code: `KHR`, number: `116`, }, }, `CAMEROON`: { { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `CANADA`: { { countries: Countries{`CANADA`}, currency: `Canadian Dollar`, code: `CAD`, number: `124`, }, }, `CAYMAN ISLANDS (THE)`: { { countries: Countries{`CAYMAN ISLANDS (THE)`, `CAYMAN ISLANDS`}, currency: `Cayman Islands Dollar`, code: `KYD`, number: `136`, }, }, `CENTRAL AFRICAN REPUBLIC (THE)`: { { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `CHAD`: { { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `CHILE`: { { countries: Countries{`CHILE`}, currency: `Chilean Peso`, code: `CLP`, number: `152`, }, { countries: Countries{`CHILE`}, currency: `Unidad de Fomento`, code: `CLF`, number: `990`, }, }, `CHINA`: { { countries: Countries{`CHINA`}, currency: `Yuan Renminbi`, code: `CNY`, number: `156`, }, }, `CHRISTMAS ISLAND`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `COCOS (KEELING) ISLANDS (THE)`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `COLOMBIA`: { { countries: Countries{`COLOMBIA`}, currency: `Colombian Peso`, code: `COP`, number: `170`, }, { countries: Countries{`COLOMBIA`}, currency: `Unidad de Valor Real`, code: `COU`, number: `970`, }, }, `COMOROS (THE)`: { { countries: Countries{`COMOROS (THE)`, `COMOROS`}, currency: `Comorian Franc `, code: `KMF`, number: `174`, }, }, `CONGO (THE DEMOCRATIC REPUBLIC OF THE)`: { { countries: Countries{`CONGO (THE DEMOCRATIC REPUBLIC OF THE)`, `CONGO`}, currency: `Congolese Franc`, code: `CDF`, number: `976`, }, }, `CONGO (THE)`: { { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `COOK ISLANDS (THE)`: { { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, }, `COSTA RICA`: { { countries: Countries{`COSTA RICA`}, currency: `Costa Rican Colon`, code: `CRC`, number: `188`, }, }, `CÔTE D'IVOIRE`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `CROATIA`: { { countries: Countries{`CROATIA`}, currency: `Kuna`, code: `HRK`, number: `191`, }, }, `CUBA`: { { countries: Countries{`CUBA`}, currency: `Cuban Peso`, code: `CUP`, number: `192`, }, { countries: Countries{`CUBA`}, currency: `Peso Convertible`, code: `CUC`, number: `931`, }, }, `CURAÇAO`: { { countries: Countries{`CURAÇAO`, `SINT MAARTEN (DUTCH PART)`, `SINT MAARTEN`}, currency: `Netherlands Antillean Guilder`, code: `ANG`, number: `532`, }, }, `CYPRUS`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `CZECHIA`: { { countries: Countries{`CZECHIA`}, currency: `Czech Koruna`, code: `CZK`, number: `203`, }, }, `DENMARK`: { { countries: Countries{`DENMARK`, `FAROE ISLANDS (THE)`, `GREENLAND`, `FAROE ISLANDS`}, currency: `Danish Krone`, code: `DKK`, number: `208`, }, }, `DJIBOUTI`: { { countries: Countries{`DJIBOUTI`}, currency: `Djibouti Franc`, code: `DJF`, number: `262`, }, }, `DOMINICA`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `DOMINICAN REPUBLIC (THE)`: { { countries: Countries{`DOMINICAN REPUBLIC (THE)`, `DOMINICAN REPUBLIC`}, currency: `Dominican Peso`, code: `DOP`, number: `214`, }, }, `ECUADOR`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `EGYPT`: { { countries: Countries{`EGYPT`}, currency: `Egyptian Pound`, code: `EGP`, number: `818`, }, }, `EL SALVADOR`: { { countries: Countries{`EL SALVADOR`}, currency: `El Salvador Colon`, code: `SVC`, number: `222`, }, { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `EQUATORIAL GUINEA`: { { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `ERITREA`: { { countries: Countries{`ERITREA`}, currency: `Nakfa`, code: `ERN`, number: `232`, }, }, `ESTONIA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `ESWATINI`: { { countries: Countries{`ESWATINI`}, currency: `Lilangeni`, code: `SZL`, number: `748`, }, }, `ETHIOPIA`: { { countries: Countries{`ETHIOPIA`}, currency: `Ethiopian Birr`, code: `ETB`, number: `230`, }, }, `EUROPEAN UNION`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `<NAME>`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `FALKLAND ISLANDS (THE) [MALVINAS]`: { { countries: Countries{`FALKLAND ISLANDS (THE) [MALVINAS]`, `FALKLAND ISLANDS [MALVINAS]`}, currency: `Falkland Islands Pound`, code: `FKP`, number: `238`, }, }, `FAROE ISLANDS (THE)`: { { countries: Countries{`DENMARK`, `FAROE ISLANDS (THE)`, `GREENLAND`, `FAROE ISLANDS`}, currency: `Danish Krone`, code: `DKK`, number: `208`, }, }, `FIJI`: { { countries: Countries{`FIJI`}, currency: `Fiji Dollar`, code: `FJD`, number: `242`, }, }, `FINLAND`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `FRANCE`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `FRENCH GUIANA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `FRENCH POLYNESIA`: { { countries: Countries{`FRENCH POLYNESIA`, `NEW CALEDONIA`, `WALLIS AND FUTUNA`}, currency: `CFP Franc`, code: `XPF`, number: `953`, }, }, `FRENCH SOUTHERN TERRITORIES (THE)`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `GABON`: { { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `GAMBIA (THE)`: { { countries: Countries{`GAMBIA (THE)`, `GAMBIA`}, currency: `Dalasi`, code: `GMD`, number: `270`, }, }, `GEORGIA`: { { countries: Countries{`GEORGIA`}, currency: `Lari`, code: `GEL`, number: `981`, }, }, `GERMANY`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `GHANA`: { { countries: Countries{`GHANA`}, currency: `Ghana Cedi`, code: `GHS`, number: `936`, }, }, `GIBRALTAR`: { { countries: Countries{`GIBRALTAR`}, currency: `Gibraltar Pound`, code: `GIP`, number: `292`, }, }, `GREECE`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `GREENLAND`: { { countries: Countries{`DENMARK`, `FAROE ISLANDS (THE)`, `GREENLAND`, `FAROE ISLANDS`}, currency: `Danish Krone`, code: `DKK`, number: `208`, }, }, `GRENADA`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `GUADELOUPE`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `GUAM`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `GUATEMALA`: { { countries: Countries{`GUATEMALA`}, currency: `Quetzal`, code: `GTQ`, number: `320`, }, }, `GUERNSEY`: { { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, }, `GUINEA`: { { countries: Countries{`GUINEA`}, currency: `Guinean Franc`, code: `GNF`, number: `324`, }, }, `GUINEA-BISSAU`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `GUYANA`: { { countries: Countries{`GUYANA`}, currency: `Guyana Dollar`, code: `GYD`, number: `328`, }, }, `HAITI`: { { countries: Countries{`HAITI`}, currency: `Gourde`, code: `HTG`, number: `332`, }, { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `HEARD ISLAND AND McDONALD ISLANDS`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `HOLY SEE (THE)`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `HONDURAS`: { { countries: Countries{`HONDURAS`}, currency: `Lempira`, code: `HNL`, number: `340`, }, }, `HONG KONG`: { { countries: Countries{`HONG KONG`}, currency: `Hong Kong Dollar`, code: `HKD`, number: `344`, }, }, `HUNGARY`: { { countries: Countries{`HUNGARY`}, currency: `Forint`, code: `HUF`, number: `348`, }, }, `ICELAND`: { { countries: Countries{`ICELAND`}, currency: `Iceland Krona`, code: `ISK`, number: `352`, }, }, `INDIA`: { { countries: Countries{`BHUTAN`, `INDIA`}, currency: `Indian Rupee`, code: `INR`, number: `356`, }, }, `INDONESIA`: { { countries: Countries{`INDONESIA`}, currency: `Rupiah`, code: `IDR`, number: `360`, }, }, `INTERNATIONAL MONETARY FUND (IMF) `: { { countries: Countries{`INTERNATIONAL MONETARY FUND (IMF) `, `INTERNATIONAL MONETARY FUND `}, currency: `SDR (Special Drawing Right)`, code: `XDR`, number: `960`, }, }, `IRAN (ISLAMIC REPUBLIC OF)`: { { countries: Countries{`IRAN (ISLAMIC REPUBLIC OF)`, `IRAN`}, currency: `Iranian Rial`, code: `IRR`, number: `364`, }, }, `IRAQ`: { { countries: Countries{`IRAQ`}, currency: `Iraqi Dinar`, code: `IQD`, number: `368`, }, }, `IRELAND`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `ISLE OF MAN`: { { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, }, `ISRAEL`: { { countries: Countries{`ISRAEL`}, currency: `New Israeli Sheqel`, code: `ILS`, number: `376`, }, }, `ITALY`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `JAMAICA`: { { countries: Countries{`JAMAICA`}, currency: `Jamaican Dollar`, code: `JMD`, number: `388`, }, }, `JAPAN`: { { countries: Countries{`JAPAN`}, currency: `Yen`, code: `JPY`, number: `392`, }, }, `JERSEY`: { { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, }, `JORDAN`: { { countries: Countries{`JORDAN`}, currency: `Jordanian Dinar`, code: `JOD`, number: `400`, }, }, `KAZAKHSTAN`: { { countries: Countries{`KAZAKHSTAN`}, currency: `Tenge`, code: `KZT`, number: `398`, }, }, `KENYA`: { { countries: Countries{`KENYA`}, currency: `Kenyan Shilling`, code: `KES`, number: `404`, }, }, `KIRIBATI`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)`: { { countries: Countries{`KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)`, `KOREA`}, currency: `North Korean Won`, code: `KPW`, number: `408`, }, }, `KOREA (THE REPUBLIC OF)`: { { countries: Countries{`KOREA (THE REPUBLIC OF)`, `KOREA`}, currency: `Won`, code: `KRW`, number: `410`, }, }, `KUWAIT`: { { countries: Countries{`KUWAIT`}, currency: `Kuwaiti Dinar`, code: `KWD`, number: `414`, }, }, `KYRGYZSTAN`: { { countries: Countries{`KYRGYZSTAN`}, currency: `Som`, code: `KGS`, number: `417`, }, }, `LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)`: { { countries: Countries{`LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)`, `LAO PEOPLE’S DEMOCRATIC REPUBLIC`}, currency: `Lao Kip`, code: `LAK`, number: `418`, }, }, `LATVIA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `LEBANON`: { { countries: Countries{`LEBANON`}, currency: `Lebanese Pound`, code: `LBP`, number: `422`, }, }, `LESOTHO`: { { countries: Countries{`LESOTHO`}, currency: `Loti`, code: `LSL`, number: `426`, }, { countries: Countries{`LESOTHO`, `NAMIBIA`, `SOUTH AFRICA`}, currency: `Rand`, code: `ZAR`, number: `710`, }, }, `LIBERIA`: { { countries: Countries{`LIBERIA`}, currency: `Liberian Dollar`, code: `LRD`, number: `430`, }, }, `LIBYA`: { { countries: Countries{`LIBYA`}, currency: `Libyan Dinar`, code: `LYD`, number: `434`, }, }, `LIECHTENSTEIN`: { { countries: Countries{`LIECHTENSTEIN`, `SWITZERLAND`}, currency: `Swiss Franc`, code: `CHF`, number: `756`, }, }, `LITHUANIA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `LUXEMBOURG`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `<NAME>`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `MACAO`: { { countries: Countries{`MACAO`}, currency: `Pataca`, code: `MOP`, number: `446`, }, }, `NORTH MACEDONIA`: { { countries: Countries{`NORTH MACEDONIA`}, currency: `Denar`, code: `MKD`, number: `807`, }, }, `MADAGASCAR`: { { countries: Countries{`MADAGASCAR`}, currency: `Malagasy Ariary`, code: `MGA`, number: `969`, }, }, `MALAWI`: { { countries: Countries{`MALAWI`}, currency: `Malawi Kwacha`, code: `MWK`, number: `454`, }, }, `MALAYSIA`: { { countries: Countries{`MALAYSIA`}, currency: `Malaysian Ringgit`, code: `MYR`, number: `458`, }, }, `MALDIVES`: { { countries: Countries{`MALDIVES`}, currency: `Rufiyaa`, code: `MVR`, number: `462`, }, }, `MALI`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `MALTA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `MARSHALL ISLANDS (THE)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `MARTINIQUE`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `MAURITANIA`: { { countries: Countries{`MAURITANIA`}, currency: `Ouguiya`, code: `MRU`, number: `929`, }, }, `MAURITIUS`: { { countries: Countries{`MAURITIUS`}, currency: `Mauritius Rupee`, code: `MUR`, number: `480`, }, }, `MAYOTTE`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP`: { { countries: Countries{`MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP`}, currency: `ADB Unit of Account`, code: `XUA`, number: `965`, }, }, `MEXICO`: { { countries: Countries{`MEXICO`}, currency: `Mexican Peso`, code: `MXN`, number: `484`, }, { countries: Countries{`MEXICO`}, currency: `Mexican Unidad de Inversion (UDI)`, code: `MXV`, number: `979`, }, }, `MICRONESIA (FEDERATED STATES OF)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `MOLDOVA (THE REPUBLIC OF)`: { { countries: Countries{`MOLDOVA (THE REPUBLIC OF)`, `MOLDOVA`}, currency: `Moldovan Leu`, code: `MDL`, number: `498`, }, }, `MONACO`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `MONGOLIA`: { { countries: Countries{`MONGOLIA`}, currency: `Tugrik`, code: `MNT`, number: `496`, }, }, `MONTENEGRO`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `MONTSERRAT`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `MOROCCO`: { { countries: Countries{`MOROCCO`, `WESTERN SAHARA`}, currency: `Moroccan Dirham`, code: `MAD`, number: `504`, }, }, `MOZAMBIQUE`: { { countries: Countries{`MOZAMBIQUE`}, currency: `Mozambique Metical`, code: `MZN`, number: `943`, }, }, `MYANMAR`: { { countries: Countries{`MYANMAR`}, currency: `Kyat`, code: `MMK`, number: `104`, }, }, `NAMIBIA`: { { countries: Countries{`NAMIBIA`}, currency: `Namibia Dollar`, code: `NAD`, number: `516`, }, { countries: Countries{`LESOTHO`, `NAMIBIA`, `SOUTH AFRICA`}, currency: `Rand`, code: `ZAR`, number: `710`, }, }, `NAURU`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `NEPAL`: { { countries: Countries{`NEPAL`}, currency: `Nepalese Rupee`, code: `NPR`, number: `524`, }, }, `NETHERLANDS (THE)`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `<NAME>`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `NEW CALEDONIA`: { { countries: Countries{`FRENCH POLYNESIA`, `NEW CALEDONIA`, `WALLIS AND FUTUNA`}, currency: `CFP Franc`, code: `XPF`, number: `953`, }, }, `NEW ZEALAND`: { { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, }, `NICARAGUA`: { { countries: Countries{`NICARAGUA`}, currency: `Cordoba Oro`, code: `NIO`, number: `558`, }, }, `NIGER (THE)`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `NIGERIA`: { { countries: Countries{`NIGERIA`}, currency: `Naira`, code: `NGN`, number: `566`, }, }, `NIUE`: { { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, }, `NORFOLK ISLAND`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `NORTHERN MARIANA ISLANDS (THE)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `NORWAY`: { { countries: Countries{`BOUVET ISLAND`, `NORWAY`, `SVALBARD AND JAN MAYEN`}, currency: `Norwegian Krone`, code: `NOK`, number: `578`, }, }, `OMAN`: { { countries: Countries{`OMAN`}, currency: `Rial Omani`, code: `OMR`, number: `512`, }, }, `PAKISTAN`: { { countries: Countries{`PAKISTAN`}, currency: `Pakistan Rupee`, code: `PKR`, number: `586`, }, }, `PALAU`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `PANAMA`: { { countries: Countries{`PANAMA`}, currency: `Balboa`, code: `PAB`, number: `590`, }, { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `PAPUA NEW GUINEA`: { { countries: Countries{`PAPUA NEW GUINEA`}, currency: `Kina`, code: `PGK`, number: `598`, }, }, `PARAGUAY`: { { countries: Countries{`PARAGUAY`}, currency: `Guarani`, code: `PYG`, number: `600`, }, }, `PERU`: { { countries: Countries{`PERU`}, currency: `Sol`, code: `PEN`, number: `604`, }, }, `PHILIPPINES (THE)`: { { countries: Countries{`PHILIPPINES (THE)`, `PHILIPPINES`}, currency: `Philippine Peso`, code: `PHP`, number: `608`, }, }, `PITCAIRN`: { { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, }, `POLAND`: { { countries: Countries{`POLAND`}, currency: `Zloty`, code: `PLN`, number: `985`, }, }, `PORTUGAL`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `PUERTO RICO`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `QATAR`: { { countries: Countries{`QATAR`}, currency: `Qatari Rial`, code: `QAR`, number: `634`, }, }, `RÉUNION`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `<NAME>`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `ROMANIA`: { { countries: Countries{`ROMANIA`}, currency: `Romanian Leu`, code: `RON`, number: `946`, }, }, `RUSSIAN FEDERATION (THE)`: { { countries: Countries{`RUSSIAN FEDERATION (THE)`, `RUSSIAN FEDERATION`}, currency: `Russian Ruble`, code: `RUB`, number: `643`, }, }, `RWANDA`: { { countries: Countries{`RWANDA`}, currency: `Rwanda Franc`, code: `RWF`, number: `646`, }, }, `SAINT BARTHÉLEMY`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA`: { { countries: Countries{`SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA`}, currency: `Saint Helena Pound`, code: `SHP`, number: `654`, }, }, `SAINT KITTS AND NEVIS`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `SAINT LUCIA`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `SAINT MARTIN (FRENCH PART)`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SAINT PIERRE AND MIQUELON`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SAINT VINCENT AND THE GRENADINES`: { { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, }, `SAMOA`: { { countries: Countries{`SAMOA`}, currency: `Tala`, code: `WST`, number: `882`, }, }, `SAN MARINO`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `<NAME>`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SAO TOME AND PRINCIPE`: { { countries: Countries{`SAO TOME AND PRINCIPE`}, currency: `Dobra`, code: `STN`, number: `930`, }, }, `SAUDI ARABIA`: { { countries: Countries{`SAUDI ARABIA`}, currency: `Saudi Riyal`, code: `SAR`, number: `682`, }, }, `SENEGAL`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `SERBIA`: { { countries: Countries{`SERBIA`}, currency: `Serbian Dinar`, code: `RSD`, number: `941`, }, }, `SEYCHELLES`: { { countries: Countries{`SEYCHELLES`}, currency: `Seychelles Rupee`, code: `SCR`, number: `690`, }, }, `SIERRA LEONE`: { { countries: Countries{`SIERRA LEONE`}, currency: `Leone`, code: `SLL`, number: `694`, }, }, `SINGAPORE`: { { countries: Countries{`SINGAPORE`}, currency: `Singapore Dollar`, code: `SGD`, number: `702`, }, }, `SINT MAARTEN (DUTCH PART)`: { { countries: Countries{`CURAÇAO`, `SINT MAARTEN (DUTCH PART)`, `SINT MAARTEN`}, currency: `Netherlands Antillean Guilder`, code: `ANG`, number: `532`, }, }, `SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"`: { { countries: Countries{`SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"`}, currency: `Sucre`, code: `XSU`, number: `994`, }, }, `SLOVAKIA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SLOVENIA`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SOLOMON ISLANDS`: { { countries: Countries{`SOLOMON ISLANDS`}, currency: `Solomon Islands Dollar`, code: `SBD`, number: `090`, }, }, `SOMALIA`: { { countries: Countries{`SOMALIA`}, currency: `Somali Shilling`, code: `SOS`, number: `706`, }, }, `SOUTH AFRICA`: { { countries: Countries{`LESOTHO`, `NAMIBIA`, `SOUTH AFRICA`}, currency: `Rand`, code: `ZAR`, number: `710`, }, }, `SOUTH SUDAN`: { { countries: Countries{`SOUTH SUDAN`}, currency: `South Sudanese Pound`, code: `SSP`, number: `728`, }, }, `SPAIN`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SRI LANKA`: { { countries: Countries{`SRI LANKA`}, currency: `Sri Lanka Rupee`, code: `LKR`, number: `144`, }, }, `SUDAN (THE)`: { { countries: Countries{`SUDAN (THE)`, `SUDAN`}, currency: `Sudanese Pound`, code: `SDG`, number: `938`, }, }, `SURINAME`: { { countries: Countries{`SURINAME`}, currency: `Surinam Dollar`, code: `SRD`, number: `968`, }, }, `SVALBARD AND JAN MAYEN`: { { countries: Countries{`BOUVET ISLAND`, `NORWAY`, `SVALBARD AND JAN MAYEN`}, currency: `Norwegian Krone`, code: `NOK`, number: `578`, }, }, `SWEDEN`: { { countries: Countries{`SWEDEN`}, currency: `Swedish Krona`, code: `SEK`, number: `752`, }, }, `SWITZERLAND`: { { countries: Countries{`LIECHTENSTEIN`, `SWITZERLAND`}, currency: `Swiss Franc`, code: `CHF`, number: `756`, }, { countries: Countries{`SWITZERLAND`}, currency: `WIR Euro`, code: `CHE`, number: `947`, }, { countries: Countries{`SWITZERLAND`}, currency: `WIR Franc`, code: `CHW`, number: `948`, }, }, `SYRIAN ARAB REPUBLIC`: { { countries: Countries{`SYRIAN ARAB REPUBLIC`}, currency: `Syrian Pound`, code: `SYP`, number: `760`, }, }, `TAIWAN (PROVINCE OF CHINA)`: { { countries: Countries{`TAIWAN (PROVINCE OF CHINA)`, `TAIWAN`}, currency: `New Taiwan Dollar`, code: `TWD`, number: `901`, }, }, `TAJIKISTAN`: { { countries: Countries{`TAJIKISTAN`}, currency: `Somoni`, code: `TJS`, number: `972`, }, }, `TANZANIA, UNITED REPUBLIC OF`: { { countries: Countries{`TANZANIA, UNITED REPUBLIC OF`}, currency: `Tanzanian Shilling`, code: `TZS`, number: `834`, }, }, `THAILAND`: { { countries: Countries{`THAILAND`}, currency: `Baht`, code: `THB`, number: `764`, }, }, `TIMOR-LESTE`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `TOGO`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `TOKELAU`: { { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, }, `TONGA`: { { countries: Countries{`TONGA`}, currency: `Pa’anga`, code: `TOP`, number: `776`, }, }, `TRINIDAD AND TOBAGO`: { { countries: Countries{`TRINIDAD AND TOBAGO`}, currency: `Trinidad and Tobago Dollar`, code: `TTD`, number: `780`, }, }, `TUNISIA`: { { countries: Countries{`TUNISIA`}, currency: `Tunisian Dinar`, code: `TND`, number: `788`, }, }, `TURKEY`: { { countries: Countries{`TURKEY`}, currency: `Turkish Lira`, code: `TRY`, number: `949`, }, }, `TURKMENISTAN`: { { countries: Countries{`TURKMENISTAN`}, currency: `Turkmenistan New Manat`, code: `TMT`, number: `934`, }, }, `TURKS AND CAICOS ISLANDS (THE)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `TUVALU`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `UGANDA`: { { countries: Countries{`UGANDA`}, currency: `Uganda Shilling`, code: `UGX`, number: `800`, }, }, `UKRAINE`: { { countries: Countries{`UKRAINE`}, currency: `Hryvnia`, code: `UAH`, number: `980`, }, }, `UNITED ARAB EMIRATES (THE)`: { { countries: Countries{`UNITED ARAB EMIRATES (THE)`, `UNITED ARAB EMIRATES`}, currency: `UAE Dirham`, code: `AED`, number: `784`, }, }, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`: { { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, }, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `UNITED STATES OF AMERICA (THE)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, { countries: Countries{`UNITED STATES OF AMERICA (THE)`, `UNITED STATES OF AMERICA`}, currency: `US Dollar (Next day)`, code: `USN`, number: `997`, }, }, `URUGUAY`: { { countries: Countries{`URUGUAY`}, currency: `Peso Uruguayo`, code: `UYU`, number: `858`, }, { countries: Countries{`URUGUAY`}, currency: `Uruguay Peso en Unidades Indexadas (UI)`, code: `UYI`, number: `940`, }, { countries: Countries{`URUGUAY`}, currency: `Unidad Previsional`, code: `UYW`, number: `927`, }, }, `UZBEKISTAN`: { { countries: Countries{`UZBEKISTAN`}, currency: `Uzbekistan Sum`, code: `UZS`, number: `860`, }, }, `VANUATU`: { { countries: Countries{`VANUATU`}, currency: `Vatu`, code: `VUV`, number: `548`, }, }, `VENEZUELA (BOLIVARIAN REPUBLIC OF)`: { { countries: Countries{`VENEZUELA (BOLIVARIAN REPUBLIC OF)`, `VENEZUELA`}, currency: `Bolívar Soberano`, code: `VES`, number: `928`, }, }, `VIET NAM`: { { countries: Countries{`VIET NAM`}, currency: `Dong`, code: `VND`, number: `704`, }, }, `VIRGIN ISLANDS (BRITISH)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `VIRGIN ISLANDS (U.S.)`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `WALLIS AND FUTUNA`: { { countries: Countries{`FRENCH POLYNESIA`, `NEW CALEDONIA`, `WALLIS AND FUTUNA`}, currency: `CFP Franc`, code: `XPF`, number: `953`, }, }, `WESTERN SAHARA`: { { countries: Countries{`MOROCCO`, `WESTERN SAHARA`}, currency: `Moroccan Dirham`, code: `MAD`, number: `504`, }, }, `YEMEN`: { { countries: Countries{`YEMEN`}, currency: `Yemeni Rial`, code: `YER`, number: `886`, }, }, `ZAMBIA`: { { countries: Countries{`ZAMBIA`}, currency: `Zambian Kwacha`, code: `ZMW`, number: `967`, }, }, `ZIMBABWE`: { { countries: Countries{`ZIMBABWE`}, currency: `Zimbabwe Dollar`, code: `ZWL`, number: `932`, }, }, `BAHAMAS`: { { countries: Countries{`BAHAMAS (THE)`, `BAHAMAS`}, currency: `Bahamian Dollar`, code: `BSD`, number: `044`, }, }, `BOLIVIA`: { { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Boliviano`, code: `BOB`, number: `068`, }, { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Mvdol`, code: `BOV`, number: `984`, }, }, `BRITISH INDIAN OCEAN TERRITORY`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `CAYMAN ISLANDS`: { { countries: Countries{`CAYMAN ISLANDS (THE)`, `CAYMAN ISLANDS`}, currency: `Cayman Islands Dollar`, code: `KYD`, number: `136`, }, }, `CENTRAL AFRICAN REPUBLIC`: { { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `COCOS ISLANDS`: { { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, }, `COMOROS`: { { countries: Countries{`COMOROS (THE)`, `COMOROS`}, currency: `Comorian Franc `, code: `KMF`, number: `174`, }, }, `CONGO`: { { countries: Countries{`CONGO (THE DEMOCRATIC REPUBLIC OF THE)`, `CONGO`}, currency: `Congolese Franc`, code: `CDF`, number: `976`, }, { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, }, `COOK ISLANDS`: { { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, }, `DOMINICAN REPUBLIC`: { { countries: Countries{`DOMINICAN REPUBLIC (THE)`, `DOMINICAN REPUBLIC`}, currency: `Dominican Peso`, code: `DOP`, number: `214`, }, }, `FALKLAND ISLANDS [MALVINAS]`: { { countries: Countries{`FALKLAND ISLANDS (THE) [MALVINAS]`, `FALKLAND ISLANDS [MALVINAS]`}, currency: `Falkland Islands Pound`, code: `FKP`, number: `238`, }, }, `FAROE ISLANDS`: { { countries: Countries{`DENMARK`, `FAROE ISLANDS (THE)`, `GREENLAND`, `FAROE ISLANDS`}, currency: `Danish Krone`, code: `DKK`, number: `208`, }, }, `FRENCH SOUTHERN TERRITORIES`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `<NAME>`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `GAMBIA`: { { countries: Countries{`GAMBIA (THE)`, `GAMBIA`}, currency: `Dalasi`, code: `GMD`, number: `270`, }, }, `HOLY SEE`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PI<NAME>`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `INTERNATIONAL MONETARY FUND `: { { countries: Countries{`INTERNATIONAL MONETARY FUND (IMF) `, `INTERNATIONAL MONETARY FUND `}, currency: `SDR (Special Drawing Right)`, code: `XDR`, number: `960`, }, }, `IRAN`: { { countries: Countries{`IRAN (ISLAMIC REPUBLIC OF)`, `IRAN`}, currency: `Iranian Rial`, code: `IRR`, number: `364`, }, }, `KOREA`: { { countries: Countries{`KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)`, `KOREA`}, currency: `North Korean Won`, code: `KPW`, number: `408`, }, { countries: Countries{`KOREA (THE REPUBLIC OF)`, `KOREA`}, currency: `Won`, code: `KRW`, number: `410`, }, }, `LAO PEOPLE’S DEMOCRATIC REPUBLIC`: { { countries: Countries{`LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)`, `LAO PEOPLE’S DEMOCRATIC REPUBLIC`}, currency: `Lao Kip`, code: `LAK`, number: `418`, }, }, `MARSHALL ISLANDS`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `MICRONESIA`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `MOLDOVA`: { { countries: Countries{`MOLDOVA (THE REPUBLIC OF)`, `MOLDOVA`}, currency: `Moldovan Leu`, code: `MDL`, number: `498`, }, }, `NETHERLANDS`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `NIGER`: { { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, }, `NORTHERN MARIANA ISLANDS`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `PHILIPPINES`: { { countries: Countries{`PHILIPPINES (THE)`, `PHILIPPINES`}, currency: `Philippine Peso`, code: `PHP`, number: `608`, }, }, `RUSSIAN FEDERATION`: { { countries: Countries{`RUSSIAN FEDERATION (THE)`, `RUSSIAN FEDERATION`}, currency: `Russian Ruble`, code: `RUB`, number: `643`, }, }, `SAINT MARTIN`: { { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, }, `SINT MAARTEN`: { { countries: Countries{`CURAÇAO`, `SINT MAARTEN (DUTCH PART)`, `SINT MAARTEN`}, currency: `Netherlands Antillean Guilder`, code: `ANG`, number: `532`, }, }, `SUDAN`: { { countries: Countries{`SUDAN (THE)`, `SUDAN`}, currency: `Sudanese Pound`, code: `SDG`, number: `938`, }, }, `TAIWAN`: { { countries: Countries{`TAIWAN (PROVINCE OF CHINA)`, `TAIWAN`}, currency: `New Taiwan Dollar`, code: `TWD`, number: `901`, }, }, `TURKS AND CAICOS ISLANDS`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `UNITED ARAB EMIRATES`: { { countries: Countries{`UNITED ARAB EMIRATES (THE)`, `UNITED ARAB EMIRATES`}, currency: `UAE Dirham`, code: `AED`, number: `784`, }, }, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`: { { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, }, `UNITED STATES MINOR OUTLYING ISLANDS`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, `UNITED STATES OF AMERICA`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, { countries: Countries{`UNITED STATES OF AMERICA (THE)`, `UNITED STATES OF AMERICA`}, currency: `US Dollar (Next day)`, code: `USN`, number: `997`, }, }, `VENEZUELA`: { { countries: Countries{`VENEZUELA (BOLIVARIAN REPUBLIC OF)`, `VENEZUELA`}, currency: `Bolívar Soberano`, code: `VES`, number: `928`, }, }, `VIRGIN ISLANDS`: { { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, }, } var currenciesByCurrency = map[string]currency{ `Afghani`: { countries: Countries{`AFGHANISTAN`}, currency: `Afghani`, code: `AFN`, number: `971`, }, `Euro`: { countries: Countries{`ÅLAND ISLANDS`, `ANDORRA`, `AUSTRIA`, `BELGIUM`, `CYPRUS`, `ESTONIA`, `EUROPEAN UNION`, `FINLAND`, `FRANCE`, `FRENCH GUIANA`, `FRENCH SOUTHERN TERRITORIES (THE)`, `GERMANY`, `GREECE`, `GUADELOUPE`, `HOLY SEE (THE)`, `IRELAND`, `ITALY`, `LATVIA`, `LITHUANIA`, `LUXEMBOURG`, `MALTA`, `MARTINIQUE`, `MAYOTTE`, `MONACO`, `MONTENEGRO`, `NETHERLANDS (THE)`, `PORTUGAL`, `RÉUNION`, `SAINT BARTHÉLEMY`, `SAINT MARTIN (FRENCH PART)`, `SAINT PIERRE AND MIQUELON`, `SAN MARINO`, `SLOVAKIA`, `SLOVENIA`, `SPAIN`, `FRENCH SOUTHERN TERRITORIES`, `HOLY SEE`, `NETHERLANDS`, `SAINT MARTIN`}, currency: `Euro`, code: `EUR`, number: `978`, }, `Lek`: { countries: Countries{`ALBANIA`}, currency: `Lek`, code: `ALL`, number: `008`, }, `Algerian Dinar`: { countries: Countries{`ALGERIA`}, currency: `Algerian Dinar`, code: `DZD`, number: `012`, }, `US Dollar`: { countries: Countries{`AMERICAN SAMOA`, `BONAIRE, SINT EUSTATIUS AND SABA`, `BRITISH INDIAN OCEAN TERRITORY (THE)`, `ECUADOR`, `EL SALVADOR`, `GUAM`, `HAITI`, `MARSHALL ISLANDS (THE)`, `MICRONESIA (FEDERATED STATES OF)`, `NORTHERN MARIANA ISLANDS (THE)`, `PALAU`, `PANAMA`, `PUERTO RICO`, `TIMOR-LESTE`, `TURKS AND CAICOS ISLANDS (THE)`, `UNITED STATES MINOR OUTLYING ISLANDS (THE)`, `UNITED STATES OF AMERICA (THE)`, `VIRGIN ISLANDS (BRITISH)`, `VIRGIN ISLANDS (U.S.)`, `BRITISH INDIAN OCEAN TERRITORY`, `MARSHALL ISLANDS`, `MICRONESIA`, `NORTHERN MARIANA ISLANDS`, `TURKS AND CAICOS ISLANDS`, `UNITED STATES MINOR OUTLYING ISLANDS`, `UNITED STATES OF AMERICA`, `VIRGIN ISLANDS`, `VIRGIN ISLANDS`}, currency: `US Dollar`, code: `USD`, number: `840`, }, `Kwanza`: { countries: Countries{`ANGOLA`}, currency: `Kwanza`, code: `AOA`, number: `973`, }, `East Caribbean Dollar`: { countries: Countries{`ANGUILLA`, `ANTIGUA AND BARBUDA`, `DOMINICA`, `GRENADA`, `MONTSERRAT`, `SAINT KITTS AND NEVIS`, `SAINT LUCIA`, `SAINT VINCENT AND THE GRENADINES`}, currency: `East Caribbean Dollar`, code: `XCD`, number: `951`, }, `Argentine Peso`: { countries: Countries{`ARGENTINA`}, currency: `Argentine Peso`, code: `ARS`, number: `032`, }, `Armenian Dram`: { countries: Countries{`ARMENIA`}, currency: `Armenian Dram`, code: `AMD`, number: `051`, }, `Aruban Florin`: { countries: Countries{`ARUBA`}, currency: `Aruban Florin`, code: `AWG`, number: `533`, }, `Australian Dollar`: { countries: Countries{`AUSTRALIA`, `CHRISTMAS ISLAND`, `COCOS (KEELING) ISLANDS (THE)`, `HEARD ISLAND AND McDONALD ISLANDS`, `KIRIBATI`, `NAURU`, `NORFOLK ISLAND`, `TUVALU`, `COCOS ISLANDS`}, currency: `Australian Dollar`, code: `AUD`, number: `036`, }, `Azerbaijan Manat`: { countries: Countries{`AZERBAIJAN`}, currency: `Azerbaijan Manat`, code: `AZN`, number: `944`, }, `Bahamian Dollar`: { countries: Countries{`BAHAMAS (THE)`, `BAHAMAS`}, currency: `Bahamian Dollar`, code: `BSD`, number: `044`, }, `Bahraini Dinar`: { countries: Countries{`BAHRAIN`}, currency: `Bahraini Dinar`, code: `BHD`, number: `048`, }, `Taka`: { countries: Countries{`BANGLADESH`}, currency: `Taka`, code: `BDT`, number: `050`, }, `Barbados Dollar`: { countries: Countries{`BARBADOS`}, currency: `Barbados Dollar`, code: `BBD`, number: `052`, }, `Belarusian Ruble`: { countries: Countries{`BELARUS`}, currency: `Belarusian Ruble`, code: `BYN`, number: `933`, }, `Belize Dollar`: { countries: Countries{`BELIZE`}, currency: `Belize Dollar`, code: `BZD`, number: `084`, }, `CFA Franc BCEAO`: { countries: Countries{`BENIN`, `BURKINA FASO`, `CÔTE D'IVOIRE`, `GUINEA-BISSAU`, `MALI`, `NIGER (THE)`, `SENEGAL`, `TOGO`, `NIGER`}, currency: `CFA Franc BCEAO`, code: `XOF`, number: `952`, }, `Bermudian Dollar`: { countries: Countries{`BERMUDA`}, currency: `Bermudian Dollar`, code: `BMD`, number: `060`, }, `Indian Rupee`: { countries: Countries{`BHUTAN`, `INDIA`}, currency: `Indian Rupee`, code: `INR`, number: `356`, }, `Ngultrum`: { countries: Countries{`BHUTAN`}, currency: `Ngultrum`, code: `BTN`, number: `064`, }, `Boliviano`: { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Boliviano`, code: `BOB`, number: `068`, }, `Mvdol`: { countries: Countries{`BOLIVIA (PLURINATIONAL STATE OF)`, `BOLIVIA`}, currency: `Mvdol`, code: `BOV`, number: `984`, }, `Convertible Mark`: { countries: Countries{`BOSNIA AND HERZEGOVINA`}, currency: `Convertible Mark`, code: `BAM`, number: `977`, }, `Pula`: { countries: Countries{`BOTSWANA`}, currency: `Pula`, code: `BWP`, number: `072`, }, `Norwegian Krone`: { countries: Countries{`BOUVET ISLAND`, `NORWAY`, `SVALBARD AND JAN MAYEN`}, currency: `Norwegian Krone`, code: `NOK`, number: `578`, }, `Brazilian Real`: { countries: Countries{`BRAZIL`}, currency: `Brazilian Real`, code: `BRL`, number: `986`, }, `Brunei Dollar`: { countries: Countries{`BRUNEI DARUSSALAM`}, currency: `Brunei Dollar`, code: `BND`, number: `096`, }, `Bulgarian Lev`: { countries: Countries{`BULGARIA`}, currency: `Bulgarian Lev`, code: `BGN`, number: `975`, }, `Burundi Franc`: { countries: Countries{`BURUNDI`}, currency: `Burundi Franc`, code: `BIF`, number: `108`, }, `Cab<NAME>`: { countries: Countries{`CABO VERDE`}, currency: `Cabo Verde Escudo`, code: `CVE`, number: `132`, }, `Riel`: { countries: Countries{`CAMBODIA`}, currency: `Riel`, code: `KHR`, number: `116`, }, `CFA Franc BEAC`: { countries: Countries{`CAMEROON`, `CENTRAL AFRICAN REPUBLIC (THE)`, `CHAD`, `CONGO (THE)`, `EQUATORIAL GUINEA`, `GABON`, `CENTRAL AFRICAN REPUBLIC`, `CONGO`}, currency: `CFA Franc BEAC`, code: `XAF`, number: `950`, }, `Canadian Dollar`: { countries: Countries{`CANADA`}, currency: `Canadian Dollar`, code: `CAD`, number: `124`, }, `Cayman Islands Dollar`: { countries: Countries{`CAYMAN ISLANDS (THE)`, `CAYMAN ISLANDS`}, currency: `Cayman Islands Dollar`, code: `KYD`, number: `136`, }, `Chilean Peso`: { countries: Countries{`CHILE`}, currency: `Chilean Peso`, code: `CLP`, number: `152`, }, `Unidad de Fomento`: { countries: Countries{`CHILE`}, currency: `Unidad de Fomento`, code: `CLF`, number: `990`, }, `Yuan Renminbi`: { countries: Countries{`CHINA`}, currency: `Yuan Renminbi`, code: `CNY`, number: `156`, }, `Colombian Peso`: { countries: Countries{`COLOMBIA`}, currency: `Colombian Peso`, code: `COP`, number: `170`, }, `Unidad de Valor Real`: { countries: Countries{`COLOMBIA`}, currency: `Unidad de Valor Real`, code: `COU`, number: `970`, }, `Comorian Franc `: { countries: Countries{`COMOROS (THE)`, `COMOROS`}, currency: `Comorian Franc `, code: `KMF`, number: `174`, }, `Congolese Franc`: { countries: Countries{`CONGO (THE DEMOCRATIC REPUBLIC OF THE)`, `CONGO`}, currency: `Congolese Franc`, code: `CDF`, number: `976`, }, `New Zealand Dollar`: { countries: Countries{`COOK ISLANDS (THE)`, `NEW ZEALAND`, `NIUE`, `PITCAIRN`, `TOKELAU`, `COOK ISLANDS`}, currency: `New Zealand Dollar`, code: `NZD`, number: `554`, }, `Costa Rican Colon`: { countries: Countries{`COSTA RICA`}, currency: `Costa Rican Colon`, code: `CRC`, number: `188`, }, `Kuna`: { countries: Countries{`CROATIA`}, currency: `Kuna`, code: `HRK`, number: `191`, }, `Cuban Peso`: { countries: Countries{`CUBA`}, currency: `Cuban Peso`, code: `CUP`, number: `192`, }, `Peso Convertible`: { countries: Countries{`CUBA`}, currency: `Peso Convertible`, code: `CUC`, number: `931`, }, `Netherlands Antillean Guilder`: { countries: Countries{`CURAÇAO`, `SINT MAARTEN (DUTCH PART)`, `SINT MAARTEN`}, currency: `Netherlands Antillean Guilder`, code: `ANG`, number: `532`, }, `Czech Koruna`: { countries: Countries{`CZECHIA`}, currency: `Czech Koruna`, code: `CZK`, number: `203`, }, `Danish Krone`: { countries: Countries{`DENMARK`, `FAROE ISLANDS (THE)`, `GREENLAND`, `FAROE ISLANDS`}, currency: `Danish Krone`, code: `DKK`, number: `208`, }, `Djibouti Franc`: { countries: Countries{`DJIBOUTI`}, currency: `Djibouti Franc`, code: `DJF`, number: `262`, }, `Dominican Peso`: { countries: Countries{`DOMINICAN REPUBLIC (THE)`, `DOMINICAN REPUBLIC`}, currency: `Dominican Peso`, code: `DOP`, number: `214`, }, `Egyptian Pound`: { countries: Countries{`EGYPT`}, currency: `Egyptian Pound`, code: `EGP`, number: `818`, }, `El Salvador Colon`: { countries: Countries{`EL SALVADOR`}, currency: `El Salvador Colon`, code: `SVC`, number: `222`, }, `Nakfa`: { countries: Countries{`ERITREA`}, currency: `Nakfa`, code: `ERN`, number: `232`, }, `Lilangeni`: { countries: Countries{`ESWATINI`}, currency: `Lilangeni`, code: `SZL`, number: `748`, }, `Ethiopian Birr`: { countries: Countries{`ETHIOPIA`}, currency: `Ethiopian Birr`, code: `ETB`, number: `230`, }, `Falkland Islands Pound`: { countries: Countries{`FALKLAND ISLANDS (THE) [MALVINAS]`, `FALKLAND ISLANDS [MALVINAS]`}, currency: `Falkland Islands Pound`, code: `FKP`, number: `238`, }, `Fiji Dollar`: { countries: Countries{`FIJI`}, currency: `Fiji Dollar`, code: `FJD`, number: `242`, }, `CFP Franc`: { countries: Countries{`FRENCH POLYNESIA`, `NEW CALEDONIA`, `WALLIS AND FUTUNA`}, currency: `CFP Franc`, code: `XPF`, number: `953`, }, `Dalasi`: { countries: Countries{`GAMBIA (THE)`, `GAMBIA`}, currency: `Dalasi`, code: `GMD`, number: `270`, }, `Lari`: { countries: Countries{`GEORGIA`}, currency: `Lari`, code: `GEL`, number: `981`, }, `Ghana Cedi`: { countries: Countries{`GHANA`}, currency: `Ghana Cedi`, code: `GHS`, number: `936`, }, `Gibraltar Pound`: { countries: Countries{`GIBRALTAR`}, currency: `Gibraltar Pound`, code: `GIP`, number: `292`, }, `Quetzal`: { countries: Countries{`GUATEMALA`}, currency: `Quetzal`, code: `GTQ`, number: `320`, }, `Pound Sterling`: { countries: Countries{`GUERNSEY`, `ISLE OF MAN`, `JERSEY`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)`, `UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND`}, currency: `Pound Sterling`, code: `GBP`, number: `826`, }, `Guinean Franc`: { countries: Countries{`GUINEA`}, currency: `Guinean Franc`, code: `GNF`, number: `324`, }, `Guyana Dollar`: { countries: Countries{`GUYANA`}, currency: `Guyana Dollar`, code: `GYD`, number: `328`, }, `Gourde`: { countries: Countries{`HAITI`}, currency: `Gourde`, code: `HTG`, number: `332`, }, `Lempira`: { countries: Countries{`HONDURAS`}, currency: `Lempira`, code: `HNL`, number: `340`, }, `Hong Kong Dollar`: { countries: Countries{`HONG KONG`}, currency: `Hong Kong Dollar`, code: `HKD`, number: `344`, }, `Forint`: { countries: Countries{`HUNGARY`}, currency: `Forint`, code: `HUF`, number: `348`, }, `Iceland Krona`: { countries: Countries{`ICELAND`}, currency: `Iceland Krona`, code: `ISK`, number: `352`, }, `Rupiah`: { countries: Countries{`INDONESIA`}, currency: `Rupiah`, code: `IDR`, number: `360`, }, `SDR (Special Drawing Right)`: { countries: Countries{`INTERNATIONAL MONETARY FUND (IMF) `, `INTERNATIONAL MONETARY FUND `}, currency: `SDR (Special Drawing Right)`, code: `XDR`, number: `960`, }, `Iranian Rial`: { countries: Countries{`IRAN (ISLAMIC REPUBLIC OF)`, `IRAN`}, currency: `Iranian Rial`, code: `IRR`, number: `364`, }, `Iraqi Dinar`: { countries: Countries{`IRAQ`}, currency: `Iraqi Dinar`, code: `IQD`, number: `368`, }, `New Israeli Sheqel`: { countries: Countries{`ISRAEL`}, currency: `New Israeli Sheqel`, code: `ILS`, number: `376`, }, `Jamaican Dollar`: { countries: Countries{`JAMAICA`}, currency: `Jamaican Dollar`, code: `JMD`, number: `388`, }, `Yen`: { countries: Countries{`JAPAN`}, currency: `Yen`, code: `JPY`, number: `392`, }, `Jordanian Dinar`: { countries: Countries{`JORDAN`}, currency: `Jordanian Dinar`, code: `JOD`, number: `400`, }, `Tenge`: { countries: Countries{`KAZAKHSTAN`}, currency: `Tenge`, code: `KZT`, number: `398`, }, `Kenyan Shilling`: { countries: Countries{`KENYA`}, currency: `Kenyan Shilling`, code: `KES`, number: `404`, }, `North Korean Won`: { countries: Countries{`KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)`, `KOREA`}, currency: `North Korean Won`, code: `KPW`, number: `408`, }, `Won`: { countries: Countries{`KOREA (THE REPUBLIC OF)`, `KOREA`}, currency: `Won`, code: `KRW`, number: `410`, }, `Kuwaiti Dinar`: { countries: Countries{`KUWAIT`}, currency: `Kuwaiti Dinar`, code: `KWD`, number: `414`, }, `Som`: { countries: Countries{`KYRGYZSTAN`}, currency: `Som`, code: `KGS`, number: `417`, }, `Lao Kip`: { countries: Countries{`LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)`, `LAO PEOPLE’S DEMOCRATIC REPUBLIC`}, currency: `Lao Kip`, code: `LAK`, number: `418`, }, `Lebanese Pound`: { countries: Countries{`LEBANON`}, currency: `Lebanese Pound`, code: `LBP`, number: `422`, }, `Loti`: { countries: Countries{`LESOTHO`}, currency: `Loti`, code: `LSL`, number: `426`, }, `Rand`: { countries: Countries{`LESOTHO`, `NAMIBIA`, `SOUTH AFRICA`}, currency: `Rand`, code: `ZAR`, number: `710`, }, `Liberian Dollar`: { countries: Countries{`LIBERIA`}, currency: `Liberian Dollar`, code: `LRD`, number: `430`, }, `Libyan Dinar`: { countries: Countries{`LIBYA`}, currency: `Libyan Dinar`, code: `LYD`, number: `434`, }, `Swiss Franc`: { countries: Countries{`LIECHTENSTEIN`, `SWITZERLAND`}, currency: `Swiss Franc`, code: `CHF`, number: `756`, }, `Pataca`: { countries: Countries{`MACAO`}, currency: `Pataca`, code: `MOP`, number: `446`, }, `Denar`: { countries: Countries{`NORTH MACEDONIA`}, currency: `Denar`, code: `MKD`, number: `807`, }, `Malagasy Ariary`: { countries: Countries{`MADAGASCAR`}, currency: `Malagasy Ariary`, code: `MGA`, number: `969`, }, `Malawi Kwacha`: { countries: Countries{`MALAWI`}, currency: `Malawi Kwacha`, code: `MWK`, number: `454`, }, `Malaysian Ringgit`: { countries: Countries{`MALAYSIA`}, currency: `Malaysian Ringgit`, code: `MYR`, number: `458`, }, `Rufiyaa`: { countries: Countries{`MALDIVES`}, currency: `Rufiyaa`, code: `MVR`, number: `462`, }, `Ouguiya`: { countries: Countries{`MAURITANIA`}, currency: `Ouguiya`, code: `MRU`, number: `929`, }, `Mauritius Rupee`: { countries: Countries{`MAURITIUS`}, currency: `Mauritius Rupee`, code: `MUR`, number: `480`, }, `ADB Unit of Account`: { countries: Countries{`MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP`}, currency: `ADB Unit of Account`, code: `XUA`, number: `965`, }, `Mexican Peso`: { countries: Countries{`MEXICO`}, currency: `Mexican Peso`, code: `MXN`, number: `484`, }, `Mexican Unidad de Inversion (UDI)`: { countries: Countries{`MEXICO`}, currency: `Mexican Unidad de Inversion (UDI)`, code: `MXV`, number: `979`, }, `<NAME>`: { countries: Countries{`MOLDOVA (THE REPUBLIC OF)`, `MOLDOVA`}, currency: `Moldovan Leu`, code: `MDL`, number: `498`, }, `Tugrik`: { countries: Countries{`MONGOLIA`}, currency: `Tugrik`, code: `MNT`, number: `496`, }, `<NAME>`: { countries: Countries{`MOROCCO`, `WESTERN SAHARA`}, currency: `Moroccan Dirham`, code: `MAD`, number: `504`, }, `Mozambique Metical`: { countries: Countries{`MOZAMBIQUE`}, currency: `Mozambique Metical`, code: `MZN`, number: `943`, }, `Kyat`: { countries: Countries{`MYANMAR`}, currency: `Kyat`, code: `MMK`, number: `104`, }, `Namibia Dollar`: { countries: Countries{`NAMIBIA`}, currency: `Namibia Dollar`, code: `NAD`, number: `516`, }, `Nepalese Rupee`: { countries: Countries{`NEPAL`}, currency: `Nepalese Rupee`, code: `NPR`, number: `524`, }, `Cordoba Oro`: { countries: Countries{`NICARAGUA`}, currency: `Cordoba Oro`, code: `NIO`, number: `558`, }, `Naira`: { countries: Countries{`NIGERIA`}, currency: `Naira`, code: `NGN`, number: `566`, }, `Rial Omani`: { countries: Countries{`OMAN`}, currency: `Rial Omani`, code: `OMR`, number: `512`, }, `Pakistan Rupee`: { countries: Countries{`PAKISTAN`}, currency: `Pakistan Rupee`, code: `PKR`, number: `586`, }, `Balboa`: { countries: Countries{`PANAMA`}, currency: `Balboa`, code: `PAB`, number: `590`, }, `Kina`: { countries: Countries{`PAPUA NEW GUINEA`}, currency: `Kina`, code: `PGK`, number: `598`, }, `Guarani`: { countries: Countries{`PARAGUAY`}, currency: `Guarani`, code: `PYG`, number: `600`, }, `Sol`: { countries: Countries{`PERU`}, currency: `Sol`, code: `PEN`, number: `604`, }, `Philippine Peso`: { countries: Countries{`PHILIPPINES (THE)`, `PHILIPPINES`}, currency: `Philippine Peso`, code: `PHP`, number: `608`, }, `Zloty`: { countries: Countries{`POLAND`}, currency: `Zloty`, code: `PLN`, number: `985`, }, `Qatari Rial`: { countries: Countries{`QATAR`}, currency: `Qatari Rial`, code: `QAR`, number: `634`, }, `Romanian Leu`: { countries: Countries{`ROMANIA`}, currency: `Romanian Leu`, code: `RON`, number: `946`, }, `Russian Ruble`: { countries: Countries{`RUSSIAN FEDERATION (THE)`, `RUSSIAN FEDERATION`}, currency: `Russian Ruble`, code: `RUB`, number: `643`, }, `Rwanda Franc`: { countries: Countries{`RWANDA`}, currency: `Rwanda Franc`, code: `RWF`, number: `646`, }, `Saint Helena Pound`: { countries: Countries{`SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA`}, currency: `Saint Helena Pound`, code: `SHP`, number: `654`, }, `Tala`: { countries: Countries{`SAMOA`}, currency: `Tala`, code: `WST`, number: `882`, }, `Dobra`: { countries: Countries{`SAO TOME AND PRINCIPE`}, currency: `Dobra`, code: `STN`, number: `930`, }, `Saudi Riyal`: { countries: Countries{`SAUDI ARABIA`}, currency: `Saudi Riyal`, code: `SAR`, number: `682`, }, `Serbian Dinar`: { countries: Countries{`SERBIA`}, currency: `Serbian Dinar`, code: `RSD`, number: `941`, }, `Seychelles Rupee`: { countries: Countries{`SEYCHELLES`}, currency: `Seychelles Rupee`, code: `SCR`, number: `690`, }, `Leone`: { countries: Countries{`SIERRA LEONE`}, currency: `Leone`, code: `SLL`, number: `694`, }, `Singapore Dollar`: { countries: Countries{`SINGAPORE`}, currency: `Singapore Dollar`, code: `SGD`, number: `702`, }, `Sucre`: { countries: Countries{`SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"`}, currency: `Sucre`, code: `XSU`, number: `994`, }, `Solomon Islands Dollar`: { countries: Countries{`SOLOMON ISLANDS`}, currency: `Solomon Islands Dollar`, code: `SBD`, number: `090`, }, `Somali Shilling`: { countries: Countries{`SOMALIA`}, currency: `Somali Shilling`, code: `SOS`, number: `706`, }, `South Sudanese Pound`: { countries: Countries{`SOUTH SUDAN`}, currency: `South Sudanese Pound`, code: `SSP`, number: `728`, }, `Sri Lanka Rupee`: { countries: Countries{`SRI LANKA`}, currency: `Sri Lanka Rupee`, code: `LKR`, number: `144`, }, `Sudanese Pound`: { countries: Countries{`SUDAN (THE)`, `SUDAN`}, currency: `Sudanese Pound`, code: `SDG`, number: `938`, }, `Surinam Dollar`: { countries: Countries{`SURINAME`}, currency: `Surinam Dollar`, code: `SRD`, number: `968`, }, `Swedish Krona`: { countries: Countries{`SWEDEN`}, currency: `Swedish Krona`, code: `SEK`, number: `752`, }, `WIR Euro`: { countries: Countries{`SWITZERLAND`}, currency: `WIR Euro`, code: `CHE`, number: `947`, }, `WIR Franc`: { countries: Countries{`SWITZERLAND`}, currency: `WIR Franc`, code: `CHW`, number: `948`, }, `Syrian Pound`: { countries: Countries{`SYRIAN ARAB REPUBLIC`}, currency: `Syrian Pound`, code: `SYP`, number: `760`, }, `New Taiwan Dollar`: { countries: Countries{`TAIWAN (PROVINCE OF CHINA)`, `TAIWAN`}, currency: `New Taiwan Dollar`, code: `TWD`, number: `901`, }, `Somoni`: { countries: Countries{`TAJIKISTAN`}, currency: `Somoni`, code: `TJS`, number: `972`, }, `Tanzanian Shilling`: { countries: Countries{`TANZANIA, UNITED REPUBLIC OF`}, currency: `Tanzanian Shilling`, code: `TZS`, number: `834`, }, `Baht`: { countries: Countries{`THAILAND`}, currency: `Baht`, code: `THB`, number: `764`, }, `Pa’anga`: { countries: Countries{`TONGA`}, currency: `Pa’anga`, code: `TOP`, number: `776`, }, `Trinidad and Tobago Dollar`: { countries: Countries{`TRINIDAD AND TOBAGO`}, currency: `Trinidad and Tobago Dollar`, code: `TTD`, number: `780`, }, `Tunisian Dinar`: { countries: Countries{`TUNISIA`}, currency: `Tunisian Dinar`, code: `TND`, number: `788`, }, `Turkish Lira`: { countries: Countries{`TURKEY`}, currency: `Turkish Lira`, code: `TRY`, number: `949`, }, `Turkmenistan New Manat`: { countries: Countries{`TURKMENISTAN`}, currency: `Turkmenistan New Manat`, code: `TMT`, number: `934`, }, `Uganda Shilling`: { countries: Countries{`UGANDA`}, currency: `Uganda Shilling`, code: `UGX`, number: `800`, }, `Hryvnia`: { countries: Countries{`UKRAINE`}, currency: `Hryvnia`, code: `UAH`, number: `980`, }, `UAE Dirham`: { countries: Countries{`UNITED ARAB EMIRATES (THE)`, `UNITED ARAB EMIRATES`}, currency: `UAE Dirham`, code: `AED`, number: `784`, }, `US Dollar (Next day)`: { countries: Countries{`UNITED STATES OF AMERICA (THE)`, `UNITED STATES OF AMERICA`}, currency: `US Dollar (Next day)`, code: `USN`, number: `997`, }, `Peso Uruguayo`: { countries: Countries{`URUGUAY`}, currency: `Peso Uruguayo`, code: `UYU`, number: `858`, }, `Uruguay Peso en Unidades Indexadas (UI)`: { countries: Countries{`URUGUAY`}, currency: `Uruguay Peso en Unidades Indexadas (UI)`, code: `UYI`, number: `940`, }, `Unidad Previsional`: { countries: Countries{`URUGUAY`}, currency: `Unidad Previsional`, code: `UYW`, number: `927`, }, `Uzbekistan Sum`: { countries: Countries{`UZBEKISTAN`}, currency: `Uzbekistan Sum`, code: `UZS`, number: `860`, }, `Vatu`: { countries: Countries{`VANUATU`}, currency: `Vatu`, code: `VUV`, number: `548`, }, `Bolívar Soberano`: { countries: Countries{`VENEZUELA (BOLIVARIAN REPUBLIC OF)`, `VENEZUELA`}, currency: `Bolívar Soberano`, code: `VES`, number: `928`, }, `Dong`: { countries: Countries{`VIET NAM`}, currency: `Dong`, code: `VND`, number: `704`, }, `Yemeni Rial`: { countries: Countries{`YEMEN`}, currency: `Yemeni Rial`, code: `YER`, number: `886`, }, `Zambian Kwacha`: { countries: Countries{`ZAMBIA`}, currency: `Zambian Kwacha`, code: `ZMW`, number: `967`, }, `Zimbabwe Dollar`: { countries: Countries{`ZIMBABWE`}, currency: `Zimbabwe Dollar`, code: `ZWL`, number: `932`, }, }
currency_gen.go
0.68056
0.45423
currency_gen.go
starcoder
package go2linq // Reimplementing LINQ to Objects: Part 35 – Zip // https://codeblog.jonskeet.uk/2011/01/14/reimplementing-linq-to-objects-part-35-zip/ // https://docs.microsoft.com/dotnet/api/system.linq.enumerable.zip // Zip applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. // 'first' and 'second' must not be based on the same Enumerator, otherwise use ZipSelf instead. func Zip[First, Second, Result any](first Enumerator[First], second Enumerator[Second], resultSelector func(First, Second) Result) (Enumerator[Result], error) { if first == nil || second == nil { return nil, ErrNilSource } if resultSelector == nil { return nil, ErrNilSelector } return OnFunc[Result]{ mvNxt: func() bool { if first.MoveNext() && second.MoveNext() { return true } return false }, crrnt: func() Result { return resultSelector(first.Current(), second.Current()) }, rst: func() { first.Reset(); second.Reset() }, }, nil } // ZipMust is like Zip but panics in case of error. func ZipMust[First, Second, Result any](first Enumerator[First], second Enumerator[Second], resultSelector func(First, Second) Result) Enumerator[Result] { r, err := Zip(first, second, resultSelector) if err != nil { panic(err) } return r } // ZipSelf applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. // 'first' and 'second' may be based on the same Enumerator. // 'first' must have real Reset method. 'second' is enumerated immediately. // (See Test_ZipSelf for examples.) func ZipSelf[First, Second, Result any](first Enumerator[First], second Enumerator[Second], resultSelector func(First, Second) Result) (Enumerator[Result], error) { if first == nil || second == nil { return nil, ErrNilSource } if resultSelector == nil { return nil, ErrNilSelector } sl2 := Slice(second) first.Reset() return Zip(first, NewOnSliceEn(sl2...), resultSelector) } // ZipSelfMust is like ZipSelf but panics in case of error. func ZipSelfMust[First, Second, Result any](first Enumerator[First], second Enumerator[Second], resultSelector func(First, Second) Result) Enumerator[Result] { r, err := ZipSelf(first, second, resultSelector) if err != nil { panic(err) } return r }
zip.go
0.759761
0.466906
zip.go
starcoder
package onshape import ( "encoding/json" ) // BTPlaneDescription692AllOf struct for BTPlaneDescription692AllOf type BTPlaneDescription692AllOf struct { BtType *string `json:"btType,omitempty"` IsOrientedWithFace *bool `json:"isOrientedWithFace,omitempty"` Normal *BTVector3d389 `json:"normal,omitempty"` Origin *BTVector3d389 `json:"origin,omitempty"` } // NewBTPlaneDescription692AllOf instantiates a new BTPlaneDescription692AllOf 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 NewBTPlaneDescription692AllOf() *BTPlaneDescription692AllOf { this := BTPlaneDescription692AllOf{} return &this } // NewBTPlaneDescription692AllOfWithDefaults instantiates a new BTPlaneDescription692AllOf 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 NewBTPlaneDescription692AllOfWithDefaults() *BTPlaneDescription692AllOf { this := BTPlaneDescription692AllOf{} return &this } // GetBtType returns the BtType field value if set, zero value otherwise. func (o *BTPlaneDescription692AllOf) GetBtType() string { if o == nil || o.BtType == nil { var ret string return ret } return *o.BtType } // GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPlaneDescription692AllOf) GetBtTypeOk() (*string, bool) { if o == nil || o.BtType == nil { return nil, false } return o.BtType, true } // HasBtType returns a boolean if a field has been set. func (o *BTPlaneDescription692AllOf) HasBtType() bool { if o != nil && o.BtType != nil { return true } return false } // SetBtType gets a reference to the given string and assigns it to the BtType field. func (o *BTPlaneDescription692AllOf) SetBtType(v string) { o.BtType = &v } // GetIsOrientedWithFace returns the IsOrientedWithFace field value if set, zero value otherwise. func (o *BTPlaneDescription692AllOf) GetIsOrientedWithFace() bool { if o == nil || o.IsOrientedWithFace == nil { var ret bool return ret } return *o.IsOrientedWithFace } // GetIsOrientedWithFaceOk returns a tuple with the IsOrientedWithFace field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPlaneDescription692AllOf) GetIsOrientedWithFaceOk() (*bool, bool) { if o == nil || o.IsOrientedWithFace == nil { return nil, false } return o.IsOrientedWithFace, true } // HasIsOrientedWithFace returns a boolean if a field has been set. func (o *BTPlaneDescription692AllOf) HasIsOrientedWithFace() bool { if o != nil && o.IsOrientedWithFace != nil { return true } return false } // SetIsOrientedWithFace gets a reference to the given bool and assigns it to the IsOrientedWithFace field. func (o *BTPlaneDescription692AllOf) SetIsOrientedWithFace(v bool) { o.IsOrientedWithFace = &v } // GetNormal returns the Normal field value if set, zero value otherwise. func (o *BTPlaneDescription692AllOf) GetNormal() BTVector3d389 { if o == nil || o.Normal == nil { var ret BTVector3d389 return ret } return *o.Normal } // GetNormalOk returns a tuple with the Normal field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPlaneDescription692AllOf) GetNormalOk() (*BTVector3d389, bool) { if o == nil || o.Normal == nil { return nil, false } return o.Normal, true } // HasNormal returns a boolean if a field has been set. func (o *BTPlaneDescription692AllOf) HasNormal() bool { if o != nil && o.Normal != nil { return true } return false } // SetNormal gets a reference to the given BTVector3d389 and assigns it to the Normal field. func (o *BTPlaneDescription692AllOf) SetNormal(v BTVector3d389) { o.Normal = &v } // GetOrigin returns the Origin field value if set, zero value otherwise. func (o *BTPlaneDescription692AllOf) GetOrigin() BTVector3d389 { if o == nil || o.Origin == nil { var ret BTVector3d389 return ret } return *o.Origin } // GetOriginOk returns a tuple with the Origin field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPlaneDescription692AllOf) GetOriginOk() (*BTVector3d389, bool) { if o == nil || o.Origin == nil { return nil, false } return o.Origin, true } // HasOrigin returns a boolean if a field has been set. func (o *BTPlaneDescription692AllOf) HasOrigin() bool { if o != nil && o.Origin != nil { return true } return false } // SetOrigin gets a reference to the given BTVector3d389 and assigns it to the Origin field. func (o *BTPlaneDescription692AllOf) SetOrigin(v BTVector3d389) { o.Origin = &v } func (o BTPlaneDescription692AllOf) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.BtType != nil { toSerialize["btType"] = o.BtType } if o.IsOrientedWithFace != nil { toSerialize["isOrientedWithFace"] = o.IsOrientedWithFace } if o.Normal != nil { toSerialize["normal"] = o.Normal } if o.Origin != nil { toSerialize["origin"] = o.Origin } return json.Marshal(toSerialize) } type NullableBTPlaneDescription692AllOf struct { value *BTPlaneDescription692AllOf isSet bool } func (v NullableBTPlaneDescription692AllOf) Get() *BTPlaneDescription692AllOf { return v.value } func (v *NullableBTPlaneDescription692AllOf) Set(val *BTPlaneDescription692AllOf) { v.value = val v.isSet = true } func (v NullableBTPlaneDescription692AllOf) IsSet() bool { return v.isSet } func (v *NullableBTPlaneDescription692AllOf) Unset() { v.value = nil v.isSet = false } func NewNullableBTPlaneDescription692AllOf(val *BTPlaneDescription692AllOf) *NullableBTPlaneDescription692AllOf { return &NullableBTPlaneDescription692AllOf{value: val, isSet: true} } func (v NullableBTPlaneDescription692AllOf) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBTPlaneDescription692AllOf) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
onshape/model_bt_plane_description_692_all_of.go
0.746139
0.494019
model_bt_plane_description_692_all_of.go
starcoder
package tables import ( "github.com/sudachen/go-ml/fu" "golang.org/x/xerrors" "reflect" ) /* Matrix the presentation of features and labels as plane []float32 slices */ type Matrix struct { Features []float32 Labels []float32 Width, Length int LabelsWidth int // 0 means no labels defined } /* Matrix returns matrix without labels */ func (t *Table) Matrix(features []string, least ...int) (m Matrix, err error) { _, m, err = t.MatrixWithLabelIf(features, "", "", nil, least...) return } /* MatrixWithLabel returns matrix with labels */ func (t *Table) MatrixWithLabel(features []string, label string, least ...int) (m Matrix, err error) { _, m, err = t.MatrixWithLabelIf(features, label, "", nil, least...) return } /* MatrixIf returns two matrices without labels the first one contains samples with column ifName equal ifValue the second one - samples with column ifName not equal ifValue */ func (t *Table) MatrixIf(features []string, ifName string, ifValue interface{}) (m0, m1 Matrix, err error) { return t.MatrixWithLabelIf(features, "", ifName, ifValue) } /* MatrixWithLabelIf returns two matrices with labels the first one contains samples with column ifName equal ifValue the second one - samples with column ifName not equal ifValue */ func (t *Table) MatrixWithLabelIf(features []string, label string, ifName string, ifValue interface{}, least ...int) (test, train Matrix, err error) { L := [2]int{0, t.Len()} filter := func(int) int { return 1 } if ifName != "" { if tc, ok := t.ColIfExists(ifName); ok { if a, ok := tc.Inspect().([]bool); ok { vt := ifValue.(bool) filter = func(i int) int { if a[i] == vt { return 0 } return 1 } } else if a, ok := tc.Inspect().([]int); ok { vt := ifValue.(int) filter = func(i int) int { if a[i] == vt { return 0 } return 1 } } else { filter = func(i int) int { if tc.Index(i).Value == ifValue { return 0 } return 1 } } l := t.Len() L = [2]int{0, 0} for i := 0; i < l; i++ { L[filter(i)]++ } } } width := 0 for _, n := range features { c := t.Col(n) if c.Type() == fu.TensorType { width += c.Inspect().([]fu.Tensor)[0].Volume() } else { width++ } } lwidth := 0 if label != "" { lc := t.Col(label) lwidth = 1 if lc.Type() == fu.TensorType { lwidth = lc.Inspect().([]fu.Tensor)[0].Volume() } } for i := range L { if L[i] > 0 { L[i] = fu.Maxi(L[i], least...) } } mx := []Matrix{ {make([]float32, L[0]*width), make([]float32, L[0]*lwidth), width, L[0], lwidth}, {make([]float32, L[1]*width), make([]float32, L[1]*lwidth), width, L[1], lwidth}, } wc := 0 for _, n := range features { if wc, err = t.addToMatrix(filter, mx, t.Col(n), false, wc, width, t.Len()); err != nil { return } } if lwidth > 0 { if _, err = t.addToMatrix(filter, mx, t.Col(label), true, 0, lwidth, t.Len()); err != nil { return } } for i, l := range L { if t.Len() < l && t.Len() > 0 { for j := t.Len() - 1; j < l; j++ { m := mx[i] copy(m.Features[j*m.Width:(j+1)*m.Width], m.Features[0:m.Width]) if m.LabelsWidth > 0 { copy(m.Labels[j*m.LabelsWidth:(j+1)*m.LabelsWidth], m.Labels[0:m.LabelsWidth]) } } } } return mx[0], mx[1], nil } func (t *Table) addToMatrix(f func(int) int, matrix []Matrix, c *Column, label bool, xc, width, length int) (wc int, err error) { where := [2][]float32{ fu.Ife(label, matrix[0].Labels, matrix[0].Features).([]float32), fu.Ife(label, matrix[1].Labels, matrix[1].Features).([]float32), } wc = xc z := [2]int{} switch c.Type() { case fu.Float32: x := c.Inspect().([]float32) for j := 0; j < length; j++ { jf := f(j) where[jf][z[jf]*width+wc] = x[j] z[jf]++ } wc++ case fu.Float64: x := c.Inspect().([]float64) for j := 0; j < length; j++ { jf := f(j) where[jf][z[jf]*width+wc] = float32(x[j]) z[jf]++ } wc++ case fu.Int: x := c.Inspect().([]int) for j := 0; j < length; j++ { jf := f(j) where[jf][z[jf]*width+wc] = float32(x[j]) z[jf]++ } wc++ case fu.TensorType: x := c.Inspect().([]fu.Tensor) vol := x[0].Volume() for j := 0; j < length; j++ { if x[j].Volume() != vol { err = xerrors.Errorf("tensors with different volumes found in one column") } jf := f(j) m := z[jf] t := where[jf] switch x[j].Type() { case fu.Float32: y := x[j].Values().([]float32) copy(t[m*width+wc:m*width+wc+vol], y) case fu.Float64: y := x[j].Values().([]float64) for k := 0; k < vol; k++ { t[m*width+wc+k] = float32(y[k]) } case fu.Byte: y := x[j].Values().([]byte) for k := 0; k < vol; k++ { t[m*width+wc+k] = float32(y[k]) / 256 } case fu.Fixed8Type: y := x[j].Values().([]fu.Fixed8) for k := 0; k < vol; k++ { t[m*width+wc+k] = y[k].Float32() } case fu.Int: y := x[j].Values().([]int) for k := 0; k < vol; k++ { t[m*width+wc+k] = float32(y[k]) } default: return width, xerrors.Errorf("unsupported tensor type %v", x[j].Type) } z[jf]++ } wc += vol default: x := c.ExtractAs(fu.Float32, true).([]float32) for j := 0; j < length; j++ { jf := f(j) where[jf][z[jf]*width+wc] = x[j] z[jf]++ } wc++ } return } /* AsTable converts raw features representation into Table */ func (m Matrix) AsTable(names ...string) *Table { columns := make([]reflect.Value, m.Width) na := make([]fu.Bits, m.Width) for i := range columns { c := make([]float32, m.Length, m.Length) for j := 0; j < m.Length; j++ { c[j] = m.Features[m.Width*j+i] } columns[i] = reflect.ValueOf(c) } return MakeTable(names, columns, na, m.Length) } /* AsColumn converts raw features representation into Column */ func (m Matrix) AsColumn() *Column { if m.Width == 1 { return &Column{column: reflect.ValueOf(m.Features[0:m.Length])} } column := make([]fu.Tensor, m.Length) for i := 0; i < m.Length; i++ { column[i] = fu.MakeFloat32Tensor(1, 1, m.Width, m.Features[m.Width*i:m.Width*(i+1)]) } return &Column{column: reflect.ValueOf(column)} } /* AsLabelColumn converts raw labels representation into Column */ func (m Matrix) AsLabelColumn() *Column { if m.LabelsWidth == 1 { return &Column{column: reflect.ValueOf(m.Labels[0:m.Length])} } column := make([]fu.Tensor, m.Length) for i := 0; i < m.Length; i++ { column[i] = fu.MakeFloat32Tensor(1, 1, m.LabelsWidth, m.Labels[m.LabelsWidth*i:m.LabelsWidth*(i+1)]) } return &Column{column: reflect.ValueOf(column)} } func MatrixColumn(dat []float32, length int) *Column { if length > 0 { return Matrix{dat, nil, len(dat) / length, length, 0}.AsColumn() } return Col([]float32{}) }
tables/matrix.go
0.573917
0.505249
matrix.go
starcoder
package bst import ( "errors" ds "github.com/DavidCai1993/datastructures.go" ) // Errors used by this package var ( ErrEmptyTree = errors.New("bst: empty tree") ) type node struct { val ds.Comparable parent *node left *node right *node } // Tree represents a binary search tree. type Tree struct { root *node } // New returns a new binary search tree instance. func New() *Tree { return &Tree{root: &node{}} } // Insert inserts a value to the tree. // Time Complexity: O(logN) func (t *Tree) Insert(val ds.Comparable) { t.root.insert(val, nil) } func (n *node) insert(val ds.Comparable, parent *node) { if n.val == nil { n.val = val n.parent = parent return } c := val.Compare(n.val) if c == 0 { return } else if c < 0 { n.left = ensureNode(n.left) n.left.insert(val, n) } else { n.right = ensureNode(n.right) n.right.insert(val, n) } } // Delete removes the node of given value in this tree. // Time Complexity: O(logN) func (t *Tree) Delete(val ds.Comparable) { n := t.root.find(val) if n == nil { return } n.delete() } func (n *node) delete() { if n.left == nil && n.right == nil { if n.parent.left == n { n.parent.left = nil } else { n.parent.right = nil } return } if n.left != nil && n.right == nil { *n = *n.left return } if n.left == nil && n.right != nil { *n = *n.right return } if n.right.left == nil { n.val = n.right.val n.right.delete() return } n.val = n.right.left.val n.right.left.delete() } // FindMin returns the value of the minimum node. // Time Complexity: O(logN) func (t Tree) FindMin() ds.Comparable { return t.root.findMin() } func (n node) findMin() ds.Comparable { if n.left == nil { return n.val } return n.left.findMin() } // FindMax returns the value of the maximum node. // Time Complexity: O(logN) func (t Tree) FindMax() ds.Comparable { return t.root.findMax() } func (n node) findMax() ds.Comparable { if n.right == nil { return n.val } return n.right.findMax() } // Find checks whether the given value is this tree. // Time Complexity: O(logN) func (t Tree) Find(val ds.Comparable) bool { n := t.root.find(val) if n != nil { return true } return false } func (n *node) find(val ds.Comparable) *node { c := val.Compare(n.val) if c == 0 { return n } if c < 0 { if n.left != nil { return n.left.find(val) } } else { if n.right != nil { return n.right.find(val) } } return nil } // PreOrderTraversal runs function f of each node's value in the tree // by pre order traversal. func (t Tree) PreOrderTraversal(f func(ds.Comparable)) { t.root.preOrderTraversal(f) } func (n node) preOrderTraversal(f func(ds.Comparable)) { if n.val == nil { return } f(n.val) if n.left != nil { n.left.preOrderTraversal(f) } if n.right != nil { n.right.preOrderTraversal(f) } } // InOrderTraversal runs function f of each node's value in the tree // by in order traversal. func (t Tree) InOrderTraversal(f func(ds.Comparable)) { t.root.inOrderTraversal(f) } func (n node) inOrderTraversal(f func(ds.Comparable)) { if n.val == nil { return } if n.left != nil { n.left.inOrderTraversal(f) } f(n.val) if n.right != nil { n.right.inOrderTraversal(f) } } // PostOrderTraversal runs function f of each node's value in the tree // by post order traversal. func (t Tree) PostOrderTraversal(f func(ds.Comparable)) { t.root.postOrderTraversal(f) } func (n node) postOrderTraversal(f func(ds.Comparable)) { if n.val == nil { return } if n.left != nil { n.left.postOrderTraversal(f) } if n.right != nil { n.right.postOrderTraversal(f) } f(n.val) } func ensureNode(n *node) *node { if n == nil { n = &node{} } return n }
binary-search-tree/bst.go
0.862496
0.449211
bst.go
starcoder
package fuse // Opt : the struct to save the fuse operations type Opt struct { /** * Init * Initialize filesystem * * This function is called when libfuse establishes * communication with the FUSE kernel module. The file system * should use this module to inspect and/or modify the * connection parameters provided in the `conn` structure. * * Note that some parameters may be overwritten by options * passed to fuse_session_new() which take precedence over the * values set in this handler. * * There's no reply to this function * * conn: The fuse connection info * userdata: userdata saved to session * * Fuse的初始化函数 * conn: 是与内核fuse协商的信息,如有需要直接修改 * userdata: 是应用需要保存的数据,不需要直接返回nil即可 */ Init *func(conn *ConnInfo) (userdata interface{}) /** * Destory * Clean up filesystem. * * Called on filesystem exit. When this method is called, the * connection to the kernel may be gone already, so that eg. calls * to fuse_lowlevel_notify_* will fail. * * There's no reply to this function * * userdata: The userdata saved in Init * * 该接口并不是FUSE应用退出时调用的程序,而是当挂载的文件系统的superblock关闭或者出错时,才触发的 * userdata: 在Init中保存的应用数据 */ Destory *func(userdata interface{}) /** * Look up a directory entry by name and get its attributes. * * req: request handle * parentId: parent inode number of the parent directory * name: the name to look up * fsStat: the file stat to return * res: the errno to fs * * 根据文件名获取文件的属性 */ Lookup *func(req Req, parentId uint64, name string) (fsStat *FileStat, res int32) /** * Forget about an inode * * This function is called when the kernel removes an inode * from its internal caches. * * The inode's lookup count increases by one for every call to * fuse_reply_entry and fuse_reply_create. The nlookup parameter * indicates by how much the lookup count should be decreased. * * Inodes with a non-zero lookup count may receive request from * the kernel even after calls to unlink, rmdir or (when * overwriting an existing file) rename. Filesystems must handle * such requests properly and it is recommended to defer removal * of the inode until the lookup count reaches zero. Calls to * unlink, rmdir or rename will be followed closely by forget * unless the file or directory is open, in which case the * kernel issues forget only after the release or releasedir * calls. * * Note that if a file system will be exported over NFS the * inodes lifetime must extend even beyond forget. See the * generation field in struct fuse_entry_param above. * * On unmount the lookup count for all inodes implicitly drops * to zero. It is not guaranteed that the file system will * receive corresponding forget messages for the affected * inodes. * * * req: request handle * nodeId: the inode number * nlookup: the number of lookups to forget */ Forget *func(req Req, nodeid uint64, nlookup uint64) /** * Get file attributes. * * If writeback caching is enabled, the kernel may have a * better idea of a file's length than the FUSE file system * (eg if there has been a write that extended the file size, * but that has not yet been passed to the filesystem.n * * In this case, the st_size value provided by the file system * will be ignored. * * * req: request handle * nodeid: the inode number * fsStat: stat the file stat * res: the errno to fs */ Getattr *func(req Req, nodeid uint64) (fsStat *FileStat, res int32) /** * Set file attributes * * In the 'attr' argument only members indicated by the 'to_set' * bitmask contain valid values. Other members contain undefined * values. * * Unless FUSE_CAP_HANDLE_KILLPRIV is disabled, this method is * expected to reset the setuid and setgid bits if the file * size or owner is being changed. * * If the setattr was invoked from the ftruncate() system call * under Linux kernel versions 2.6.15 or later, the fi->fh will * contain the value set by the open method or will be undefined * if the open method didn't set any value. Otherwise (not * ftruncate call, or kernel version earlier than 2.6.15) the fi * parameter will be NULL. * * * req: request handle * nodeid: the inode number * attr: the attributes * toSet: bit mask of attributes which should be set * res: the errno to fs */ Setattr *func(req Req, nodeid uint64, attr FileStat, toSet uint32) (res int32) /** * Read symbolic link * * * req: request handle * nodeid: the inode number * path: the contents of the symbolic link * res: the errno to fs. About readlink, please check [http://man7.org/linux/man-pages/man2/readlink.2.html] */ Readlink *func(req Req, nodeid uint64) (path string, res int32) /** * Create file node * * Create a regular file, character device, block device, fifo or * socket node. * * * req: request handle * parentid: inode number of the parent directory * name: to create * mode: file type and mode with which to create the new file * rdev: the device number (only valid if created file is a device) * fsStat: the file stat * res: the errno to fs. About mknod, please check [http://man7.org/linux/man-pages/man2/mknod.2.html] */ Mknod *func(req Req, parentid uint64, name string, mode uint32, rdev uint32) (fsStat *FileStat, res int32) /** * Create a directory * * * req: request handle * parentid: inode number of the parent directory * name: to create * mode: with which to create the new file * fsStat: the file stat * res: the errno to fs. About mkdir, please check [http://man7.org/linux/man-pages/man2/mkdir.2.html] */ Mkdir *func(req Req, parentid uint64, name string, mode uint32) (fsStat *FileStat, res int32) /** * Remove a directory * * If the directory's inode's lookup count is non-zero, the * file system is expected to postpone any removal of the * inode until the lookup count reaches zero (see description * of the forget function). * * * req: request handle * parentid: inode number of the parent directory * name: to remove * res: the errno to fs. About unlink, please check [http://man7.org/linux/man-pages/man2/unlink.2.html] */ Unlink *func(req Req, parentid uint64, name string) (res int32) /** * Remove a directory * * If the directory's inode's lookup count is non-zero, the * file system is expected to postpone any removal of the * inode until the lookup count reaches zero (see description * of the forget function). * * req: request handle * parentid: inode number of the parent directory * name: to remove * res: the errno to fs. About rmdir, please check [http://man7.org/linux/man-pages/man2/rmdir.2.html] */ Rmdir *func(req Req, parentid uint64, name string) (res int32) /** * Create a symbolic link * * * req: request handle * parentid: inode number of the parent directory * link: the contents of the symbolic link * name: to create * fsStat: the file stat * res: the errno to fs. About symlink, please check[http://man7.org/linux/man-pages/man2/symlink.2.html] */ Symlink *func(req Req, parentid uint64, link string, name string) (fsStat *FileStat, res int32) /** Rename a file * * If the target exists it should be atomically replaced. If * the target's inode's lookup count is non-zero, the file * system is expected to postpone any removal of the inode * until the lookup count reaches zero (see description of the * forget function). * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent failure with error code EINVAL, i.e. all * future bmap requests will fail with EINVAL without being * send to the filesystem process. * * *flags* may be `RENAME_EXCHANGE` or `RENAME_NOREPLACE`. If * RENAME_NOREPLACE is specified, the filesystem must not * overwrite *newname* if it exists and return an error * instead. If `RENAME_EXCHANGE` is specified, the filesystem * must atomically exchange the two files, i.e. both must * exist and neither may be deleted. * * * req: request handle * parentid: inode number of the old parent directory * name: old name * newparentid: inode number of the new parent directory * newname: new name * res: the errno to fs. About rename, please check[http://man7.org/linux/man-pages/man2/rename.2.html] */ Rename *func(req Req, parentid uint64, name string, newparentid uint64, newname string) (res int32) /** * Create a hard link * * * req: request handle * oldnodeid: the old inode number * newparentid: inode number of the new parent directory * newname: new name to create * fsStat: the new file stat * res: the errno to fs. About link, please check[http://man7.org/linux/man-pages/man2/link.2.html] */ Link *func(req Req, oldnodeid uint64, newparentid uint64, newname string) (fsStat *FileStat, res int32) /** * Open a file * * Open flags are available in fi->flags. The following rules * apply. * * - Creation (O_CREAT, O_EXCL, O_NOCTTY) flags will be * filtered out / handled by the kernel. * * - Access modes (O_RDONLY, O_WRONLY, O_RDWR) should be used * by the filesystem to check if the operation is * permitted. If the ``-o default_permissions`` mount * option is given, this check is already done by the * kernel before calling open() and may thus be omitted by * the filesystem. * * - When writeback caching is enabled, the kernel may send * read requests even for files opened with O_WRONLY. The * filesystem should be prepared to handle this. * * - When writeback caching is disabled, the filesystem is * expected to properly handle the O_APPEND flag and ensure * that each write is appending to the end of the file. * * - When writeback caching is enabled, the kernel will * handle O_APPEND. However, unless all changes to the file * come through the kernel this will not work reliably. The * filesystem should thus either ignore the O_APPEND flag * (and let the kernel handle it), or return an error * (indicating that reliably O_APPEND is not available). * * Filesystem may store an arbitrary file handle (pointer, * index, etc) in fi->fh, and use this in other all other file * operations (read, write, flush, release, fsync). * * Filesystem may also implement stateless file I/O and not store * anything in fi->fh. * * There are also some flags (direct_io, keep_cache) which the * filesystem may set in fi, to change the way the file is opened. * See fuse_file_info structure in <fuse_common.h> for more details. * * If this request is answered with an error code of ENOSYS * and FUSE_CAP_NO_OPEN_SUPPORT is set in * `fuse_conn_info.capable`, this is treated as success and * future calls to open will also succeed without being send * to the filesystem process. * * * req: request handle * nodeid: the inode number * fi: file information * res: the errno to fs. About open, please check[http://man7.org/linux/man-pages/man2/open.2.html] */ Open *func(req Req, nodeid uint64, fi *FileInfo) (res int32) /** * Read data * * Read should send exactly the number of bytes requested except * on EOF or error, otherwise the rest of the data will be * substituted with zeroes. An exception to this is when the file * has been opened in 'direct_io' mode, in which case the return * value of the read system call will reflect the return value of * this operation. * * fi->fh will contain the value set by the open method, or will * be undefined if the open method didn't set any value. * * * req: request handle * nodeid: the inode number * size: number of bytes to read * offset: offset to read from * fi: file information * content: the content to read * res: the errno to fs. About read, please check[http://man7.org/linux/man-pages/man2/read.2.html] */ Read *func(req Req, nodeid uint64, size uint32, offset uint64, fi FileInfo) (content []byte, res int32) /** * Write data * * Write should return exactly the number of bytes requested * except on error. An exception to this is when the file has * been opened in 'direct_io' mode, in which case the return value * of the write system call will reflect the return value of this * operation. * * Unless FUSE_CAP_HANDLE_KILLPRIV is disabled, this method is * expected to reset the setuid and setgid bits. * * fi->fh will contain the value set by the open method, or will * be undefined if the open method didn't set any value. * * * req: request handle * nodeid: the inode number * buf: data to write * offset: offset to write to * fi: file information * size: the size write to file * res: the errno to fs. About write, please check[http://man7.org/linux/man-pages/man2/write.2.html] */ Write *func(req Req, nodeid uint64, buf []byte, offset uint64, fi FileInfo) (size uint32, res int32) /** * Flush method * * This is called on each close() of the opened file. * * Since file descriptors can be duplicated (dup, dup2, fork), for * one open call there may be many flush calls. * * Filesystems shouldn't assume that flush will always be called * after some writes, or that if will be called at all. * * fi->fh will contain the value set by the open method, or will * be undefined if the open method didn't set any value. * * NOTE: the name of the method is misleading, since (unlike * fsync) the filesystem is not forced to flush pending writes. * One reason to flush data, is if the filesystem wants to return * write errors. * * If the filesystem supports file locking operations (setlk, * getlk) it should remove all locks belonging to 'fi->owner'. * * If this request is answered with an error code of ENOSYS, * this is treated as success and future calls to flush() will * succeed automatically without being send to the filesystem * process. * * * req: request handle * nodeid: the inode number * fi: file information * res: the errno to fs. About flush, please check[http://man7.org/linux/man-pages/man3/fflush.3.html](may be not correct) */ Flush *func(req Req, nodeid uint64, fi FileInfo) (res int32) /** * Synchronize file contents * * If the datasync parameter is non-zero, then only the user data * should be flushed, not the meta data. * * If this request is answered with an error code of ENOSYS, * this is treated as success and future calls to fsync() will * succeed automatically without being send to the filesystem * process. * * * req: request handle * nodeid: the inode number * datasync: flag indicating if only data should be flushed * fi: file information * res: the errno to fs. About fsync, please check[http://man7.org/linux/man-pages/man2/fsync.2.html] */ Fsync *func(req Req, nodeid uint64, datasync uint32, fi FileInfo) (res int32) /** * Open a directory * * Filesystem may store an arbitrary file handle (pointer, index, * etc) in fi->fh, and use this in other all other directory * stream operations (readdir, releasedir, fsyncdir). * * Filesystem may also implement stateless directory I/O and not * store anything in fi->fh, though that makes it impossible to * implement standard conforming directory stream operations in * case the contents of the directory can change between opendir * and releasedir. * * * req: request handle * nodeid: the inode number * fi: file information * res: the errno to fs. About opendir, please check[http://man7.org/linux/man-pages/man3/opendir.3.html] */ Opendir *func(req Req, nodeid uint64, fi *FileInfo) (res int32) /** * Read directory * * Send a buffer filled using fuse_add_direntry(), with size not * exceeding the requested size. Send an empty buffer on end of * stream. * * fi->fh will contain the value set by the opendir method, or * will be undefined if the opendir method didn't set any value. * * Returning a directory entry from readdir() does not affect * its lookup count. * * The function does not have to report the '.' and '..' * entries, but is allowed to do so. * * * req: request handle * nodeid: the inode number * size: maximum number of bytes to send * offset: offset to continue reading the directory stream * fi: file information * direntList: list of file in this directory, the binary size of direntList should not larget than size. * res: the errno to fs. About readdir, please check[http://man7.org/linux/man-pages/man3/readdir.3.html] * */ Readdir *func(req Req, nodeid uint64, size uint32, offset uint64, fi FileInfo) (direntList []Dirent, res int32) /** * Release an open directory * * For every opendir call there will be exactly one releasedir * call. * * fi->fh will contain the value set by the opendir method, or * will be undefined if the opendir method didn't set any value. * * * req: request handle * nodeid: the inode number * fi: file information * res: the errno to fs. */ Releasedir *func(req Req, nodeid uint64, fi FileInfo) (res int32) /** * Release an open file * * Release is called when there are no more references to an open * file: all file descriptors are closed and all memory mappings * are unmapped. * * For every open call there will be exactly one release call. * * The filesystem may reply with an error, but error values are * not returned to close() or munmap() which triggered the * release. * * fi->fh will contain the value set by the open method, or will * be undefined if the open method didn't set any value. * fi->flags will contain the same flags as for open. * * * req: request handle * nodeid: the inode number * fi: file information * res: the errno to fs. */ Release *func(req Req, nodeid uint64, fi FileInfo) (res int32) /** * Synchronize directory contents * * If the datasync parameter is non-zero, then only the directory * contents should be flushed, not the meta data. * * fi->fh will contain the value set by the opendir method, or * will be undefined if the opendir method didn't set any value. * * If this request is answered with an error code of ENOSYS, * this is treated as success and future calls to fsyncdir() will * succeed automatically without being send to the filesystem * process. * * * req: request handle * nodeid: the inode number * datasync: flag indicating if only data should be flushed * fi: file information. * res: the errno to fs. About fsyncdir, please check[http://man7.org/linux/man-pages/man2/fsync.2.html] */ Fsyncdir *func(req Req, nodeid uint64, datasync uint32, fi FileInfo) (res int32) /** * Get file system statistics * * * req: request handle * nodeid: the inode number, zero means "undefined" * statfs: stat of file system * res: the errno to fs. About fsyncdir, please check[http://man7.org/linux/man-pages/man2/fstatfs.2.html] */ Statfs *func(req Req, nodeid uint64) (statfs *Statfs, res int32) /** * Set an extended attribute * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent failure with error code EOPNOTSUPP, i.e. all * future setxattr() requests will fail with EOPNOTSUPP without being * send to the filesystem process. * * req: request handle * nodeid: the inode number, zero means "undefined" * name: name of attribute * value: value of attribute * flags: setxattr flags * res: the errno to fs. About setxattr, pease check[http://man7.org/linux/man-pages/man2/fsetxattr.2.html] */ Setxattr *func(req Req, nodeid uint64, name string, value string, flags uint32) (res int32) /** * Get an extended attribute * * If size is zero, the size of the value should be sent with * fuse_reply_xattr. * * If the size is non-zero, and the value fits in the buffer, the * value should be sent with fuse_reply_buf. * * If the size is too small for the value, the ERANGE error should * be sent. * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent failure with error code EOPNOTSUPP, i.e. all * future getxattr() requests will fail with EOPNOTSUPP without being * send to the filesystem process. * * * req: request handle * nodeid: the inode number * name: name of the extended attribute * size: maximum size of the value to send * value: value of the extended attribute * res: the errno to fs. About getxattr, pease check[http://man7.org/linux/man-pages/man2/fgetxattr.2.html] */ Getxattr *func(req Req, nodeid uint64, name string, size uint32) (value string, res int32) /** * List extended attribute names * * If size is zero, the total size of the attribute list should be * sent with fuse_reply_xattr. * * If the size is non-zero, and the null character separated * attribute list fits in the buffer, the list should be sent with * fuse_reply_buf. * * If the size is too small for the list, the ERANGE error should * be sent. * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent failure with error code EOPNOTSUPP, i.e. all * future listxattr() requests will fail with EOPNOTSUPP without being * send to the filesystem process. * * * req: request handle * nodeid: the inode number * size: maximum size of the list to send * list: the extended attributes names string, eatch name use '\0' to split it * res: the errno to fs. About getxattr, pease check[http://man7.org/linux/man-pages/man2/flistxattr.2.html] */ Listxattr *func(req Req, nodeid uint64, size uint32) (list string, res int32) /** * Remove an extended attribute * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent failure with error code EOPNOTSUPP, i.e. all * future removexattr() requests will fail with EOPNOTSUPP without being * send to the filesystem process. * * * req: request handle * nodeid: the inode number * name: name of the extended attribute * res: the errno to fs. About removexattr, pease check[http://man7.org/linux/man-pages/man2/removexattr.2.html] */ Removexattr *func(req Req, nodeid uint64, name string) (res int32) /** * Check file access permissions * * This will be called for the access() and chdir() system * calls. If the 'default_permissions' mount option is given, * this method is not called. * * This method is not called under Linux kernel versions 2.4.x * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent success, i.e. this and all future access() * requests will succeed without being send to the filesystem process. * * * req: request handle * nodeid: the inode number * mask: requested access mode * res: the errno to fs. About access, pease check[http://man7.org/linux/man-pages/man2/access.2.html] */ Access *func(req Req, nodeid uint64, mask uint32) (res int32) /** * Create and open a file * * If the file does not exist, first create it with the specified * mode, and then open it. * * See the description of the open handler for more * information. * * If this method is not implemented or under Linux kernel * versions earlier than 2.6.15, the mknod() and open() methods * will be called instead. * * If this request is answered with an error code of ENOSYS, the handler * is treated as not implemented (i.e., for this and future requests the * mknod() and open() handlers will be called instead). * * * req: request handle * parentid: inode number of the parent directory * name: to create * mode: file type and mode with which to create the new file * fi: file information, use to control open process * fsStat: file stat * res: the errno to fs. */ Create *func(req Req, parentid uint64, name string, mode uint32, fi *FileInfo) (fsStat *FileStat, res int32) /** * Test for a POSIX file lock * * * req: request handle * nodeid: the inode number * fi: file information * lock: the region/type to test * res: the errno to fs. About getlk, please check [http://man7.org/linux/man-pages/man3/lockf.3.html] */ Getlk *func(req Req, nodeid uint64, fi FileInfo, lock *Flock) (res int32) /** * Acquire, modify or release a POSIX file lock * * For POSIX threads (NPTL) there's a 1-1 relation between pid and * owner, but otherwise this is not always the case. For checking * lock ownership, 'fi->owner' must be used. The l_pid field in * 'struct flock' should only be used to fill in this field in * getlk(). * * Note: if the locking methods are not implemented, the kernel * will still allow file locking to work locally. Hence these are * only interesting for network filesystems and similar. * * * req: request handle * nodeid: the inode number * fi: file information * lock: the region/type to set * sleep: locking operation may sleep * res: the errno to fs. About setlk, please check [http://man7.org/linux/man-pages/man3/lockf.3.html] */ Setlk *func(req Req, nodeid uint64, fi FileInfo, lock Flock, lksleep int) (res int32) /** * Map block index within file to block index within device * * Note: This makes sense only for block device backed filesystems * mounted with the 'blkdev' option * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent failure, i.e. all future bmap() requests will * fail with the same error code without being send to the filesystem * process. * * * req: request handle * nodeid: the inode number * blocksize: unit of block index * idx: block index within file * res: the errno to fs. */ Bmap *func(req Req, nodeid uint64, blocksize uint32, idx *uint64) (res int32) /** * Ioctl * * Note: For unrestricted ioctls (not allowed for FUSE * servers), data in and out areas can be discovered by giving * iovs and setting FUSE_IOCTL_RETRY in *flags*. For * restricted ioctls, kernel prepares in/out data area * according to the information encoded in cmd. * * * req: request handle * nodeid: the inode number * cmd: ioctl command * arg: ioctl argument * fi: file information * inbuf: data fetched from the caller * outbufsz: maximum size of output data * ioctl: result to kernel * res: the errno to fs. About ioctl, please check[http://man7.org/linux/man-pages/man2/ioctl.2.html] */ Ioctl *func(req Req, nodeid uint64, cmd uint32, arg uint64, fi FileInfo, inbuf []byte, outbufsz uint32) (ioctl *Ioctl, res int32) /** * Poll for IO readiness * * Note: If ph is non-NULL, the client should notify * when IO readiness events occur by calling * fuse_lowlevel_notify_poll() with the specified ph. * * Regardless of the number of times poll with a non-NULL ph * is received, single notification is enough to clear all. * Notifying more times incurs overhead but doesn't harm * correctness. * * The callee is responsible for destroying ph with * fuse_pollhandle_destroy() when no longer in use. * * If this request is answered with an error code of ENOSYS, this is * treated as success (with a kernel-defined default poll-mask) and * future calls to pull() will succeed the same way without being send * to the filesystem process. * * * req: request handle * nodeid: the inode number * fi: file information * ph: poll handle to be used for notification * revents: returned events * res: the errno to fs. About poll, please check[http://man7.org/linux/man-pages/man2/poll.2.html] */ Poll *func(req Req, nodeid uint64, fi FileInfo, ph *Pollhandle) (revents uint32, res int32) /** * Forget about multiple inodes * * See description of the forget function for more * information. * * * req: request handle * nodeList: the node list to forget */ ForgetMulti *func(req Req, nodeList []ForgetOne) /** * Allocate requested space. If this function returns success then * subsequent writes to the specified range shall not fail due to the lack * of free space on the file system storage media. * * If this request is answered with an error code of ENOSYS, this is * treated as a permanent failure with error code EOPNOTSUPP, i.e. all * future fallocate() requests will fail with EOPNOTSUPP without being * send to the filesystem process. * * * req: request handle * nodeid: the inode number * mode: determines the operation to be performed on the given range, * see fallocate(2) * offset: starting point for allocated region * length: size of allocated region * fi: file information * res: the errno to fs. About fallocate, please check[http://man7.org/linux/man-pages/man2/fallocate.2.html] */ Fallocate *func(req Req, nodeid uint64, mode uint32, offset uint64, length uint64, fi FileInfo) (res int32) /** * Read directory with attributes * * Send a buffer filled using fuse_add_direntry_plus(), with size not * exceeding the requested size. Send an empty buffer on end of * stream. * * fi->fh will contain the value set by the opendir method, or * will be undefined if the opendir method didn't set any value. * * In contrast to readdir() (which does not affect the lookup counts), * the lookup count of every entry returned by readdirplus(), except "." * and "..", is incremented by one. * * * req: request handle * nodeid: the inode number * size: maximum number of bytes to send * offset: offset to continue reading the directory stream * fi: file information * buf: result to kernel * res: the errno to fs. About readdirplus , please check[http://man7.org/linux/man-pages/man3/readdir.3.html] */ Readdirplus *func(req Req, nodeid uint64, size uint32, offset uint64, fi FileInfo) (buf []byte, res int32) Interrupt *func(req Req) }
fuse/opt_h.go
0.57093
0.435481
opt_h.go
starcoder
package cppn import ( "errors" "fmt" "github.com/yaricom/goNEAT/neat/genetics" "github.com/yaricom/goNEAT/neat/network" "math" "os" ) // Defines point with float precision coordinates type PointF struct { X, Y float64 } func NewPointF(x, y float64) *PointF { return &PointF{X: x, Y: y} } func (p *PointF) String() string { return fmt.Sprintf("(%f, %f)", p.X, p.Y) } // Defines the quad-point in the 4 dimensional hypercube type QuadPoint struct { // The associated coordinates X1, X2, Y1, Y2 float64 // The value for this point Value float64 } func (q *QuadPoint) String() string { return fmt.Sprintf("((%f, %f),(%f, %f)) = %f", q.X1, q.Y1, q.X2, q.Y2, q.Value) } // Creates new quad point func NewQuadPoint(x1, y1, x2, y2, value float64) *QuadPoint { return &QuadPoint{X1: x1, Y1: y1, X2: x2, Y2: y2, Value: value} } // Defines quad-tree node to model 4 dimensional hypercube type QuadNode struct { // The coordinates of center of this quad-tree node's square X, Y float64 // The width of this quad-tree node's square Width float64 // The CPPN activation level for this node W float64 // The level of this node in the quad-tree Level int // The children of this node Nodes []*QuadNode } func (q *QuadNode) String() string { return fmt.Sprintf("((%f, %f), %f) = %f at %d", q.X, q.Y, q.Width, q.W, q.Level) } // Creates new quad-node with given parameters func NewQuadNode(x, y, width float64, level int) *QuadNode { node := QuadNode{ X: x, Y: y, Width: width, W: 0.0, Level: level, } return &node } // Reads CPPN from specified genome and creates network solver func ReadCPPNfromGenomeFile(genomePath string) (network.NetworkSolver, error) { if genomeFile, err := os.Open(genomePath); err != nil { return nil, err } else if r, err := genetics.NewGenomeReader(genomeFile, genetics.YAMLGenomeEncoding); err != nil { return nil, err } else if genome, err := r.Read(); err != nil { return nil, err } else if netw, err := genome.Genesis(genome.Id); err != nil { return nil, err } else { return netw.FastNetworkSolver() } } // Creates normalized by threshold value link between source and target nodes, given calculated CPPN output for their coordinates func createThresholdNormalizedLink(cppnOutput float64, srcIndex, dstIndex int, linkThreshold, weightRange float64) *network.FastNetworkLink { weight := (math.Abs(cppnOutput) - linkThreshold) / (1 - linkThreshold) // normalize [0, 1] weight *= weightRange // scale to fit given weight range if math.Signbit(cppnOutput) { weight *= -1 // restore sign } link := network.FastNetworkLink{ Weight: weight, SourceIndx: srcIndex, TargetIndx: dstIndex, } return &link } // Creates link between source and target nodes, given calculated CPPN output for their coordinates func createLink(cppnOutput float64, srcIndex, dstIndex int, weightRange float64) *network.FastNetworkLink { weight := cppnOutput weight *= weightRange // scale to fit given weight range link := network.FastNetworkLink{ Weight: weight, SourceIndx: srcIndex, TargetIndx: dstIndex, } return &link } // Calculates outputs of provided CPPN network solver with given hypercube coordinates. func queryCPPN(coordinates []float64, cppn network.NetworkSolver) ([]float64, error) { // flush networks activation from previous run if res, err := cppn.Flush(); err != nil { return nil, err } else if !res { return nil, errors.New("failed to flush CPPN network") } // load inputs if err := cppn.LoadSensors(coordinates); err != nil { return nil, err } // do activations if res, err := cppn.RecursiveSteps(); err != nil { return nil, err } else if !res { return nil, errors.New("failed to relax CPPN network recursively") } return cppn.ReadOutputs(), nil } // Determines variance among CPPN values for certain hypercube region around specified node. // This variance is a heuristic indicator of the heterogeneity (i.e. presence of information) of a region. func nodeVariance(node *QuadNode) float64 { // quick check if len(node.Nodes) == 0 { return 0.0 } cppn_vals := nodeCPPNValues(node) // calculate median and variance m, v := 0.0, 0.0 for _, f := range cppn_vals { m += f } m /= float64(len(cppn_vals)) for _, f := range cppn_vals { v += math.Pow(f-m, 2) } v /= float64(len(cppn_vals)) return v } // Collects the CPPN values stored in a given quadtree node // Used to estimate the variance in a certain region of space around node func nodeCPPNValues(n *QuadNode) []float64 { if len(n.Nodes) > 0 { accumulator := make([]float64, 0) for _, p := range n.Nodes { // go into child nodes p_vals := nodeCPPNValues(p) accumulator = append(accumulator, p_vals...) } return accumulator } else { return []float64{n.W} } }
cppn/cppn.go
0.82994
0.567997
cppn.go
starcoder
package engine import ( "fmt" "github.com/ivan1993spb/snake-bot/internal/types" ) type Area struct { Width uint8 Height uint8 } func NewArea(width, height uint8) Area { return Area{ Width: width, Height: height, } } func (a Area) Navigate(dot types.Dot) []types.Dot { dots := make([]types.Dot, 0, 4) // North if dot.Y > 0 { dots = append(dots, types.Dot{ X: dot.X, Y: dot.Y - 1, }) } else { dots = append(dots, types.Dot{ X: dot.X, Y: a.Height - 1, }) } // South dots = append(dots, types.Dot{ X: dot.X, Y: (dot.Y + 1) % a.Height, }) // East dots = append(dots, types.Dot{ X: (dot.X + 1) % a.Width, Y: dot.Y, }) // West if dot.X > 0 { dots = append(dots, types.Dot{ X: dot.X - 1, Y: dot.Y, }) } else { dots = append(dots, types.Dot{ X: a.Width - 1, Y: dot.Y, }) } return dots } func (a Area) FindDirection(from, to types.Dot) types.Direction { if from == to || !a.Fits(from) || !a.Fits(to) { return types.DirectionNorth } var ( minDiffX, minDiffY uint8 dirX, dirY types.Direction ) if from.X > to.X { minDiffX = from.X - to.X dirX = types.DirectionWest if diff := a.Width - from.X + to.X; diff < minDiffX { minDiffX = diff dirX = types.DirectionEast } } else { minDiffX = to.X - from.X dirX = types.DirectionEast if diff := a.Width - to.X + from.X; diff < minDiffX { minDiffX = diff dirX = types.DirectionWest } } if from.Y > to.Y { minDiffY = from.Y - to.Y dirY = types.DirectionNorth if diff := a.Height - from.Y + to.Y; diff < minDiffY { minDiffY = diff dirY = types.DirectionSouth } } else { minDiffY = to.Y - from.Y dirY = types.DirectionSouth if diff := a.Height - to.Y + from.Y; diff < minDiffY { minDiffY = diff dirY = types.DirectionNorth } } if minDiffX > minDiffY { return dirX } return dirY } func (a Area) FitDistance(distance, divisor, gap uint8) uint8 { if distance >= a.Width/divisor { distance = a.Width / divisor if gap > 0 && a.Width%divisor == 0 { distance -= gap } } if distance >= a.Height/divisor { distance = a.Height / divisor if gap > 0 && a.Height%divisor == 0 { distance -= gap } } return distance } func (a Area) Fits(dot types.Dot) bool { return a.Width > dot.X && a.Height > dot.Y } func (a Area) String() string { return fmt.Sprintf("Area[%d, %d]", a.Width, a.Height) }
internal/bot/engine/area.go
0.718199
0.406361
area.go
starcoder
package hashmultimaps // New factory that creates a new Hash Multi Map func New() *HashMultiMap { multiMap := HashMultiMap{data: make(map[interface{}][]interface{})} return &multiMap } // HashMultiMap a data structure representing a map of keys with lists of values type HashMultiMap struct { data map[interface{}][]interface{} } // Merge merge multiple multi maps func (s *HashMultiMap) Merge(maps ...*HashMultiMap) { for _, multiMap := range maps { for _, key := range multiMap.GetKeys() { values := multiMap.GetValues(key) s.PutAll(key, values...) } } } // Put key/value pair to the multi map func (s *HashMultiMap) Put(key interface{}, value interface{}) { values, ok := s.data[key] if !ok { values = make([]interface{}, 0) } values = append(values, value) s.data[key] = values } // PutAll put key/values to the multi map func (s *HashMultiMap) PutAll(key interface{}, values ...interface{}) { for _, value := range values { s.Put(key, value) } } // GetKeys returns a list of the multi map's keys func (s *HashMultiMap) GetKeys() []interface{} { keys := make([]interface{}, 0, s.Size()) for key := range s.data { keys = append(keys, key) } return keys } // Contains checks if a key is in the multi map func (s *HashMultiMap) Contains(key interface{}) bool { _, exists := s.data[key] return exists } // ContainsAll checks if all keys are in the multi map func (s *HashMultiMap) ContainsAll(keys ...interface{}) bool { for _, key := range keys { if !s.Contains(key) { return false } } return true } // ContainsAny checks if any keys are in the multi map func (s *HashMultiMap) ContainsAny(keys ...interface{}) bool { for _, key := range keys { if s.Contains(key) { return true } } return false } // GetValues returns values associated with the key func (s *HashMultiMap) GetValues(key interface{}) []interface{} { values, ok := s.data[key] if !ok { return make([]interface{}, 0) } return values } // RemoveKey removes a key and all its values func (s *HashMultiMap) RemoveKey(keys ...interface{}) { for _, key := range keys { delete(s.data, key) } } // Remove removes a value from a key's values func (s *HashMultiMap) Remove(key interface{}, value interface{}) { values, ok := s.data[key] if !ok { return } index := getIndex(value, values...) if index == -1 { return } newValues := make([]interface{}, 0) newValues = append(newValues, values[:index]...) s.data[key] = append(newValues, values[index+1:]...) } // Clear clears the multiMap func (s *HashMultiMap) Clear() { s.data = make(map[interface{}][]interface{}) } // IsEmpty checks if the multiMap is empty func (s *HashMultiMap) IsEmpty() bool { return s.Size() == 0 } // Size returns size of the multiMap func (s *HashMultiMap) Size() int { return len(s.data) } func getIndex(value interface{}, values ...interface{}) int { for i, v := range values { if v == value { return i } } return -1 }
datastructures/maps/hashmultimaps/hash_multi_map.go
0.822617
0.409103
hash_multi_map.go
starcoder
package util import ( "errors" "time" "github.com/deejross/mydis/pb" "github.com/gogo/protobuf/proto" ) // Value object. type Value struct { err error b []byte } // NewValue returns a new Value object. func NewValue(t interface{}) Value { switch t := t.(type) { case error: return Value{err: t} case Value: return t case []byte: return Value{b: t} case string: return Value{b: StringToBytes(t)} case bool: if t { return Value{b: []byte{1}} } return Value{b: ZeroByte} case proto.Message: b, _ := proto.Marshal(t) return Value{b: b} case int: b, _ := proto.Marshal(&pb.IntValue{Value: int64(t)}) return Value{b: b} case int8: b, _ := proto.Marshal(&pb.IntValue{Value: int64(t)}) return Value{b: b} case int16: b, _ := proto.Marshal(&pb.IntValue{Value: int64(t)}) return Value{b: b} case int32: b, _ := proto.Marshal(&pb.IntValue{Value: int64(t)}) return Value{b: b} case int64: b, _ := proto.Marshal(&pb.IntValue{Value: t}) return Value{b: b} case float32: b, _ := proto.Marshal(&pb.FloatValue{Value: float64(t)}) return Value{b: b} case float64: b, _ := proto.Marshal(&pb.FloatValue{Value: t}) return Value{b: b} case time.Time: b, _ := proto.Marshal(&pb.IntValue{Value: int64(t.Nanosecond())}) return Value{b: b} case time.Duration: b, _ := proto.Marshal(&pb.IntValue{Value: t.Nanoseconds()}) return Value{b: b} case [][]byte: b, _ := proto.Marshal(&pb.List{Value: t}) return Value{b: b} case []string: b, _ := proto.Marshal(&pb.List{Value: ListStringToBytes(t)}) return Value{b: b} case []Value: b, _ := proto.Marshal(&pb.List{Value: ListValueToBytes(t)}) return Value{b: b} case map[string]string: b, _ := proto.Marshal(&pb.Hash{Value: MapStringToMapBytes(t)}) return Value{b: b} case map[string][]byte: b, _ := proto.Marshal(&pb.Hash{Value: t}) return Value{b: b} case map[string]bool: b, _ := proto.Marshal(&pb.Hash{Value: MapBoolToMapBytes(t)}) return Value{b: b} case map[string]int64: b, _ := proto.Marshal(&pb.Hash{Value: MapIntToMapBytes(t)}) return Value{b: b} case map[string]float64: b, _ := proto.Marshal(&pb.Hash{Value: MapFloatToMapBytes(t)}) return Value{b: b} case map[string]Value: b, _ := proto.Marshal(&pb.Hash{Value: MapValueToMapBytes(t)}) return Value{b: b} default: return Value{err: errors.New("Unknown type, recommend marshalling to byte slice")} } } // Error returns the error associated with this Value, if one exists. func (v Value) Error() error { return v.err } // Bytes returns the Value as a byte slice. func (v Value) Bytes() ([]byte, error) { if v.err != nil { return nil, v.err } return v.b, nil } // RawBytes returns the Value as a byte slice, ignoring any error. func (v Value) RawBytes() []byte { return v.b } // String returns the Value as a string. func (v Value) String() (string, error) { if v.err != nil { return "", v.err } return BytesToString(v.b), nil } // Bool returns the Value as bool. func (v Value) Bool() (bool, error) { if v.err != nil { return false, v.err } if len(v.b) > 0 && v.b[0] != 0 { return true, nil } return false, nil } // Proto returns the given ProtoMessage. func (v Value) Proto(pb proto.Message) error { if v.err != nil { return v.err } if pb == nil { return nil } err := proto.Unmarshal(v.b, pb) if err != nil { return err } return nil } // Int returns the Value as an int64. func (v Value) Int() (int64, error) { iv := &pb.IntValue{} if err := v.Proto(iv); err != nil { return 0, err } return iv.Value, nil } // Float returns the Value as a flat64. func (v Value) Float() (float64, error) { fv := &pb.FloatValue{} if err := v.Proto(fv); err != nil { return 0, err } return fv.Value, nil } // Time returns the Value as a Time. func (v Value) Time() (time.Time, error) { iv := &pb.IntValue{} if err := v.Proto(iv); err != nil { return time.Time{}, err } return time.Unix(0, iv.Value), nil } // Duration returns the Value as a Duration. func (v Value) Duration() (time.Duration, error) { iv := &pb.IntValue{} if err := v.Proto(iv); err != nil { return 0, err } return time.Duration(iv.Value), nil } // List returns the Value as a List. func (v Value) List() ([]Value, error) { lst := &pb.List{} if err := v.Proto(lst); err != nil { return nil, err } return ListToValues(lst.Value), nil } // Map returns the Value as a Map. func (v Value) Map() (map[string]Value, error) { h := &pb.Hash{} if err := v.Proto(h); err != nil { return nil, err } return MapBytesToValues(h.Value), nil } // ListToValues converts a [][]byte to []Value. func ListToValues(lst [][]byte) []Value { if lst == nil { return []Value{} } newLst := make([]Value, len(lst)) for i := 0; i < len(lst); i++ { newLst[i] = NewValue(lst[i]) } return newLst } // ListStringToValues converts a []string to []Value. func ListStringToValues(lst []string) []Value { if lst == nil { return []Value{} } newLst := make([]Value, len(lst)) for i := 0; i < len(lst); i++ { newLst[i] = NewValue(lst[i]) } return newLst } // ListStringToBytes converts a []string to [][]byte. func ListStringToBytes(lst []string) [][]byte { if lst == nil { return [][]byte{} } newLst := make([][]byte, len(lst)) for i := 0; i < len(lst); i++ { newLst[i] = NewValue(lst[i]).b } return newLst } // ListValueToBytes converts a []Value to [][]byte. func ListValueToBytes(lst []Value) [][]byte { if lst == nil { return [][]byte{} } newLst := make([][]byte, len(lst)) for i := 0; i < len(lst); i++ { newLst[i] = NewValue(lst[i]).b } return newLst } // MapBytesToValues converts a map[string][]byte to map[string]Value. func MapBytesToValues(h map[string][]byte) map[string]Value { m := map[string]Value{} if h == nil { return m } for k, v := range h { m[k] = NewValue(v) } return m }
util/value.go
0.708313
0.536859
value.go
starcoder
package ctime import ( "time" ) // An Interval is a period of time with a defined start and end. The interval // includes the start time and every time instant up to but not including the // end time. type Interval struct { Start time.Time End time.Time } // Duration returns the duration of the time interval i. func (i Interval) Duration() time.Duration { return i.End.Sub(i.Start) } // Contains reports whether the time instant t is contained within the time interval i. func (i Interval) Contains(t time.Time) bool { return i.Duration() != 0 && t.Before(i.End) && !t.Before(i.Start) } // Before reports whether the time interval i ends before time interval n starts. // ..|------ i ------|..................... // .....................|------ n ------|.. func (i Interval) Before(n Interval) bool { return i.Duration() != 0 && n.Duration() != 0 && i.End.Before(n.Start) } // After reports whether the time interval i starts after time interval n ends. // .....................|------ i ------|.. // ..|------ n ------|..................... func (i Interval) After(n Interval) bool { return n.Before(i) } // Overlaps reports whether the time interval i starts before time interval n starts // and ends after n starts but before n ends. // ....|------ i ------|................... // ...............|------ n ------|........ func (i Interval) Overlaps(n Interval) bool { end := i.End return i.Duration() != 0 && n.Duration() != 0 && i.Start.Before(n.Start) && n.Start.Before(end) && end.Before(n.End) } // OverlappedBy reports whether the time interval i ends after time interval n ends // and starts after time interval n starts but before n ends. // ...............|------ i ------|........ // ....|------ n ------|................... func (i Interval) OverlappedBy(n Interval) bool { return n.Overlaps(i) } // During reports whether the time interval i starts after time interval n // starts and ends before n ends. // ......|---- i ----|..................... // ....|------ n ------|................... func (i Interval) During(n Interval) bool { return i.Duration() != 0 && n.Duration() != 0 && n.Start.Before(i.Start) && i.End.Before(n.End) } // Meets reports whether the time interval i ends at the same time that // time interval n starts. // ..|------ i ------|..................... // ..................|------ n ------|..... func (i Interval) Meets(n Interval) bool { return i.Duration() != 0 && n.Duration() != 0 && i.End == n.Start } // MetBy reports whether the time interval i starts at the same time that // time interval n ends. // ..................|------ i ------|..... // ..|------ n ------|..................... func (i Interval) MetBy(n Interval) bool { return n.Meets(i) } // Starts reports whether the time interval i starts at the same time that // time interval n starts but ends before n ends. // ..|---- i ----|......................... // ..|------ n ------|..................... func (i Interval) Starts(n Interval) bool { return i.Duration() != 0 && n.Duration() != 0 && i.Start == n.Start && i.End.Before(n.End) } // StartedBy reports whether the time interval i starts at the same time that // time interval n starts but ends after n ends. // ..|------ i ------|......................... // ..|---- n ----|..................... func (i Interval) StartedBy(n Interval) bool { return n.Starts(i) } // Finishes reports whether the time interval i ends at the same time that // time interval n ends but starts after n starts. // ......|---- i ----|..................... // ..|------ n ------|..................... func (i Interval) Finishes(n Interval) bool { return i.Duration() != 0 && n.Duration() != 0 && n.Start.Before(i.Start) && i.End == n.End } // FinishedBy reports whether the time interval i ends at the same time that // time interval n ends but starts before n starts. // ..|------ i ------|..................... // ......|---- n ----|..................... func (i Interval) FinishedBy(n Interval) bool { return n.Finishes(i) } // Equals reports whether the time interval i ends at the same time that // time interval n ends and starts at the same time n starts. // ..|------ i ------|..................... // ..|------ n ------|..................... func (i Interval) Equals(n Interval) bool { return i.Duration() != 0 && n.Duration() != 0 && i.Start == n.Start && i.End == n.End } // Intersects reports whether the time interval i ends after time interval n // starts and starts before n ends. // ..|------ i ------|..................... // ......|------ n ------|................. func (i Interval) Intersects(n Interval) bool { return i.Duration() != 0 && n.Duration() != 0 && n.Start.Before(i.End) && i.Start.Before(n.End) }
ctime.go
0.760384
0.494629
ctime.go
starcoder
package contains_duplicate import "math" /* 219. 存在重复元素 II https://leetcode-cn.com/problems/contains-duplicate-ii 给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j, 使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。 示例 1: 输入: nums = [1,2,3,1], k = 3 输出: true 示例 2: 输入: nums = [1,0,1,1], k = 1 输出: true 示例 3: 输入: nums = [1,2,3,1,2,3], k = 2 输出: false */ func containsNearbyDuplicate(nums []int, k int) bool { m := make(map[int]int, len(nums)) for i, v := range nums { if index, ok := m[v]; ok && i-index <= k { return true } m[v] = i } return false } /* 220. 存在重复元素 III https://leetcode-cn.com/problems/contains-duplicate-iii 给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j, 使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。 示例 1: 输入: nums = [1,2,3,1], k = 3, t = 0 输出: true 示例 2: 输入: nums = [1,0,1,1], k = 1, t = 2 输出: true 示例 3: 输入: nums = [1,5,9,1,5,9], k = 2, t = 3 输出: false */ /* 线性搜索 时间复杂度O(n * min(n, k)) 空间复杂度O(1) */ func containsNearbyAlmostDuplicate1(nums []int, k int, t int) bool { n := len(nums) for i := 0; i < n; i++ { end := min(n-1, i+k) for j := i + 1; j <= end; j++ { if abs(nums[i]-nums[j]) <= t { return true } } } return false } func min(a, b int) int { return int(math.Min(float64(a), float64(b))) } /* 滑动窗口+桶 维持一个长度为k的滑动窗口;用若干桶来装各个数字; 不断右移这个窗口,先根据当前数字的值计算出它应该放入的桶,如果桶里已有数字,表示找到了差值绝对值在t之内的数字直接返回,否则放入对应的桶 如t = 2, 每个桶内应该有3个数字,每个桶内的数字如下: 桶的编号 ... -2 -1 0 1 ... ------- ------- ------- ------- 桶内数字范围 | -6 ~ -4 | | -3 ~ -1 | | 0 ~ 2 | | 3 ~ 5 | ------- ------- ------- ------- 时间复杂度O(n) 空间复杂度O(min(n,k)), 最坏情况下所有元素都放入map */ func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { if t < 0 { return false } // 所有的桶,键为桶id,值为数字,没必要记录桶里所有的数字只需要记录一个,后续再向桶里插入的时候如果桶里已有数字可以直接返回true buckets := map[int]int{} bucketSize := t + 1 // 桶的大小,即每个桶里应该放几个数字 for i, v := range nums { // 删除窗口中第一个数字对应的桶 if i > k { firstBucket := getBucket(nums[i-k-1], bucketSize) delete(buckets, firstBucket) } // v应该放入的桶编号 bucket := getBucket(v, bucketSize) // 检查当前桶里是否已经有值 if _, ok := buckets[bucket]; ok { return true } // 检查前一个桶里是否有满足题意的值 n, ok := buckets[bucket-1] if ok && abs(v-n) <= t { return true } // 检查后一个桶里是否有满足题意的值 n, ok = buckets[bucket+1] if ok && abs(v-n) <= t { return true } buckets[bucket] = v } return false } func getBucket(num, size int) int { if num >= 0 { return num / size } // num加1, 把负数移动到从0开始,这样计算出的标号最小是0,需要再减1 return (num+1)/size - 1 } func abs(x int) int { return int(math.Abs(float64(x))) }
solutions/contains-duplicate/d.go
0.585338
0.46794
d.go
starcoder
package main var samples = ` { "contractState": { "activeAssets": [ "The ID of a managed asset. The resource focal point for a smart contract." ], "nickname": "TRADELANE", "version": "The version number of the current contract" }, "event": { "allottedCredits": 123.456, "assetID": "The ID of a managed asset. The resource focal point for a smart contract.", "boughtCredits": 123.456, "creditsForSale": 123.456, "creditsRequestBuy": 123.456, "email": "Contact information of the company will be stored here", "extension": {}, "iconUrl": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "location": { "latitude": 123.456, "longitude": 123.456 }, "notificationRead": true, "phoneNum": "Contact information of the company will be stored here", "precipitation": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "pricePerCredit": 123.456, "priceRequestBuy": 123.456, "reading": 123.456, "sensorID": 123.456, "sensorlocation": { "latitude": 123.456, "longitude": 123.456 }, "soldCredits": 123.456, "temperatureCelsius": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "temperatureFahrenheit": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "threshold": 123.456, "timestamp": "2016-08-09T15:49:18.021728986-05:00", "tradeBuySell": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradeCompany": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradeCredits": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradePrice": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradeTimestamp": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "updateBuyCredits": 123.456, "updateBuyIndex": 123.456, "updateSellCredits": 123.456, "updateSellIndex": 123.456, "windDegrees": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "windGustSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "windSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" }, "initEvent": { "nickname": "TRADELANE", "version": "The ID of a managed asset. The resource focal point for a smart contract." }, "state": { "alerts": { "active": [ "OVERCARBONEMISSION" ], "cleared": [ "OVERCARBONEMISSION" ], "raised": [ "OVERCARBONEMISSION" ] }, "allottedCredits": 123.456, "assetID": "The ID of a managed asset. The resource focal point for a smart contract.", "boughtCredits": 123.456, "compliant": true, "contactInformation": { "email": "Contact information of the company will be stored here", "phoneNum": "Contact information of the company will be stored here" }, "creditsBuyList": [ "<NAME>" ], "creditsForSale": 123.456, "creditsRequestBuy": 123.456, "creditsSellList": [ "<NAME>" ], "email": "Contact information of the company will be stored here", "extension": {}, "iconUrl": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "lastEvent": { "args": [ "parameters to the function, usually args[0] is populated with a JSON encoded event object" ], "function": "function that created this state object", "redirectedFromFunction": "function that originally received the event" }, "location": { "latitude": 123.456, "longitude": 123.456 }, "notificationRead": true, "phoneNum": "Contact information of the company will be stored here", "precipitation": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "priceBuyList": [ "<NAME>" ], "pricePerCredit": 123.456, "priceRequestBuy": 123.456, "priceSellList": [ "<NAME>" ], "reading": 123.456, "sensorID": 123.456, "sensorWeatherHistory": { "iconUrl": "<NAME>", "precipitation": [ "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" ], "sensorReading": [ "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" ], "tempCelsius": [ "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" ], "tempFahrenheit": [ "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" ], "timestamp": [ "2016-08-09T15:49:18.022023884-05:00" ], "windDegrees": [ "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" ], "windGustSpeed": [ "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" ], "windSpeed": [ "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" ] }, "sensorlocation": { "latitude": 123.456, "longitude": 123.456 }, "soldCredits": 123.456, "temperatureCelsius": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "temperatureFahrenheit": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "threshold": 123.456, "timestamp": "2016-08-09T15:49:18.022033248-05:00", "tradeBuySell": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradeCompany": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradeCredits": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradeHistory": { "buysell": [ "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies" ], "company": [ "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies" ], "credits": [ "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies" ], "price": [ "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies" ], "timestamp": [ "2016-08-09T15:49:18.022017853-05:00" ] }, "tradePrice": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "tradeTimestamp": "Trade values are triggered for every trade which is processed. This contract stores every trade which will be made between two companies", "txntimestamp": "Transaction timestamp matching that in the blockchain.", "txnuuid": "Transaction UUID matching that in the blockchain.", "updateBuyCredits": 123.456, "updateBuyIndex": 123.456, "updateSellCredits": 123.456, "updateSellIndex": 123.456, "windDegrees": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "windGustSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value", "windSpeed": "Sensor and weather value will be stored in a string. So sensorWeatherData object could refer to this definition to store its value" } }`
contracts/industry/carbon_trading/samples.go
0.71403
0.595816
samples.go
starcoder
package camera import ( "github.com/g3n/engine/core" "github.com/g3n/engine/gui" "github.com/g3n/engine/math32" "github.com/g3n/engine/window" "math" ) // OrbitEnabled specifies which control types are enabled. type OrbitEnabled int // The possible control types. const ( OrbitNone OrbitEnabled = 0x00 OrbitRot OrbitEnabled = 0x01 OrbitZoom OrbitEnabled = 0x02 OrbitPan OrbitEnabled = 0x04 OrbitKeys OrbitEnabled = 0x08 OrbitAll OrbitEnabled = 0xFF ) // orbitState bitmask type orbitState int const ( stateNone = orbitState(iota) stateRotate stateZoom statePan ) // OrbitControl is a camera controller that allows orbiting a target point while looking at it. // It allows the user to rotate, zoom, and pan a 3D scene using the mouse or keyboard. type OrbitControl struct { core.Dispatcher // Embedded event dispatcher cam *Camera // Controlled camera target math32.Vector3 // Camera target, around which the camera orbits up math32.Vector3 // The orbit axis (Y+) enabled OrbitEnabled // Which controls are enabled state orbitState // Current control state // Public properties MinDistance float32 // Minimum distance from target (default is 1) MaxDistance float32 // Maximum distance from target (default is infinity) MinPolarAngle float32 // Minimum polar angle in radians (default is 0) MaxPolarAngle float32 // Maximum polar angle in radians (default is Pi) MinAzimuthAngle float32 // Minimum azimuthal angle in radians (default is negative infinity) MaxAzimuthAngle float32 // Maximum azimuthal angle in radians (default is infinity) RotSpeed float32 // Rotation speed factor (default is 1) ZoomSpeed float32 // Zoom speed factor (default is 0.1) KeyRotSpeed float32 // Rotation delta in radians used on each rotation key event (default is the equivalent of 15 degrees) KeyZoomSpeed float32 // Zoom delta used on each zoom key event (default is 2) KeyPanSpeed float32 // Pan delta used on each pan key event (default is 35) // Internal rotStart math32.Vector2 panStart math32.Vector2 zoomStart float32 } // NewOrbitControl creates and returns a pointer to a new orbit control for the specified camera. func NewOrbitControl(cam *Camera) *OrbitControl { oc := new(OrbitControl) oc.Dispatcher.Initialize() oc.cam = cam oc.target = *math32.NewVec3() oc.up = *math32.NewVector3(0, 1, 0) oc.enabled = OrbitAll oc.MinDistance = 1.0 oc.MaxDistance = float32(math.Inf(1)) oc.MinPolarAngle = 0 oc.MaxPolarAngle = math32.Pi // 180 degrees as radians oc.MinAzimuthAngle = float32(math.Inf(-1)) oc.MaxAzimuthAngle = float32(math.Inf(1)) oc.RotSpeed = 1.0 oc.ZoomSpeed = 0.1 oc.KeyRotSpeed = 15 * math32.Pi / 180 // 15 degrees as radians oc.KeyZoomSpeed = 2.0 oc.KeyPanSpeed = 35.0 // Subscribe to events gui.Manager().SubscribeID(window.OnMouseUp, &oc, oc.onMouse) gui.Manager().SubscribeID(window.OnMouseDown, &oc, oc.onMouse) gui.Manager().SubscribeID(window.OnScroll, &oc, oc.onScroll) gui.Manager().SubscribeID(window.OnKeyDown, &oc, oc.onKey) gui.Manager().SubscribeID(window.OnKeyRepeat, &oc, oc.onKey) oc.SubscribeID(window.OnCursor, &oc, oc.onCursor) return oc } // Dispose unsubscribes from all events. func (oc *OrbitControl) Dispose() { gui.Manager().UnsubscribeID(window.OnMouseUp, &oc) gui.Manager().UnsubscribeID(window.OnMouseDown, &oc) gui.Manager().UnsubscribeID(window.OnScroll, &oc) gui.Manager().UnsubscribeID(window.OnKeyDown, &oc) gui.Manager().UnsubscribeID(window.OnKeyRepeat, &oc) oc.UnsubscribeID(window.OnCursor, &oc) } // Reset resets the orbit control. func (oc *OrbitControl) Reset() { oc.target = *math32.NewVec3() } // Target returns the current orbit target. func (oc *OrbitControl) Target() math32.Vector3 { return oc.target } // Enabled returns the current OrbitEnabled bitmask. func (oc *OrbitControl) Enabled() OrbitEnabled { return oc.enabled } // SetEnabled sets the current OrbitEnabled bitmask. func (oc *OrbitControl) SetEnabled(bitmask OrbitEnabled) { oc.enabled = bitmask } // Rotate rotates the camera around the target by the specified angles. func (oc *OrbitControl) Rotate(thetaDelta, phiDelta float32) { const EPS = 0.0001 // Compute direction vector from target to camera tcam := oc.cam.Position() tcam.Sub(&oc.target) // Calculate angles based on current camera position plus deltas radius := tcam.Length() theta := math32.Atan2(tcam.X, tcam.Z) + thetaDelta phi := math32.Acos(tcam.Y/radius) + phiDelta // Restrict phi and theta to be between desired limits phi = math32.Clamp(phi, oc.MinPolarAngle, oc.MaxPolarAngle) phi = math32.Clamp(phi, EPS, math32.Pi-EPS) theta = math32.Clamp(theta, oc.MinAzimuthAngle, oc.MaxAzimuthAngle) // Calculate new cartesian coordinates tcam.X = radius * math32.Sin(phi) * math32.Sin(theta) tcam.Y = radius * math32.Cos(phi) tcam.Z = radius * math32.Sin(phi) * math32.Cos(theta) // Update camera position and orientation oc.cam.SetPositionVec(oc.target.Clone().Add(&tcam)) oc.cam.LookAt(&oc.target, &oc.up) } // Zoom moves the camera closer or farther from the target the specified amount // and also updates the camera's orthographic size to match. func (oc *OrbitControl) Zoom(delta float32) { // Compute direction vector from target to camera tcam := oc.cam.Position() tcam.Sub(&oc.target) // Calculate new distance from target and apply limits dist := tcam.Length() * (1 + delta/10) dist = math32.Max(oc.MinDistance, math32.Min(oc.MaxDistance, dist)) tcam.SetLength(dist) // Update orthographic size and camera position with new distance oc.cam.UpdateSize(tcam.Length()) oc.cam.SetPositionVec(oc.target.Clone().Add(&tcam)) } // Pan pans the camera and target the specified amount on the plane perpendicular to the viewing direction. func (oc *OrbitControl) Pan(deltaX, deltaY float32) { // Compute direction vector from camera to target position := oc.cam.Position() vdir := oc.target.Clone().Sub(&position) // Conversion constant between an on-screen cursor delta and its projection on the target plane c := 2 * vdir.Length() * math32.Tan((oc.cam.Fov()/2.0)*math32.Pi/180.0) / oc.winSize() // Calculate pan components, scale by the converted offsets and combine them var pan, panX, panY math32.Vector3 panX.CrossVectors(&oc.up, vdir).Normalize() panY.CrossVectors(vdir, &panX).Normalize() panY.MultiplyScalar(c * deltaY) panX.MultiplyScalar(c * deltaX) pan.AddVectors(&panX, &panY) // Add pan offset to camera and target oc.cam.SetPositionVec(position.Add(&pan)) oc.target.Add(&pan) } // onMouse is called when an OnMouseDown/OnMouseUp event is received. func (oc *OrbitControl) onMouse(evname string, ev interface{}) { // If nothing enabled ignore event if oc.enabled == OrbitNone { return } switch evname { case window.OnMouseDown: gui.Manager().SetCursorFocus(oc) mev := ev.(*window.MouseEvent) switch mev.Button { case window.MouseButtonLeft: // Rotate if oc.enabled&OrbitRot != 0 { oc.state = stateRotate oc.rotStart.Set(mev.Xpos, mev.Ypos) } case window.MouseButtonMiddle: // Zoom if oc.enabled&OrbitZoom != 0 { oc.state = stateZoom oc.zoomStart = mev.Ypos } case window.MouseButtonRight: // Pan if oc.enabled&OrbitPan != 0 { oc.state = statePan oc.panStart.Set(mev.Xpos, mev.Ypos) } } case window.OnMouseUp: gui.Manager().SetCursorFocus(nil) oc.state = stateNone } } // onCursor is called when an OnCursor event is received. func (oc *OrbitControl) onCursor(evname string, ev interface{}) { // If nothing enabled ignore event if oc.enabled == OrbitNone || oc.state == stateNone { return } mev := ev.(*window.CursorEvent) switch oc.state { case stateRotate: c := -2 * math32.Pi * oc.RotSpeed / oc.winSize() oc.Rotate(c*(mev.Xpos-oc.rotStart.X), c*(mev.Ypos-oc.rotStart.Y)) oc.rotStart.Set(mev.Xpos, mev.Ypos) case stateZoom: oc.Zoom(oc.ZoomSpeed * (mev.Ypos - oc.zoomStart)) oc.zoomStart = mev.Ypos case statePan: oc.Pan(mev.Xpos-oc.panStart.X, mev.Ypos-oc.panStart.Y) oc.panStart.Set(mev.Xpos, mev.Ypos) } } // onScroll is called when an OnScroll event is received. func (oc *OrbitControl) onScroll(evname string, ev interface{}) { if oc.enabled&OrbitZoom != 0 { sev := ev.(*window.ScrollEvent) oc.Zoom(-sev.Yoffset) } } // onKey is called when an OnKeyDown/OnKeyRepeat event is received. func (oc *OrbitControl) onKey(evname string, ev interface{}) { // If keyboard control is disabled ignore event if oc.enabled&OrbitKeys == 0 { return } kev := ev.(*window.KeyEvent) if kev.Mods == 0 && oc.enabled&OrbitRot != 0 { switch kev.Key { case window.KeyUp: oc.Rotate(0, -oc.KeyRotSpeed) case window.KeyDown: oc.Rotate(0, oc.KeyRotSpeed) case window.KeyLeft: oc.Rotate(-oc.KeyRotSpeed, 0) case window.KeyRight: oc.Rotate(oc.KeyRotSpeed, 0) } } if kev.Mods == window.ModControl && oc.enabled&OrbitZoom != 0 { switch kev.Key { case window.KeyUp: oc.Zoom(-oc.KeyZoomSpeed) case window.KeyDown: oc.Zoom(oc.KeyZoomSpeed) } } if kev.Mods == window.ModShift && oc.enabled&OrbitPan != 0 { switch kev.Key { case window.KeyUp: oc.Pan(0, oc.KeyPanSpeed) case window.KeyDown: oc.Pan(0, -oc.KeyPanSpeed) case window.KeyLeft: oc.Pan(oc.KeyPanSpeed, 0) case window.KeyRight: oc.Pan(-oc.KeyPanSpeed, 0) } } } // winSize returns the window height or width based on the camera reference axis. func (oc *OrbitControl) winSize() float32 { width, size := window.Get().GetSize() if oc.cam.Axis() == Horizontal { size = width } return float32(size) }
camera/orbit_control.go
0.865622
0.550245
orbit_control.go
starcoder
package sampler import ( "github.com/mattkimber/gorender/internal/geometry" "image" "image/color" "image/draw" "math" "math/rand" ) type Sample struct { Location geometry.Vector2 Influence float64 } type SampleList []Sample type Samples [][]SampleList func (s Samples) Width() int { return len(s) } func (s Samples) Height() int { return len(s[0]) } func (s Samples) GetImage() (img *image.RGBA) { rect := image.Rect(0, 0, 200, 200) img = image.NewRGBA(rect) // Clear to white draw.Draw(img, rect, image.NewUniform(color.White), image.Point{}, draw.Over) samples := s[0][0] for _, smp := range samples { x, y := int(100.0+(smp.Location.X*50.0)), int(100.0+(smp.Location.Y*50.0)) if x >= 0 && y >= 0 && x < 200 && y < 200 { img.Set(x, y, color.RGBA{R: uint8(smp.Influence * 255.0), G: 0, B: 0, A: 255}) } } return } func Get(name string) func(int, int, int, float64, float64) Samples { switch name { case "square": return Square case "disc": return Disc default: return Square } } func Square(width, height int, accuracy int, overlap float64, falloff float64) (result Samples) { fAccuracy := float64(accuracy) centre := geometry.Vector2{ X: 0.5, Y: 0.5, } var location geometry.Vector2 result = make([][]SampleList, width) for i := 0; i < width; i++ { result[i] = make([]SampleList, height) for j := 0; j < height; j++ { result[i][j] = make(SampleList, accuracy*accuracy) for k := 0; k < accuracy; k++ { fractionK := (1.0 + float64(k)) / (1.0 + fAccuracy) for l := 0; l < accuracy; l++ { fractionL := (1.0 + float64(l)) / (1.0 + fAccuracy) fraction := geometry.Vector2{ X: fractionK, Y: fractionL, } location = geometry.Vector2{ X: (float64(i*accuracy) + (fractionK*(1.0+overlap))*fAccuracy) / (float64(width * accuracy)), Y: (float64(j*accuracy) + (fractionL*(1.0+overlap))*fAccuracy) / (float64(height * accuracy)), } influence := 1.0 - (math.Pow(centre.DistanceSquared(fraction), falloff) * 2.0) if influence < 0 { influence = 0 } result[i][j][l+(k*accuracy)] = Sample{ Location: location, Influence: influence, } } } } } return result } const discs = 10 var discCache [][]geometry.Vector2 func Disc(width, height int, accuracy int, overlap float64, falloff float64) (result Samples) { radiusSquared := (0.5 + overlap) * (0.5 + overlap) var location geometry.Vector2 result = make([][]SampleList, width) scaleVec := geometry.Vector2{X: float64(width), Y: float64(height)} for i := 0; i < width; i++ { result[i] = make([]SampleList, height) for j := 0; j < height; j++ { loc := geometry.Vector2{X: float64(i) / scaleVec.X, Y: float64(j) / scaleVec.Y} disc := getPoissonDisc(accuracy, overlap) result[i][j] = make(SampleList, len(disc)) for k, s := range disc { location = loc.Add(s.DivideByVector(scaleVec)) influence := 1.0 - (math.Pow(radiusSquared, falloff)) if influence < 0 { influence = 0 } result[i][j][k] = Sample{ Location: location, Influence: influence, } } } } return } // Get a poisson disc using the naive/slow dart throwing algorithm func getPoissonDisc(accuracy int, overlap float64) []geometry.Vector2 { if discCache == nil { discCache = make([][]geometry.Vector2, discs) } discNum := rand.Intn(discs) if discCache[discNum] != nil { return discCache[discNum] } numSamples := accuracy * accuracy distance := 1.0 / float64(accuracy) distance = distance * distance radius := 0.5 + overlap disc := make([]geometry.Vector2, 0) var valid bool // Create a poisson disc by dart throwing for i := 0; i < numSamples*1000; i++ { valid = true trial := geometry.Vector2{X: (rand.Float64() - 0.5) * 2.0 * radius, Y: (rand.Float64() - 0.5) * 2.0 * radius} for k := 0; k < len(disc); k++ { if trial.LengthSquared() > radius*radius || trial.DistanceSquared(disc[k]) < distance { valid = false break } } if valid { disc = append(disc, trial) if len(disc) >= numSamples { break } } } discCache[discNum] = disc return disc }
internal/sampler/sampler.go
0.789518
0.554832
sampler.go
starcoder
package nbt import "strconv" // ListByte satisfies the List interface for a list of Bytes type ListByte []Byte // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListByte) Equal(e interface{}) bool { m, ok := e.(ListByte) if !ok { var n *ListByte if n, ok = e.(*ListByte); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagByte && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListByte) Copy() Data { m := make(ListByte, len(l)) for n, e := range l { m[n] = e.Copy().(Byte) } return &m } func (l ListByte) String() string { s := strconv.Itoa(len(l)) + " entries of type Byte {" for _, d := range l { s += "\n Byte: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListByte) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListByte) TagType() TagID { return TagByte } // Set sets the data at the given position. It does not append func (l ListByte) Set(i int, d Data) error { if m, ok := d.(Byte); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagByte, d.Type()} } return nil } // Get returns the data at the given positon func (l ListByte) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListByte) Append(d ...Data) error { toAppend := make(ListByte, len(d)) for n, e := range d { if f, ok := e.(Byte); ok { toAppend[n] = f } else { return &WrongTag{TagByte, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListByte) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListByte, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Byte); ok { toInsert[n] = f } else { return &WrongTag{TagByte, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListByte) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListByte) Len() int { return len(l) } // ListByte returns the list as a specifically typed List func (l ListData) ListByte() ListByte { if l.tagType != TagByte { return nil } s := make(ListByte, len(l.data)) for n, v := range l.data { s[n] = v.(Byte) } return s } // ListShort satisfies the List interface for a list of Shorts type ListShort []Short // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListShort) Equal(e interface{}) bool { m, ok := e.(ListShort) if !ok { var n *ListShort if n, ok = e.(*ListShort); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagShort && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListShort) Copy() Data { m := make(ListShort, len(l)) for n, e := range l { m[n] = e.Copy().(Short) } return &m } func (l ListShort) String() string { s := strconv.Itoa(len(l)) + " entries of type Short {" for _, d := range l { s += "\n Short: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListShort) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListShort) TagType() TagID { return TagShort } // Set sets the data at the given position. It does not append func (l ListShort) Set(i int, d Data) error { if m, ok := d.(Short); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagShort, d.Type()} } return nil } // Get returns the data at the given positon func (l ListShort) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListShort) Append(d ...Data) error { toAppend := make(ListShort, len(d)) for n, e := range d { if f, ok := e.(Short); ok { toAppend[n] = f } else { return &WrongTag{TagShort, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListShort) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListShort, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Short); ok { toInsert[n] = f } else { return &WrongTag{TagShort, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListShort) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListShort) Len() int { return len(l) } // ListShort returns the list as a specifically typed List func (l ListData) ListShort() ListShort { if l.tagType != TagShort { return nil } s := make(ListShort, len(l.data)) for n, v := range l.data { s[n] = v.(Short) } return s } // ListInt satisfies the List interface for a list of Ints type ListInt []Int // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListInt) Equal(e interface{}) bool { m, ok := e.(ListInt) if !ok { var n *ListInt if n, ok = e.(*ListInt); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagInt && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListInt) Copy() Data { m := make(ListInt, len(l)) for n, e := range l { m[n] = e.Copy().(Int) } return &m } func (l ListInt) String() string { s := strconv.Itoa(len(l)) + " entries of type Int {" for _, d := range l { s += "\n Int: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListInt) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListInt) TagType() TagID { return TagInt } // Set sets the data at the given position. It does not append func (l ListInt) Set(i int, d Data) error { if m, ok := d.(Int); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagInt, d.Type()} } return nil } // Get returns the data at the given positon func (l ListInt) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListInt) Append(d ...Data) error { toAppend := make(ListInt, len(d)) for n, e := range d { if f, ok := e.(Int); ok { toAppend[n] = f } else { return &WrongTag{TagInt, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListInt) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListInt, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Int); ok { toInsert[n] = f } else { return &WrongTag{TagInt, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListInt) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListInt) Len() int { return len(l) } // ListInt returns the list as a specifically typed List func (l ListData) ListInt() ListInt { if l.tagType != TagInt { return nil } s := make(ListInt, len(l.data)) for n, v := range l.data { s[n] = v.(Int) } return s } // ListLong satisfies the List interface for a list of Longs type ListLong []Long // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListLong) Equal(e interface{}) bool { m, ok := e.(ListLong) if !ok { var n *ListLong if n, ok = e.(*ListLong); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagLong && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListLong) Copy() Data { m := make(ListLong, len(l)) for n, e := range l { m[n] = e.Copy().(Long) } return &m } func (l ListLong) String() string { s := strconv.Itoa(len(l)) + " entries of type Long {" for _, d := range l { s += "\n Long: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListLong) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListLong) TagType() TagID { return TagLong } // Set sets the data at the given position. It does not append func (l ListLong) Set(i int, d Data) error { if m, ok := d.(Long); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagLong, d.Type()} } return nil } // Get returns the data at the given positon func (l ListLong) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListLong) Append(d ...Data) error { toAppend := make(ListLong, len(d)) for n, e := range d { if f, ok := e.(Long); ok { toAppend[n] = f } else { return &WrongTag{TagLong, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListLong) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListLong, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Long); ok { toInsert[n] = f } else { return &WrongTag{TagLong, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListLong) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListLong) Len() int { return len(l) } // ListLong returns the list as a specifically typed List func (l ListData) ListLong() ListLong { if l.tagType != TagLong { return nil } s := make(ListLong, len(l.data)) for n, v := range l.data { s[n] = v.(Long) } return s } // ListFloat satisfies the List interface for a list of Floats type ListFloat []Float // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListFloat) Equal(e interface{}) bool { m, ok := e.(ListFloat) if !ok { var n *ListFloat if n, ok = e.(*ListFloat); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagFloat && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListFloat) Copy() Data { m := make(ListFloat, len(l)) for n, e := range l { m[n] = e.Copy().(Float) } return &m } func (l ListFloat) String() string { s := strconv.Itoa(len(l)) + " entries of type Float {" for _, d := range l { s += "\n Float: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListFloat) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListFloat) TagType() TagID { return TagFloat } // Set sets the data at the given position. It does not append func (l ListFloat) Set(i int, d Data) error { if m, ok := d.(Float); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagFloat, d.Type()} } return nil } // Get returns the data at the given positon func (l ListFloat) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListFloat) Append(d ...Data) error { toAppend := make(ListFloat, len(d)) for n, e := range d { if f, ok := e.(Float); ok { toAppend[n] = f } else { return &WrongTag{TagFloat, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListFloat) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListFloat, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Float); ok { toInsert[n] = f } else { return &WrongTag{TagFloat, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListFloat) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListFloat) Len() int { return len(l) } // ListFloat returns the list as a specifically typed List func (l ListData) ListFloat() ListFloat { if l.tagType != TagFloat { return nil } s := make(ListFloat, len(l.data)) for n, v := range l.data { s[n] = v.(Float) } return s } // ListDouble satisfies the List interface for a list of Doubles type ListDouble []Double // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListDouble) Equal(e interface{}) bool { m, ok := e.(ListDouble) if !ok { var n *ListDouble if n, ok = e.(*ListDouble); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagDouble && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListDouble) Copy() Data { m := make(ListDouble, len(l)) for n, e := range l { m[n] = e.Copy().(Double) } return &m } func (l ListDouble) String() string { s := strconv.Itoa(len(l)) + " entries of type Double {" for _, d := range l { s += "\n Double: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListDouble) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListDouble) TagType() TagID { return TagDouble } // Set sets the data at the given position. It does not append func (l ListDouble) Set(i int, d Data) error { if m, ok := d.(Double); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagDouble, d.Type()} } return nil } // Get returns the data at the given positon func (l ListDouble) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListDouble) Append(d ...Data) error { toAppend := make(ListDouble, len(d)) for n, e := range d { if f, ok := e.(Double); ok { toAppend[n] = f } else { return &WrongTag{TagDouble, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListDouble) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListDouble, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Double); ok { toInsert[n] = f } else { return &WrongTag{TagDouble, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListDouble) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListDouble) Len() int { return len(l) } // ListDouble returns the list as a specifically typed List func (l ListData) ListDouble() ListDouble { if l.tagType != TagDouble { return nil } s := make(ListDouble, len(l.data)) for n, v := range l.data { s[n] = v.(Double) } return s } // ListCompound satisfies the List interface for a list of Compounds type ListCompound []Compound // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListCompound) Equal(e interface{}) bool { m, ok := e.(ListCompound) if !ok { var n *ListCompound if n, ok = e.(*ListCompound); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagCompound && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListCompound) Copy() Data { m := make(ListCompound, len(l)) for n, e := range l { m[n] = e.Copy().(Compound) } return &m } func (l ListCompound) String() string { s := strconv.Itoa(len(l)) + " entries of type Compound {" for _, d := range l { s += "\n Compound: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListCompound) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListCompound) TagType() TagID { return TagCompound } // Set sets the data at the given position. It does not append func (l ListCompound) Set(i int, d Data) error { if m, ok := d.(Compound); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagCompound, d.Type()} } return nil } // Get returns the data at the given positon func (l ListCompound) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListCompound) Append(d ...Data) error { toAppend := make(ListCompound, len(d)) for n, e := range d { if f, ok := e.(Compound); ok { toAppend[n] = f } else { return &WrongTag{TagCompound, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListCompound) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListCompound, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Compound); ok { toInsert[n] = f } else { return &WrongTag{TagCompound, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListCompound) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) (*l)[i] = nil *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListCompound) Len() int { return len(l) } // ListCompound returns the list as a specifically typed List func (l ListData) ListCompound() ListCompound { if l.tagType != TagCompound { return nil } s := make(ListCompound, len(l.data)) for n, v := range l.data { s[n] = v.(Compound) } return s } // ListIntArray satisfies the List interface for a list of IntArrays type ListIntArray []IntArray // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListIntArray) Equal(e interface{}) bool { m, ok := e.(ListIntArray) if !ok { var n *ListIntArray if n, ok = e.(*ListIntArray); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagIntArray && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListIntArray) Copy() Data { m := make(ListIntArray, len(l)) for n, e := range l { m[n] = e.Copy().(IntArray) } return &m } func (l ListIntArray) String() string { s := strconv.Itoa(len(l)) + " entries of type IntArray {" for _, d := range l { s += "\n IntArray: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListIntArray) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListIntArray) TagType() TagID { return TagIntArray } // Set sets the data at the given position. It does not append func (l ListIntArray) Set(i int, d Data) error { if m, ok := d.(IntArray); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagIntArray, d.Type()} } return nil } // Get returns the data at the given positon func (l ListIntArray) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListIntArray) Append(d ...Data) error { toAppend := make(ListIntArray, len(d)) for n, e := range d { if f, ok := e.(IntArray); ok { toAppend[n] = f } else { return &WrongTag{TagIntArray, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListIntArray) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListIntArray, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(IntArray); ok { toInsert[n] = f } else { return &WrongTag{TagIntArray, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListIntArray) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListIntArray) Len() int { return len(l) } // ListIntArray returns the list as a specifically typed List func (l ListData) ListIntArray() ListIntArray { if l.tagType != TagIntArray { return nil } s := make(ListIntArray, len(l.data)) for n, v := range l.data { s[n] = v.(IntArray) } return s } // ListBool satisfies the List interface for a list of Bools type ListBool []Bool // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListBool) Equal(e interface{}) bool { m, ok := e.(ListBool) if !ok { var n *ListBool if n, ok = e.(*ListBool); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagBool && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListBool) Copy() Data { m := make(ListBool, len(l)) for n, e := range l { m[n] = e.Copy().(Bool) } return &m } func (l ListBool) String() string { s := strconv.Itoa(len(l)) + " entries of type Bool {" for _, d := range l { s += "\n Bool: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListBool) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListBool) TagType() TagID { return TagBool } // Set sets the data at the given position. It does not append func (l ListBool) Set(i int, d Data) error { if m, ok := d.(Bool); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagBool, d.Type()} } return nil } // Get returns the data at the given positon func (l ListBool) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListBool) Append(d ...Data) error { toAppend := make(ListBool, len(d)) for n, e := range d { if f, ok := e.(Bool); ok { toAppend[n] = f } else { return &WrongTag{TagBool, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListBool) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListBool, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Bool); ok { toInsert[n] = f } else { return &WrongTag{TagBool, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListBool) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListBool) Len() int { return len(l) } // ListBool returns the list as a specifically typed List func (l ListData) ListBool() ListBool { if l.tagType != TagBool { return nil } s := make(ListBool, len(l.data)) for n, v := range l.data { s[n] = v.(Bool) } return s } // ListUint8 satisfies the List interface for a list of Uint8s type ListUint8 []Uint8 // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListUint8) Equal(e interface{}) bool { m, ok := e.(ListUint8) if !ok { var n *ListUint8 if n, ok = e.(*ListUint8); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagUint8 && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListUint8) Copy() Data { m := make(ListUint8, len(l)) for n, e := range l { m[n] = e.Copy().(Uint8) } return &m } func (l ListUint8) String() string { s := strconv.Itoa(len(l)) + " entries of type Uint8 {" for _, d := range l { s += "\n Uint8: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListUint8) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListUint8) TagType() TagID { return TagUint8 } // Set sets the data at the given position. It does not append func (l ListUint8) Set(i int, d Data) error { if m, ok := d.(Uint8); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagUint8, d.Type()} } return nil } // Get returns the data at the given positon func (l ListUint8) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListUint8) Append(d ...Data) error { toAppend := make(ListUint8, len(d)) for n, e := range d { if f, ok := e.(Uint8); ok { toAppend[n] = f } else { return &WrongTag{TagUint8, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListUint8) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListUint8, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Uint8); ok { toInsert[n] = f } else { return &WrongTag{TagUint8, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListUint8) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListUint8) Len() int { return len(l) } // ListUint8 returns the list as a specifically typed List func (l ListData) ListUint8() ListUint8 { if l.tagType != TagUint8 { return nil } s := make(ListUint8, len(l.data)) for n, v := range l.data { s[n] = v.(Uint8) } return s } // ListUint16 satisfies the List interface for a list of Uint16s type ListUint16 []Uint16 // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListUint16) Equal(e interface{}) bool { m, ok := e.(ListUint16) if !ok { var n *ListUint16 if n, ok = e.(*ListUint16); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagUint16 && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListUint16) Copy() Data { m := make(ListUint16, len(l)) for n, e := range l { m[n] = e.Copy().(Uint16) } return &m } func (l ListUint16) String() string { s := strconv.Itoa(len(l)) + " entries of type Uint16 {" for _, d := range l { s += "\n Uint16: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListUint16) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListUint16) TagType() TagID { return TagUint16 } // Set sets the data at the given position. It does not append func (l ListUint16) Set(i int, d Data) error { if m, ok := d.(Uint16); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagUint16, d.Type()} } return nil } // Get returns the data at the given positon func (l ListUint16) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListUint16) Append(d ...Data) error { toAppend := make(ListUint16, len(d)) for n, e := range d { if f, ok := e.(Uint16); ok { toAppend[n] = f } else { return &WrongTag{TagUint16, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListUint16) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListUint16, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Uint16); ok { toInsert[n] = f } else { return &WrongTag{TagUint16, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListUint16) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListUint16) Len() int { return len(l) } // ListUint16 returns the list as a specifically typed List func (l ListData) ListUint16() ListUint16 { if l.tagType != TagUint16 { return nil } s := make(ListUint16, len(l.data)) for n, v := range l.data { s[n] = v.(Uint16) } return s } // ListUint32 satisfies the List interface for a list of Uint32s type ListUint32 []Uint32 // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListUint32) Equal(e interface{}) bool { m, ok := e.(ListUint32) if !ok { var n *ListUint32 if n, ok = e.(*ListUint32); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagUint32 && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListUint32) Copy() Data { m := make(ListUint32, len(l)) for n, e := range l { m[n] = e.Copy().(Uint32) } return &m } func (l ListUint32) String() string { s := strconv.Itoa(len(l)) + " entries of type Uint32 {" for _, d := range l { s += "\n Uint32: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListUint32) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListUint32) TagType() TagID { return TagUint32 } // Set sets the data at the given position. It does not append func (l ListUint32) Set(i int, d Data) error { if m, ok := d.(Uint32); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagUint32, d.Type()} } return nil } // Get returns the data at the given positon func (l ListUint32) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListUint32) Append(d ...Data) error { toAppend := make(ListUint32, len(d)) for n, e := range d { if f, ok := e.(Uint32); ok { toAppend[n] = f } else { return &WrongTag{TagUint32, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListUint32) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListUint32, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Uint32); ok { toInsert[n] = f } else { return &WrongTag{TagUint32, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListUint32) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListUint32) Len() int { return len(l) } // ListUint32 returns the list as a specifically typed List func (l ListData) ListUint32() ListUint32 { if l.tagType != TagUint32 { return nil } s := make(ListUint32, len(l.data)) for n, v := range l.data { s[n] = v.(Uint32) } return s } // ListUint64 satisfies the List interface for a list of Uint64s type ListUint64 []Uint64 // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListUint64) Equal(e interface{}) bool { m, ok := e.(ListUint64) if !ok { var n *ListUint64 if n, ok = e.(*ListUint64); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagUint64 && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListUint64) Copy() Data { m := make(ListUint64, len(l)) for n, e := range l { m[n] = e.Copy().(Uint64) } return &m } func (l ListUint64) String() string { s := strconv.Itoa(len(l)) + " entries of type Uint64 {" for _, d := range l { s += "\n Uint64: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListUint64) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListUint64) TagType() TagID { return TagUint64 } // Set sets the data at the given position. It does not append func (l ListUint64) Set(i int, d Data) error { if m, ok := d.(Uint64); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagUint64, d.Type()} } return nil } // Get returns the data at the given positon func (l ListUint64) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListUint64) Append(d ...Data) error { toAppend := make(ListUint64, len(d)) for n, e := range d { if f, ok := e.(Uint64); ok { toAppend[n] = f } else { return &WrongTag{TagUint64, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListUint64) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListUint64, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Uint64); ok { toInsert[n] = f } else { return &WrongTag{TagUint64, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListUint64) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListUint64) Len() int { return len(l) } // ListUint64 returns the list as a specifically typed List func (l ListData) ListUint64() ListUint64 { if l.tagType != TagUint64 { return nil } s := make(ListUint64, len(l.data)) for n, v := range l.data { s[n] = v.(Uint64) } return s } // ListComplex64 satisfies the List interface for a list of Complex64s type ListComplex64 []Complex64 // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListComplex64) Equal(e interface{}) bool { m, ok := e.(ListComplex64) if !ok { var n *ListComplex64 if n, ok = e.(*ListComplex64); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagComplex64 && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListComplex64) Copy() Data { m := make(ListComplex64, len(l)) for n, e := range l { m[n] = e.Copy().(Complex64) } return &m } func (l ListComplex64) String() string { s := strconv.Itoa(len(l)) + " entries of type Complex64 {" for _, d := range l { s += "\n Complex64: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListComplex64) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListComplex64) TagType() TagID { return TagComplex64 } // Set sets the data at the given position. It does not append func (l ListComplex64) Set(i int, d Data) error { if m, ok := d.(Complex64); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagComplex64, d.Type()} } return nil } // Get returns the data at the given positon func (l ListComplex64) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListComplex64) Append(d ...Data) error { toAppend := make(ListComplex64, len(d)) for n, e := range d { if f, ok := e.(Complex64); ok { toAppend[n] = f } else { return &WrongTag{TagComplex64, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListComplex64) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListComplex64, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Complex64); ok { toInsert[n] = f } else { return &WrongTag{TagComplex64, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListComplex64) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListComplex64) Len() int { return len(l) } // ListComplex64 returns the list as a specifically typed List func (l ListData) ListComplex64() ListComplex64 { if l.tagType != TagComplex64 { return nil } s := make(ListComplex64, len(l.data)) for n, v := range l.data { s[n] = v.(Complex64) } return s } // ListComplex128 satisfies the List interface for a list of Complex128s type ListComplex128 []Complex128 // Equal satisfies the equaler.Equaler interface, allowing for types to be // checked for equality func (l ListComplex128) Equal(e interface{}) bool { m, ok := e.(ListComplex128) if !ok { var n *ListComplex128 if n, ok = e.(*ListComplex128); ok { m = *n } } if ok { if len(l) == len(m) { for n, t := range m { if !t.Equal(l[n]) { return false } } return true } } else if d, ok := e.(List); ok && d.TagType() == TagComplex128 && d.Len() == len(l) { for i := 0; i < d.Len(); i++ { if !d.Get(i).Equal(l[i]) { return false } } return true } return false } // Copy simply returns a deep-copy the the data func (l ListComplex128) Copy() Data { m := make(ListComplex128, len(l)) for n, e := range l { m[n] = e.Copy().(Complex128) } return &m } func (l ListComplex128) String() string { s := strconv.Itoa(len(l)) + " entries of type Complex128 {" for _, d := range l { s += "\n Complex128: " + indent(d.String()) } return s + "\n}" } // Type returns the TagID of the data func (ListComplex128) Type() TagID { return TagList } // TagType returns the TagID of the type of tag this list contains func (ListComplex128) TagType() TagID { return TagComplex128 } // Set sets the data at the given position. It does not append func (l ListComplex128) Set(i int, d Data) error { if m, ok := d.(Complex128); ok { if i <= 0 || i >= len(l) { return ErrBadRange } l[i] = m } else { return &WrongTag{TagComplex128, d.Type()} } return nil } // Get returns the data at the given positon func (l ListComplex128) Get(i int) Data { return l[i] } // Append adds data to the list func (l *ListComplex128) Append(d ...Data) error { toAppend := make(ListComplex128, len(d)) for n, e := range d { if f, ok := e.(Complex128); ok { toAppend[n] = f } else { return &WrongTag{TagComplex128, e.Type()} } } *l = append(*l, toAppend...) return nil } // Insert will add the given data at the specified position, moving other // up func (l *ListComplex128) Insert(i int, d ...Data) error { if i >= len(*l) { return l.Append(d...) } toInsert := make(ListComplex128, len(d), len(d)+len(*l)-i) for n, e := range d { if f, ok := e.(Complex128); ok { toInsert[n] = f } else { return &WrongTag{TagComplex128, e.Type()} } } *l = append((*l)[:i], append(toInsert, (*l)[i:]...)...) return nil } // Remove deletes the specified position and shifts remaing data down func (l *ListComplex128) Remove(i int) { if i >= len(*l) { return } copy((*l)[i:], (*l)[i+1:]) *l = (*l)[:len(*l)-1] } // Len returns the length of the list func (l ListComplex128) Len() int { return len(l) } // ListComplex128 returns the list as a specifically typed List func (l ListData) ListComplex128() ListComplex128 { if l.tagType != TagComplex128 { return nil } s := make(ListComplex128, len(l.data)) for n, v := range l.data { s[n] = v.(Complex128) } return s }
nbt/lists.go
0.724188
0.443781
lists.go
starcoder
package geo import ( "math" ) // Represents a Physical Point in geographic notation [lat, lng]. type Point struct { lat float64 lng float64 } const ( EARTH_RADIUS = 6371 // Earth's radius ~= 6,371km, according to wikipedia ) // Returns a new Point populated by the passed in latitude (lat) and longitude (lng) values. func NewPoint(lat float64, lng float64) *Point { return &Point{lat: lat, lng: lng} } // Returns Point p's latitude. func (p *Point) Lat() float64 { return p.lat } // Returns Point p's longitude. func (p *Point) Lng() float64 { return p.lng } // Returns a Point populated with the lat and lng coordinates of transposing the origin point the distance (in meters) supplied by the compass bearing (in degrees) supplied. // Original Implementation from: http://www.movable-type.co.uk/scripts/latlong.html func (p *Point) PointAtDistanceAndBearing(dist float64, bearing float64) *Point { dr := dist / EARTH_RADIUS bearing = (bearing * (math.Pi / 180.0)) lat1 := (p.lat * (math.Pi / 180.0)) lng1 := (p.lng * (math.Pi / 180.0)) lat2_part1 := math.Sin(lat1) * math.Cos(dr) lat2_part2 := math.Cos(lat1) * math.Sin(dr) * math.Cos(bearing) lat2 := math.Asin(lat2_part1 + lat2_part2) lng2_part1 := math.Sin(bearing) * math.Sin(dr) * math.Cos(lat1) lng2_part2 := math.Cos(dr) - (math.Sin(lat1) * math.Sin(lat2)) lng2 := lng1 + math.Atan2(lng2_part1, lng2_part2) lng2 = math.Mod((lng2+3*math.Pi), (2*math.Pi)) - math.Pi lat2 = lat2 * (180.0 / math.Pi) lng2 = lng2 * (180.0 / math.Pi) return &Point{lat: lat2, lng: lng2} } // Calculates the Haversine distance between two points. // Original Implementation from: http://www.movable-type.co.uk/scripts/latlong.html func (p *Point) GreatCircleDistance(p2 *Point) float64 { dLat := (p2.lat - p.lat) * (math.Pi / 180.0) dLon := (p2.lng - p.lng) * (math.Pi / 180.0) lat1 := p.lat * (math.Pi / 180.0) lat2 := p2.lat * (math.Pi / 180.0) a1 := math.Sin(dLat/2) * math.Sin(dLat/2) a2 := math.Sin(dLon/2) * math.Sin(dLon/2) * math.Cos(lat1) * math.Cos(lat2) a := a1 + a2 c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) return EARTH_RADIUS * c }
point.go
0.901232
0.646865
point.go
starcoder
package prettytest import ( "fmt" "os" "reflect" ) type Assertion struct { Line int Name string Filename string ErrorMessage string Passed bool suite *Suite testFunc *TestFunc } func (assertion *Assertion) fail() { assertion.Passed = false assertion.testFunc.Status = STATUS_FAIL logError(&Error{assertion.suite, assertion.testFunc, assertion}) } // Not asserts the given assertion is false. func (s *Suite) Not(result *Assertion, messages ...string) *Assertion { assertion := s.setup(fmt.Sprintf("Expected assertion to fail"), messages) if result.Passed { assertion.fail() } else { result.Passed = true assertion.testFunc.resetLastError() } return assertion } // Not asserts the given assertion is false. func (s *Suite) False(value bool, messages ...string) *Assertion { assertion := s.setup(fmt.Sprintf("Expected value to be false"), messages) if value { assertion.fail() } return assertion } // Equal asserts that the expected value equals the actual value. func (s *Suite) Equal(exp, act interface{}, messages ...string) *Assertion { actType := reflect.TypeOf(act) expType := reflect.TypeOf(exp) assertion := s.setup(fmt.Sprintf("Expected %v[%s] to be equal to %v[%s]", act, actType, exp, expType), messages) if exp != act { assertion.fail() } return assertion } // True asserts that the value is true. func (s *Suite) True(value bool, messages ...string) *Assertion { assertion := s.setup(fmt.Sprintf("Expected value to be true"), messages) if !value { assertion.fail() } return assertion } // Path asserts that the given path exists. func (s *Suite) Path(path string, messages ...string) *Assertion { assertion := s.setup(fmt.Sprintf("Path %s doesn't exist", path), messages) if _, err := os.Stat(path); err != nil { assertion.fail() } return assertion } // Nil asserts that the value is nil. func (s *Suite) Nil(value interface{}, messages ...string) *Assertion { assertion := s.setup(fmt.Sprintf("Value %v is not nil", value), messages) if value == nil { return assertion } val := reflect.ValueOf(value) val.Kind() switch v := reflect.ValueOf(value); v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: if !v.IsNil() { assertion.fail() } } return assertion } // Error logs an error and marks the test function as failed. func (s *Suite) Error(args ...interface{}) { assertion := s.setup("", []string{}) assertion.testFunc.Status = STATUS_FAIL assertion.ErrorMessage = fmt.Sprint(args...) assertion.fail() } // Pending marks the test function as pending. func (s *Suite) Pending() { s.currentTestFunc().Status = STATUS_PENDING } // MustFail marks the current test function as an expected failure. func (s *Suite) MustFail() { s.currentTestFunc().mustFail = true } // Failed checks if the test function has failed. func (s *Suite) Failed() bool { return s.currentTestFunc().Status == STATUS_FAIL }
Godeps/_workspace/src/github.com/remogatto/prettytest/assertions.go
0.661486
0.53279
assertions.go
starcoder
package iso20022 // Provides further details specific to the individual direct debit transaction(s) included in the message. type DirectDebitTransactionInformation17 struct { // Set of elements used to reference a payment instruction. PaymentIdentification *PaymentIdentification3 `xml:"PmtId"` // Set of elements used to further specify the type of transaction. PaymentTypeInformation *PaymentTypeInformation25 `xml:"PmtTpInf,omitempty"` // Amount of money moved between the instructing agent and the instructed agent. InterbankSettlementAmount *ActiveCurrencyAndAmount `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"` // Indicator of the urgency or order of importance that the instructing party would like the instructed party to apply to the processing of the settlement instruction. SettlementPriority *Priority3Code `xml:"SttlmPrty,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. // Usage: This amount has to be transported unchanged through the transaction chain. InstructedAmount *ActiveOrHistoricCurrencyAndAmount `xml:"InstdAmt,omitempty"` // Factor used to convert an amount from one currency into 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 to be paid by the charge bearer(s) related to the payment transaction. ChargesInformation []*Charges2 `xml:"ChrgsInf,omitempty"` // Date and time at which the creditor requests that the amount of money is to be collected from the debtor. RequestedCollectionDate *ISODate `xml:"ReqdColltnDt,omitempty"` // Provides information specific to the direct debit mandate. DirectDebitTransaction *DirectDebitTransaction8 `xml:"DrctDbtTx,omitempty"` // Party to which an amount of money is due. Creditor *PartyIdentification43 `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 *CashAccount24 `xml:"CdtrAcct,omitempty"` // Financial institution servicing an account for the creditor. CreditorAgent *BranchAndFinancialInstitutionIdentification5 `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 *CashAccount24 `xml:"CdtrAgtAcct,omitempty"` // Ultimate party to which an amount of money is due. UltimateCreditor *PartyIdentification43 `xml:"UltmtCdtr,omitempty"` // Party that initiates the payment. // Usage: This can be either the creditor or a party that initiates the direct debit on behalf of the creditor. InitiatingParty *PartyIdentification43 `xml:"InitgPty,omitempty"` // Agent that instructs the next party in the chain to carry out the (set of) instruction(s). InstructingAgent *BranchAndFinancialInstitutionIdentification5 `xml:"InstgAgt,omitempty"` // Agent that is instructed by the previous party in the chain to carry out the (set of) instruction(s). InstructedAgent *BranchAndFinancialInstitutionIdentification5 `xml:"InstdAgt,omitempty"` // Agent between the debtor's agent and the creditor's agent. // // Usage: If more than one intermediary agent is present, then IntermediaryAgent1 identifies the agent between the DebtorAgent and the IntermediaryAgent2. IntermediaryAgent1 *BranchAndFinancialInstitutionIdentification5 `xml:"IntrmyAgt1,omitempty"` // Unambiguous identification of the account of the intermediary agent 1 at its servicing agent in the payment chain. IntermediaryAgent1Account *CashAccount24 `xml:"IntrmyAgt1Acct,omitempty"` // Agent between the debtor's agent and the creditor's agent. // // Usage: If more than two intermediary agents are present, then IntermediaryAgent2 identifies the agent between the IntermediaryAgent1 and the IntermediaryAgent3. IntermediaryAgent2 *BranchAndFinancialInstitutionIdentification5 `xml:"IntrmyAgt2,omitempty"` // Unambiguous identification of the account of the intermediary agent 2 at its servicing agent in the payment chain. IntermediaryAgent2Account *CashAccount24 `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 debtor agent. IntermediaryAgent3 *BranchAndFinancialInstitutionIdentification5 `xml:"IntrmyAgt3,omitempty"` // Unambiguous identification of the account of the intermediary agent 3 at its servicing agent in the payment chain. IntermediaryAgent3Account *CashAccount24 `xml:"IntrmyAgt3Acct,omitempty"` // Party that owes an amount of money to the (ultimate) creditor. Debtor *PartyIdentification43 `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 *CashAccount24 `xml:"DbtrAcct"` // Financial institution servicing an account for the debtor. DebtorAgent *BranchAndFinancialInstitutionIdentification5 `xml:"DbtrAgt"` // Unambiguous identification of the account of the debtor agent at its servicing agent in the payment chain. DebtorAgentAccount *CashAccount24 `xml:"DbtrAgtAcct,omitempty"` // Ultimate party that owes an amount of money to the (ultimate) creditor. UltimateDebtor *PartyIdentification43 `xml:"UltmtDbtr,omitempty"` // Underlying reason for the payment transaction. // Usage: Purpose is used by the end-customers, that is 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 *Purpose2Choice `xml:"Purp,omitempty"` // Information needed due to regulatory and statutory requirements. RegulatoryReporting []*RegulatoryReporting3 `xml:"RgltryRptg,omitempty"` // Provides information related to the handling of the remittance information by any of the agents in the transaction processing chain. RelatedRemittanceInformation []*RemittanceLocation4 `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 *RemittanceInformation10 `xml:"RmtInf,omitempty"` // Additional information that cannot be captured in the structured elements and/or any other specific block. SupplementaryData []*SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (d *DirectDebitTransactionInformation17) AddPaymentIdentification() *PaymentIdentification3 { d.PaymentIdentification = new(PaymentIdentification3) return d.PaymentIdentification } func (d *DirectDebitTransactionInformation17) AddPaymentTypeInformation() *PaymentTypeInformation25 { d.PaymentTypeInformation = new(PaymentTypeInformation25) return d.PaymentTypeInformation } func (d *DirectDebitTransactionInformation17) SetInterbankSettlementAmount(value, currency string) { d.InterbankSettlementAmount = NewActiveCurrencyAndAmount(value, currency) } func (d *DirectDebitTransactionInformation17) SetInterbankSettlementDate(value string) { d.InterbankSettlementDate = (*ISODate)(&value) } func (d *DirectDebitTransactionInformation17) SetSettlementPriority(value string) { d.SettlementPriority = (*Priority3Code)(&value) } func (d *DirectDebitTransactionInformation17) SetInstructedAmount(value, currency string) { d.InstructedAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency) } func (d *DirectDebitTransactionInformation17) SetExchangeRate(value string) { d.ExchangeRate = (*BaseOneRate)(&value) } func (d *DirectDebitTransactionInformation17) SetChargeBearer(value string) { d.ChargeBearer = (*ChargeBearerType1Code)(&value) } func (d *DirectDebitTransactionInformation17) AddChargesInformation() *Charges2 { newValue := new (Charges2) d.ChargesInformation = append(d.ChargesInformation, newValue) return newValue } func (d *DirectDebitTransactionInformation17) SetRequestedCollectionDate(value string) { d.RequestedCollectionDate = (*ISODate)(&value) } func (d *DirectDebitTransactionInformation17) AddDirectDebitTransaction() *DirectDebitTransaction8 { d.DirectDebitTransaction = new(DirectDebitTransaction8) return d.DirectDebitTransaction } func (d *DirectDebitTransactionInformation17) AddCreditor() *PartyIdentification43 { d.Creditor = new(PartyIdentification43) return d.Creditor } func (d *DirectDebitTransactionInformation17) AddCreditorAccount() *CashAccount24 { d.CreditorAccount = new(CashAccount24) return d.CreditorAccount } func (d *DirectDebitTransactionInformation17) AddCreditorAgent() *BranchAndFinancialInstitutionIdentification5 { d.CreditorAgent = new(BranchAndFinancialInstitutionIdentification5) return d.CreditorAgent } func (d *DirectDebitTransactionInformation17) AddCreditorAgentAccount() *CashAccount24 { d.CreditorAgentAccount = new(CashAccount24) return d.CreditorAgentAccount } func (d *DirectDebitTransactionInformation17) AddUltimateCreditor() *PartyIdentification43 { d.UltimateCreditor = new(PartyIdentification43) return d.UltimateCreditor } func (d *DirectDebitTransactionInformation17) AddInitiatingParty() *PartyIdentification43 { d.InitiatingParty = new(PartyIdentification43) return d.InitiatingParty } func (d *DirectDebitTransactionInformation17) AddInstructingAgent() *BranchAndFinancialInstitutionIdentification5 { d.InstructingAgent = new(BranchAndFinancialInstitutionIdentification5) return d.InstructingAgent } func (d *DirectDebitTransactionInformation17) AddInstructedAgent() *BranchAndFinancialInstitutionIdentification5 { d.InstructedAgent = new(BranchAndFinancialInstitutionIdentification5) return d.InstructedAgent } func (d *DirectDebitTransactionInformation17) AddIntermediaryAgent1() *BranchAndFinancialInstitutionIdentification5 { d.IntermediaryAgent1 = new(BranchAndFinancialInstitutionIdentification5) return d.IntermediaryAgent1 } func (d *DirectDebitTransactionInformation17) AddIntermediaryAgent1Account() *CashAccount24 { d.IntermediaryAgent1Account = new(CashAccount24) return d.IntermediaryAgent1Account } func (d *DirectDebitTransactionInformation17) AddIntermediaryAgent2() *BranchAndFinancialInstitutionIdentification5 { d.IntermediaryAgent2 = new(BranchAndFinancialInstitutionIdentification5) return d.IntermediaryAgent2 } func (d *DirectDebitTransactionInformation17) AddIntermediaryAgent2Account() *CashAccount24 { d.IntermediaryAgent2Account = new(CashAccount24) return d.IntermediaryAgent2Account } func (d *DirectDebitTransactionInformation17) AddIntermediaryAgent3() *BranchAndFinancialInstitutionIdentification5 { d.IntermediaryAgent3 = new(BranchAndFinancialInstitutionIdentification5) return d.IntermediaryAgent3 } func (d *DirectDebitTransactionInformation17) AddIntermediaryAgent3Account() *CashAccount24 { d.IntermediaryAgent3Account = new(CashAccount24) return d.IntermediaryAgent3Account } func (d *DirectDebitTransactionInformation17) AddDebtor() *PartyIdentification43 { d.Debtor = new(PartyIdentification43) return d.Debtor } func (d *DirectDebitTransactionInformation17) AddDebtorAccount() *CashAccount24 { d.DebtorAccount = new(CashAccount24) return d.DebtorAccount } func (d *DirectDebitTransactionInformation17) AddDebtorAgent() *BranchAndFinancialInstitutionIdentification5 { d.DebtorAgent = new(BranchAndFinancialInstitutionIdentification5) return d.DebtorAgent } func (d *DirectDebitTransactionInformation17) AddDebtorAgentAccount() *CashAccount24 { d.DebtorAgentAccount = new(CashAccount24) return d.DebtorAgentAccount } func (d *DirectDebitTransactionInformation17) AddUltimateDebtor() *PartyIdentification43 { d.UltimateDebtor = new(PartyIdentification43) return d.UltimateDebtor } func (d *DirectDebitTransactionInformation17) AddPurpose() *Purpose2Choice { d.Purpose = new(Purpose2Choice) return d.Purpose } func (d *DirectDebitTransactionInformation17) AddRegulatoryReporting() *RegulatoryReporting3 { newValue := new (RegulatoryReporting3) d.RegulatoryReporting = append(d.RegulatoryReporting, newValue) return newValue } func (d *DirectDebitTransactionInformation17) AddRelatedRemittanceInformation() *RemittanceLocation4 { newValue := new (RemittanceLocation4) d.RelatedRemittanceInformation = append(d.RelatedRemittanceInformation, newValue) return newValue } func (d *DirectDebitTransactionInformation17) AddRemittanceInformation() *RemittanceInformation10 { d.RemittanceInformation = new(RemittanceInformation10) return d.RemittanceInformation } func (d *DirectDebitTransactionInformation17) AddSupplementaryData() *SupplementaryData1 { newValue := new (SupplementaryData1) d.SupplementaryData = append(d.SupplementaryData, newValue) return newValue }
DirectDebitTransactionInformation17.go
0.751557
0.581244
DirectDebitTransactionInformation17.go
starcoder
package model import ( "github.com/newm4n/grool/pkg" "log" "reflect" "strings" "time" ) // GroolFunctions strucr hosts the built-in functions ready to invoke from the rule engine execution. type GroolFunctions struct { Knowledge *KnowledgeBase } func (gf *GroolFunctions) MakeTime(year, month, day, hour, minute, second int64) time.Time { return time.Date(int(year), time.Month(month), int(day), int(hour), int(minute), int(second), 0, time.Local) } // Now is an extension tn time.Now(). func (gf *GroolFunctions) Now() time.Time { return time.Now() } // Log extension to log.Print func (gf *GroolFunctions) Log(text string) { log.Println(text) } // Enables nill checking on variables. func (gf *GroolFunctions) IsNil(i interface{}) bool { val := reflect.ValueOf(i) if val.Kind() == reflect.Struct { return false } return !val.IsValid() || val.IsNil() } // Enable zero checking func (gf *GroolFunctions) IsZero(i interface{}) bool { val := reflect.ValueOf(i) switch val.Kind() { case reflect.Struct: if val.Type().String() == "time.Time" { return i.(time.Time).IsZero() } return false case reflect.Ptr: return val.IsNil() default: switch pkg.GetBaseKind(val) { case reflect.String: return len(val.String()) == 0 case reflect.Int64: return val.Int() == 0 case reflect.Uint64: return val.Uint() == 0 case reflect.Float64: return val.Float() == 0 default: return false } } } // Retract will retract a rule from next evaluation cycle. func (gf *GroolFunctions) Retract(ruleName string) { gf.Knowledge.Retract(strings.ReplaceAll(ruleName, "\"", "")) } // GetTimeYear will get the year value of time func (gf *GroolFunctions) GetTimeYear(time time.Time) int { return time.Year() } // GetTimeMonth will get the month value of time func (gf *GroolFunctions) GetTimeMonth(time time.Time) int { return int(time.Month()) } // GetTimeDay will get the day value of time func (gf *GroolFunctions) GetTimeDay(time time.Time) int { return time.Day() } // GetTimeHour will get the hour value of time func (gf *GroolFunctions) GetTimeHour(time time.Time) int { return time.Hour() } // GetTimeMinute will get the minute value of time func (gf *GroolFunctions) GetTimeMinute(time time.Time) int { return time.Minute() } // GetTimeSecond will get the second value of time func (gf *GroolFunctions) GetTimeSecond(time time.Time) int { return time.Second() } // IsTimeBefore will check if the 1st argument is before the 2nd argument. func (gf *GroolFunctions) IsTimeBefore(time, before time.Time) bool { return time.Before(before) } // IsTimeAfter will check if the 1st argument is after the 2nd argument. func (gf *GroolFunctions) IsTimeAfter(time, after time.Time) bool { return time.After(after) } // TimeFormat will format a time according to format layout. func (gf *GroolFunctions) TimeFormat(time time.Time, layout string) string { return time.Format(layout) }
model/GroolFunctions.go
0.688992
0.40536
GroolFunctions.go
starcoder
package oxyde import ( "fmt" "reflect" ) // Function AssertNil asserts that actual value is nil. // When actual value is not nil, an error is reported. func AssertNil(actual interface{}) { if !isNil(actual) { displayAssertionError(nil, actual) } } func AssertNotNil(actual interface{}) { if isNil(actual) { displayAssertionError("not nil", actual) } } func AssertNilError(e error) { if e != nil { displayAssertionError(nil, e) } } func AssertNilString(actual *string) { if actual != nil { displayAssertionError(nil, actual) } } func AssertNotNilString(actual *string) { if actual == nil { displayAssertionError("not nil", actual) } } func AssertTrue(actual bool) { if !actual { displayAssertionError(true, actual) } } func AssertFalse(actual bool) { if actual { displayAssertionError(false, actual) } } func AssertNotNilId(actual *string) { AssertNotNilString(actual) AssertEqualInt(36, len(*actual)) } func AssertEqualString(expected string, actual string) { if !equalString(expected, actual) { displayAssertionError(expected, actual) } } func AssertEqualStringNullable(expected *string, actual *string) { if !equalStringNullable(expected, actual) { if expected != nil && actual != nil { displayAssertionError(*expected, *actual) } displayAssertionError(expected, actual) } } func AssertNilInt(actual *int) { if actual != nil { displayAssertionError(nil, actual) } } func AssertEqualInt(expected int, actual int) { if !equalInt(expected, actual) { displayAssertionError(expected, actual) } } func AssertEqualIntNullable(expected *int, actual *int) { if !equalIntNullable(expected, actual) { if expected != nil && actual != nil { displayAssertionError(*expected, *actual) } displayAssertionError(expected, actual) } } func AssertEqualInt64Nullable(expected *int64, actual *int64) { if !equalInt64Nullable(expected, actual) { if expected != nil && actual != nil { displayAssertionError(*expected, *actual) } displayAssertionError(expected, actual) } } func AssertEqualFloat64(expected float64, actual float64) { if !equalFloat64(expected, actual) { displayAssertionError(expected, actual) } } func AssertEqualBool(expected bool, actual bool) { if !equalBool(expected, actual) { displayAssertionError(expected, actual) } } // Function isNil checks if the value specified as parameter is nil. func isNil(value interface{}) bool { return value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) } // Function equalString checks if two string values are equal. func equalString(expected string, actual string) bool { return expected == actual } // Function equalStringNullable checks if two pointers to string values are equal. func equalStringNullable(expected *string, actual *string) bool { if expected != nil && actual != nil { return equalString(*expected, *actual) } if expected != nil || actual != nil { return false } return true } // Function equalInt checks if two int values are equal. func equalInt(expected int, actual int) bool { return expected == actual } // Function equalIntNullable checks if two pointers to int values are equal. func equalIntNullable(expected *int, actual *int) bool { if expected != nil && actual != nil { return equalInt(*expected, *actual) } if expected != nil || actual != nil { return false } return true } // Function equalInt64 checks if two int64 values are equal. func equalInt64(expected int64, actual int64) bool { return expected == actual } // Function equalInt64Nullable checks if two pointers to int64 values are equal. func equalInt64Nullable(expected *int64, actual *int64) bool { if expected != nil && actual != nil { return equalInt64(*expected, *actual) } if expected != nil || actual != nil { return false } return true } // Function equalFloat64 checks if two float64 values are equal. func equalFloat64(expected float64, actual float64) bool { return expected == actual } // Function equalBool checks if two boolean values are equal. func equalBool(expected bool, actual bool) bool { return expected == actual } // Function displayAssertionError displays assertion error details. func displayAssertionError(expected interface{}, actual interface{}) { separator := makeText("-", 120) fmt.Printf("\n\n%s\n> ERROR: assertion error\n> Expected: %+v\n> Actual: %+v\n%s\n\n", separator, expected, actual, separator) brexit() }
assert.go
0.757077
0.658414
assert.go
starcoder
package view import ( "fmt" "image" "log" "github.com/nictuku/stardew-rocks/parser" ) var treeRects = map[int]image.Rectangle{ 0: xnaRect(32, 128, 16, 16), 1: xnaRect(0, 128, 16, 16), 2: xnaRect(16, 128, 16, 16), 3: xnaRect(0, 96, 16, 32), 4: xnaRect(0, 96, 16, 32), } func treeAsset(terrainType string, treeType int, season string) string { if terrainType == "Tree" { if treeType == 3 && season == "summer" { season = "spring" } else if treeType == 6 { return "../TerrainFeatures/tree_palm.png" } else if treeType == 7 { return "../TerrainFeatures/mushroom_tree.png" } return fmt.Sprintf("../TerrainFeatures/tree%d_%v.png", treeType, season) } else if terrainType == "FruitTree" { return "../TileSheets/fruitTrees.png" } else { return "" // error? } } func (s *screenshot) drawTree(pm *parser.Map, season string, item *parser.TerrainItem) { if item.Value.TerrainFeature.Type != "Tree" && item.Value.TerrainFeature.Type != "FruitTree" { return } p := treeAsset(item.Value.TerrainFeature.Type, item.Value.TerrainFeature.TreeType, season) src, err := pm.FetchSource(p) if err != nil { log.Printf("Error fetching terrain asset %v: %v", p, err) return } stage := item.Value.TerrainFeature.GrowthStage if item.Value.TerrainFeature.Type == "Tree" { s.drawRegularTree(pm, season, item, src, stage) } else if item.Value.TerrainFeature.Type == "FruitTree" { s.drawFruitTree(pm, season, item, src, stage) } return } func (s *screenshot) drawRegularTree(pm *parser.Map, season string, item *parser.TerrainItem, src image.Image, stage int) { m := pm.TMX if stage < 5 { sr, ok := treeRects[stage] if !ok { log.Printf("Unknown tree rect for %v", item.Value.TerrainFeature.GrowthStage) return } var r image.Rectangle if stage < 3 { r = sr.Sub(sr.Min).Add(image.Point{item.Key.Vector2.X * m.TileWidth, item.Key.Vector2.Y * m.TileHeight}) } else { r = midLeftAlign(sr, image.Point{item.Key.Vector2.X * m.TileWidth, item.Key.Vector2.Y * m.TileHeight}) } s.Draw(r, src, sr.Min, treeLayer) } else { { // shadow src, err := pm.FetchSource("../LooseSprites/Cursors.png") if err != nil { log.Printf("Error fetching terrain asset %v", err) return } sr := xnaRect(663, 1011, 41, 30) r := sr.Sub(sr.Min).Add(image.Point{item.Key.Vector2.X*m.TileWidth - m.TileWidth, // centralize item.Key.Vector2.Y*m.TileHeight - 0, // vertical centralize }) s.Draw(r, src, sr.Min, treeLayer) } { // stump sr := xnaRect(32, 96, 16, 32) r := sr.Sub(sr.Min).Add(image.Point{item.Key.Vector2.X * m.TileWidth, item.Key.Vector2.Y*m.TileHeight - m.TileHeight, // stump offset }) s.Draw(r, cropAndMaybeFlip(item.Value.TerrainFeature.Flipped, src, sr), image.ZP, treeLayer) } { // tree sr := image.Rect(0, 0, 48, 96) r := sr.Sub(sr.Min).Add(image.Point{ item.Key.Vector2.X*m.TileWidth - m.TileWidth, // centralize item.Key.Vector2.Y*m.TileHeight - 80, // stump offset }) s.Draw(r, cropAndMaybeFlip(item.Value.TerrainFeature.Flipped, src, sr), image.ZP, treeLayer) } } } func (s *screenshot) drawFruitTree(pm *parser.Map, season string, item *parser.TerrainItem, src image.Image, stage int) { m := pm.TMX stump := false col := 4 if stage < 4 { col = stage } else if !stump { var season_num_map = map[string]int{ "spring": 0, "summer": 1, "fall": 2, "winter": 3, } season_num, ok := season_num_map[season] if !ok { log.Printf("Unknown season for %v", season) return } col = 4 + season_num } else { // A stump. Draw a winter tree for now. col = 7 } row := item.Value.TerrainFeature.TreeType // Rectangle around the tree. This is only valid for live trees. sr := xnaRect(col*m.TileWidth*3, row*m.TileHeight*5, m.TileWidth*3, m.TileHeight*5) // Tree rects are all 3 tiles wide by 5 tiles tall, but the center tile on the bottom is the footprint of the tree's tile. var r image.Rectangle = sr.Sub(sr.Min).Add(image.Point{item.Key.Vector2.X * m.TileWidth, item.Key.Vector2.Y * m.TileHeight}).Sub(image.Point{m.TileWidth, m.TileHeight * 4}) s.Draw(r, src, sr.Min, treeLayer) }
view/draw_tree.go
0.543106
0.447581
draw_tree.go
starcoder
package convert import "time" // Converter supports conversion across Go types. type Converter interface { // Bool returns the bool representation from the given interface value. // Returns the default value of false and an error on failure. Bool(from interface{}) (to bool, err error) // Duration returns the time.Duration representation from the given // interface{} value. Returns the default value of 0 and an error on failure. Duration(from interface{}) (to time.Duration, err error) // Float32 returns the float32 representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Float32(from interface{}) (to float32, err error) // Float64 returns the float64 representation from the given interface // value. Returns the default value of 0 and an error on failure. Float64(from interface{}) (to float64, err error) // Infer will perform conversion by inferring the conversion operation from // a pointer to a supported T of the `into` param. Infer(into, from interface{}) error // Int returns the int representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Int(from interface{}) (to int, err error) // Int8 returns the int8 representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Int8(from interface{}) (to int8, err error) // Int16 returns the int16 representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Int16(from interface{}) (to int16, err error) // Int32 returns the int32 representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Int32(from interface{}) (to int32, err error) // Int64 returns the int64 representation from the given interface // value. Returns the default value of 0 and an error on failure. Int64(from interface{}) (to int64, err error) // String returns the string representation from the given interface // value and can not fail. An error is provided only for API cohesion. String(from interface{}) (to string, err error) // Time returns the time.Time{} representation from the given interface // value. Returns an empty time.Time struct and an error on failure. Time(from interface{}) (to time.Time, err error) // Uint returns the uint representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Uint(from interface{}) (to uint, err error) // Uint8 returns the uint8 representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Uint8(from interface{}) (to uint8, err error) // Uint16 returns the uint16 representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Uint16(from interface{}) (to uint16, err error) // Uint32 returns the uint32 representation from the given empty interface // value. Returns the default value of 0 and an error on failure. Uint32(from interface{}) (to uint32, err error) // Uint64 returns the uint64 representation from the given interface // value. Returns the default value of 0 and an error on failure. Uint64(from interface{}) (to uint64, err error) }
lib/conv/internal/convert/convert.go
0.843154
0.603231
convert.go
starcoder
package trinary import ( "bytes" "math" "strings" . "github.com/iotaledger/iota.go/consts" iotaGoMath "github.com/iotaledger/iota.go/math" "github.com/pkg/errors" ) var ( // TryteValueToTritsLUT is a lookup table to convert tryte values into trits. TryteValueToTritsLUT = [TryteRadix][TritsPerTryte]int8{ {-1, -1, -1}, {0, -1, -1}, {1, -1, -1}, {-1, 0, -1}, {0, 0, -1}, {1, 0, -1}, {-1, 1, -1}, {0, 1, -1}, {1, 1, -1}, {-1, -1, 0}, {0, -1, 0}, {1, -1, 0}, {-1, 0, 0}, {0, 0, 0}, {1, 0, 0}, {-1, 1, 0}, {0, 1, 0}, {1, 1, 0}, {-1, -1, 1}, {0, -1, 1}, {1, -1, 1}, {-1, 0, 1}, {0, 0, 1}, {1, 0, 1}, {-1, 1, 1}, {0, 1, 1}, {1, 1, 1}, } // TryteValueToTyteLUT is a lookup table to convert tryte values into trytes. TryteValueToTyteLUT = [TryteRadix]byte{'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'} // TryteToTryteValueLUT is a lookup table to convert trytes into tryte values. TryteToTryteValueLUT = [...]int8{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, } // Pow27LUT is a Look-up-table for Decoding Trits to int64 Pow27LUT = []int64{1, 27, 729, 19683, 531441, 14348907, 387420489, 10460353203, 282429536481, 7625597484987, 205891132094649, 5559060566555523, 150094635296999136, 4052555153018976256} encodedZero = []int8{1, 0, 0, -1} ) // Trits is a slice of int8. You should not use cast, use NewTrits instead to ensure the validity. type Trits = []int8 // Trytes is a string of trytes. Use NewTrytes() instead of typecasting. type Trytes = string // Hash represents a trinary hash type Hash = Trytes // Hashes is a slice of Hash. type Hashes = []Hash // ValidTrit returns true if t is a valid trit. func ValidTrit(t int8) bool { return t >= -1 && t <= 1 } // ValidTrits returns true if t is valid trits (non-empty and -1, 0 or 1). func ValidTrits(trits Trits) error { if len(trits) == 0 { return errors.Wrap(ErrInvalidTrit, "trits slice is empty") } for i, trit := range trits { if !ValidTrit(trit) { return errors.Wrapf(ErrInvalidTrit, "at index %d", i) } } return nil } // NewTrits casts Trits and checks its validity. func NewTrits(t []int8) (Trits, error) { err := ValidTrits(t) return t, err } // TritsEqual returns true if t and b are equal Trits. func TritsEqual(a Trits, b Trits) (bool, error) { if err := ValidTrits(a); err != nil { return false, err } if err := ValidTrits(b); err != nil { return false, err } if len(a) != len(b) { return false, nil } for i := range a { if a[i] != b[i] { return false, nil } } return true, nil } // ReverseTrits reverses the given trits. func ReverseTrits(trits Trits) Trits { for left, right := 0, len(trits)-1; left < right; left, right = left+1, right-1 { trits[left], trits[right] = trits[right], trits[left] } return trits } // TrailingZeros returns the number of trailing zeros of the given trits. func TrailingZeros(trits Trits) int { var z int for i := len(trits) - 1; i >= 0 && trits[i] == 0; i-- { z++ } return z } // roundUpToTryteMultiple rounds the given number up the the nearest multiple of 3 to make a valid tryte count. func roundUpToTryteMultiple(n uint) uint { rem := n % TritsPerTryte if rem == 0 { return n } return n + TritsPerTryte - rem } // MinTrits returns the length of trits needed to encode the value. func MinTrits(value int64) int { valueAbs := iotaGoMath.AbsInt64(value) var vp uint64 var num int switch { case valueAbs >= 308836698141973: vp = 308836698141973 num = 31 case valueAbs >= 5230176601: vp = 5230176601 num = 21 case valueAbs >= 88573: vp = 88573 num = 11 default: vp = 1 num = 1 } for valueAbs > vp { vp = vp*TrinaryRadix + 1 num++ } return num } // IntToTrits converts int64 to a slice of trits. func IntToTrits(value int64) Trits { numTrits := MinTrits(value) numTrytes := (numTrits + TritsPerTryte - 1) / TritsPerTryte trits := MustTrytesToTrits(IntToTrytes(value, numTrytes)) return trits[:numTrits] } // TritsToInt converts a slice of trits into an integer and assumes little-endian notation. func TritsToInt(t Trits) int64 { var val int64 for i := len(t) - 1; i >= 0; i-- { val = val*TrinaryRadix + int64(t[i]) } return val } // IntToTrytes converts int64 to a slice of trytes. func IntToTrytes(value int64, trytesCnt int) Trytes { negative := value < 0 v := iotaGoMath.AbsInt64(value) var trytes strings.Builder trytes.Grow(trytesCnt) for i := 0; i < trytesCnt; i++ { if v == 0 { trytes.WriteByte('9') continue } v += TryteRadix / 2 tryte := int8(v%TryteRadix) - TryteRadix/2 v /= TryteRadix if negative { tryte = -tryte } trytes.WriteByte(MustTryteValueToTryte(tryte)) } return trytes.String() } // TrytesToInt converts a slice of trytes to int64. func TrytesToInt(t Trytes) int64 { // ignore tailing 9s var i int for i = len(t) - 1; i >= 0; i-- { if t[i] != '9' { break } } var val int64 for ; i >= 0; i-- { val = val*TryteRadix + int64(MustTryteToTryteValue(t[i])) } return val } // CanTritsToTrytes returns true if t can be converted to trytes. func CanTritsToTrytes(trits Trits) bool { if len(trits) == 0 { return false } return len(trits)%TritsPerTryte == 0 } // MustTryteValueToTryte converts the value of a tryte v in [-13,13] to a tryte char in [9A-Z]. // It panics when v is an invalid value. func MustTryteValueToTryte(v int8) byte { idx := uint(v - MinTryteValue) if idx >= uint(len(TryteValueToTyteLUT)) { panic(ErrInvalidTrytes) } return TryteValueToTyteLUT[idx] } // MustTryteToTryteValue converts a tryte char t in [9A-Z] to a tryte value in [-13,13]. // Performs no validation on t (therefore might return an invalid representation) and might panic. func MustTryteToTryteValue(t byte) int8 { return TryteToTryteValueLUT[t-'9'] } // TritsToTrytes converts a slice of trits into trytes. Returns an error if len(t)%3!=0 func TritsToTrytes(trits Trits) (Trytes, error) { if err := ValidTrits(trits); err != nil { return "", err } if !CanTritsToTrytes(trits) { return "", errors.Wrap(ErrInvalidTritsLength, "trits slice size must be a multiple of 3") } return MustTritsToTrytes(trits), nil } // MustTritsToTrytes converts a slice of trits into trytes. // Performs no validation on the input trits and might therefore return an invalid trytes representation // (without a panic). func MustTritsToTrytes(trits Trits) Trytes { trytes := make([]byte, len(trits)/TritsPerTryte) for i := range trytes { v := MustTritsToTryteValue(trits[i*TritsPerTryte:]) trytes[i] = MustTryteValueToTryte(v) } return string(trytes) } func validTryte(t rune) bool { return (t >= 'A' && t <= 'Z') || t == '9' } // ValidTryte returns the validity of a tryte (must be rune A-Z or 9) func ValidTryte(t rune) error { if !validTryte(t) { return ErrInvalidTrytes } return nil } // ValidTrytes returns true if t is made of valid trytes. func ValidTrytes(trytes Trytes) error { if trytes == "" { return ErrInvalidTrytes } for _, tryte := range trytes { if !validTryte(tryte) { return ErrInvalidTrytes } } return nil } // NewTrytes casts to Trytes and checks its validity. func NewTrytes(s string) (Trytes, error) { err := ValidTrytes(s) return s, err } // TrytesToTrits converts a slice of trytes into trits. func TrytesToTrits(trytes Trytes) (Trits, error) { if err := ValidTrytes(trytes); err != nil { return nil, err } return MustTrytesToTrits(trytes), nil } // MustTrytesToTrits converts a slice of trytes into trits. // Performs no validation on the provided inputs (therefore might return an invalid representation) and might panic. func MustTrytesToTrits(trytes Trytes) Trits { trits := make(Trits, len(trytes)*TritsPerTryte) for i := 0; i < len(trytes); i++ { MustPutTryteTrits(trits[i*TritsPerTryte:], MustTryteToTryteValue(trytes[i])) } return trits } // MustTritsToTryteValue converts a slice of 3 into its corresponding value. // It performs no validation on the provided inputs (therefore might return an invalid representation) and might panic. func MustTritsToTryteValue(trits Trits) int8 { _ = trits[2] // bounds check hint to compiler return trits[0] + trits[1]*3 + trits[2]*9 } // MustPutTryteTrits converts v in [-13,13] to its corresponding 3-trit value and writes this to trits. // It panics on invalid input. func MustPutTryteTrits(trits []int8, v int8) { idx := v - MinTryteValue _ = trits[2] // early bounds check to guarantee safety of writes below trits[0] = TryteValueToTritsLUT[idx][0] trits[1] = TryteValueToTritsLUT[idx][1] trits[2] = TryteValueToTritsLUT[idx][2] } // CanBeHash returns the validity of the trit length. func CanBeHash(trits Trits) bool { return len(trits) == HashTrinarySize } // Pad pads the given trytes with 9s up to the given size. func Pad(trytes Trytes, n int) (Trytes, error) { if len(trytes) > 0 { if err := ValidTrytes(trytes); err != nil { return "", err } } return MustPad(trytes, n), nil } // MustPad pads the given trytes with 9s up to the given size. // Performs no validation on the provided inputs (therefore might return an invalid representation) and might panic. func MustPad(trytes Trytes, n int) Trytes { if len(trytes) >= n { return trytes } var result strings.Builder result.Grow(n) result.WriteString(trytes) result.Write(bytes.Repeat([]byte{'9'}, n-len(trytes))) return result.String() } // PadTrits pads the given trits with 0 up to the given size. func PadTrits(trits Trits, n int) (Trits, error) { if len(trits) > 0 { if err := ValidTrits(trits); err != nil { return nil, err } } return MustPadTrits(trits, n), nil } // MustPadTrits pads the given trits with 0 up to the given size. // Performs no validation on the provided inputs (therefore might return an invalid representation) and might panic. func MustPadTrits(trits Trits, n int) Trits { if len(trits) >= n { return trits } result := make(Trits, n) copy(result, trits) return result } // Sum returns the sum of two trits. func Sum(a int8, b int8) int8 { s := a + b switch s { case 2: return -1 case -2: return 1 default: return s } } func cons(a int8, b int8) int8 { if a == b { return a } return 0 } func any(a int8, b int8) int8 { s := a + b if s > 0 { return 1 } if s < 0 { return -1 } return 0 } func fullAdd(a int8, b int8, c int8) [2]int8 { sA := Sum(a, b) cA := cons(a, b) cB := cons(sA, c) cOut := any(cA, cB) sOut := Sum(sA, c) return [2]int8{sOut, cOut} } // AddTrits adds a to b. func AddTrits(a Trits, b Trits) Trits { maxLen := int64(math.Max(float64(len(a)), float64(len(b)))) if maxLen == 0 { return Trits{0} } out := make(Trits, maxLen) var aI, bI, carry int8 for i := 0; i < len(out); i++ { if i < len(a) { aI = a[i] } else { aI = 0 } if i < len(b) { bI = b[i] } else { bI = 0 } fA := fullAdd(aI, bI, carry) out[i] = fA[0] carry = fA[1] } return out }
trinary/trinary.go
0.654232
0.45944
trinary.go
starcoder
package edlib import ( "errors" "github.com/hbollon/go-edlib/internal/orderedmap" ) // Algorithm is an Integer type used to identify edit distance algorithms type Algorithm uint8 // Algorithm identifiers const ( Levenshtein Algorithm = iota DamerauLevenshtein OSADamerauLevenshtein Lcs Hamming Jaro JaroWinkler Cosine ) // StringsSimilarity return a similarity index [0..1] between two strings based on given edit distance algorithm in parameter. // Use defined Algorithm type. func StringsSimilarity(str1 string, str2 string, algo Algorithm) (float32, error) { switch algo { case Levenshtein: return matchingIndex(str1, str2, LevenshteinDistance(str1, str2)), nil case DamerauLevenshtein: return matchingIndex(str1, str2, DamerauLevenshteinDistance(str1, str2)), nil case OSADamerauLevenshtein: return matchingIndex(str1, str2, OSADamerauLevenshteinDistance(str1, str2)), nil case Lcs: return matchingIndex(str1, str2, LCSEditDistance(str1, str2)), nil case Hamming: distance, err := HammingDistance(str1, str2) if err == nil { return matchingIndex(str1, str2, distance), nil } return 0.0, err case Jaro: return JaroSimilarity(str1, str2), nil case JaroWinkler: return JaroWinklerSimilarity(str1, str2), nil case Cosine: return CosineSimilarity(str1, str2), nil default: return 0.0, errors.New("Illegal argument for algorithm method") } } // Return matching index E [0..1] from two strings and an edit distance func matchingIndex(str1 string, str2 string, distance int) float32 { // Compare strings length and make a matching percentage between them if len(str1) >= len(str2) { return float32(len(str1)-distance) / float32(len(str1)) } return float32(len(str2)-distance) / float32(len(str2)) } // FuzzySearch realize an approximate search on a string list and return the closest one compared // to the string input func FuzzySearch(str string, strList []string, algo Algorithm) (string, error) { var higherMatchPercent float32 var tmpStr string for _, strToCmp := range strList { sim, err := StringsSimilarity(str, strToCmp, algo) if err != nil { return "", err } if sim == 1.0 { return strToCmp, nil } else if sim > higherMatchPercent { higherMatchPercent = sim tmpStr = strToCmp } } return tmpStr, nil } // FuzzySearchThreshold realize an approximate search on a string list and return the closest one compared // to the string input. Takes a similarity threshold in parameter. func FuzzySearchThreshold(str string, strList []string, minSim float32, algo Algorithm) (string, error) { var higherMatchPercent float32 var tmpStr string for _, strToCmp := range strList { sim, err := StringsSimilarity(str, strToCmp, algo) if err != nil { return "", err } if sim == 1.0 { return strToCmp, nil } else if sim > higherMatchPercent && sim >= minSim { higherMatchPercent = sim tmpStr = strToCmp } } return tmpStr, nil } // FuzzySearchSet realize an approximate search on a string list and return a set composed with x strings compared // to the string input sorted by similarity with the base string. // Takes the a quantity parameter to define the number of output strings desired (For example 3 in the case of the Google Keyboard word suggestion). func FuzzySearchSet(str string, strList []string, quantity int, algo Algorithm) ([]string, error) { sortedMap := make(orderedmap.OrderedMap, quantity) for _, strToCmp := range strList { sim, err := StringsSimilarity(str, strToCmp, algo) if err != nil { return nil, err } if sim > sortedMap[sortedMap.Len()-1].Value { sortedMap[sortedMap.Len()-1].Key = strToCmp sortedMap[sortedMap.Len()-1].Value = sim sortedMap.SortByValues() } } return sortedMap.ToArray(), nil } // FuzzySearchSetThreshold realize an approximate search on a string list and return a set composed with x strings compared // to the string input sorted by similarity with the base string. Take a similarity threshold in parameter. // Takes the a quantity parameter to define the number of output strings desired (For example 3 in the case of the Google Keyboard word suggestion). // Takes also a threshold parameter for similarity with base string. func FuzzySearchSetThreshold(str string, strList []string, quantity int, minSim float32, algo Algorithm) ([]string, error) { sortedMap := make(orderedmap.OrderedMap, quantity) for _, strToCmp := range strList { sim, err := StringsSimilarity(str, strToCmp, algo) if err != nil { return nil, err } if sim >= minSim && sim > sortedMap[sortedMap.Len()-1].Value { sortedMap[sortedMap.Len()-1].Key = strToCmp sortedMap[sortedMap.Len()-1].Value = sim sortedMap.SortByValues() } } return sortedMap.ToArray(), nil }
vendor/github.com/hbollon/go-edlib/string-analysis.go
0.737347
0.503601
string-analysis.go
starcoder
package asyncassertion import ( "errors" "fmt" "reflect" "time" "github.com/onsi/gomega/internal/oraclematcher" "github.com/onsi/gomega/types" ) type AsyncAssertionType uint const ( AsyncAssertionTypeEventually AsyncAssertionType = iota AsyncAssertionTypeConsistently ) type AsyncAssertion struct { asyncType AsyncAssertionType actualInput interface{} timeoutInterval time.Duration pollingInterval time.Duration failWrapper *types.GomegaFailWrapper offset int } func New(asyncType AsyncAssertionType, actualInput interface{}, failWrapper *types.GomegaFailWrapper, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion { actualType := reflect.TypeOf(actualInput) if actualType.Kind() == reflect.Func { if actualType.NumIn() != 0 || actualType.NumOut() == 0 { panic("Expected a function with no arguments and one or more return values.") } } return &AsyncAssertion{ asyncType: asyncType, actualInput: actualInput, failWrapper: failWrapper, timeoutInterval: timeoutInterval, pollingInterval: pollingInterval, offset: offset, } } func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { assertion.failWrapper.TWithHelper.Helper() return assertion.match(matcher, true, optionalDescription...) } func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { assertion.failWrapper.TWithHelper.Helper() return assertion.match(matcher, false, optionalDescription...) } func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interface{}) string { switch len(optionalDescription) { case 0: return "" default: return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" } } func (assertion *AsyncAssertion) actualInputIsAFunction() bool { actualType := reflect.TypeOf(assertion.actualInput) return actualType.Kind() == reflect.Func && actualType.NumIn() == 0 && actualType.NumOut() > 0 } func (assertion *AsyncAssertion) pollActual() (interface{}, error) { if assertion.actualInputIsAFunction() { values := reflect.ValueOf(assertion.actualInput).Call([]reflect.Value{}) extras := []interface{}{} for _, value := range values[1:] { extras = append(extras, value.Interface()) } success, message := vetExtras(extras) if !success { return nil, errors.New(message) } return values[0].Interface(), nil } return assertion.actualInput, nil } func (assertion *AsyncAssertion) matcherMayChange(matcher types.GomegaMatcher, value interface{}) bool { if assertion.actualInputIsAFunction() { return true } return oraclematcher.MatchMayChangeInTheFuture(matcher, value) } func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { timer := time.Now() timeout := time.After(assertion.timeoutInterval) description := assertion.buildDescription(optionalDescription...) var matches bool var err error mayChange := true value, err := assertion.pollActual() if err == nil { mayChange = assertion.matcherMayChange(matcher, value) matches, err = matcher.Match(value) } assertion.failWrapper.TWithHelper.Helper() fail := func(preamble string) { errMsg := "" message := "" if err != nil { errMsg = "Error: " + err.Error() } else { if desiredMatch { message = matcher.FailureMessage(value) } else { message = matcher.NegatedFailureMessage(value) } } assertion.failWrapper.TWithHelper.Helper() assertion.failWrapper.Fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset) } if assertion.asyncType == AsyncAssertionTypeEventually { for { if err == nil && matches == desiredMatch { return true } if !mayChange { fail("No future change is possible. Bailing out early") return false } select { case <-time.After(assertion.pollingInterval): value, err = assertion.pollActual() if err == nil { mayChange = assertion.matcherMayChange(matcher, value) matches, err = matcher.Match(value) } case <-timeout: fail("Timed out") return false } } } else if assertion.asyncType == AsyncAssertionTypeConsistently { for { if !(err == nil && matches == desiredMatch) { fail("Failed") return false } if !mayChange { return true } select { case <-time.After(assertion.pollingInterval): value, err = assertion.pollActual() if err == nil { mayChange = assertion.matcherMayChange(matcher, value) matches, err = matcher.Match(value) } case <-timeout: return true } } } return false } func vetExtras(extras []interface{}) (bool, string) { for i, extra := range extras { if extra != nil { zeroValue := reflect.Zero(reflect.TypeOf(extra)).Interface() if !reflect.DeepEqual(zeroValue, extra) { message := fmt.Sprintf("Unexpected non-nil/non-zero extra argument at index %d:\n\t<%T>: %#v", i+1, extra, extra) return false, message } } } return true, "" }
vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go
0.668556
0.511656
async_assertion.go
starcoder
package k8sresource import ( "fmt" "math" "strconv" "strings" ) const ( _ = iota _ // Mi = Megabytes Mi float64 = 1 << (10 * iota) // Gi = Gigabytes Gi ) // Memory allows converstion between string and float representations and basic math operations on memory types type Memory struct { m float64 } // NewMem returns a new memory instance initialized at 0 func NewMem() Memory { return Memory{0} } // NewMemFromString parses a Kubernetes-style memory string (e.g., 256Mi, 1Gi) func NewMemFromString(m string) (Memory, error) { f, err := memToFloat64(m) if err != nil { return Memory{}, err } return Memory{f}, nil } // NewMemFromFloat creates a new memory instance initialized to m func NewMemFromFloat(m float64) Memory { return Memory{m} } // Add will parse the memory expressed as a string and return a new memory instance // equal to the sum of the current instance plus m func (s Memory) Add(m string) (Memory, error) { f, err := memToFloat64(m) if err != nil { return Memory{}, err } return Memory{s.m + f}, nil } // Sub will parse the memory expressed as a string and return a new memory instance // equal to the current instance minus m func (s Memory) Sub(m string) (Memory, error) { f, err := memToFloat64(m) if err != nil { return Memory{}, err } return Memory{s.m - f}, nil } // AddF will return a new memory instance equal to the sum of the current instance plus m func (s Memory) AddF(m float64) Memory { return Memory{s.m + m} } // SubF will return a new memory instance equal to the current instance minus m func (s Memory) SubF(m float64) Memory { return Memory{s.m - m} } // ToString returns the Kubernetes-style memory value as a string rounded up to the nearest // megabyte. Values over 1Gi will still be returned as an equivalent Mi value. func (s Memory) ToString() string { return float64ToMi(s.m) } // ToFloat64 returns the memory value as a float func (s Memory) ToFloat64() float64 { return s.m } func memToFloat64(s string) (float64, error) { switch { case strings.HasSuffix(s, "Mi"): mem, err := strconv.ParseFloat(strings.TrimSuffix(s, "Mi"), 64) if err != nil { return 0, fmt.Errorf("failed to convert memory string %s to float", s) } return mem * Mi, nil case strings.HasSuffix(s, "Gi"): mem, err := strconv.ParseFloat(strings.TrimSuffix(s, "Gi"), 64) if err != nil { return 0, fmt.Errorf("failed to convert memory string %s to float", s) } return mem * Gi, nil default: return 0, fmt.Errorf("failed to convert memory string %s to float, unknown units", s) } } func float64ToMi(m float64) string { return fmt.Sprintf("%dMi", int(math.Ceil(m/Mi))) }
memcalc.go
0.839668
0.438785
memcalc.go
starcoder
package period import ( "time" ) type Period struct { period string startTime time.Time endTime time.Time } func Parse(unit string) *Period { p := &Period{period: unit} now := time.Now() var start, end time.Time var period string switch unit { case "t": period = "Today" start = p.BeginningOfDay(now) end = p.EndOfDay(now) case "w": period = "This Week" start = p.BeginningOfWeek(now) end = p.EndOfWeek(now) case "m": period = "This Month" start = p.BeginningOfMonth(now) end = p.EndOfMonth(now) case "y": period = "This Year" start = p.BeginningOfYear(now) end = p.EndOfYear(now) case "1d": period = "Yesterday" t := p.Yesterday(now) start = p.BeginningOfDay(t) end = p.EndOfDay(t) case "1w": period = "Last Week" start = p.BeginningOfPreviousWeek(now) end = p.EndOfPreviousWeek(now) case "1m": period = "Last Month" start = p.BeginningOfPreviousMonth(now) end = p.EndOfPreviousMonth(now) case "1y": period = "Last Year" start = p.BeginningOfPreviousYear(now) end = p.EndOfPreviousYear(now) default: start = p.BeginningOfDay(now) end = p.EndOfDay(now) } p.period = period p.startTime = start p.endTime = end return p } func (p Period) Period() string { return p.period } func (p Period) From() time.Time { return p.startTime } func (p Period) To() time.Time { return p.endTime } func (p Period) IsSet() bool { return p.period != "" } func (p Period) BeginningOfDay(t time.Time) time.Time { year, month, day := t.Date() return time.Date(year, month, day, 0, 0, 0, 0, t.Location()) } func (p Period) EndOfDay(t time.Time) time.Time { year, month, day := t.Date() return time.Date(year, month, day, 23, 59, 59, 0, t.Location()) } func (p Period) Yesterday(t time.Time) time.Time { return t.AddDate(0, 0, -1) } func (p Period) lastWeek(t time.Time) time.Time { return t.AddDate(0, 0, -7) } func (p Period) BeginningOfWeek(t time.Time) time.Time { for t.Weekday() != time.Monday { t = t.AddDate(0, 0, -1) } year, month, day := t.Date() return time.Date(year, month, day, 0, 0, 0, 0, t.Location()) } func (p Period) EndOfWeek(t time.Time) time.Time { return p.BeginningOfWeek(t).AddDate(0, 0, 7).Add(-time.Second) } func (p Period) BeginningOfPreviousWeek(t time.Time) time.Time { lastWeek := p.lastWeek(t) return p.BeginningOfWeek(lastWeek) } func (p Period) EndOfPreviousWeek(t time.Time) time.Time { return p.BeginningOfPreviousWeek(t).AddDate(0, 0, 7).Add(-time.Second) } func (p Period) BeginningOfMonth(t time.Time) time.Time { y, m, _ := t.Date() return time.Date(y, m, 1, 0, 0, 0, 0, t.Location()) } func (p Period) EndOfMonth(t time.Time) time.Time { return p.BeginningOfMonth(t).AddDate(0, 1, 0).Add(-time.Second) } func (p Period) BeginningOfPreviousMonth(t time.Time) time.Time { year, month, _ := p.EndOfPreviousMonth(t).Date() return time.Date(year, month, 1, 0, 0, 0, 0, t.Location()) } func (p Period) EndOfPreviousMonth(t time.Time) time.Time { return p.BeginningOfMonth(t).Add(-time.Second) } func (p Period) BeginningOfYear(t time.Time) time.Time { y, _, _ := t.Date() return time.Date(y, time.January, 1, 0, 0, 0, 0, t.Location()) } func (p Period) EndOfYear(t time.Time) time.Time { y, _, _ := t.Date() return time.Date(y, time.December, 31, 23, 59, 59, 0, t.Location()) } func (p Period) BeginningOfPreviousYear(t time.Time) time.Time { return p.BeginningOfYear(t).AddDate(-1, 0, 0) } func (p Period) EndOfPreviousYear(t time.Time) time.Time { return p.BeginningOfPreviousYear(t).AddDate(1, 0, 0).Add(-time.Second) }
reports/period/period.go
0.712432
0.770918
period.go
starcoder
package binary import ( "errors" "strings" "math" "fmt" ) // Binary tree // References: // https://appliedgo.net/bintree/ // https://github.com/karlstroetmann/Algorithms/blob/master/SetlX/BinaryTree/binary-tree.stlx type tree struct { root *node } func NewTree() *tree { return &tree{} } // Inserts new key-Value pair to the tree // arguments: // - key int: key to find the Value // - Value string: Value to insert at the key // returns: error if insertion fails func (t *tree) Insert(key int, value string) error { if t.root == nil { t.root = &node{Key: key, Value: value} t.root.restoreHeight() return nil } return t.root.insert(key, value) } // Finds Value in tree for given key // arguments: // - key int: key to find the Value for // returns: // - string: Value of the key (empty string if no Value was found) // - bool: true if key was found in tree func (t *tree) Find(key int) (string, bool) { if t.root == nil { return "", false } return t.root.find(key) } // Deletes key-Value pair from tree // arguments: // - key int: key and a associated Value, which should be deleted // returns: error if key was not found in tree func (t *tree) Delete(key int) error { if t.root == nil { return errors.New("Cannot delete from an empty tree") } fakeParent := &node{right: t.root} err := t.root.delete(key, fakeParent) if err != nil { return err } if fakeParent.right == nil { t.root = nil } return nil } // Calls the given function with every key and Value ordered by the key (ascending) // arguments: // - f func(int,string): the function to call, first argument is key, second Value func (t *tree) ForEach(f func(int, string)) { t.root.traverse(t.root, func(n *node) { f(n.Key, n.Value) }) } func (t *tree) Keys() []int { keys := []int{} t.ForEach(func(key int, value string) { keys = append(keys, key) }) return keys } func contains(s []string, e string) bool { for _, a := range s { if strings.Compare(a, e) == 0 { return true } } return false } func (t *tree) Values(distinct bool) []string { values := []string{} t.ForEach(func(key int, value string) { if !distinct || !contains(values, value) { values = append(values, value) } }) return values } func (t *tree) ContainsValue(s string) bool { found := false t.ForEach(func(key int, value string) { if strings.Compare(s, value) == 0 { found = true return } }) return found } func (t *tree) ContainsKey(key int) bool { found := false t.ForEach(func(k int, value string) { if k == key { found = true return } }) return found } func (t *tree) ToMap() map[int]string { m := make(map[int]string) t.ForEach(func(key int, value string) { m[key] = value }) return m } func (t *tree) Size() int { size := 0 t.ForEach(func(key int, value string) { size++ }) return size } func (t *tree) GetKeys(value string) []int { result := []int{} t.ForEach(func(k int, v string) { if strings.Compare(value, v) == 0 { result = append(result, k) } }) return result } func (t *tree) String() string { if t.root == nil { return "{}" } else { result := "{" max := t.Size() i := 0 t.root.traverse(t.root, func(n *node) { result += fmt.Sprintf("%v", n.Key) + "=" + n.Value if i+1 < max { result += "," } i++ }) return result + "}" } } // Node structure for the tree // Key int: node key // Value string: node Value // left,right *node: the nodes left and right children type node struct { Key int Value string left, right *node height int } func (n *node) update(s *node) { n.Key, n.Value, n.left, n.right = s.Key, s.Value, s.left, s.right } func (n *node) delMin() (*node, int, string) { if n.left == nil { return n.right, n.Key, n.Value } else { ls, km, vm := n.left.delMin() n.left = ls return n, km, vm } } func (n *node) insert(key int, value string) error { if n == nil { return errors.New("Cannot insert a key into a nil tree") } switch { case key == n.Key: return nil case key < n.Key: if n.left == nil { n.left = &node{Key: key, Value: value} n.left.restoreHeight() return nil } err := n.left.insert(key, value) if err != nil { n.restore() } return err case key > n.Key: if n.right == nil { n.right = &node{Key: key, Value: value} n.right.restoreHeight() return nil } err := n.right.insert(key, value) if err != nil { n.restore() } return err } return nil } func (n *node) find(key int) (string, bool) { if n == nil { return "", false } switch { case key == n.Key: return n.Value, true case key < n.Key: return n.left.find(key) default: return n.right.find(key) } } /// Finds recursive the node with max value in the current node func (n *node) findMax(parent *node) (*node, *node) { if n.right == nil { return n, parent } return n.right.findMax(n) } /// Replaces a node in parent with the replacement func (n *node) replaceNode(parent, replacement *node) error { if n == nil { return errors.New("replaceNode() not allowed on a nil node") } if n == parent.left { parent.left = replacement return nil } parent.right = replacement return nil } /// Deletes the key-value-pair in the tree for the given key. /// If the value was not found an error is return (else nil) func (n *node) delete(key int, parent *node) error { if n == nil { return errors.New("Key to be deleted does not exist in the tree") } switch { case key < n.Key: err := n.left.delete(key, n) if err != nil { n.restore() } return err case key > n.Key: err := n.right.delete(key, n) if err != nil { n.restore() } return err default: if n.left == nil && n.right == nil { n.replaceNode(parent, nil) return nil } if n.left == nil { n.replaceNode(parent, n.right) return nil } if n.right == nil { n.replaceNode(parent, n.left) return nil } replacement, replParent := n.left.findMax(n) n.Key = replacement.Key n.Value = replacement.Value return replacement.delete(replacement.Key, replParent) } } // Calculates the height of a node func (n *node) restoreHeight() { switch { case n.left == nil && n.right == nil: n.height = 1 return case n.left == nil: n.height = 1 + n.right.height return case n.right == nil: n.height = 1 + n.left.height return default: n.height = 1 + int(math.Max(float64(n.right.height), float64(n.left.height))) } } /// Calls the given function for every node in the tree func (n *node) traverse(t *node, f func(*node)) { if t == nil { return } n.traverse(t.left, f) f(t) n.traverse(t.right, f) } /// Restores the trees structure, /// to ensure the height height difference between the left and the right node is never bigger than 1 func (n *node) restore() { if math.Abs(float64(n.left.height-n.right.height)) <= 1 { n.restoreHeight() return } if n.left.height > n.right.height { k1, v1, l1, r1 := n.Key, n.Value, n.left, n.right; k2, v2, l2, r2 := l1.Key, l1.Value, l1.left, l1.right; if l2.height >= r2.height { n.Key, n.Value, n.left, n.right = k2, v2, l2, &node{k1, v1, r2, r1, 1} n.right.restoreHeight() } else { k3, v3, l3, r3 := r2.Key, r2.Value, r2.left, r2.right; n.Key, n.Value, n.left, n.right = k3, v3, &node{k2, v2, l2, l3, 1}, &node{k1, v1, r3, r1, 1} n.left.restoreHeight() n.right.restoreHeight() } } else if n.right.height > n.left.height { k1, v1, l1, r1 := n.Key, n.Value, n.left, n.right k2, v2, l2, r2 := r1.Key, r1.Value, r1.left, r1.right; if r2.height >= l2.height { n.Key, n.Value, n.left, n.right = k2, v2, &node{k1, v1, l1, l2, 1}, r2 n.left.restoreHeight() } else { k3, v3, l3, r3 := l2.Key, l2.Value, l2.left, l2.right n.Key, n.Value, n.left, n.right = k3, v3, &node{k1, v1, l1, l3, 1}, &node{k2, v2, r3, r2, 1} n.left.restoreHeight() n.right.restoreHeight() } } n.restoreHeight() }
src/trees/binary/binaryTree.go
0.829077
0.469824
binaryTree.go
starcoder
package main import ( "../gen-go/com/maxeler/VectorAddition" "fmt" "git.apache.org/thrift.git/lib/go/thrift" "os" "math/rand" "time" ) func checkForErrors(err error){ if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(-1) } } func check(dataOutDFE []int32, dataOutCPU []int32, size int64) (int64) { status := int64(0); for i := int64(0); i < size; i++ { if dataOutDFE[i] != dataOutCPU[i] { fmt.Printf("Output data @ %v = %v (expected %v)\r\n", i, dataOutDFE[i], dataOutCPU[i]) status++ } } return status; } func calcTime(startTime time.Time) (float64){ return float64(time.Now().UnixNano() - startTime.UnixNano()) / 1000000000 } // VectorAdditionCPU implementation func VectorAdditionCPU(x []int32, y []int32, scalar int64, size int64) ([]int32) { dataOut := make([]int32, size) scalarInt := int32(scalar) for i := int64(0) ; i < size ; i++ { dataOut[i] = x[i] + y[i] + scalarInt } return dataOut } // VectorAdditionDFE Dynamic implementation func VectorAdditionDFE(x []int32, y []int32, scalar int64, size int64) ([]int32) { startTime := time.Now() // Make socket transport, err := thrift.NewTSocket("localhost:9090"); checkForErrors(err) // Wrap in a protocol protocol := thrift.NewTBinaryProtocolFactoryDefault() // Create a client to use the protocol encoder client := VectorAddition.NewVectorAdditionServiceClientFactory(transport, protocol) currentTime := calcTime(startTime) fmt.Printf("Creating a client:\t\t\t\t%.5fs\n", currentTime) // Connect! startTime = time.Now() err = transport.Open(); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Opening connection:\t\t\t\t%.5fs\n", currentTime) // Initialize maxfile startTime = time.Now() maxfile, err := client.VectorAdditionInit(); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Initializing maxfile:\t\t\t\t%.5fs\n", currentTime) // Load DFE startTime = time.Now() engine, err := client.MaxLoad(maxfile, "*"); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Loading DFE:\t\t\t\t\t%.5fs\n", currentTime) // Allocate and send input streams to server startTime = time.Now() addressX, err := client.MallocInt32T(size); checkForErrors(err) err = client.SendDataInt32T(addressX, x); checkForErrors(err) addressY, err := client.MallocInt32T(size); checkForErrors(err) err = client.SendDataInt32T(addressY, y); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Sending input data:\t\t\t\t%.5fs\n", currentTime) // Allocate memory for output stream on server startTime = time.Now() addressS, err := client.MallocInt32T(size); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Allocating memory for output stream on server:\t%.5fs\n", currentTime) // Writing to LMem startTime = time.Now() act, err := client.MaxActionsInit(maxfile, "writeLMem"); checkForErrors(err) err = client.MaxSetParamUint64t(act, "address", 0); checkForErrors(err) err = client.MaxSetParamUint64t(act, "nbytes", size*4); checkForErrors(err) err = client.MaxQueueInput(act, "cpu_to_lmem", addressX, size * 4); checkForErrors(err) err = client.MaxRun(engine, act); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Writing to LMem:\t\t\t\t%.5fs\n", currentTime) // Action default startTime = time.Now() act, err = client.MaxActionsInit(maxfile, "default"); checkForErrors(err) err = client.MaxSetParamUint64t(act, "N", size); checkForErrors(err) err = client.MaxSetParamUint64t(act, "A", scalar); checkForErrors(err) err = client.MaxQueueInput(act, "y", addressY, size * 4); checkForErrors(err) err = client.MaxQueueOutput(act, "s", addressS, size * 4); checkForErrors(err) err = client.MaxRun(engine, act); checkForErrors(err) //err = client.Free(act); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Vector addition time:\t\t\t\t%.5fs\n", currentTime) // Unload DFE startTime = time.Now() err = client.MaxUnload(engine); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Unloading DFE:\t\t\t\t\t%.5fs\n", currentTime) // Get output stream from server startTime = time.Now() s, err := client.ReceiveDataInt32T(addressS, size); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Getting output stream:\t(size = %v bit)\t%.5fs\n", size * 32, currentTime) // Free allocated memory for streams on server startTime = time.Now() client.Free(addressX); checkForErrors(err) client.Free(addressY); checkForErrors(err) client.Free(addressS); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Freeing allocated memory for streams on server:\t%.5fs\n", currentTime) // Free allocated maxfile data startTime = time.Now() client.VectorAdditionFree() err = client.Free(act); checkForErrors(err) currentTime = calcTime(startTime) fmt.Printf("Freeing allocated maxfile data:\t\t\t%.5fs\n", currentTime) // Close! startTime = time.Now() defer transport.Close() currentTime = calcTime(startTime) fmt.Printf("Closing connection:\t\t\t\t%.5fs\n", currentTime) return s } func main() { // Generating input data startTime := time.Now() const size int64 = 384 x := make([]int32, size) y := make([]int32, size) scalar := int64(3) for i := int64(0); i < size; i++ { x[i] = int32(rand.Intn(100)) y[i] = int32(rand.Intn(100)) } currentTime := calcTime(startTime) fmt.Printf("Generating input data:\t\t\t\t%.5fs\n", currentTime) // DFE Output startTime = time.Now() dataOutDFE := VectorAdditionDFE(x, y, scalar, size); currentTime = calcTime(startTime) fmt.Printf("DFE vector addition total time:\t\t\t%.5fs\n", currentTime) // CPU Output startTime = time.Now() dataOutCPU := VectorAdditionCPU(x, y, scalar, size); currentTime = calcTime(startTime) fmt.Printf("CPU vector addition total time:\t\t\t%.5fs\n", currentTime) // Checking results startTime = time.Now() status := check(dataOutDFE, dataOutCPU, size) currentTime = calcTime(startTime) fmt.Printf("Checking results:\t\t\t\t%.5fs\n", currentTime) if status == 0 { fmt.Printf("Test passed!\r\n") } else { fmt.Printf("Test failed %v times!", status) os.Exit(-1) } }
examples/VectorAddition/client/go/Dynamic/VectorAdditionClient.go
0.550366
0.418578
VectorAdditionClient.go
starcoder
package intersect // Rectangle is a simple geometry struct type Rectangle struct { X float64 Y float64 Width float64 Height float64 } // NewRect returns a new rectangle func NewRect(x, y, w, h float64) Rectangle { return Rectangle{x, y, w, h} } // IsPointIn returns true if the point is in the rectangle func (r1 Rectangle) IsPointIn(p2 Vector) bool { return within(r1.X, p2.X, r1.X+r1.Width) && within(r1.Y, p2.Y, r1.Y+r1.Height) } // Equals returns true if all the parameters are close enough to the other rectangle func (r1 Rectangle) Equals(r2 Rectangle) bool { return floatEquals(r1.X, r2.X) && floatEquals(r1.Y, r2.Y) && floatEquals(r1.Width, r2.Width) && floatEquals(r1.Height, r2.Height) } func (r1 Rectangle) getCorner() Vector { return Vector{r1.X, r1.Y} } // This function assumes x1 < x2 func overlapCollinearLines(x1, w1, x2, w2 float64) (float64, float64) { var w float64 if x2 > x1+w1 { // no overlap w = 0 } else if x1+w1 > x2+w2 { // line 1 encompasses line 2 w = w2 } else { // normal case w = x1 + w1 - x2 } return x2, w } func intersectNormalizedRectangles(r1, r2 Rectangle) Rectangle { x, w := overlapCollinearLines(r1.X, r1.Width, r2.X, r2.Width) y, h := overlapCollinearLines(r1.Y, r1.Height, r2.Y, r2.Height) return NewRect(x, y, w, h) } // Intersect returns rectangle formed by the intersection as well as a boolean indicating if there was an itersection func (r1 Rectangle) Intersect(r2 Rectangle) (Rectangle, bool) { var x1, y1, w1, h1 float64 var x2, y2, w2, h2 float64 if r1.X < r2.X { x1 = r1.X w1 = r1.Width x2 = r2.X w2 = r2.Width } else { x2 = r1.X w2 = r1.Width x1 = r2.X w1 = r2.Width } if r1.Y < r2.Y { y1 = r1.Y h1 = r1.Height y2 = r2.Y h2 = r2.Height } else { y2 = r1.Y h2 = r1.Height y1 = r2.Y h1 = r2.Height } r := intersectNormalizedRectangles(NewRect(x1, y1, w1, h1), NewRect(x2, y2, w2, h2)) return r, r.Width > 0 && r.Height > 0 } // ToPoly returns a polygon that is this rectangle func (r1 Rectangle) ToPoly() Polygon { ss := [4]Segment{ NewSegment(r1.getCorner(), r1.getCorner().Add(NewVector(r1.Width, 0))), NewSegment(r1.getCorner().Add(NewVector(r1.Width, 0)), r1.getCorner().Add(NewVector(r1.Width, r1.Height))), NewSegment(r1.getCorner().Add(NewVector(r1.Width, r1.Height)), r1.getCorner().Add(NewVector(0, r1.Height))), NewSegment(r1.getCorner().Add(NewVector(0, r1.Height)), r1.getCorner()), } return NewPolyFromSegments(ss[:]) } // IntersectEdge calculates the intersection with a straight edge func (r1 Rectangle) IntersectEdge(e2 Edge) ([]Vector, int) { return r1.ToPoly().IntersectEdge(e2) }
rectangle.go
0.927519
0.837288
rectangle.go
starcoder
package imut import ( "bytes" "image" "image/color" "image/draw" "image/png" "io/ioutil" "github.com/gitchander/neural" ) func SaveImagePNG(m image.Image, filename string) error { var buf bytes.Buffer err := png.Encode(&buf, m) if err != nil { return err } return ioutil.WriteFile(filename, buf.Bytes(), 0666) } func MakeGray(m image.Image) *image.Gray { if g, ok := m.(*image.Gray); ok { return g } r := m.Bounds() g := image.NewGray(r) draw.Draw(g, r, m, image.ZP, draw.Src) return g } func MakeSamplesGray(g *image.Gray) []neural.Sample { r := g.Bounds() size := image.Point{ X: r.Dx(), Y: r.Dy(), } samples := make([]neural.Sample, 0, size.X*size.Y) for x := r.Min.X; x < r.Max.X; x++ { for y := r.Min.Y; y < r.Max.Y; y++ { cg := g.GrayAt(x, y) var ( xf = float64(x-r.Min.X) / float64(size.X) yf = float64(y-r.Min.Y) / float64(size.Y) ) out := float64(cg.Y) / 255 sample := neural.Sample{ Inputs: []float64{xf, yf}, Outputs: []float64{out}, } samples = append(samples, sample) } } return samples } func MakeGrayFromMLP_outs(p *neural.MLP, size image.Point) *image.Gray { var ( r = image.Rectangle{Max: size} g = image.NewGray(r) ) var ( inputs = make([]float64, 2) outputs = make([]float64, 2) ) for x := 0; x < size.X; x++ { for y := 0; y < size.Y; y++ { var ( norm_X = float64(x) / float64(size.X-1) // [0..1) norm_Y = float64(y) / float64(size.Y-1) // [0..1) ) inputs[0] = norm_X inputs[1] = norm_Y p.SetInputs(inputs) p.Calculate() p.GetOutputs(outputs) g.Set(x, y, color.Gray{ Y: uint8(neural.IndexOfMax(outputs) * 255), }) } } return g } func MakeGrayFromMLP(p *neural.MLP, size image.Point) *image.Gray { var ( r = image.Rectangle{Max: size} g = image.NewGray(r) ) var ( inputs = make([]float64, 2) outputs = make([]float64, 1) ) for x := 0; x < size.X; x++ { for y := 0; y < size.Y; y++ { var ( norm_X = float64(x) / float64(size.X-1) // [0..1) norm_Y = float64(y) / float64(size.Y-1) // [0..1) ) inputs[0] = norm_X inputs[1] = norm_Y p.SetInputs(inputs) p.Calculate() p.GetOutputs(outputs) g.Set(x, y, color.Gray{ Y: uint8(outputs[0] * 255), }) } } return g }
neutil/imut/image.go
0.633524
0.404066
image.go
starcoder
package models import ( i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time" i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" ) // CloudPC type CloudPC struct { Entity // The Azure Active Directory (Azure AD) device ID of the Cloud PC. aadDeviceId *string // The display name of the Cloud PC. displayName *string // The date and time when the grace period ends and reprovisioning/deprovisioning happens. Required only if the status is inGracePeriod. The timestamp is shown in ISO 8601 format and Coordinated Universal Time (UTC). For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. gracePeriodEndDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time // Name of the OS image that's on the Cloud PC. imageDisplayName *string // The last login result of the Cloud PC. For example, { 'time': '2014-01-01T00:00:00Z'}. lastLoginResult CloudPcLoginResultable // The last modified date and time of the Cloud PC. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. lastModifiedDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time // The last remote action result of the enterprise Cloud PCs. The supported remote actions are: Reboot, Rename, Reprovision, Restore, and Troubleshoot. lastRemoteActionResult CloudPcRemoteActionResultable // The Intune device ID of the Cloud PC. managedDeviceId *string // The Intune device name of the Cloud PC. managedDeviceName *string // The Azure network connection that is applied during the provisioning of Cloud PCs. onPremisesConnectionName *string // The version of the operating system (OS) to provision on Cloud PCs. Possible values are: windows10, windows11, and unknownFutureValue. osVersion *CloudPcOperatingSystem // The provisioning policy ID of the Cloud PC. provisioningPolicyId *string // The provisioning policy that is applied during the provisioning of Cloud PCs. provisioningPolicyName *string // The service plan ID of the Cloud PC. servicePlanId *string // The service plan name of the Cloud PC. servicePlanName *string // The service plan type of the Cloud PC. servicePlanType *CloudPcServicePlanType // The status of the Cloud PC. Possible values are: notProvisioned, provisioning, provisioned, upgrading, inGracePeriod, deprovisioning, failed, restoring. status *CloudPcStatus // The details of the Cloud PC status. statusDetails CloudPcStatusDetailsable // The account type of the user on provisioned Cloud PCs. Possible values are: standardUser, administrator, and unknownFutureValue. userAccountType *CloudPcUserAccountType // The user principal name (UPN) of the user assigned to the Cloud PC. userPrincipalName *string } // NewCloudPC instantiates a new cloudPC and sets the default values. func NewCloudPC()(*CloudPC) { m := &CloudPC{ Entity: *NewEntity(), } return m } // CreateCloudPCFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateCloudPCFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewCloudPC(), nil } // GetAadDeviceId gets the aadDeviceId property value. The Azure Active Directory (Azure AD) device ID of the Cloud PC. func (m *CloudPC) GetAadDeviceId()(*string) { if m == nil { return nil } else { return m.aadDeviceId } } // GetDisplayName gets the displayName property value. The display name of the Cloud PC. func (m *CloudPC) GetDisplayName()(*string) { if m == nil { return nil } else { return m.displayName } } // GetFieldDeserializers the deserialization information for the current model func (m *CloudPC) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := m.Entity.GetFieldDeserializers() res["aadDeviceId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetAadDeviceId(val) } return nil } res["displayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetDisplayName(val) } return nil } res["gracePeriodEndDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetGracePeriodEndDateTime(val) } return nil } res["imageDisplayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetImageDisplayName(val) } return nil } res["lastLoginResult"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreateCloudPcLoginResultFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetLastLoginResult(val.(CloudPcLoginResultable)) } return nil } res["lastModifiedDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetTimeValue() if err != nil { return err } if val != nil { m.SetLastModifiedDateTime(val) } return nil } res["lastRemoteActionResult"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreateCloudPcRemoteActionResultFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetLastRemoteActionResult(val.(CloudPcRemoteActionResultable)) } return nil } res["managedDeviceId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetManagedDeviceId(val) } return nil } res["managedDeviceName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetManagedDeviceName(val) } return nil } res["onPremisesConnectionName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetOnPremisesConnectionName(val) } return nil } res["osVersion"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseCloudPcOperatingSystem) if err != nil { return err } if val != nil { m.SetOsVersion(val.(*CloudPcOperatingSystem)) } return nil } res["provisioningPolicyId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetProvisioningPolicyId(val) } return nil } res["provisioningPolicyName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetProvisioningPolicyName(val) } return nil } res["servicePlanId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetServicePlanId(val) } return nil } res["servicePlanName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetServicePlanName(val) } return nil } res["servicePlanType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseCloudPcServicePlanType) if err != nil { return err } if val != nil { m.SetServicePlanType(val.(*CloudPcServicePlanType)) } return nil } res["status"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseCloudPcStatus) if err != nil { return err } if val != nil { m.SetStatus(val.(*CloudPcStatus)) } return nil } res["statusDetails"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreateCloudPcStatusDetailsFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetStatusDetails(val.(CloudPcStatusDetailsable)) } return nil } res["userAccountType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseCloudPcUserAccountType) if err != nil { return err } if val != nil { m.SetUserAccountType(val.(*CloudPcUserAccountType)) } return nil } res["userPrincipalName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetUserPrincipalName(val) } return nil } return res } // GetGracePeriodEndDateTime gets the gracePeriodEndDateTime property value. The date and time when the grace period ends and reprovisioning/deprovisioning happens. Required only if the status is inGracePeriod. The timestamp is shown in ISO 8601 format and Coordinated Universal Time (UTC). For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. func (m *CloudPC) GetGracePeriodEndDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.gracePeriodEndDateTime } } // GetImageDisplayName gets the imageDisplayName property value. Name of the OS image that's on the Cloud PC. func (m *CloudPC) GetImageDisplayName()(*string) { if m == nil { return nil } else { return m.imageDisplayName } } // GetLastLoginResult gets the lastLoginResult property value. The last login result of the Cloud PC. For example, { 'time': '2014-01-01T00:00:00Z'}. func (m *CloudPC) GetLastLoginResult()(CloudPcLoginResultable) { if m == nil { return nil } else { return m.lastLoginResult } } // GetLastModifiedDateTime gets the lastModifiedDateTime property value. The last modified date and time of the Cloud PC. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. func (m *CloudPC) GetLastModifiedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) { if m == nil { return nil } else { return m.lastModifiedDateTime } } // GetLastRemoteActionResult gets the lastRemoteActionResult property value. The last remote action result of the enterprise Cloud PCs. The supported remote actions are: Reboot, Rename, Reprovision, Restore, and Troubleshoot. func (m *CloudPC) GetLastRemoteActionResult()(CloudPcRemoteActionResultable) { if m == nil { return nil } else { return m.lastRemoteActionResult } } // GetManagedDeviceId gets the managedDeviceId property value. The Intune device ID of the Cloud PC. func (m *CloudPC) GetManagedDeviceId()(*string) { if m == nil { return nil } else { return m.managedDeviceId } } // GetManagedDeviceName gets the managedDeviceName property value. The Intune device name of the Cloud PC. func (m *CloudPC) GetManagedDeviceName()(*string) { if m == nil { return nil } else { return m.managedDeviceName } } // GetOnPremisesConnectionName gets the onPremisesConnectionName property value. The Azure network connection that is applied during the provisioning of Cloud PCs. func (m *CloudPC) GetOnPremisesConnectionName()(*string) { if m == nil { return nil } else { return m.onPremisesConnectionName } } // GetOsVersion gets the osVersion property value. The version of the operating system (OS) to provision on Cloud PCs. Possible values are: windows10, windows11, and unknownFutureValue. func (m *CloudPC) GetOsVersion()(*CloudPcOperatingSystem) { if m == nil { return nil } else { return m.osVersion } } // GetProvisioningPolicyId gets the provisioningPolicyId property value. The provisioning policy ID of the Cloud PC. func (m *CloudPC) GetProvisioningPolicyId()(*string) { if m == nil { return nil } else { return m.provisioningPolicyId } } // GetProvisioningPolicyName gets the provisioningPolicyName property value. The provisioning policy that is applied during the provisioning of Cloud PCs. func (m *CloudPC) GetProvisioningPolicyName()(*string) { if m == nil { return nil } else { return m.provisioningPolicyName } } // GetServicePlanId gets the servicePlanId property value. The service plan ID of the Cloud PC. func (m *CloudPC) GetServicePlanId()(*string) { if m == nil { return nil } else { return m.servicePlanId } } // GetServicePlanName gets the servicePlanName property value. The service plan name of the Cloud PC. func (m *CloudPC) GetServicePlanName()(*string) { if m == nil { return nil } else { return m.servicePlanName } } // GetServicePlanType gets the servicePlanType property value. The service plan type of the Cloud PC. func (m *CloudPC) GetServicePlanType()(*CloudPcServicePlanType) { if m == nil { return nil } else { return m.servicePlanType } } // GetStatus gets the status property value. The status of the Cloud PC. Possible values are: notProvisioned, provisioning, provisioned, upgrading, inGracePeriod, deprovisioning, failed, restoring. func (m *CloudPC) GetStatus()(*CloudPcStatus) { if m == nil { return nil } else { return m.status } } // GetStatusDetails gets the statusDetails property value. The details of the Cloud PC status. func (m *CloudPC) GetStatusDetails()(CloudPcStatusDetailsable) { if m == nil { return nil } else { return m.statusDetails } } // GetUserAccountType gets the userAccountType property value. The account type of the user on provisioned Cloud PCs. Possible values are: standardUser, administrator, and unknownFutureValue. func (m *CloudPC) GetUserAccountType()(*CloudPcUserAccountType) { if m == nil { return nil } else { return m.userAccountType } } // GetUserPrincipalName gets the userPrincipalName property value. The user principal name (UPN) of the user assigned to the Cloud PC. func (m *CloudPC) GetUserPrincipalName()(*string) { if m == nil { return nil } else { return m.userPrincipalName } } // Serialize serializes information the current object func (m *CloudPC) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { err := m.Entity.Serialize(writer) if err != nil { return err } { err = writer.WriteStringValue("aadDeviceId", m.GetAadDeviceId()) if err != nil { return err } } { err = writer.WriteStringValue("displayName", m.GetDisplayName()) if err != nil { return err } } { err = writer.WriteTimeValue("gracePeriodEndDateTime", m.GetGracePeriodEndDateTime()) if err != nil { return err } } { err = writer.WriteStringValue("imageDisplayName", m.GetImageDisplayName()) if err != nil { return err } } { err = writer.WriteObjectValue("lastLoginResult", m.GetLastLoginResult()) if err != nil { return err } } { err = writer.WriteTimeValue("lastModifiedDateTime", m.GetLastModifiedDateTime()) if err != nil { return err } } { err = writer.WriteObjectValue("lastRemoteActionResult", m.GetLastRemoteActionResult()) if err != nil { return err } } { err = writer.WriteStringValue("managedDeviceId", m.GetManagedDeviceId()) if err != nil { return err } } { err = writer.WriteStringValue("managedDeviceName", m.GetManagedDeviceName()) if err != nil { return err } } { err = writer.WriteStringValue("onPremisesConnectionName", m.GetOnPremisesConnectionName()) if err != nil { return err } } if m.GetOsVersion() != nil { cast := (*m.GetOsVersion()).String() err = writer.WriteStringValue("osVersion", &cast) if err != nil { return err } } { err = writer.WriteStringValue("provisioningPolicyId", m.GetProvisioningPolicyId()) if err != nil { return err } } { err = writer.WriteStringValue("provisioningPolicyName", m.GetProvisioningPolicyName()) if err != nil { return err } } { err = writer.WriteStringValue("servicePlanId", m.GetServicePlanId()) if err != nil { return err } } { err = writer.WriteStringValue("servicePlanName", m.GetServicePlanName()) if err != nil { return err } } if m.GetServicePlanType() != nil { cast := (*m.GetServicePlanType()).String() err = writer.WriteStringValue("servicePlanType", &cast) if err != nil { return err } } if m.GetStatus() != nil { cast := (*m.GetStatus()).String() err = writer.WriteStringValue("status", &cast) if err != nil { return err } } { err = writer.WriteObjectValue("statusDetails", m.GetStatusDetails()) if err != nil { return err } } if m.GetUserAccountType() != nil { cast := (*m.GetUserAccountType()).String() err = writer.WriteStringValue("userAccountType", &cast) if err != nil { return err } } { err = writer.WriteStringValue("userPrincipalName", m.GetUserPrincipalName()) if err != nil { return err } } return nil } // SetAadDeviceId sets the aadDeviceId property value. The Azure Active Directory (Azure AD) device ID of the Cloud PC. func (m *CloudPC) SetAadDeviceId(value *string)() { if m != nil { m.aadDeviceId = value } } // SetDisplayName sets the displayName property value. The display name of the Cloud PC. func (m *CloudPC) SetDisplayName(value *string)() { if m != nil { m.displayName = value } } // SetGracePeriodEndDateTime sets the gracePeriodEndDateTime property value. The date and time when the grace period ends and reprovisioning/deprovisioning happens. Required only if the status is inGracePeriod. The timestamp is shown in ISO 8601 format and Coordinated Universal Time (UTC). For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. func (m *CloudPC) SetGracePeriodEndDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.gracePeriodEndDateTime = value } } // SetImageDisplayName sets the imageDisplayName property value. Name of the OS image that's on the Cloud PC. func (m *CloudPC) SetImageDisplayName(value *string)() { if m != nil { m.imageDisplayName = value } } // SetLastLoginResult sets the lastLoginResult property value. The last login result of the Cloud PC. For example, { 'time': '2014-01-01T00:00:00Z'}. func (m *CloudPC) SetLastLoginResult(value CloudPcLoginResultable)() { if m != nil { m.lastLoginResult = value } } // SetLastModifiedDateTime sets the lastModifiedDateTime property value. The last modified date and time of the Cloud PC. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. func (m *CloudPC) SetLastModifiedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() { if m != nil { m.lastModifiedDateTime = value } } // SetLastRemoteActionResult sets the lastRemoteActionResult property value. The last remote action result of the enterprise Cloud PCs. The supported remote actions are: Reboot, Rename, Reprovision, Restore, and Troubleshoot. func (m *CloudPC) SetLastRemoteActionResult(value CloudPcRemoteActionResultable)() { if m != nil { m.lastRemoteActionResult = value } } // SetManagedDeviceId sets the managedDeviceId property value. The Intune device ID of the Cloud PC. func (m *CloudPC) SetManagedDeviceId(value *string)() { if m != nil { m.managedDeviceId = value } } // SetManagedDeviceName sets the managedDeviceName property value. The Intune device name of the Cloud PC. func (m *CloudPC) SetManagedDeviceName(value *string)() { if m != nil { m.managedDeviceName = value } } // SetOnPremisesConnectionName sets the onPremisesConnectionName property value. The Azure network connection that is applied during the provisioning of Cloud PCs. func (m *CloudPC) SetOnPremisesConnectionName(value *string)() { if m != nil { m.onPremisesConnectionName = value } } // SetOsVersion sets the osVersion property value. The version of the operating system (OS) to provision on Cloud PCs. Possible values are: windows10, windows11, and unknownFutureValue. func (m *CloudPC) SetOsVersion(value *CloudPcOperatingSystem)() { if m != nil { m.osVersion = value } } // SetProvisioningPolicyId sets the provisioningPolicyId property value. The provisioning policy ID of the Cloud PC. func (m *CloudPC) SetProvisioningPolicyId(value *string)() { if m != nil { m.provisioningPolicyId = value } } // SetProvisioningPolicyName sets the provisioningPolicyName property value. The provisioning policy that is applied during the provisioning of Cloud PCs. func (m *CloudPC) SetProvisioningPolicyName(value *string)() { if m != nil { m.provisioningPolicyName = value } } // SetServicePlanId sets the servicePlanId property value. The service plan ID of the Cloud PC. func (m *CloudPC) SetServicePlanId(value *string)() { if m != nil { m.servicePlanId = value } } // SetServicePlanName sets the servicePlanName property value. The service plan name of the Cloud PC. func (m *CloudPC) SetServicePlanName(value *string)() { if m != nil { m.servicePlanName = value } } // SetServicePlanType sets the servicePlanType property value. The service plan type of the Cloud PC. func (m *CloudPC) SetServicePlanType(value *CloudPcServicePlanType)() { if m != nil { m.servicePlanType = value } } // SetStatus sets the status property value. The status of the Cloud PC. Possible values are: notProvisioned, provisioning, provisioned, upgrading, inGracePeriod, deprovisioning, failed, restoring. func (m *CloudPC) SetStatus(value *CloudPcStatus)() { if m != nil { m.status = value } } // SetStatusDetails sets the statusDetails property value. The details of the Cloud PC status. func (m *CloudPC) SetStatusDetails(value CloudPcStatusDetailsable)() { if m != nil { m.statusDetails = value } } // SetUserAccountType sets the userAccountType property value. The account type of the user on provisioned Cloud PCs. Possible values are: standardUser, administrator, and unknownFutureValue. func (m *CloudPC) SetUserAccountType(value *CloudPcUserAccountType)() { if m != nil { m.userAccountType = value } } // SetUserPrincipalName sets the userPrincipalName property value. The user principal name (UPN) of the user assigned to the Cloud PC. func (m *CloudPC) SetUserPrincipalName(value *string)() { if m != nil { m.userPrincipalName = value } }
models/cloud_p_c.go
0.669096
0.41182
cloud_p_c.go
starcoder
package docs import ( "bytes" "encoding/json" "strings" "github.com/alecthomas/template" "github.com/swaggo/swag" ) var doc = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{.Description}}", "title": "{{.Title}}", "contact": {}, "license": { "name": "MIT License" }, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/health/hello": { "get": { "description": "Non-authenticated endpoint that returns 200 with hello message. Used to validate that the service is responsive.", "produces": [ "application/json" ], "tags": [ "health" ], "summary": "Hello sanity endpoint", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/health.Ping" } } } } }, "/portfolio": { "get": { "description": "Non-authenticated endpoint that returns array of all stored portfolios.", "produces": [ "application/json" ], "tags": [ "portfolio" ], "summary": "Get portfolios endpoint", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/model.AllPortfoliosViewModel" } }, "404": { "description": "Not Found", "schema": { "type": "string" } } } }, "post": { "description": "Insert portfolio. Returns the portfolio ID.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "portfolio" ], "summary": "Creates portfolio a unique ID", "parameters": [ { "description": "Add account", "name": "portfolio", "in": "body", "required": true, "schema": { "$ref": "#/definitions/model.PortfolioCreateModel" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/model.PortfolioID" } }, "404": { "description": "Not Found", "schema": { "type": "string" } } } }, "delete": { "description": "Deletes a portfolio with the specified ID. Returns 200 if the resource did not already exist.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "portfolio" ], "summary": "Deletes a portfolio at the specified ID", "parameters": [ { "type": "string", "description": "Portfolio ID", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "ok", "schema": { "type": "string" } }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/model.Error" } } } } }, "/portfolio/{id}": { "get": { "description": "Non-authenticated endpoint that returns a portfolio with matching key.", "produces": [ "application/json" ], "tags": [ "portfolio" ], "summary": "Get portfolios endpoint", "parameters": [ { "type": "string", "description": "Portfolio ID", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/model.PortfolioViewModel" } }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/model.Error" } } } } } }, "definitions": { "health.Ping": { "type": "object", "properties": { "response": { "type": "string", "example": "hello" } } }, "model.AllPortfoliosViewModel": { "type": "object", "properties": { "portfolios": { "type": "array", "items": { "$ref": "#/definitions/model.PortfolioViewModel" } } } }, "model.Error": { "type": "object", "properties": { "message": { "type": "string" } } }, "model.MetadataViewModel": { "type": "object", "properties": { "createTime": { "type": "string", "example": "02/01/2020 11:12:00" }, "id": { "type": "string", "example": "123884" }, "lastUpdated": { "type": "string", "example": "02/01/2020 11:12:00" } } }, "model.PortfolioCreateModel": { "type": "object", "properties": { "stocks": { "type": "array", "items": { "$ref": "#/definitions/model.StockViewModel" } } } }, "model.PortfolioID": { "type": "object", "properties": { "id": { "type": "string" } } }, "model.PortfolioViewModel": { "type": "object", "properties": { "metadata": { "type": "object", "$ref": "#/definitions/model.MetadataViewModel" }, "stocks": { "type": "object", "additionalProperties": { "$ref": "#/definitions/model.StockViewModel" } } } }, "model.StockViewModel": { "type": "object", "properties": { "currency": { "type": "string", "example": "CAD" }, "currentPrice": { "type": "number", "example": 105 }, "name": { "type": "string", "example": "Canadian Pacific Railway Limited" }, "purchaseDate": { "type": "string", "example": "02/03/2020" }, "purchasePrice": { "type": "number", "example": 10000 }, "quantity": { "type": "integer", "example": 100 }, "ticker": { "type": "string", "example": "CP.TO" } } } } }` type swaggerInfo struct { Version string Host string BasePath string Schemes []string Title string Description string } // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = swaggerInfo{ Version: "1.0", Host: "", BasePath: "/api/v1", Schemes: []string{}, Title: "Portfolio Service API", Description: "Stores and fetches user and model data", } type s struct{} func (s *s) ReadDoc() string { sInfo := SwaggerInfo sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1) t, err := template.New("swagger_info").Funcs(template.FuncMap{ "marshal": func(v interface{}) string { a, _ := json.Marshal(v) return string(a) }, }).Parse(doc) if err != nil { return doc } var tpl bytes.Buffer if err := t.Execute(&tpl, sInfo); err != nil { return doc } return tpl.String() } func init() { swag.Register(swag.Name, &s{}) }
docs/docs.go
0.616359
0.412767
docs.go
starcoder
package function import ( "fmt" "math" "sort" "github.com/lindb/lindb/pkg/collections" ) type bucket struct { upperBound float64 count float64 itr *collections.FloatArrayIterator } type buckets []bucket func (bkt buckets) Len() int { return len(bkt) } func (bkt buckets) Less(i, j int) bool { return bkt[i].upperBound < bkt[j].upperBound } func (bkt buckets) Swap(i, j int) { bkt[i], bkt[j] = bkt[j], bkt[i] } // EnsureCountFieldCumulative ensures count in buckets are cumulative for quantile function func (bkt buckets) EnsureCountFieldCumulative() { if bkt.Len() == 0 { return } last := bkt[0].count for i := 1; i < bkt.Len(); i++ { last += bkt[i].count bkt[i].count = last } } // QuantileCall references to prometheus implementation. // https://github.com/prometheus/prometheus/blob/39d79c3cfb86c47d6bc06a9e9317af582f1833bb/promql/quantile.go // 0 <= q <= 1 // q = 0, returns 0 // q = 1, last UpperBound before Inf is returned func QuantileCall(q float64, histogramFields map[float64][]*collections.FloatArray) (*collections.FloatArray, error) { if q < 0 || q > 1 { return nil, fmt.Errorf("QuantileCall with illegal value: %f", q) } var histogramBuckets = make(buckets, len(histogramFields)) var idx = 0 for upperBound, arrays := range histogramFields { if len(arrays) != 1 { return nil, fmt.Errorf("QuantileCall buckets's floatArray count: %d not equals 1", len(arrays)) } histogramBuckets[idx] = bucket{upperBound: upperBound, itr: arrays[0].NewIterator()} idx++ } sort.Sort(histogramBuckets) if len(histogramBuckets) < 2 { return nil, fmt.Errorf("QuantileCall with buckets count: %d less than 2", len(histogramBuckets)) } if !math.IsInf(histogramBuckets[len(histogramBuckets)-1].upperBound, +1) { return nil, fmt.Errorf("QuantileCall's largest upper bound is not +Inf") } capacity := histogramFields[histogramBuckets[0].upperBound][0].Capacity() targetFloatArray := collections.NewFloatArray(capacity) itr := histogramBuckets[0].itr for itr.HasNext() { pos, v := itr.Next() histogramBuckets[0].count = v for bucketIdx := 1; bucketIdx < len(histogramBuckets); bucketIdx++ { if !histogramBuckets[bucketIdx].itr.HasNext() { return nil, fmt.Errorf("QuantileCall floatArray length") } _, v := histogramBuckets[bucketIdx].itr.Next() histogramBuckets[bucketIdx].count = v } histogramBuckets.EnsureCountFieldCumulative() observations := histogramBuckets[len(histogramFields)-1].count if observations == 0 { targetFloatArray.SetValue(pos, 0) continue } rank := q * observations b := sort.Search(len(histogramBuckets)-1, func(i int) bool { return histogramBuckets[i].count >= rank }) if b == len(histogramBuckets)-1 { targetFloatArray.SetValue(pos, histogramBuckets[len(histogramBuckets)-2].upperBound) continue } else if b == 0 && histogramBuckets[0].upperBound <= 0 { targetFloatArray.SetValue(pos, histogramBuckets[0].upperBound) continue } var ( bucketStart float64 bucketEnd = histogramBuckets[b].upperBound count = histogramBuckets[b].count ) if b > 0 { bucketStart = histogramBuckets[b-1].upperBound count -= histogramBuckets[b-1].count rank -= histogramBuckets[b-1].count } targetFloatArray.SetValue(pos, bucketStart+(bucketEnd-bucketStart)*(rank/count)) } return targetFloatArray, nil }
aggregation/function/quantile.go
0.742141
0.410047
quantile.go
starcoder
package csv import ( "fmt" "strconv" ) /* Row represents one line from a data source like a .csv file. Each Row is a map from column names to the string values under that columns on the current line. It is assumed that each column has a unique name. In a .csv file, the column names may either come from the first line of the file ("expected header"), or they can be set-up via configuration of the reader object ("assumed header"). Using meaningful column names instead of indices is usually more convenient when the columns get rearranged during the execution of the processing pipeline. */ type Row map[string]string // HasColumn is a predicate returning 'true' when the specified column is present. func (row Row) HasColumn(col string) (found bool) { _, found = row[col] return } // SafeGetValue returns the value under the specified column, if present, otherwise it returns the // substitution value. func (row Row) SafeGetValue(col, subst string) string { if value, found := row[col]; found { return value } return subst } // Header returns a slice of all column names, sorted via sort.Strings. func (row Row) Header() []string { r := make([]string, 0, len(row)) for col := range row { r = append(r, col) } sort.Strings(r) return r } // String returns a string representation of the Row. func (row Row) String() string { if len(row) == 0 { return "{}" } header := row.Header() // make order predictable buff := append(append(append(append([]byte(`{ "`), header[0]...), `" : "`...), row[header[0]]...), '"') for _, col := range header[1:] { buff = append(append(append(append(append(buff, `, "`...), col...), `" : "`...), row[col]...), '"') } buff = append(buff, " }"...) return *(*string)(unsafe.Pointer(&buff)) } // SelectExisting takes a list of column names and returns a new Row // containing only those columns from the list that are present in the current Row. func (row Row) SelectExisting(cols ...string) Row { r := make(map[string]string, len(cols)) for _, name := range cols { if val, found := row[name]; found { r[name] = val } } return r } // Select takes a list of column names and returns a new Row // containing only the specified columns, or an error if any column is not present. func (row Row) Select(cols ...string) (Row, error) { r := make(map[string]string, len(cols)) for _, name := range cols { var found bool if r[name], found = row[name]; !found { return nil, fmt.Errorf(`Missing column %q`, name) } } return r, nil } // SelectValues takes a list of column names and returns a slice of their // corresponding values, or an error if any column is not present. func (row Row) SelectValues(cols ...string) ([]string, error) { r := make([]string, len(cols)) for i, name := range cols { var found bool if r[i], found = row[name]; !found { return nil, fmt.Errorf(`Missing column %q`, name) } } return r, nil } // Clone returns a copy of the current Row. func (row Row) Clone() Row { r := make(map[string]string, len(row)) for k, v := range row { r[k] = v } return r } // ValueAsInt returns the value of the given column converted to integer type, or an error. // The column must be present on the row. func (row Row) ValueAsInt(column string) (res int, err error) { var val string var found bool if val, found = row[column]; !found { err = fmt.Errorf(`Missing column %q`, column) return } if res, err = strconv.Atoi(val); err != nil { if e, ok := err.(*strconv.NumError); ok { err = fmt.Errorf(`Column %q: Cannot convert %q to integer: %s`, column, val, e.Err) } else { err = fmt.Errorf(`Column %q: %s`, column, err) } } return } // ValueAsFloat64 returns the value of the given column converted to floating point type, or an error. // The column must be present on the row. func (row Row) ValueAsFloat64(column string) (res float64, err error) { var val string var found bool if val, found = row[column]; !found { err = fmt.Errorf(`Missing column %q`, column) return } if res, err = strconv.ParseFloat(val, 64); err != nil { if e, ok := err.(*strconv.NumError); ok { err = fmt.Errorf(`Column %q: Cannot convert %q to float: %s`, column, val, e.Err) } else { err = fmt.Errorf(`Column %q: %s`, column, err.Error()) } } return } // RowFunc is the function type used when iterating Rows. type RowFunc func(Row) error
plugins/data/encoding/csv/rows.go
0.829699
0.624866
rows.go
starcoder
package main import ( "github.com/gen2brain/raylib-go/raylib" ) func main() { screenWidth := int32(800) screenHeight := int32(450) raylib.InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions") camera := raylib.Camera{} camera.Position = raylib.NewVector3(0.0, 10.0, 10.0) camera.Target = raylib.NewVector3(0.0, 0.0, 0.0) camera.Up = raylib.NewVector3(0.0, 1.0, 0.0) camera.Fovy = 45.0 camera.Type = raylib.CameraPerspective playerPosition := raylib.NewVector3(0.0, 1.0, 2.0) playerSize := raylib.NewVector3(1.0, 2.0, 1.0) playerColor := raylib.Green enemyBoxPos := raylib.NewVector3(-4.0, 1.0, 0.0) enemyBoxSize := raylib.NewVector3(2.0, 2.0, 2.0) enemySpherePos := raylib.NewVector3(4.0, 0.0, 0.0) enemySphereSize := float32(1.5) collision := false raylib.SetTargetFPS(60) for !raylib.WindowShouldClose() { // Update // Move player if raylib.IsKeyDown(raylib.KeyRight) { playerPosition.X += 0.2 } else if raylib.IsKeyDown(raylib.KeyLeft) { playerPosition.X -= 0.2 } else if raylib.IsKeyDown(raylib.KeyDown) { playerPosition.Z += 0.2 } else if raylib.IsKeyDown(raylib.KeyUp) { playerPosition.Z -= 0.2 } collision = false // Check collisions player vs enemy-box if raylib.CheckCollisionBoxes( raylib.NewBoundingBox( raylib.NewVector3(playerPosition.X-playerSize.X/2, playerPosition.Y-playerSize.Y/2, playerPosition.Z-playerSize.Z/2), raylib.NewVector3(playerPosition.X+playerSize.X/2, playerPosition.Y+playerSize.Y/2, playerPosition.Z+playerSize.Z/2)), raylib.NewBoundingBox( raylib.NewVector3(enemyBoxPos.X-enemyBoxSize.X/2, enemyBoxPos.Y-enemyBoxSize.Y/2, enemyBoxPos.Z-enemyBoxSize.Z/2), raylib.NewVector3(enemyBoxPos.X+enemyBoxSize.X/2, enemyBoxPos.Y+enemyBoxSize.Y/2, enemyBoxPos.Z+enemyBoxSize.Z/2)), ) { collision = true } // Check collisions player vs enemy-sphere if raylib.CheckCollisionBoxSphere( raylib.NewBoundingBox( raylib.NewVector3(playerPosition.X-playerSize.X/2, playerPosition.Y-playerSize.Y/2, playerPosition.Z-playerSize.Z/2), raylib.NewVector3(playerPosition.X+playerSize.X/2, playerPosition.Y+playerSize.Y/2, playerPosition.Z+playerSize.Z/2)), enemySpherePos, enemySphereSize, ) { collision = true } if collision { playerColor = raylib.Red } else { playerColor = raylib.Green } // Draw raylib.BeginDrawing() raylib.ClearBackground(raylib.RayWhite) raylib.BeginMode3D(camera) // Draw enemy-box raylib.DrawCube(enemyBoxPos, enemyBoxSize.X, enemyBoxSize.Y, enemyBoxSize.Z, raylib.Gray) raylib.DrawCubeWires(enemyBoxPos, enemyBoxSize.X, enemyBoxSize.Y, enemyBoxSize.Z, raylib.DarkGray) // Draw enemy-sphere raylib.DrawSphere(enemySpherePos, enemySphereSize, raylib.Gray) raylib.DrawSphereWires(enemySpherePos, enemySphereSize, 16, 16, raylib.DarkGray) // Draw player raylib.DrawCubeV(playerPosition, playerSize, playerColor) raylib.DrawGrid(10, 1.0) // Draw a grid raylib.EndMode3D() raylib.DrawText("Move player with cursors to collide", 220, 40, 20, raylib.Gray) raylib.DrawFPS(10, 10) raylib.EndDrawing() } raylib.CloseWindow() }
examples/models/box_collisions/main.go
0.668123
0.432423
main.go
starcoder
package types import ( "bytes" "io" "reflect" "regexp" "github.com/lyraproj/issue/issue" "github.com/lyraproj/pcore/px" "github.com/lyraproj/pcore/utils" ) type ( RegexpType struct { pattern *regexp.Regexp } // Regexp represents RegexpType as a value Regexp RegexpType ) var regexpTypeDefault = &RegexpType{pattern: regexp.MustCompile(``)} var RegexpMetaType px.ObjectType func init() { RegexpMetaType = newObjectType(`Pcore::RegexpType`, `Pcore::ScalarType { attributes => { pattern => { type => Variant[Undef,String,Regexp], value => undef } } }`, func(ctx px.Context, args []px.Value) px.Value { return newRegexpType2(args...) }) newGoConstructor(`Regexp`, func(d px.Dispatch) { d.Param(`Variant[String,Regexp]`) d.Function(func(c px.Context, args []px.Value) px.Value { arg := args[0] if s, ok := arg.(*Regexp); ok { return s } return WrapRegexp(arg.String()) }) }, ) } func DefaultRegexpType() *RegexpType { return regexpTypeDefault } func NewRegexpType(patternString string) *RegexpType { if patternString == `` { return DefaultRegexpType() } pattern, err := regexp.Compile(patternString) if err != nil { panic(px.Error(px.InvalidRegexp, issue.H{`pattern`: patternString, `detail`: err.Error()})) } return &RegexpType{pattern: pattern} } func NewRegexpTypeR(pattern *regexp.Regexp) *RegexpType { if pattern.String() == `` { return DefaultRegexpType() } return &RegexpType{pattern: pattern} } func newRegexpType2(args ...px.Value) *RegexpType { switch len(args) { case 0: return regexpTypeDefault case 1: rx := args[0] if str, ok := rx.(stringValue); ok { return NewRegexpType(string(str)) } if rt, ok := rx.(*Regexp); ok { return rt.PType().(*RegexpType) } panic(illegalArgumentType(`Regexp[]`, 0, `Variant[Regexp,String]`, args[0])) default: panic(illegalArgumentCount(`Regexp[]`, `0 - 1`, len(args))) } } func (t *RegexpType) Accept(v px.Visitor, g px.Guard) { v(t) } func (t *RegexpType) Default() px.Type { return regexpTypeDefault } func (t *RegexpType) Equals(o interface{}, g px.Guard) bool { ot, ok := o.(*RegexpType) return ok && t.pattern.String() == ot.pattern.String() } func (t *RegexpType) Get(key string) (value px.Value, ok bool) { switch key { case `pattern`: if t.String() == `` { return undef, true } return stringValue(t.pattern.String()), true } return nil, false } func (t *RegexpType) IsAssignable(o px.Type, g px.Guard) bool { rx, ok := o.(*RegexpType) return ok && (t.pattern.String() == `` || t.pattern.String() == rx.PatternString()) } func (t *RegexpType) IsInstance(o px.Value, g px.Guard) bool { rx, ok := o.(*Regexp) return ok && (t.pattern.String() == `` || t.pattern.String() == rx.PatternString()) } func (t *RegexpType) MetaType() px.ObjectType { return RegexpMetaType } func (t *RegexpType) Name() string { return `Regexp` } func (t *RegexpType) Parameters() []px.Value { if t.pattern.String() == `` { return px.EmptyValues } return []px.Value{WrapRegexp2(t.pattern)} } func (t *RegexpType) ReflectType(c px.Context) (reflect.Type, bool) { return reflect.TypeOf(regexpTypeDefault.pattern), true } func (t *RegexpType) PatternString() string { return t.pattern.String() } func (t *RegexpType) Regexp() *regexp.Regexp { return t.pattern } func (t *RegexpType) CanSerializeAsString() bool { return true } func (t *RegexpType) SerializationString() string { return t.String() } func (t *RegexpType) String() string { return px.ToString2(t, None) } func (t *RegexpType) ToString(b io.Writer, s px.FormatContext, g px.RDetect) { TypeToString(t, b, s, g) } func (t *RegexpType) PType() px.Type { return &TypeType{t} } func MapToRegexps(regexpTypes []*RegexpType) []*regexp.Regexp { top := len(regexpTypes) result := make([]*regexp.Regexp, top) for idx := 0; idx < top; idx++ { result[idx] = regexpTypes[idx].Regexp() } return result } func UniqueRegexps(regexpTypes []*RegexpType) []*RegexpType { top := len(regexpTypes) if top < 2 { return regexpTypes } result := make([]*RegexpType, 0, top) exists := make(map[string]bool, top) for _, regexpType := range regexpTypes { key := regexpType.String() if !exists[key] { exists[key] = true result = append(result, regexpType) } } return result } func WrapRegexp(str string) *Regexp { pattern, err := regexp.Compile(str) if err != nil { panic(px.Error(px.InvalidRegexp, issue.H{`pattern`: str, `detail`: err.Error()})) } return &Regexp{pattern} } func WrapRegexp2(pattern *regexp.Regexp) *Regexp { return &Regexp{pattern} } func (r *Regexp) Equals(o interface{}, g px.Guard) bool { if ov, ok := o.(*Regexp); ok { return r.pattern.String() == ov.pattern.String() } return false } func (r *Regexp) Match(s string) []string { return r.pattern.FindStringSubmatch(s) } func (r *Regexp) Regexp() *regexp.Regexp { return r.pattern } func (r *Regexp) PatternString() string { return r.pattern.String() } func (r *Regexp) Reflect(c px.Context) reflect.Value { return reflect.ValueOf(r.pattern) } func (r *Regexp) ReflectTo(c px.Context, dest reflect.Value) { rv := r.Reflect(c) if rv.Kind() == reflect.Ptr && dest.Kind() != reflect.Ptr { rv = rv.Elem() } if !rv.Type().AssignableTo(dest.Type()) { panic(px.Error(px.AttemptToSetWrongKind, issue.H{`expected`: rv.Type().String(), `actual`: dest.Type().String()})) } dest.Set(rv) } func (r *Regexp) String() string { return px.ToString2(r, None) } func (r *Regexp) ToKey(b *bytes.Buffer) { b.WriteByte(1) b.WriteByte(HkRegexp) b.Write([]byte(r.pattern.String())) } func (r *Regexp) ToString(b io.Writer, s px.FormatContext, g px.RDetect) { utils.RegexpQuote(b, r.pattern.String()) } func (r *Regexp) PType() px.Type { rt := RegexpType(*r) return &rt }
types/regexptype.go
0.642769
0.430626
regexptype.go
starcoder
package indicator import ( "math" "testing" ) // Check values same size. func checkSameSize(values ...[]float64) { if len(values) < 2 { return } n := len(values[0]) for i := 1; i < len(values); i++ { if len(values[i]) != n { panic("not all same size") } } } // Multiply values by multipler. func multiplyBy(values []float64, multiplier float64) []float64 { result := make([]float64, len(values)) for i, value := range values { result[i] = value * multiplier } return result } // Multiply values1 and values2. func multiply(values1, values2 []float64) []float64 { checkSameSize(values1, values2) result := make([]float64, len(values1)) for i := 0; i < len(result); i++ { result[i] = values1[i] * values2[i] } return result } // Divide values by divider. func divideBy(values []float64, divider float64) []float64 { return multiplyBy(values, float64(1)/divider) } // Divide values1 by values2. func divide(values1, values2 []float64) []float64 { checkSameSize(values1, values2) result := make([]float64, len(values1)) for i := 0; i < len(result); i++ { result[i] = values1[i] / values2[i] } return result } // Add values1 and values2. func add(values1, values2 []float64) []float64 { checkSameSize(values1, values2) result := make([]float64, len(values1)) for i := 0; i < len(result); i++ { result[i] = values1[i] + values2[i] } return result } // Add addition to values. func addBy(values []float64, addition float64) []float64 { result := make([]float64, len(values)) for i := 0; i < len(result); i++ { result[i] = values[i] + addition } return result } // Substract values2 from values1. func substract(values1, values2 []float64) []float64 { substract := multiplyBy(values2, float64(-1)) return add(values1, substract) } // Difference between current and before values. func diff(values []float64, before int) []float64 { return substract(values, shiftRight(before, values)) } // Percent difference between current and before values. func percentDiff(values []float64, before int) []float64 { result := make([]float64, len(values)) for i := before; i < len(values); i++ { result[i] = (values[i] - values[i-before]) / values[i-before] } return result } // Shift right for period. func shiftRight(period int, values []float64) []float64 { result := make([]float64, len(values)) for i := period; i < len(result); i++ { result[i] = values[i-period] } return result } // Round value to digits. func roundDigits(value float64, digits int) float64 { n := math.Pow(10, float64(digits)) return math.Round(value*n) / n } // Round values to digits. func roundDigitsAll(values []float64, digits int) []float64 { result := make([]float64, len(values)) for i := 0; i < len(result); i++ { result[i] = roundDigits(values[i], digits) } return result } // Generate numbers. func generateNumbers(begin, end, step float64) []float64 { n := int(math.Round((end - begin) / step)) numbers := make([]float64, n) for i := 0; i < n; i++ { numbers[i] = begin + (step * float64(i)) } return numbers } // Convets the []int64 to []float64. func asFloat64(values []int64) []float64 { result := make([]float64, len(values)) for i := 0; i < len(values); i++ { result[i] = float64(values[i]) } return result } // Calculate power of base with exponent. func pow(base []float64, exponent float64) []float64 { result := make([]float64, len(base)) for i := 0; i < len(result); i++ { result[i] = math.Pow(base[i], exponent) } return result } // Extact sign. func extractSign(values []float64) []float64 { result := make([]float64, len(values)) for i := 0; i < len(result); i++ { if values[i] >= 0 { result[i] = 1 } else { result[i] = -1 } } return result } // Keep positives. func keepPositives(values []float64) []float64 { result := make([]float64, len(values)) for i := 0; i < len(values); i++ { if values[i] > 0 { result[i] = values[i] } else { result[i] = 0 } } return result } // Keep negatives. func keepNegatives(values []float64) []float64 { result := make([]float64, len(values)) for i := 0; i < len(values); i++ { if values[i] < 0 { result[i] = values[i] } else { result[i] = 0 } } return result } // Test equals. func testEquals(t *testing.T, actual, expected []float64) { if len(actual) != len(expected) { t.Fatal("not the same size") } for i := 0; i < len(expected); i++ { if actual[i] != expected[i] { t.Fatalf("at %d actual %f expected %f", i, actual[i], expected[i]) } } }
helper.go
0.735737
0.696268
helper.go
starcoder
package bing import "math" const ( // EarthRadius is the radius of the earth EarthRadius = 6378137.0 // MinLatitude is the min lat MinLatitude = -85.05112878 // MaxLatitude is the max lat MaxLatitude = 85.05112878 // MinLongitude is the min lon MinLongitude = -180.0 // MaxLongitude is the max lon MaxLongitude = 180.0 // TileSize is the size of a tile TileSize = 256 // MaxLevelOfDetail is the max level of detail MaxLevelOfDetail = 38 ) // Clips a number to the specified minimum and maximum values. // Param 'n' is the number to clip. // Param 'minValue' is the minimum allowable value. // Param 'maxValue' is the maximum allowable value. // Returns the clipped value. func clip(n, minValue, maxValue float64) float64 { if n < minValue { return minValue } if n > maxValue { return maxValue } return n } // MapSize determines the map width and height (in pixels) at a specified level of detail. // Param 'levelOfDetail' is the level of detail, from 1 (lowest detail) to N (highest detail). // Returns the map width and height in pixels. func MapSize(levelOfDetail uint64) uint64 { return TileSize << levelOfDetail } // // Determines the ground resolution (in meters per pixel) at a specified latitude and level of detail. // // Param 'latitude' is the Latitude (in degrees) at which to measure the ground resolution. // // Param 'levelOfDetail' is the Level of detail, from 1 (lowest detail) to N (highest detail). // // Returns the ground resolution, in meters per pixel. // func GroundResolution(latitude float64, levelOfDetail uint64) float64 { // latitude = clip(latitude, MinLatitude, MaxLatitude) // return math.Cos(latitude*math.Pi/180) * 2 * math.Pi * EarthRadius / float64(MapSize(levelOfDetail)) // } // // Determines the map scale at a specified latitude, level of detail, and screen resolution. // // Param 'latitude' is the latitude (in degrees) at which to measure the map scale. // // Param 'levelOfDetail' is the level of detail, from 1 (lowest detail) to N (highest detail). // // Param 'screenDpi' is the resolution of the screen, in dots per inch. // // Returns the map scale, expressed as the denominator N of the ratio 1 : N. // func MapScale(latitude float64, levelOfDetail, screenDpi uint64) float64 { // return GroundResolution(latitude, levelOfDetail) * float64(screenDpi) / 0.0254 // } // LatLongToPixelXY converts a point from latitude/longitude WGS-84 coordinates (in degrees) into pixel XY coordinates at a specified level of detail. // Param 'latitude' is the latitude of the point, in degrees. // Param 'longitude' is the longitude of the point, in degrees. // Param 'levelOfDetail' is the level of detail, from 1 (lowest detail) to N (highest detail). // Return value 'pixelX' is the output parameter receiving the X coordinate in pixels. // Return value 'pixelY' is the output parameter receiving the Y coordinate in pixels. func LatLongToPixelXY(latitude, longitude float64, levelOfDetail uint64) (pixelX, pixelY int64) { latitude = clip(latitude, MinLatitude, MaxLatitude) longitude = clip(longitude, MinLongitude, MaxLongitude) x := (longitude + 180) / 360 sinLatitude := math.Sin(latitude * math.Pi / 180) y := 0.5 - math.Log((1+sinLatitude)/(1-sinLatitude))/(4*math.Pi) mapSize := float64(MapSize(levelOfDetail)) pixelX = int64(clip(x*mapSize+0.5, 0, mapSize-1)) pixelY = int64(clip(y*mapSize+0.5, 0, mapSize-1)) return } // PixelXYToLatLong converts a pixel from pixel XY coordinates at a specified level of detail into latitude/longitude WGS-84 coordinates (in degrees). // Param 'pixelX' is the X coordinate of the point, in pixels. // Param 'pixelY' is the Y coordinates of the point, in pixels. // Param 'levelOfDetail' is the level of detail, from 1 (lowest detail) to N (highest detail). // Return value 'latitude' is the output parameter receiving the latitude in degrees. // Return value 'longitude' is the output parameter receiving the longitude in degrees. func PixelXYToLatLong(pixelX, pixelY int64, levelOfDetail uint64) (latitude, longitude float64) { mapSize := float64(MapSize(levelOfDetail)) x := (clip(float64(pixelX), 0, mapSize-1) / mapSize) - 0.5 y := 0.5 - (clip(float64(pixelY), 0, mapSize-1) / mapSize) latitude = 90 - 360*math.Atan(math.Exp(-y*2*math.Pi))/math.Pi longitude = 360 * x return } // PixelXYToTileXY converts pixel XY coordinates into tile XY coordinates of the tile containing the specified pixel. // Param 'pixelX' is the pixel X coordinate. // Param 'pixelY' is the pixel Y coordinate. // Return value 'tileX' is the output parameter receiving the tile X coordinate. // Return value 'tileY' is the output parameter receiving the tile Y coordinate. func PixelXYToTileXY(pixelX, pixelY int64) (tileX, tileY int64) { return pixelX >> 8, pixelY >> 8 } // TileXYToPixelXY converts tile XY coordinates into pixel XY coordinates of the upper-left pixel of the specified tile. // Param 'tileX' is the tile X coordinate. // Param 'tileY' is the tile Y coordinate. // Return value 'pixelX' is the output parameter receiving the pixel X coordinate. // Return value 'pixelY' is the output parameter receiving the pixel Y coordinate. func TileXYToPixelXY(tileX, tileY int64) (pixelX, pixelY int64) { return tileX << 8, tileY << 8 } // TileXYToQuadKey converts tile XY coordinates into a QuadKey at a specified level of detail. // Param 'tileX' is the tile X coordinate. // Param 'tileY' is the tile Y coordinate. // Param 'levelOfDetail' is the Level of detail, from 1 (lowest detail) to N (highest detail). // Returns a string containing the QuadKey. func TileXYToQuadKey(tileX, tileY int64, levelOfDetail uint64) string { quadKey := make([]byte, levelOfDetail) for i, j := levelOfDetail, 0; i > 0; i, j = i-1, j+1 { mask := int64(1 << (i - 1)) if (tileX & mask) != 0 { if (tileY & mask) != 0 { quadKey[j] = '3' } else { quadKey[j] = '1' } } else if (tileY & mask) != 0 { quadKey[j] = '2' } else { quadKey[j] = '0' } } return string(quadKey) } // QuadKeyToTileXY converts a QuadKey into tile XY coordinates. // Param 'quadKey' is the quadKey of the tile. // Return value 'tileX' is the output parameter receiving the tile X coordinate. // Return value 'tileY is the output parameter receiving the tile Y coordinate. // Return value 'levelOfDetail' is the output parameter receiving the level of detail. func QuadKeyToTileXY(quadKey string) (tileX, tileY int64, levelOfDetail uint64) { levelOfDetail = uint64(len(quadKey)) for i := levelOfDetail; i > 0; i-- { mask := int64(1 << (i - 1)) switch quadKey[levelOfDetail-i] { case '0': case '1': tileX |= mask case '2': tileY |= mask case '3': tileX |= mask tileY |= mask default: panic("Invalid QuadKey digit sequence.") } } return }
internal/bing/bing.go
0.889229
0.718619
bing.go
starcoder
package function import ( "errors" "fmt" "time" "github.com/src-d/go-mysql-server/sql" "github.com/src-d/go-mysql-server/sql/expression" ) func getDate(ctx *sql.Context, u expression.UnaryExpression, row sql.Row) (interface{}, error) { val, err := u.Child.Eval(ctx, row) if err != nil { return nil, err } if val == nil { return nil, nil } date, err := sql.Timestamp.Convert(val) if err != nil { date, err = sql.Date.Convert(val) if err != nil { date = nil } } return date, nil } func getDatePart(ctx *sql.Context, u expression.UnaryExpression, row sql.Row, f func(interface{}) interface{}) (interface{}, error) { date, err := getDate(ctx, u, row) if err != nil { return nil, err } return f(date), nil } // Year is a function that returns the year of a date. type Year struct { expression.UnaryExpression } // NewYear creates a new Year UDF. func NewYear(date sql.Expression) sql.Expression { return &Year{expression.UnaryExpression{Child: date}} } func (y *Year) String() string { return fmt.Sprintf("YEAR(%s)", y.Child) } // Type implements the Expression interface. func (y *Year) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (y *Year) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, y.UnaryExpression, row, year) } // WithChildren implements the Expression interface. func (y *Year) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(y, len(children), 1) } return NewYear(children[0]), nil } // Month is a function that returns the month of a date. type Month struct { expression.UnaryExpression } // NewMonth creates a new Month UDF. func NewMonth(date sql.Expression) sql.Expression { return &Month{expression.UnaryExpression{Child: date}} } func (m *Month) String() string { return fmt.Sprintf("MONTH(%s)", m.Child) } // Type implements the Expression interface. func (m *Month) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (m *Month) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, m.UnaryExpression, row, month) } // WithChildren implements the Expression interface. func (m *Month) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(m, len(children), 1) } return NewMonth(children[0]), nil } // Day is a function that returns the day of a date. type Day struct { expression.UnaryExpression } // NewDay creates a new Day UDF. func NewDay(date sql.Expression) sql.Expression { return &Day{expression.UnaryExpression{Child: date}} } func (d *Day) String() string { return fmt.Sprintf("DAY(%s)", d.Child) } // Type implements the Expression interface. func (d *Day) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (d *Day) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, d.UnaryExpression, row, day) } // WithChildren implements the Expression interface. func (d *Day) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(d, len(children), 1) } return NewDay(children[0]), nil } // Weekday is a function that returns the weekday of a date where 0 = Monday, // ..., 6 = Sunday. type Weekday struct { expression.UnaryExpression } // NewWeekday creates a new Weekday UDF. func NewWeekday(date sql.Expression) sql.Expression { return &Weekday{expression.UnaryExpression{Child: date}} } func (d *Weekday) String() string { return fmt.Sprintf("WEEKDAY(%s)", d.Child) } // Type implements the Expression interface. func (d *Weekday) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (d *Weekday) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, d.UnaryExpression, row, weekday) } // WithChildren implements the Expression interface. func (d *Weekday) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(d, len(children), 1) } return NewWeekday(children[0]), nil } // Hour is a function that returns the hour of a date. type Hour struct { expression.UnaryExpression } // NewHour creates a new Hour UDF. func NewHour(date sql.Expression) sql.Expression { return &Hour{expression.UnaryExpression{Child: date}} } func (h *Hour) String() string { return fmt.Sprintf("HOUR(%s)", h.Child) } // Type implements the Expression interface. func (h *Hour) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (h *Hour) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, h.UnaryExpression, row, hour) } // WithChildren implements the Expression interface. func (h *Hour) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(h, len(children), 1) } return NewHour(children[0]), nil } // Minute is a function that returns the minute of a date. type Minute struct { expression.UnaryExpression } // NewMinute creates a new Minute UDF. func NewMinute(date sql.Expression) sql.Expression { return &Minute{expression.UnaryExpression{Child: date}} } func (m *Minute) String() string { return fmt.Sprintf("MINUTE(%d)", m.Child) } // Type implements the Expression interface. func (m *Minute) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (m *Minute) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, m.UnaryExpression, row, minute) } // WithChildren implements the Expression interface. func (m *Minute) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(m, len(children), 1) } return NewMinute(children[0]), nil } // Second is a function that returns the second of a date. type Second struct { expression.UnaryExpression } // NewSecond creates a new Second UDF. func NewSecond(date sql.Expression) sql.Expression { return &Second{expression.UnaryExpression{Child: date}} } func (s *Second) String() string { return fmt.Sprintf("SECOND(%s)", s.Child) } // Type implements the Expression interface. func (s *Second) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (s *Second) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, s.UnaryExpression, row, second) } // WithChildren implements the Expression interface. func (s *Second) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(s, len(children), 1) } return NewSecond(children[0]), nil } // DayOfWeek is a function that returns the day of the week from a date where // 1 = Sunday, ..., 7 = Saturday. type DayOfWeek struct { expression.UnaryExpression } // NewDayOfWeek creates a new DayOfWeek UDF. func NewDayOfWeek(date sql.Expression) sql.Expression { return &DayOfWeek{expression.UnaryExpression{Child: date}} } func (d *DayOfWeek) String() string { return fmt.Sprintf("DAYOFWEEK(%s)", d.Child) } // Type implements the Expression interface. func (d *DayOfWeek) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (d *DayOfWeek) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, d.UnaryExpression, row, dayOfWeek) } // WithChildren implements the Expression interface. func (d *DayOfWeek) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(d, len(children), 1) } return NewDayOfWeek(children[0]), nil } // DayOfYear is a function that returns the day of the year from a date. type DayOfYear struct { expression.UnaryExpression } // NewDayOfYear creates a new DayOfYear UDF. func NewDayOfYear(date sql.Expression) sql.Expression { return &DayOfYear{expression.UnaryExpression{Child: date}} } func (d *DayOfYear) String() string { return fmt.Sprintf("DAYOFYEAR(%s)", d.Child) } // Type implements the Expression interface. func (d *DayOfYear) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (d *DayOfYear) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, d.UnaryExpression, row, dayOfYear) } // WithChildren implements the Expression interface. func (d *DayOfYear) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(d, len(children), 1) } return NewDayOfYear(children[0]), nil } func datePartFunc(fn func(time.Time) int) func(interface{}) interface{} { return func(v interface{}) interface{} { if v == nil { return nil } return int32(fn(v.(time.Time))) } } // YearWeek is a function that returns year and week for a date. // The year in the result may be different from the year in the date argument for the first and the last week of the year. // Details: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_yearweek type YearWeek struct { date sql.Expression mode sql.Expression } // NewYearWeek creates a new YearWeek UDF func NewYearWeek(args ...sql.Expression) (sql.Expression, error) { if len(args) == 0 { return nil, sql.ErrInvalidArgumentNumber.New("YEARWEEK", "1 or more", 0) } yw := &YearWeek{date: args[0]} if len(args) > 1 && args[1].Resolved() && sql.IsInteger(args[1].Type()) { yw.mode = args[1] } else { yw.mode = expression.NewLiteral(0, sql.Int64) } return yw, nil } func (d *YearWeek) String() string { return fmt.Sprintf("YEARWEEK(%s, %d)", d.date, d.mode) } // Type implements the Expression interface. func (d *YearWeek) Type() sql.Type { return sql.Int32 } // Eval implements the Expression interface. func (d *YearWeek) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { date, err := getDate(ctx, expression.UnaryExpression{Child: d.date}, row) if err != nil { return nil, err } yyyy, ok := year(date).(int32) if !ok { return nil, errors.New("YEARWEEK: invalid year") } mm, ok := month(date).(int32) if !ok { return nil, errors.New("YEARWEEK: invalid month") } dd, ok := day(date).(int32) if !ok { return nil, errors.New("YEARWEEK: invalid day") } mode := int64(0) val, err := d.mode.Eval(ctx, row) if err != nil { return nil, err } if val != nil { if i64, err := sql.Int64.Convert(val); err == nil { if mode, ok = i64.(int64); ok { mode %= 8 // mode in [0, 7] } } } yyyy, week := calcWeek(yyyy, mm, dd, weekMode(mode)|weekBehaviourYear) return (yyyy * 100) + week, nil } // Resolved implements the Expression interface. func (d *YearWeek) Resolved() bool { return d.date.Resolved() && d.mode.Resolved() } // Children implements the Expression interface. func (d *YearWeek) Children() []sql.Expression { return []sql.Expression{d.date, d.mode} } // IsNullable implements the Expression interface. func (d *YearWeek) IsNullable() bool { return d.date.IsNullable() } // WithChildren implements the Expression interface. func (*YearWeek) WithChildren(children ...sql.Expression) (sql.Expression, error) { return NewYearWeek(children...) } // Following solution of YearWeek was taken from tidb: https://github.com/pingcap/tidb/blob/master/types/mytime.go type weekBehaviour int64 const ( // weekBehaviourMondayFirst set Monday as first day of week; otherwise Sunday is first day of week weekBehaviourMondayFirst weekBehaviour = 1 << iota // If set, Week is in range 1-53, otherwise Week is in range 0-53. // Note that this flag is only relevant if WEEK_JANUARY is not set. weekBehaviourYear // If not set, Weeks are numbered according to ISO 8601:1988. // If set, the week that contains the first 'first-day-of-week' is week 1. weekBehaviourFirstWeekday ) func (v weekBehaviour) test(flag weekBehaviour) bool { return (v & flag) != 0 } func weekMode(mode int64) weekBehaviour { weekFormat := weekBehaviour(mode & 7) if (weekFormat & weekBehaviourMondayFirst) == 0 { weekFormat ^= weekBehaviourFirstWeekday } return weekFormat } // calcWeekday calculates weekday from daynr, returns 0 for Monday, 1 for Tuesday ... func calcWeekday(daynr int32, sundayFirstDayOfWeek bool) int32 { daynr += 5 if sundayFirstDayOfWeek { daynr++ } return daynr % 7 } // calcWeek calculates week and year for the time. func calcWeek(yyyy, mm, dd int32, wb weekBehaviour) (int32, int32) { daynr := calcDaynr(yyyy, mm, dd) firstDaynr := calcDaynr(yyyy, 1, 1) mondayFirst := wb.test(weekBehaviourMondayFirst) weekYear := wb.test(weekBehaviourYear) firstWeekday := wb.test(weekBehaviourFirstWeekday) weekday := calcWeekday(firstDaynr, !mondayFirst) week, days := int32(0), int32(0) if mm == 1 && dd <= 7-weekday { if !weekYear && ((firstWeekday && weekday != 0) || (!firstWeekday && weekday >= 4)) { return yyyy, week } weekYear = true yyyy-- days = calcDaysInYear(yyyy) firstDaynr -= days weekday = (weekday + 53*7 - days) % 7 } if (firstWeekday && weekday != 0) || (!firstWeekday && weekday >= 4) { days = daynr - (firstDaynr + 7 - weekday) } else { days = daynr - (firstDaynr - weekday) } if weekYear && days >= 52*7 { weekday = (weekday + calcDaysInYear(yyyy)) % 7 if (!firstWeekday && weekday < 4) || (firstWeekday && weekday == 0) { yyyy++ week = 1 return yyyy, week } } week = days/7 + 1 return yyyy, week } // calcDaysInYear calculates days in one year, it works with 0 <= yyyy <= 99. func calcDaysInYear(yyyy int32) int32 { if (yyyy&3) == 0 && (yyyy%100 != 0 || (yyyy%400 == 0 && (yyyy != 0))) { return 366 } return 365 } // calcDaynr calculates days since 0000-00-00. func calcDaynr(yyyy, mm, dd int32) int32 { if yyyy == 0 && mm == 0 { return 0 } delsum := 365*yyyy + 31*(mm-1) + dd if mm <= 2 { yyyy-- } else { delsum -= (mm*4 + 23) / 10 } return delsum + yyyy/4 - ((yyyy/100+1)*3)/4 } var ( year = datePartFunc((time.Time).Year) month = datePartFunc(func(t time.Time) int { return int(t.Month()) }) day = datePartFunc((time.Time).Day) weekday = datePartFunc(func(t time.Time) int { return (int(t.Weekday()) + 6) % 7 }) hour = datePartFunc((time.Time).Hour) minute = datePartFunc((time.Time).Minute) second = datePartFunc((time.Time).Second) dayOfWeek = datePartFunc(func(t time.Time) int { return int(t.Weekday()) + 1 }) dayOfYear = datePartFunc((time.Time).YearDay) ) type clock func() time.Time var defaultClock = time.Now // Now is a function that returns the current time. type Now struct { clock } // NewNow returns a new Now node. func NewNow() sql.Expression { return &Now{defaultClock} } // Type implements the sql.Expression interface. func (*Now) Type() sql.Type { return sql.Timestamp } func (*Now) String() string { return "NOW()" } // IsNullable implements the sql.Expression interface. func (*Now) IsNullable() bool { return false } // Resolved implements the sql.Expression interface. func (*Now) Resolved() bool { return true } // Children implements the sql.Expression interface. func (*Now) Children() []sql.Expression { return nil } // Eval implements the sql.Expression interface. func (n *Now) Eval(*sql.Context, sql.Row) (interface{}, error) { return n.clock(), nil } // WithChildren implements the Expression interface. func (n *Now) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 0 { return nil, sql.ErrInvalidChildrenNumber.New(n, len(children), 0) } return n, nil } // Date a function takes the DATE part out from a datetime expression. type Date struct { expression.UnaryExpression } // NewDate returns a new Date node. func NewDate(date sql.Expression) sql.Expression { return &Date{expression.UnaryExpression{Child: date}} } func (d *Date) String() string { return fmt.Sprintf("DATE(%s)", d.Child) } // Type implements the Expression interface. func (d *Date) Type() sql.Type { return sql.Text } // Eval implements the Expression interface. func (d *Date) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { return getDatePart(ctx, d.UnaryExpression, row, func(v interface{}) interface{} { if v == nil { return nil } return v.(time.Time).Format("2006-01-02") }) } // WithChildren implements the Expression interface. func (d *Date) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(d, len(children), 1) } return NewDate(children[0]), nil }
sql/expression/function/time.go
0.746878
0.451871
time.go
starcoder
package ec import ( "errors" "fmt" "math/big" "github.com/WaykiChain/wicc-wallet-utils-go/commons/bytes" ) const ( PubKeyBytesLenCompressed = 33 PubKeyBytesLenUncompressed = 65 PubKeyBytesLenHybrid = 65 pubKeyCompressed byte = 0x2 pubKeyUncompressed byte = 0x4 pubKeyHybrid byte = 0x6 ) // PublicKey struct type PublicKey struct { X, Y *big.Int } func isOdd(a *big.Int) bool { return a.Bit(0) == 1 } // decompressPoint decompresses a point on the given curve given the X point and // the solution to use. func decompressPoint(x *big.Int, ybit bool) (*big.Int, error) { // TODO: This will probably only work for secp256k1 due to // optimizations. // Y = +-sqrt(x^3 + B) x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) x3.Add(x3, secp256k1.Params().B) x3.Mod(x3, secp256k1.Params().P) // Now calculate sqrt mod p of x^3 + B // This code used to do a full sqrt based on tonelli/shanks, // but this was replaced by the algorithms referenced in // https://bitcointalk.org/index.php?topic=162805.msg1712294#msg1712294 y := new(big.Int).Exp(x3, secp256k1.QPlus1Div4(), secp256k1.Params().P) if ybit != isOdd(y) { y.Sub(secp256k1.Params().P, y) } // Check that y is a square root of x^3 + B. y2 := new(big.Int).Mul(y, y) y2.Mod(y2, secp256k1.Params().P) if y2.Cmp(x3) != 0 { return nil, fmt.Errorf("invalid square root") } // Verify that y-coord has expected parity. if ybit != isOdd(y) { return nil, fmt.Errorf("ybit doesn't match oddness") } return y, nil } // ParsePubKey parses a public key for a koblitz curve from a bytestring into a // ecdsa.Publickey, verifying that it is valid. It supports compressed, // uncompressed and hybrid signature formats. func ParsePubKey(pubKeyStr []byte) (key *PublicKey, err error) { pubkey := PublicKey{} if len(pubKeyStr) == 0 { return nil, errors.New("pubkey string is empty") } format := pubKeyStr[0] ybit := (format & 0x1) == 0x1 format &= ^byte(0x1) switch len(pubKeyStr) { case PubKeyBytesLenUncompressed: if format != pubKeyUncompressed && format != pubKeyHybrid { return nil, fmt.Errorf("invalid magic in pubkey str: "+ "%d", pubKeyStr[0]) } pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) pubkey.Y = new(big.Int).SetBytes(pubKeyStr[33:]) // hybrid keys have extra information, make use of it. if format == pubKeyHybrid && ybit != isOdd(pubkey.Y) { return nil, fmt.Errorf("ybit doesn't match oddness") } case PubKeyBytesLenCompressed: // format is 0x2 | solution, <X coordinate> // solution determines which solution of the curve we use. /// y^2 = x^3 + Curve.B if format != pubKeyCompressed { return nil, fmt.Errorf("invalid magic in compressed "+ "pubkey string: %d", pubKeyStr[0]) } pubkey.X = new(big.Int).SetBytes(pubKeyStr[1:33]) pubkey.Y, err = decompressPoint(pubkey.X, ybit) if err != nil { return nil, err } default: // wrong! return nil, fmt.Errorf("invalid pub key length %d", len(pubKeyStr)) } if pubkey.X.Cmp(secp256k1.Params().P) >= 0 { return nil, fmt.Errorf("pubkey X parameter is >= to P") } if pubkey.Y.Cmp(secp256k1.Params().P) >= 0 { return nil, fmt.Errorf("pubkey Y parameter is >= to P") } if !secp256k1.IsOnCurve(pubkey.X, pubkey.Y) { return nil, fmt.Errorf("pubkey isn't on secp256k1 curve") } return &pubkey, nil } // SerializeCompressed serializes a public key 33-byte compressed format func (key *PublicKey) SerializeCompressed() []byte { b := make([]byte, 0, PubKeyBytesLenCompressed) format := pubKeyCompressed if isOdd(key.Y) { format |= 0x1 } b = append(b, format) return bytes.PaddedAppend(b, 32, key.X.Bytes()) }
commons/ec/pubkey.go
0.558568
0.459197
pubkey.go
starcoder
// Package dk provides holiday definitions for Denmark. package dk import ( "time" "github.com/rickar/cal/v2" "github.com/rickar/cal/v2/aa" ) var ( // Nytaarsdag represents New Year's Day on 1-Jan Nytaarsdag = aa.NewYear.Clone(&cal.Holiday{Name: "Nytårsdag", Type: cal.ObservancePublic}) // Skaertorsdag represents Maundy Thursday on the Thursday before Easter Skaertorsdag = aa.MaundyThursday.Clone(&cal.Holiday{Name: "Skærtorsdag", Type: cal.ObservancePublic}) // Langfredag represents Good Friday on the Friday before Easter Langfredag = aa.GoodFriday.Clone(&cal.Holiday{Name: "Langfredag", Type: cal.ObservancePublic}) // AndenPaaskedag represents Easter Monday on the day after Easter AndenPaaskedag = aa.EasterMonday.Clone(&cal.Holiday{Name: "Anden påskedag", Type: cal.ObservancePublic}) // StoreBededag represents General Prayer Day on the fourth Friday after Easter StoreBededag = &cal.Holiday{ Name: "Store bededag", Type: cal.ObservancePublic, Offset: 26, Func: cal.CalcEasterOffset, } // KristiHimmelfartsdag represents Ascension Day on the 39th day after Easter KristiHimmelfartsdag = aa.AscensionDay.Clone(&cal.Holiday{Name: "Kristi Himmelfartsdag", Type: cal.ObservancePublic}) // AndenPinsedag represents Pentecost Monday on the day after Pentecost (50 days after Easter) AndenPinsedag = aa.PentecostMonday.Clone(&cal.Holiday{Name: "<NAME>", Type: cal.ObservancePublic}) // Grundlovsdag represents Constitution Day on 5-Jun Grundlovsdag = &cal.Holiday{ Name: "Grundlovsdag", Type: cal.ObservancePublic, Month: time.June, Day: 5, Func: cal.CalcDayOfMonth, } // Juledag represents Christmas Day on 25-Dec Juledag = aa.ChristmasDay.Clone(&cal.Holiday{Name: "Juledag", Type: cal.ObservancePublic}) // AndenJuledag represents the second day of Christmas on 26-Dec AndenJuledag = aa.ChristmasDay2.Clone(&cal.Holiday{Name: "Anden juledag", Type: cal.ObservancePublic}) // Holidays provides a list of the standard national holidays Holidays = []*cal.Holiday{ Nytaarsdag, Skaertorsdag, Langfredag, AndenPaaskedag, StoreBededag, KristiHimmelfartsdag, AndenPinsedag, Grundlovsdag, Juledag, AndenJuledag, } )
v2/dk/dk_holidays.go
0.542136
0.407451
dk_holidays.go
starcoder
package matrix import ( "sync" "time" ) // Plane stores consecutive axes. Each axis has StartTime, EndTime. The EndTime of each axis is the StartTime of its // next axis. Therefore satisfies: // len(Times) == len(Axes) + 1. type Plane struct { Times []time.Time Axes []Axis } // CreatePlane checks the given parameters and uses them to build the Plane. func CreatePlane(times []time.Time, axes []Axis) Plane { if len(times) <= 1 { panic("Times length must be greater than 1") } return Plane{ Times: times, Axes: axes, } } // CreateEmptyPlane constructs a minimal empty Plane with the given parameters. func CreateEmptyPlane(startTime, endTime time.Time, startKey, endKey string, valuesListLen int) Plane { return CreatePlane([]time.Time{startTime, endTime}, []Axis{CreateEmptyAxis(startKey, endKey, valuesListLen)}) } // Compact compacts Plane into an axis. func (plane *Plane) Compact(strategy SplitStrategy) Axis { chunks := make([]chunk, len(plane.Axes)) for i, axis := range plane.Axes { chunks[i] = createChunk(axis.Keys, axis.ValuesList[0]) } compactChunk, splitter := compact(strategy, chunks) valuesListLen := len(plane.Axes[0].ValuesList) valuesList := make([][]uint64, valuesListLen) valuesList[0] = compactChunk.Values for j := 1; j < valuesListLen; j++ { compactChunk.SetZeroValues() for i, axis := range plane.Axes { chunks[i].SetValues(axis.ValuesList[j]) splitter.Split(compactChunk, chunks[i], splitAdd, i) } valuesList[j] = compactChunk.Values } return CreateAxis(compactChunk.Keys, valuesList) } // Pixel pixelates Plane into a matrix with a number of rows close to the target. func (plane *Plane) Pixel(strategy *Strategy, target int, displayTags []string) Matrix { valuesListLen := len(plane.Axes[0].ValuesList) if valuesListLen != len(displayTags) { panic("the length of displayTags and valuesList should be equal") } axesLen := len(plane.Axes) chunks := make([]chunk, axesLen) for i, axis := range plane.Axes { chunks[i] = createChunk(axis.Keys, axis.ValuesList[0]) } compactChunk, splitter := compact(strategy, chunks) labeler := strategy.NewLabeler() baseKeys := compactChunk.Divide(labeler, target, NotMergeLogicalRange).Keys matrix := CreateMatrix(labeler, plane.Times, baseKeys, valuesListLen) var wg sync.WaitGroup var mutex sync.Mutex generateFunc := func(j int) { defer wg.Done() data := make([][]uint64, axesLen) goCompactChunk := createZeroChunk(compactChunk.Keys) for i, axis := range plane.Axes { goCompactChunk.Clear() splitter.Split(goCompactChunk, createChunk(chunks[i].Keys, axis.ValuesList[j]), splitTo, i) data[i] = goCompactChunk.Reduce(baseKeys).Values } mutex.Lock() defer mutex.Unlock() matrix.DataMap[displayTags[j]] = data } wg.Add(valuesListLen) for j := 0; j < valuesListLen; j++ { go generateFunc(j) } wg.Wait() return matrix } func compact(strategy SplitStrategy, chunks []chunk) (compactChunk chunk, splitter Splitter) { // get compact chunk keys keySet := make(map[string]struct{}) unlimitedEnd := false for _, c := range chunks { end := len(c.Keys) - 1 endKey := c.Keys[end] if endKey == "" { unlimitedEnd = true } else { keySet[endKey] = struct{}{} } for _, key := range c.Keys[:end] { keySet[key] = struct{}{} } } var compactKeys []string if unlimitedEnd { compactKeys = MakeKeysWithUnlimitedEnd(keySet) } else { compactKeys = MakeKeys(keySet) } compactChunk = createZeroChunk(compactKeys) splitter = strategy.NewSplitter(chunks, compactChunk.Keys) for i, c := range chunks { splitter.Split(compactChunk, c, splitAdd, i) } return }
pkg/keyvisual/matrix/plane.go
0.664649
0.560794
plane.go
starcoder
package camera import ( "math" "github.com/hajimehoshi/ebiten/v2" ) // Camera can look at positions, zoom and rotate. type Camera struct { X, Y, Rot, Scale float64 Width, Height int Surface *ebiten.Image } // NewCamera returns a new Camera func NewCamera(width, height int, x, y, rotation, zoom float64) *Camera { return &Camera{ X: x, Y: y, Width: width, Height: height, Rot: rotation, Scale: zoom, Surface: ebiten.NewImage(width, height), } } // SetPosition looks at a position func (c *Camera) SetPosition(x, y float64) *Camera { c.X = x c.Y = y return c } // MovePosition moves the Camera by x and y. // Use SetPosition if you want to set the position func (c *Camera) MovePosition(x, y float64) *Camera { c.X += x c.Y += y return c } // Rotate rotates by phi func (c *Camera) Rotate(phi float64) *Camera { c.Rot += phi return c } // SetRotation sets the rotation to rot func (c *Camera) SetRotation(rot float64) *Camera { c.Rot = rot return c } // Zoom *= the current zoom func (c *Camera) Zoom(mul float64) *Camera { c.Scale *= mul if c.Scale <= 0.01 { c.Scale = 0.01 } c.Resize(c.Width, c.Height) return c } // SetZoom sets the zoom func (c *Camera) SetZoom(zoom float64) *Camera { c.Scale = zoom if c.Scale <= 0.01 { c.Scale = 0.01 } c.Resize(c.Width, c.Height) return c } // Resize resizes the camera Surface func (c *Camera) Resize(w, h int) *Camera { c.Width = w c.Height = h newW := int(float64(w) * 1.0 / c.Scale) newH := int(float64(h) * 1.0 / c.Scale) if newW <= 16384 && newH <= 16384 { c.Surface.Dispose() c.Surface = ebiten.NewImage(newW, newH) } return c } // GetTranslation returns the coordinates based on the given x,y offset and the // camera's position func (c *Camera) GetTranslation(x, y float64) *ebiten.DrawImageOptions { w, h := c.Surface.Size() op := &ebiten.DrawImageOptions{} op.GeoM.Translate(float64(w)/2, float64(h)/2) op.GeoM.Translate(-c.X+x, -c.Y+y) return op } // Blit draws the camera's surface to the screen and applies zoom func (c *Camera) Blit(screen *ebiten.Image) { op := &ebiten.DrawImageOptions{} w, h := c.Surface.Size() cx := float64(w) / 2.0 cy := float64(h) / 2.0 op.GeoM.Rotate(c.Rot) op.GeoM.Translate(-cx, -cy) op.GeoM.Scale(c.Scale, c.Scale) op.GeoM.Translate(cx*c.Scale, cy*c.Scale) screen.DrawImage(c.Surface, op) } // GetScreenCoords converts world coords into screen coords func (c *Camera) GetScreenCoords(x, y float64) (float64, float64) { w, h := c.Width, c.Height co := math.Cos(c.Rot) si := math.Sin(c.Rot) x, y = x-c.X, y-c.Y x, y = co*x-si*y, si*x+co*y return x*c.Scale + float64(w)/2, y*c.Scale + float64(h)/2 } // GetWorldCoords converts screen coords into world coords func (c *Camera) GetWorldCoords(x, y float64) (float64, float64) { w, h := c.Width, c.Height co := math.Cos(-c.Rot) si := math.Sin(-c.Rot) x, y = (x-float64(w)/2)/c.Scale, (y-float64(h)/2)/c.Scale x, y = co*x-si*y, si*x+co*y return x + c.X, y + c.Y } // GetCursorCoords converts cursor/screen coords into world coords func (c *Camera) GetCursorCoords() (float64, float64) { cx, cy := ebiten.CursorPosition() return c.GetWorldCoords(float64(cx), float64(cy)) }
camera.go
0.901346
0.530419
camera.go
starcoder
package cmd import ( "context" "errors" "hash" "github.com/minio/highwayhash" "github.com/minio/minio/cmd/logger" sha256 "github.com/minio/sha256-simd" "golang.org/x/crypto/blake2b" ) // magic HH-256 key as HH-256 hash of the first 100 decimals of π as utf-8 string with a zero key. var magicHighwayHash256Key = []byte("\<KEY>") // BitrotAlgorithm specifies a algorithm used for bitrot protection. type BitrotAlgorithm uint const ( // SHA256 represents the SHA-256 hash function SHA256 BitrotAlgorithm = 1 + iota // HighwayHash256 represents the HighwayHash-256 hash function HighwayHash256 // BLAKE2b512 represents the BLAKE2b-512 hash function BLAKE2b512 ) // DefaultBitrotAlgorithm is the default algorithm used for bitrot protection. const ( DefaultBitrotAlgorithm = HighwayHash256 ) var bitrotAlgorithms = map[BitrotAlgorithm]string{ SHA256: "sha256", BLAKE2b512: "blake2b", HighwayHash256: "highwayhash256", } // New returns a new hash.Hash calculating the given bitrot algorithm. func (a BitrotAlgorithm) New() hash.Hash { switch a { case SHA256: return sha256.New() case BLAKE2b512: b2, _ := blake2b.New512(nil) // New512 never returns an error if the key is nil return b2 case HighwayHash256: hh, _ := highwayhash.New(magicHighwayHash256Key) // New will never return error since key is 256 bit return hh default: logger.CriticalIf(context.Background(), errors.New("Unsupported bitrot algorithm")) return nil } } // Available reports whether the given algorithm is available. func (a BitrotAlgorithm) Available() bool { _, ok := bitrotAlgorithms[a] return ok } // String returns the string identifier for a given bitrot algorithm. // If the algorithm is not supported String panics. func (a BitrotAlgorithm) String() string { name, ok := bitrotAlgorithms[a] if !ok { logger.CriticalIf(context.Background(), errors.New("Unsupported bitrot algorithm")) } return name } // NewBitrotVerifier returns a new BitrotVerifier implementing the given algorithm. func NewBitrotVerifier(algorithm BitrotAlgorithm, checksum []byte) *BitrotVerifier { return &BitrotVerifier{algorithm, checksum} } // BitrotVerifier can be used to verify protected data. type BitrotVerifier struct { algorithm BitrotAlgorithm sum []byte } // BitrotAlgorithmFromString returns a bitrot algorithm from the given string representation. // It returns 0 if the string representation does not match any supported algorithm. // The zero value of a bitrot algorithm is never supported. func BitrotAlgorithmFromString(s string) (a BitrotAlgorithm) { for alg, name := range bitrotAlgorithms { if name == s { return alg } } return } // To read bit-rot verified data. type bitrotReader struct { disk StorageAPI volume string filePath string verifier *BitrotVerifier // Holds the bit-rot info endOffset int64 // Affects the length of data requested in disk.ReadFile depending on Read()'s offset buf []byte // Holds bit-rot verified data } // newBitrotReader returns bitrotReader. // Note that the buffer is allocated later in Read(). This is because we will know the buffer length only // during the bitrotReader.Read(). Depending on when parallelReader fails-over, the buffer length can be different. func newBitrotReader(disk StorageAPI, volume, filePath string, algo BitrotAlgorithm, endOffset int64, sum []byte) *bitrotReader { return &bitrotReader{ disk: disk, volume: volume, filePath: filePath, verifier: &BitrotVerifier{algo, sum}, endOffset: endOffset, buf: nil, } } // ReadChunk returns requested data. func (b *bitrotReader) ReadChunk(offset int64, length int64) ([]byte, error) { if b.buf == nil { b.buf = make([]byte, b.endOffset-offset) if _, err := b.disk.ReadFile(b.volume, b.filePath, offset, b.buf, b.verifier); err != nil { ctx := context.Background() logger.GetReqInfo(ctx).AppendTags("disk", b.disk.String()) logger.LogIf(ctx, err) return nil, err } } if int64(len(b.buf)) < length { logger.LogIf(context.Background(), errLessData) return nil, errLessData } retBuf := b.buf[:length] b.buf = b.buf[length:] return retBuf, nil } // To calculate the bit-rot of the written data. type bitrotWriter struct { disk StorageAPI volume string filePath string h hash.Hash } // newBitrotWriter returns bitrotWriter. func newBitrotWriter(disk StorageAPI, volume, filePath string, algo BitrotAlgorithm) *bitrotWriter { return &bitrotWriter{ disk: disk, volume: volume, filePath: filePath, h: algo.New(), } } // Append appends the data and while calculating the hash. func (b *bitrotWriter) Append(buf []byte) error { n, err := b.h.Write(buf) if err != nil { return err } if n != len(buf) { logger.LogIf(context.Background(), errUnexpected) return errUnexpected } if err = b.disk.AppendFile(b.volume, b.filePath, buf); err != nil { logger.LogIf(context.Background(), err) return err } return nil } // Sum returns bit-rot sum. func (b *bitrotWriter) Sum() []byte { return b.h.Sum(nil) }
cmd/bitrot.go
0.704872
0.406744
bitrot.go
starcoder
package vp8l // This file deals with image transforms, specified in section 3. // nTiles returns the number of tiles needed to cover size pixels, where each // tile's side is 1<<bits pixels long. func nTiles(size int32, bits uint32) int32 { return (size + 1<<bits - 1) >> bits } const ( transformTypePredictor = 0 transformTypeCrossColor = 1 transformTypeSubtractGreen = 2 transformTypeColorIndexing = 3 nTransformTypes = 4 ) // transform holds the parameters for an invertible transform. type transform struct { // transformType is the type of the transform. transformType uint32 // oldWidth is the width of the image before transformation (or // equivalently, after inverse transformation). The color-indexing // transform can reduce the width. For example, a 50-pixel-wide // image that only needs 4 bits (half a byte) per color index can // be transformed into a 25-pixel-wide image. oldWidth int32 // bits is the log-2 size of the transform's tiles, for the predictor // and cross-color transforms. 8>>bits is the number of bits per // color index, for the color-index transform. bits uint32 // pix is the tile values, for the predictor and cross-color // transforms, and the color palette, for the color-index transform. pix []byte } var inverseTransforms = [nTransformTypes]func(*transform, []byte, int32) []byte{ transformTypePredictor: inversePredictor, transformTypeCrossColor: inverseCrossColor, transformTypeSubtractGreen: inverseSubtractGreen, transformTypeColorIndexing: inverseColorIndexing, } func inversePredictor(t *transform, pix []byte, h int32) []byte { if t.oldWidth == 0 || h == 0 { return pix } // The first pixel's predictor is mode 0 (opaque black). pix[3] += 0xff p, mask := int32(4), int32(1)<<t.bits-1 for x := int32(1); x < t.oldWidth; x++ { // The rest of the first row's predictor is mode 1 (L). pix[p+0] += pix[p-4] pix[p+1] += pix[p-3] pix[p+2] += pix[p-2] pix[p+3] += pix[p-1] p += 4 } top, tilesPerRow := 0, nTiles(t.oldWidth, t.bits) for y := int32(1); y < h; y++ { // The first column's predictor is mode 2 (T). pix[p+0] += pix[top+0] pix[p+1] += pix[top+1] pix[p+2] += pix[top+2] pix[p+3] += pix[top+3] p, top = p+4, top+4 q := 4 * (y >> t.bits) * tilesPerRow predictorMode := t.pix[q+1] & 0x0f q += 4 for x := int32(1); x < t.oldWidth; x++ { if x&mask == 0 { predictorMode = t.pix[q+1] & 0x0f q += 4 } switch predictorMode { case 0: // Opaque black. pix[p+3] += 0xff case 1: // L. pix[p+0] += pix[p-4] pix[p+1] += pix[p-3] pix[p+2] += pix[p-2] pix[p+3] += pix[p-1] case 2: // T. pix[p+0] += pix[top+0] pix[p+1] += pix[top+1] pix[p+2] += pix[top+2] pix[p+3] += pix[top+3] case 3: // TR. pix[p+0] += pix[top+4] pix[p+1] += pix[top+5] pix[p+2] += pix[top+6] pix[p+3] += pix[top+7] case 4: // TL. pix[p+0] += pix[top-4] pix[p+1] += pix[top-3] pix[p+2] += pix[top-2] pix[p+3] += pix[top-1] case 5: // Average2(Average2(L, TR), T). pix[p+0] += avg2(avg2(pix[p-4], pix[top+4]), pix[top+0]) pix[p+1] += avg2(avg2(pix[p-3], pix[top+5]), pix[top+1]) pix[p+2] += avg2(avg2(pix[p-2], pix[top+6]), pix[top+2]) pix[p+3] += avg2(avg2(pix[p-1], pix[top+7]), pix[top+3]) case 6: // Average2(L, TL). pix[p+0] += avg2(pix[p-4], pix[top-4]) pix[p+1] += avg2(pix[p-3], pix[top-3]) pix[p+2] += avg2(pix[p-2], pix[top-2]) pix[p+3] += avg2(pix[p-1], pix[top-1]) case 7: // Average2(L, T). pix[p+0] += avg2(pix[p-4], pix[top+0]) pix[p+1] += avg2(pix[p-3], pix[top+1]) pix[p+2] += avg2(pix[p-2], pix[top+2]) pix[p+3] += avg2(pix[p-1], pix[top+3]) case 8: // Average2(TL, T). pix[p+0] += avg2(pix[top-4], pix[top+0]) pix[p+1] += avg2(pix[top-3], pix[top+1]) pix[p+2] += avg2(pix[top-2], pix[top+2]) pix[p+3] += avg2(pix[top-1], pix[top+3]) case 9: // Average2(T, TR). pix[p+0] += avg2(pix[top+0], pix[top+4]) pix[p+1] += avg2(pix[top+1], pix[top+5]) pix[p+2] += avg2(pix[top+2], pix[top+6]) pix[p+3] += avg2(pix[top+3], pix[top+7]) case 10: // Average2(Average2(L, TL), Average2(T, TR)). pix[p+0] += avg2(avg2(pix[p-4], pix[top-4]), avg2(pix[top+0], pix[top+4])) pix[p+1] += avg2(avg2(pix[p-3], pix[top-3]), avg2(pix[top+1], pix[top+5])) pix[p+2] += avg2(avg2(pix[p-2], pix[top-2]), avg2(pix[top+2], pix[top+6])) pix[p+3] += avg2(avg2(pix[p-1], pix[top-1]), avg2(pix[top+3], pix[top+7])) case 11: // Select(L, T, TL). l0 := int32(pix[p-4]) l1 := int32(pix[p-3]) l2 := int32(pix[p-2]) l3 := int32(pix[p-1]) c0 := int32(pix[top-4]) c1 := int32(pix[top-3]) c2 := int32(pix[top-2]) c3 := int32(pix[top-1]) t0 := int32(pix[top+0]) t1 := int32(pix[top+1]) t2 := int32(pix[top+2]) t3 := int32(pix[top+3]) l := abs(c0-t0) + abs(c1-t1) + abs(c2-t2) + abs(c3-t3) t := abs(c0-l0) + abs(c1-l1) + abs(c2-l2) + abs(c3-l3) if l < t { pix[p+0] += uint8(l0) pix[p+1] += uint8(l1) pix[p+2] += uint8(l2) pix[p+3] += uint8(l3) } else { pix[p+0] += uint8(t0) pix[p+1] += uint8(t1) pix[p+2] += uint8(t2) pix[p+3] += uint8(t3) } case 12: // ClampAddSubtractFull(L, T, TL). pix[p+0] += clampAddSubtractFull(pix[p-4], pix[top+0], pix[top-4]) pix[p+1] += clampAddSubtractFull(pix[p-3], pix[top+1], pix[top-3]) pix[p+2] += clampAddSubtractFull(pix[p-2], pix[top+2], pix[top-2]) pix[p+3] += clampAddSubtractFull(pix[p-1], pix[top+3], pix[top-1]) case 13: // ClampAddSubtractHalf(Average2(L, T), TL). pix[p+0] += clampAddSubtractHalf(avg2(pix[p-4], pix[top+0]), pix[top-4]) pix[p+1] += clampAddSubtractHalf(avg2(pix[p-3], pix[top+1]), pix[top-3]) pix[p+2] += clampAddSubtractHalf(avg2(pix[p-2], pix[top+2]), pix[top-2]) pix[p+3] += clampAddSubtractHalf(avg2(pix[p-1], pix[top+3]), pix[top-1]) } p, top = p+4, top+4 } } return pix } func inverseCrossColor(t *transform, pix []byte, h int32) []byte { var greenToRed, greenToBlue, redToBlue int32 p, mask, tilesPerRow := int32(0), int32(1)<<t.bits-1, nTiles(t.oldWidth, t.bits) for y := int32(0); y < h; y++ { q := 4 * (y >> t.bits) * tilesPerRow for x := int32(0); x < t.oldWidth; x++ { if x&mask == 0 { redToBlue = int32(int8(t.pix[q+0])) greenToBlue = int32(int8(t.pix[q+1])) greenToRed = int32(int8(t.pix[q+2])) q += 4 } red := pix[p+0] green := pix[p+1] blue := pix[p+2] red += uint8(uint32(greenToRed*int32(int8(green))) >> 5) blue += uint8(uint32(greenToBlue*int32(int8(green))) >> 5) blue += uint8(uint32(redToBlue*int32(int8(red))) >> 5) pix[p+0] = red pix[p+2] = blue p += 4 } } return pix } func inverseSubtractGreen(t *transform, pix []byte, h int32) []byte { for p := 0; p < len(pix); p += 4 { green := pix[p+1] pix[p+0] += green pix[p+2] += green } return pix } func inverseColorIndexing(t *transform, pix []byte, h int32) []byte { if t.bits == 0 { for p := 0; p < len(pix); p += 4 { i := 4 * uint32(pix[p+1]) pix[p+0] = t.pix[i+0] pix[p+1] = t.pix[i+1] pix[p+2] = t.pix[i+2] pix[p+3] = t.pix[i+3] } return pix } vMask, xMask, bitsPerPixel := uint32(0), int32(0), uint32(8>>t.bits) switch t.bits { case 1: vMask, xMask = 0x0f, 0x01 case 2: vMask, xMask = 0x03, 0x03 case 3: vMask, xMask = 0x01, 0x07 } d, p, v, dst := 0, 0, uint32(0), make([]byte, 4*t.oldWidth*h) for y := int32(0); y < h; y++ { for x := int32(0); x < t.oldWidth; x++ { if x&xMask == 0 { v = uint32(pix[p+1]) p += 4 } i := 4 * (v & vMask) dst[d+0] = t.pix[i+0] dst[d+1] = t.pix[i+1] dst[d+2] = t.pix[i+2] dst[d+3] = t.pix[i+3] d += 4 v >>= bitsPerPixel } } return dst } func abs(x int32) int32 { if x < 0 { return -x } return x } func avg2(a, b uint8) uint8 { return uint8((int32(a) + int32(b)) / 2) } func clampAddSubtractFull(a, b, c uint8) uint8 { x := int32(a) + int32(b) - int32(c) if x < 0 { return 0 } if x > 255 { return 255 } return uint8(x) } func clampAddSubtractHalf(a, b uint8) uint8 { x := int32(a) + (int32(a)-int32(b))/2 if x < 0 { return 0 } if x > 255 { return 255 } return uint8(x) }
vendor/golang.org/x/image/vp8l/transform.go
0.650689
0.608827
transform.go
starcoder
package tibialevellookup import ( "errors" "fmt" "math" ) var expTable []uint // Calculates approximate experience based on level. // The actual math formula has been taken from: https://tibia.fandom.com/wiki/Experience_Table // It is worth to mention that Tibia.com's experience table does not exceed level 2000: https://www.tibia.com/library/?subtopic=experiencetable // It is unsure how precise the formula is itself, but when checking highscores for Bobeek and Goraca (the highest levels at the time of writing this) // it seems accurate. func formula(level float64) float64 { return math.Floor(((50.0 * math.Pow(level, 3)) / 3.0) - (100 * math.Pow(level, 2)) + ((850 * level) / 3) - 200) } // Returns base required experience for a level. // Uses pregenerated expTable if there's one (see GenerateExperienceTable()), // otherwise falls back to the formula(). func LevelToExperience(level int) uint { if len(expTable) >= level { return expTable[level] } else { return uint(math.Floor(formula(float64(level)))) } } // Returns approximate level based on experience - basing off of math formula for calculating experience for a level. // Returns an error if level is out of the table or expTable is nonexistent - see GenerateExperienceTable. func ExperienceToLevel(experience uint) (int, error) { if len(expTable) == 0 { return 0, errors.New("cannot use ExperienceToLevel() if expTable was not pregenerated - make sure GenerateExperienceTable() is called before calling ExperienceToLevel") } for id := range expTable { if expTable[id] < experience && len(expTable)-1 == id { break } if expTable[id] <= experience && expTable[id+1] > experience { return id, nil } } return 0, fmt.Errorf("experience %d not matched - perhaps pass a higher number to GenerateExperienceTable()", experience) } // Generates experience table up to the first passed uinteger argument. Default is 2500. // Required for ExperienceToLevel function to work. func GenerateExperienceTable(params ...int) { var targetLevel int if len(params) == 0 { targetLevel = 2500 } else { targetLevel = params[0] } if len(expTable) >= targetLevel { return } tmpExpTable := make([]uint, targetLevel+1) for k := 1; k < targetLevel+1; k++ { tmpExpTable[k] = LevelToExperience(k) } expTable = tmpExpTable } // Replaces expTable with an empty uinteger array func ClearExpTable() { expTable = make([]uint, 0) }
level.go
0.755186
0.413004
level.go
starcoder
package golinear /* #include "wrap.h" */ import "C" // Parameters for training a linear model. type Parameters struct { // The type of solver SolverType SolverType // The cost of constraints violation. Cost float64 // The relative penalty for each class. RelCosts []ClassWeight // The number of threads to use if liblinear is built with OpenMP support. // Default value is 0 and will use all the cores. NThreads int } // ClassWeight instances are used in the solver parameters to scale // the constraint violation cost of certain labels. type ClassWeight struct { Label int Value float64 } // A SolverType specifies represents one of the liblinear solvers. type SolverType struct { solverType C.int epsilon C.double } // NewL2RLogisticRegression creates an L2-regularized logistic regression // (primal) solver. func NewL2RLogisticRegression(epsilon float64) SolverType { return SolverType{C.L2R_LR, C.double(epsilon)} } // NewL2RLogisticRegressionDefault creates an L2-regularized logistic // regression (primal) solver, epsilon = 0.01. func NewL2RLogisticRegressionDefault() SolverType { return NewL2RLogisticRegression(0.01) } // NewL2RL2LossSvcDual creates an L2-regularized L2-loss support vector // classification (dual) solver. func NewL2RL2LossSvcDual(epsilon float64) SolverType { return SolverType{C.L2R_L2LOSS_SVC_DUAL, C.double(epsilon)} } // NewL2RL2LossSvcDualDefault creates an L2-regularized L2-loss support // vector classification (dual) solver, epsilon = 0.1. func NewL2RL2LossSvcDualDefault() SolverType { return NewL2RL2LossSvcDual(0.1) } // NewL2RL2LossSvcPrimal creates an L2-regularized L2-loss support vector // classification (primal) solver. func NewL2RL2LossSvcPrimal(epsilon float64) SolverType { return SolverType{C.L2R_L2LOSS_SVC, C.double(epsilon)} } // NewL2RL2LossSvcPrimalDefault creates an L2-regularized L2-loss support // vector classification (primal) solver, epsilon = 0.01. func NewL2RL2LossSvcPrimalDefault() SolverType { return NewL2RL2LossSvcPrimal(0.01) } // NewL2RL1LossSvcDual creates an L2-regularized L1-loss support vector // classification (dual) solver. func NewL2RL1LossSvcDual(epsilon float64) SolverType { return SolverType{C.L2R_L1LOSS_SVC_DUAL, C.double(epsilon)} } // NewL2RL1LossSvcDualDefault creates an L2-regularized L1-loss support // vector classification (dual) solver, epsilon = 0.1. func NewL2RL1LossSvcDualDefault() SolverType { return NewL2RL1LossSvcDual(0.1) } // NewMCSVMCS creates a Support vector classification solver // (Crammer and Singer). func NewMCSVMCS(epsilon float64) SolverType { return SolverType{C.MCSVM_CS, C.double(epsilon)} } // NewMCSVMCSDefault creates a Support vector classification solver // (Crammer and Singer), epsilon = 0.1. func NewMCSVMCSDefault() SolverType { return NewMCSVMCS(0.1) } // NewL1RL2LossSvc creates an L1-regularized L2-loss support vector // classification solver. func NewL1RL2LossSvc(epsilon float64) SolverType { return SolverType{C.L1R_L2LOSS_SVC, C.double(epsilon)} } // NewL1RL2LossSvcDefault creates an L1-regularized L2-loss support // vector classification solver, epsilon = 0.01. func NewL1RL2LossSvcDefault() SolverType { return NewL1RL2LossSvc(0.01) } // NewL1RLogisticRegression creates an L1-regularized logistic // regression solver. func NewL1RLogisticRegression(epsilon float64) SolverType { return SolverType{C.L1R_LR, C.double(epsilon)} } // NewL1RLogisticRegressionDefault creates an L1-regularized logistic // regression solver, epsilon = 0.01. func NewL1RLogisticRegressionDefault() SolverType { return NewL1RLogisticRegression(0.01) } // NewL2RLogisticRegressionDual creates an L2-regularized logistic // regression (dual) for regression solver. func NewL2RLogisticRegressionDual(epsilon float64) SolverType { return SolverType{C.L2R_LR_DUAL, C.double(epsilon)} } // NewL2RLogisticRegressionDualDefault creates an L2-regularized logistic // regression (dual) for regression solver, epsilon = 0.1. func NewL2RLogisticRegressionDualDefault() SolverType { return NewL2RLogisticRegressionDual(0.1) } // NewL2RL2LossSvRegression creates an L2-regularized L2-loss support vector // regression (primal) solver. func NewL2RL2LossSvRegression(epsilon float64) SolverType { return SolverType{C.L2R_L2LOSS_SVR, C.double(epsilon)} } // NewL2RL2LossSvRegressionDefault creates an L2-regularized L2-loss support // vector regression (primal) solver, epsilon = 0.001. func NewL2RL2LossSvRegressionDefault() SolverType { return NewL2RL2LossSvRegression(0.001) } // NewL2RL2LossSvRegressionDual creates an L2-regularized L2-loss support // vector regression (dual) solver. func NewL2RL2LossSvRegressionDual(epsilon float64) SolverType { return SolverType{C.L2R_L2LOSS_SVR_DUAL, C.double(epsilon)} } // NewL2RL2LossSvRegressionDualDefault creates an L2-regularized L2-loss // support vector regression (dual) solver, epsilon = 0.1. func NewL2RL2LossSvRegressionDualDefault() SolverType { return NewL2RL2LossSvRegressionDual(0.1) } // NewL2RL1LossSvRegressionDual creates an L2-regularized L1-loss support // vector regression solver (dual). func NewL2RL1LossSvRegressionDual(epsilon float64) SolverType { return SolverType{C.L2R_L1LOSS_SVR_DUAL, C.double(epsilon)} } // NewL2RL1LossSvRegressionDualDefault creates an L2-regularized L1-loss // support vector regression (dual) solver, epsilon = 0.1. func NewL2RL1LossSvRegressionDualDefault() SolverType { return NewL2RL1LossSvRegressionDual(0.1) } // DefaultParameters returns a set of reasonable default parameters: // L2-regularized L2-loss spport vector classification (dual) and a // constraint violation cost of 1. func DefaultParameters() Parameters { return Parameters{NewL2RL2LossSvcDualDefault(), 1, nil, 0} } func toCParameter(param Parameters) *C.parameter_t { cParam := newParameter() cParam.solver_type = param.SolverType.solverType cParam.eps = param.SolverType.epsilon cParam.C = C.double(param.Cost) // Copy relative costs into C structure. n := len(param.RelCosts) if n > 0 { cParam.nr_weight = C.int(n) cParam.weight_label = newLabels(C.int(n)) cParam.weight = newDouble(C.size_t(n)) for i, weight := range param.RelCosts { C.set_int_idx(cParam.weight_label, C.int(i), C.int(weight.Label)) C.set_double_idx(cParam.weight, C.int(i), C.double(weight.Value)) } } // Set the number of threads to use by OpenMP. C.parameter_set_nthreads(cParam, C.int(param.NThreads)) return cParam }
param.go
0.79546
0.501953
param.go
starcoder
package rfc2869 import ( "errors" "strconv" "time" "fbc/lib/go/radius" ) const ( AcctInputGigawords_Type radius.Type = 52 AcctOutputGigawords_Type radius.Type = 53 EventTimestamp_Type radius.Type = 55 ARAPPassword_Type radius.Type = 70 ARAPFeatures_Type radius.Type = 71 ARAPZoneAccess_Type radius.Type = 72 ARAPSecurity_Type radius.Type = 73 ARAPSecurityData_Type radius.Type = 74 PasswordRetry_Type radius.Type = 75 Prompt_Type radius.Type = 76 ConnectInfo_Type radius.Type = 77 ConfigurationToken_Type radius.Type = 78 EAPMessage_Type radius.Type = 79 MessageAuthenticator_Type radius.Type = 80 ARAPChallengeResponse_Type radius.Type = 84 AcctInterimInterval_Type radius.Type = 85 NASPortID_Type radius.Type = 87 FramedPool_Type radius.Type = 88 ) type AcctInputGigawords uint32 var AcctInputGigawords_Strings = map[AcctInputGigawords]string{} func (a AcctInputGigawords) String() string { if str, ok := AcctInputGigawords_Strings[a]; ok { return str } return "AcctInputGigawords(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctInputGigawords_Add(p *radius.Packet, value AcctInputGigawords) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctInputGigawords_Type, a) return } func AcctInputGigawords_Get(p *radius.Packet) (value AcctInputGigawords) { value, _ = AcctInputGigawords_Lookup(p) return } func AcctInputGigawords_Gets(p *radius.Packet) (values []AcctInputGigawords, err error) { var i uint32 for _, attr := range p.Attributes[AcctInputGigawords_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctInputGigawords(i)) } return } func AcctInputGigawords_Lookup(p *radius.Packet) (value AcctInputGigawords, err error) { a, ok := p.Lookup(AcctInputGigawords_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctInputGigawords(i) return } func AcctInputGigawords_Set(p *radius.Packet, value AcctInputGigawords) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctInputGigawords_Type, a) return } func AcctInputGigawords_Del(p *radius.Packet) { p.Attributes.Del(AcctInputGigawords_Type) } type AcctOutputGigawords uint32 var AcctOutputGigawords_Strings = map[AcctOutputGigawords]string{} func (a AcctOutputGigawords) String() string { if str, ok := AcctOutputGigawords_Strings[a]; ok { return str } return "AcctOutputGigawords(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctOutputGigawords_Add(p *radius.Packet, value AcctOutputGigawords) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctOutputGigawords_Type, a) return } func AcctOutputGigawords_Get(p *radius.Packet) (value AcctOutputGigawords) { value, _ = AcctOutputGigawords_Lookup(p) return } func AcctOutputGigawords_Gets(p *radius.Packet) (values []AcctOutputGigawords, err error) { var i uint32 for _, attr := range p.Attributes[AcctOutputGigawords_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctOutputGigawords(i)) } return } func AcctOutputGigawords_Lookup(p *radius.Packet) (value AcctOutputGigawords, err error) { a, ok := p.Lookup(AcctOutputGigawords_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctOutputGigawords(i) return } func AcctOutputGigawords_Set(p *radius.Packet, value AcctOutputGigawords) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctOutputGigawords_Type, a) return } func AcctOutputGigawords_Del(p *radius.Packet) { p.Attributes.Del(AcctOutputGigawords_Type) } func EventTimestamp_Add(p *radius.Packet, value time.Time) (err error) { var a radius.Attribute a, err = radius.NewDate(value) if err != nil { return } p.Add(EventTimestamp_Type, a) return } func EventTimestamp_Get(p *radius.Packet) (value time.Time) { value, _ = EventTimestamp_Lookup(p) return } func EventTimestamp_Gets(p *radius.Packet) (values []time.Time, err error) { var i time.Time for _, attr := range p.Attributes[EventTimestamp_Type] { i, err = radius.Date(attr) if err != nil { return } values = append(values, i) } return } func EventTimestamp_Lookup(p *radius.Packet) (value time.Time, err error) { a, ok := p.Lookup(EventTimestamp_Type) if !ok { err = radius.ErrNoAttribute return } value, err = radius.Date(a) return } func EventTimestamp_Set(p *radius.Packet, value time.Time) (err error) { var a radius.Attribute a, err = radius.NewDate(value) if err != nil { return } p.Set(EventTimestamp_Type, a) return } func EventTimestamp_Del(p *radius.Packet) { p.Attributes.Del(EventTimestamp_Type) } func ARAPPassword_Add(p *radius.Packet, value []byte) (err error) { if len(value) != 16 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(ARAPPassword_Type, a) return } func ARAPPassword_AddString(p *radius.Packet, value string) (err error) { if len(value) != 16 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(ARAPPassword_Type, a) return } func ARAPPassword_Get(p *radius.Packet) (value []byte) { value, _ = ARAPPassword_Lookup(p) return } func ARAPPassword_GetString(p *radius.Packet) (value string) { value, _ = ARAPPassword_LookupString(p) return } func ARAPPassword_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[ARAPPassword_Type] { i = radius.Bytes(attr) if err == nil && len(i) != 16 { err = errors.New("invalid value length") } if err != nil { return } values = append(values, i) } return } func ARAPPassword_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[ARAPPassword_Type] { i = radius.String(attr) if err == nil && len(i) != 16 { err = errors.New("invalid value length") } if err != nil { return } values = append(values, i) } return } func ARAPPassword_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(ARAPPassword_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) if err == nil && len(value) != 16 { err = errors.New("invalid value length") } return } func ARAPPassword_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(ARAPPassword_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) if err == nil && len(value) != 16 { err = errors.New("invalid value length") } return } func ARAPPassword_Set(p *radius.Packet, value []byte) (err error) { if len(value) != 16 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(ARAPPassword_Type, a) return } func ARAPPassword_SetString(p *radius.Packet, value string) (err error) { if len(value) != 16 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(ARAPPassword_Type, a) return } func ARAPPassword_Del(p *radius.Packet) { p.Attributes.Del(ARAPPassword_Type) } func ARAPFeatures_Add(p *radius.Packet, value []byte) (err error) { if len(value) != 14 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(ARAPFeatures_Type, a) return } func ARAPFeatures_AddString(p *radius.Packet, value string) (err error) { if len(value) != 14 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(ARAPFeatures_Type, a) return } func ARAPFeatures_Get(p *radius.Packet) (value []byte) { value, _ = ARAPFeatures_Lookup(p) return } func ARAPFeatures_GetString(p *radius.Packet) (value string) { value, _ = ARAPFeatures_LookupString(p) return } func ARAPFeatures_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[ARAPFeatures_Type] { i = radius.Bytes(attr) if err == nil && len(i) != 14 { err = errors.New("invalid value length") } if err != nil { return } values = append(values, i) } return } func ARAPFeatures_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[ARAPFeatures_Type] { i = radius.String(attr) if err == nil && len(i) != 14 { err = errors.New("invalid value length") } if err != nil { return } values = append(values, i) } return } func ARAPFeatures_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(ARAPFeatures_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) if err == nil && len(value) != 14 { err = errors.New("invalid value length") } return } func ARAPFeatures_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(ARAPFeatures_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) if err == nil && len(value) != 14 { err = errors.New("invalid value length") } return } func ARAPFeatures_Set(p *radius.Packet, value []byte) (err error) { if len(value) != 14 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(ARAPFeatures_Type, a) return } func ARAPFeatures_SetString(p *radius.Packet, value string) (err error) { if len(value) != 14 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(ARAPFeatures_Type, a) return } func ARAPFeatures_Del(p *radius.Packet) { p.Attributes.Del(ARAPFeatures_Type) } type ARAPZoneAccess uint32 const ( ARAPZoneAccess_Value_DefaultZone ARAPZoneAccess = 1 ARAPZoneAccess_Value_ZoneFilterInclusive ARAPZoneAccess = 2 ARAPZoneAccess_Value_ZoneFilterExclusive ARAPZoneAccess = 4 ) var ARAPZoneAccess_Strings = map[ARAPZoneAccess]string{ ARAPZoneAccess_Value_DefaultZone: "Default-Zone", ARAPZoneAccess_Value_ZoneFilterInclusive: "Zone-Filter-Inclusive", ARAPZoneAccess_Value_ZoneFilterExclusive: "Zone-Filter-Exclusive", } func (a ARAPZoneAccess) String() string { if str, ok := ARAPZoneAccess_Strings[a]; ok { return str } return "ARAPZoneAccess(" + strconv.FormatUint(uint64(a), 10) + ")" } func ARAPZoneAccess_Add(p *radius.Packet, value ARAPZoneAccess) (err error) { a := radius.NewInteger(uint32(value)) p.Add(ARAPZoneAccess_Type, a) return } func ARAPZoneAccess_Get(p *radius.Packet) (value ARAPZoneAccess) { value, _ = ARAPZoneAccess_Lookup(p) return } func ARAPZoneAccess_Gets(p *radius.Packet) (values []ARAPZoneAccess, err error) { var i uint32 for _, attr := range p.Attributes[ARAPZoneAccess_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, ARAPZoneAccess(i)) } return } func ARAPZoneAccess_Lookup(p *radius.Packet) (value ARAPZoneAccess, err error) { a, ok := p.Lookup(ARAPZoneAccess_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = ARAPZoneAccess(i) return } func ARAPZoneAccess_Set(p *radius.Packet, value ARAPZoneAccess) (err error) { a := radius.NewInteger(uint32(value)) p.Set(ARAPZoneAccess_Type, a) return } func ARAPZoneAccess_Del(p *radius.Packet) { p.Attributes.Del(ARAPZoneAccess_Type) } type ARAPSecurity uint32 var ARAPSecurity_Strings = map[ARAPSecurity]string{} func (a ARAPSecurity) String() string { if str, ok := ARAPSecurity_Strings[a]; ok { return str } return "ARAPSecurity(" + strconv.FormatUint(uint64(a), 10) + ")" } func ARAPSecurity_Add(p *radius.Packet, value ARAPSecurity) (err error) { a := radius.NewInteger(uint32(value)) p.Add(ARAPSecurity_Type, a) return } func ARAPSecurity_Get(p *radius.Packet) (value ARAPSecurity) { value, _ = ARAPSecurity_Lookup(p) return } func ARAPSecurity_Gets(p *radius.Packet) (values []ARAPSecurity, err error) { var i uint32 for _, attr := range p.Attributes[ARAPSecurity_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, ARAPSecurity(i)) } return } func ARAPSecurity_Lookup(p *radius.Packet) (value ARAPSecurity, err error) { a, ok := p.Lookup(ARAPSecurity_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = ARAPSecurity(i) return } func ARAPSecurity_Set(p *radius.Packet, value ARAPSecurity) (err error) { a := radius.NewInteger(uint32(value)) p.Set(ARAPSecurity_Type, a) return } func ARAPSecurity_Del(p *radius.Packet) { p.Attributes.Del(ARAPSecurity_Type) } func ARAPSecurityData_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(ARAPSecurityData_Type, a) return } func ARAPSecurityData_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(ARAPSecurityData_Type, a) return } func ARAPSecurityData_Get(p *radius.Packet) (value []byte) { value, _ = ARAPSecurityData_Lookup(p) return } func ARAPSecurityData_GetString(p *radius.Packet) (value string) { value, _ = ARAPSecurityData_LookupString(p) return } func ARAPSecurityData_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[ARAPSecurityData_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func ARAPSecurityData_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[ARAPSecurityData_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func ARAPSecurityData_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(ARAPSecurityData_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func ARAPSecurityData_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(ARAPSecurityData_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func ARAPSecurityData_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(ARAPSecurityData_Type, a) return } func ARAPSecurityData_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(ARAPSecurityData_Type, a) return } func ARAPSecurityData_Del(p *radius.Packet) { p.Attributes.Del(ARAPSecurityData_Type) } type PasswordRetry uint32 var PasswordRetry_Strings = map[PasswordRetry]string{} func (a PasswordRetry) String() string { if str, ok := PasswordRetry_Strings[a]; ok { return str } return "PasswordRetry(" + strconv.FormatUint(uint64(a), 10) + ")" } func PasswordRetry_Add(p *radius.Packet, value PasswordRetry) (err error) { a := radius.NewInteger(uint32(value)) p.Add(PasswordRetry_Type, a) return } func PasswordRetry_Get(p *radius.Packet) (value PasswordRetry) { value, _ = PasswordRetry_Lookup(p) return } func PasswordRetry_Gets(p *radius.Packet) (values []PasswordRetry, err error) { var i uint32 for _, attr := range p.Attributes[PasswordRetry_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, PasswordRetry(i)) } return } func PasswordRetry_Lookup(p *radius.Packet) (value PasswordRetry, err error) { a, ok := p.Lookup(PasswordRetry_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = PasswordRetry(i) return } func PasswordRetry_Set(p *radius.Packet, value PasswordRetry) (err error) { a := radius.NewInteger(uint32(value)) p.Set(PasswordRetry_Type, a) return } func PasswordRetry_Del(p *radius.Packet) { p.Attributes.Del(PasswordRetry_Type) } type Prompt uint32 const ( Prompt_Value_NoEcho Prompt = 0 Prompt_Value_Echo Prompt = 1 ) var Prompt_Strings = map[Prompt]string{ Prompt_Value_NoEcho: "No-Echo", Prompt_Value_Echo: "Echo", } func (a Prompt) String() string { if str, ok := Prompt_Strings[a]; ok { return str } return "Prompt(" + strconv.FormatUint(uint64(a), 10) + ")" } func Prompt_Add(p *radius.Packet, value Prompt) (err error) { a := radius.NewInteger(uint32(value)) p.Add(Prompt_Type, a) return } func Prompt_Get(p *radius.Packet) (value Prompt) { value, _ = Prompt_Lookup(p) return } func Prompt_Gets(p *radius.Packet) (values []Prompt, err error) { var i uint32 for _, attr := range p.Attributes[Prompt_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, Prompt(i)) } return } func Prompt_Lookup(p *radius.Packet) (value Prompt, err error) { a, ok := p.Lookup(Prompt_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = Prompt(i) return } func Prompt_Set(p *radius.Packet, value Prompt) (err error) { a := radius.NewInteger(uint32(value)) p.Set(Prompt_Type, a) return } func Prompt_Del(p *radius.Packet) { p.Attributes.Del(Prompt_Type) } func ConnectInfo_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(ConnectInfo_Type, a) return } func ConnectInfo_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(ConnectInfo_Type, a) return } func ConnectInfo_Get(p *radius.Packet) (value []byte) { value, _ = ConnectInfo_Lookup(p) return } func ConnectInfo_GetString(p *radius.Packet) (value string) { value, _ = ConnectInfo_LookupString(p) return } func ConnectInfo_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[ConnectInfo_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func ConnectInfo_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[ConnectInfo_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func ConnectInfo_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(ConnectInfo_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func ConnectInfo_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(ConnectInfo_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func ConnectInfo_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(ConnectInfo_Type, a) return } func ConnectInfo_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(ConnectInfo_Type, a) return } func ConnectInfo_Del(p *radius.Packet) { p.Attributes.Del(ConnectInfo_Type) } func ConfigurationToken_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(ConfigurationToken_Type, a) return } func ConfigurationToken_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(ConfigurationToken_Type, a) return } func ConfigurationToken_Get(p *radius.Packet) (value []byte) { value, _ = ConfigurationToken_Lookup(p) return } func ConfigurationToken_GetString(p *radius.Packet) (value string) { value, _ = ConfigurationToken_LookupString(p) return } func ConfigurationToken_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[ConfigurationToken_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func ConfigurationToken_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[ConfigurationToken_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func ConfigurationToken_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(ConfigurationToken_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func ConfigurationToken_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(ConfigurationToken_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func ConfigurationToken_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(ConfigurationToken_Type, a) return } func ConfigurationToken_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(ConfigurationToken_Type, a) return } func ConfigurationToken_Del(p *radius.Packet) { p.Attributes.Del(ConfigurationToken_Type) } func EAPMessage_Get(p *radius.Packet) (value []byte) { value, _ = EAPMessage_Lookup(p) return } func EAPMessage_GetString(p *radius.Packet) (value string) { value, _ = EAPMessage_LookupString(p) return } func EAPMessage_Lookup(p *radius.Packet) (value []byte, err error) { var i []byte var valid bool for _, attr := range p.Attributes[EAPMessage_Type] { i = radius.Bytes(attr) if err != nil { return } value = append(value, i...) valid = true } if !valid { err = radius.ErrNoAttribute } return } func EAPMessage_LookupString(p *radius.Packet) (value string, err error) { var i string var valid bool for _, attr := range p.Attributes[EAPMessage_Type] { i = radius.String(attr) if err != nil { return } value += i valid = true } if !valid { err = radius.ErrNoAttribute } return } func EAPMessage_Set(p *radius.Packet, value []byte) (err error) { const maximumChunkSize = 253 var attrs []radius.Attribute for len(value) > 0 { var a radius.Attribute n := len(value) if n > maximumChunkSize { n = maximumChunkSize } a, err = radius.NewBytes(value[:n]) if err != nil { return } attrs = append(attrs, a) value = value[n:] } p.Attributes[EAPMessage_Type] = attrs return } func EAPMessage_SetString(p *radius.Packet, value string) (err error) { const maximumChunkSize = 253 var attrs []radius.Attribute for len(value) > 0 { var a radius.Attribute n := len(value) if n > maximumChunkSize { n = maximumChunkSize } a, err = radius.NewString(value[:n]) if err != nil { return } attrs = append(attrs, a) value = value[n:] } p.Attributes[EAPMessage_Type] = attrs return } func EAPMessage_Del(p *radius.Packet) { p.Attributes.Del(EAPMessage_Type) } func MessageAuthenticator_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(MessageAuthenticator_Type, a) return } func MessageAuthenticator_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(MessageAuthenticator_Type, a) return } func MessageAuthenticator_Get(p *radius.Packet) (value []byte) { value, _ = MessageAuthenticator_Lookup(p) return } func MessageAuthenticator_GetString(p *radius.Packet) (value string) { value, _ = MessageAuthenticator_LookupString(p) return } func MessageAuthenticator_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[MessageAuthenticator_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func MessageAuthenticator_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[MessageAuthenticator_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func MessageAuthenticator_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(MessageAuthenticator_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func MessageAuthenticator_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(MessageAuthenticator_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func MessageAuthenticator_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(MessageAuthenticator_Type, a) return } func MessageAuthenticator_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(MessageAuthenticator_Type, a) return } func MessageAuthenticator_Del(p *radius.Packet) { p.Attributes.Del(MessageAuthenticator_Type) } func ARAPChallengeResponse_Add(p *radius.Packet, value []byte) (err error) { if len(value) != 8 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(ARAPChallengeResponse_Type, a) return } func ARAPChallengeResponse_AddString(p *radius.Packet, value string) (err error) { if len(value) != 8 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(ARAPChallengeResponse_Type, a) return } func ARAPChallengeResponse_Get(p *radius.Packet) (value []byte) { value, _ = ARAPChallengeResponse_Lookup(p) return } func ARAPChallengeResponse_GetString(p *radius.Packet) (value string) { value, _ = ARAPChallengeResponse_LookupString(p) return } func ARAPChallengeResponse_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[ARAPChallengeResponse_Type] { i = radius.Bytes(attr) if err == nil && len(i) != 8 { err = errors.New("invalid value length") } if err != nil { return } values = append(values, i) } return } func ARAPChallengeResponse_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[ARAPChallengeResponse_Type] { i = radius.String(attr) if err == nil && len(i) != 8 { err = errors.New("invalid value length") } if err != nil { return } values = append(values, i) } return } func ARAPChallengeResponse_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(ARAPChallengeResponse_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) if err == nil && len(value) != 8 { err = errors.New("invalid value length") } return } func ARAPChallengeResponse_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(ARAPChallengeResponse_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) if err == nil && len(value) != 8 { err = errors.New("invalid value length") } return } func ARAPChallengeResponse_Set(p *radius.Packet, value []byte) (err error) { if len(value) != 8 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(ARAPChallengeResponse_Type, a) return } func ARAPChallengeResponse_SetString(p *radius.Packet, value string) (err error) { if len(value) != 8 { err = errors.New("invalid value length") return } var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(ARAPChallengeResponse_Type, a) return } func ARAPChallengeResponse_Del(p *radius.Packet) { p.Attributes.Del(ARAPChallengeResponse_Type) } type AcctInterimInterval uint32 var AcctInterimInterval_Strings = map[AcctInterimInterval]string{} func (a AcctInterimInterval) String() string { if str, ok := AcctInterimInterval_Strings[a]; ok { return str } return "AcctInterimInterval(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctInterimInterval_Add(p *radius.Packet, value AcctInterimInterval) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctInterimInterval_Type, a) return } func AcctInterimInterval_Get(p *radius.Packet) (value AcctInterimInterval) { value, _ = AcctInterimInterval_Lookup(p) return } func AcctInterimInterval_Gets(p *radius.Packet) (values []AcctInterimInterval, err error) { var i uint32 for _, attr := range p.Attributes[AcctInterimInterval_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctInterimInterval(i)) } return } func AcctInterimInterval_Lookup(p *radius.Packet) (value AcctInterimInterval, err error) { a, ok := p.Lookup(AcctInterimInterval_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctInterimInterval(i) return } func AcctInterimInterval_Set(p *radius.Packet, value AcctInterimInterval) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctInterimInterval_Type, a) return } func AcctInterimInterval_Del(p *radius.Packet) { p.Attributes.Del(AcctInterimInterval_Type) } func NASPortID_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(NASPortID_Type, a) return } func NASPortID_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(NASPortID_Type, a) return } func NASPortID_Get(p *radius.Packet) (value []byte) { value, _ = NASPortID_Lookup(p) return } func NASPortID_GetString(p *radius.Packet) (value string) { value, _ = NASPortID_LookupString(p) return } func NASPortID_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[NASPortID_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func NASPortID_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[NASPortID_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func NASPortID_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(NASPortID_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func NASPortID_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(NASPortID_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func NASPortID_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(NASPortID_Type, a) return } func NASPortID_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(NASPortID_Type, a) return } func NASPortID_Del(p *radius.Packet) { p.Attributes.Del(NASPortID_Type) } func FramedPool_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(FramedPool_Type, a) return } func FramedPool_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(FramedPool_Type, a) return } func FramedPool_Get(p *radius.Packet) (value []byte) { value, _ = FramedPool_Lookup(p) return } func FramedPool_GetString(p *radius.Packet) (value string) { value, _ = FramedPool_LookupString(p) return } func FramedPool_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[FramedPool_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func FramedPool_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[FramedPool_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func FramedPool_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(FramedPool_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func FramedPool_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(FramedPool_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func FramedPool_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(FramedPool_Type, a) return } func FramedPool_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(FramedPool_Type, a) return } func FramedPool_Del(p *radius.Packet) { p.Attributes.Del(FramedPool_Type) }
feg/radius/lib/go/radius/rfc2869/generated.go
0.585931
0.561816
generated.go
starcoder
package configify import ( "strconv" "strings" "time" ) // Massage standardizes how we try to convert values from a source into raw values to // feed to your program. type Massage struct { } // StringToSlice splits the value by commas, stripping any spaces in the tokens. func (Massage) StringToSlice(value string) ([]string, bool) { if value == "" { return []string{}, true } slice := strings.Split(value, ",") for i := range slice { slice[i] = strings.TrimSpace(slice[i]) } return slice, true } // StringToInt64 parses the value as an integer. This will strip out any commas and // decimal info before performing the actual parse. func (m Massage) StringToInt64(value string) (int64, bool) { number, err := strconv.ParseInt(m.normalizeInteger(value), 10, 64) if err != nil { return 0, false } return number, true } // StringToUint64 parses the value as an integer. This will strip out any commas and // decimal info before performing the actual parse. func (m Massage) StringToUint64(value string) (uint64, bool) { number, err := strconv.ParseUint(m.normalizeInteger(value), 10, 64) if err != nil { return 0, false } return number, true } // StringToFloat64 parses the value as a floating point number. func (m Massage) StringToFloat64(value string) (float64, bool) { number, err := strconv.ParseFloat(value, 64) if err != nil { return 0, false } return number, true } // StringToBool converts the strings "true" and "false" (case insensitive) into the // raw boolean values they represent. func (m Massage) StringToBool(value string) (bool, bool) { switch strings.ToLower(value) { case "true": return true, true case "false": return false, true default: return false, false } } // StringToDuration parses Go duration strings such as "5m30s" into raw durations. func (m Massage) StringToDuration(value string) (time.Duration, bool) { duration, err := time.ParseDuration(value) if err != nil { return time.Duration(0), false } return duration, true } // StringToTime parses date/times to the raw time instance it represents. We support // YYYY-MM-DD strings as well as RFC3339 strings. func (m Massage) StringToTime(value string) (time.Time, bool) { var t time.Time var err error switch len(value) { case 0: return time.Time{}, false case 10: t, err = time.Parse("2006-01-02", value) default: t, err = time.Parse(time.RFC3339, value) } if err != nil { return time.Time{}, false } return t, true } // normalizeInteger strips all commas and decimal points so you get the raw integer // encoded in this string. func (m Massage) normalizeInteger(value string) string { decimalPos := strings.IndexRune(value, '.') if decimalPos == 0 { return "" } if decimalPos > 0 { value = value[:decimalPos] } return strings.ReplaceAll(value, string(','), "") }
massage.go
0.733833
0.487307
massage.go
starcoder
package percentile import ( "math" "sort" log "github.com/cihub/seelog" ) // CompleteDS stores all the data and therefore provides accurate // percentiles to compare to. type CompleteDS struct { Values []float64 `json:"vals"` Min float64 `json:"min"` Max float64 `json:"max"` Count int64 `json:"cnt"` Sum float64 `json:"sum"` Avg float64 `json:"avg"` sorted bool } // NewCompleteDS returns a newly initialized CompleteDS func NewCompleteDS() CompleteDS { return CompleteDS{Min: math.Inf(1), Max: math.Inf(-1)} } // Add a new value to the sketch func (s CompleteDS) Add(v float64) QSketch { s.Count++ s.Sum += v s.Avg += (v - s.Avg) / float64(s.Count) if v < s.Min { s.Min = v } if v > s.Max { s.Max = v } s.Values = append(s.Values, v) s.sorted = false return QSketch(s) } // Merge another CompleteDS to the current func (s CompleteDS) Merge(o CompleteDS) CompleteDS { if o.Count == 0 { return s } if s.Count == 0 { return o } s.Count += o.Count s.Sum += o.Sum s.Avg = s.Avg + (o.Avg-s.Avg)*float64(o.Count)/float64(s.Count) if o.Min < s.Min { s.Min = o.Min } if o.Max > s.Max { s.Max = o.Max } s.Values = append(s.Values, o.Values...) s.sorted = false return s } // Quantile returns the accurate quantile q func (s CompleteDS) Quantile(q float64) float64 { if q < 0 || q > 1 { log.Errorf("Quantile out of bounds") return math.NaN() } if s.Count == 0 { return math.NaN() } if q == 0 { return s.Min } else if q == 1 { return s.Max } if s.Count < int64(1/EPSILON) { return s.interpolatedQuantile(q) } if !s.sorted { sort.Float64s(s.Values) s.sorted = true } rank := int64(q * float64(s.Count-1)) return s.Values[rank] } func (s CompleteDS) interpolatedQuantile(q float64) float64 { if !s.sorted { sort.Float64s(s.Values) s.sorted = true } rank := q * float64(s.Count-1) indexBelow := int64(rank) indexAbove := indexBelow + 1 if indexAbove > s.Count-1 { indexAbove = s.Count - 1 } weightAbove := rank - float64(indexBelow) weightBelow := 1.0 - weightAbove return weightBelow*s.Values[indexBelow] + weightAbove*s.Values[indexAbove] }
vendor/github.com/DataDog/datadog-agent/pkg/metrics/percentile/complete_ds.go
0.707708
0.401277
complete_ds.go
starcoder
package dsf import ( "encoding/binary" "fmt" ) // DataChunk is the file structure of the data chunk within a DSD stream file, // excluding the variable length sample data. See "DSF File Format // Specification", v1.01, Sony Corporation. All data is little-endian. This is // exported to allow reading with binary.Read. type DataChunk struct { // data chunk header. // 'd' , 'a' , 't', 'a '. Header [4]byte // Size of this chunk. Size [8]byte // Sample data, omitted because this is not a fixed size. // Samples []byte } // Header identifying a data chunk within a DSD stream file. const dataChunkHeader = "data" // Size in bytes of a data chunk within a DSD stream file, excluding samples. const dataChunkSize = 12 // readDataChunk reads the data chunk and stores the result in d. The audio // samples are typically huge (tens or hundreds of MB) and hence are written // directly into the audio.Audio in d. func (d *decoder) readDataChunk() error { // Read the chunk excluding the sample data err := binary.Read(d.reader, binary.LittleEndian, &d.data) if err != nil { return err } // Chunk header header := string(d.data.Header[:]) switch header { case dataChunkHeader: // This is the expected chunk header case dsdChunkHeader: return fmt.Errorf("data: expected data chunk but found DSD chunk") case fmtChunkHeader: return fmt.Errorf("data: expected data chunk but found fmt chunk") default: return fmt.Errorf("data: bad chunk header: %q\ndata chunk: % x", header, d.data) } // Size of this chunk size := binary.LittleEndian.Uint64(d.data.Size[:]) if size != dataChunkSize+uint64(len(d.audio.EncodedSamples)) { return fmt.Errorf("data: bad chunk size: %v\nfmt chunk: % x\ndata chunk: % x", size, d.fmt, d.data) } // Read the sample data directly into the audio.Audio in d err = binary.Read(d.reader, binary.LittleEndian, &d.audio.EncodedSamples) if err != nil { return err } // Log the fields of the chunk (only active if a log output has been set) d.logger.Print("\nData Chunk\n==========\n") d.logger.Printf("Chunk header: %q\n", header) d.logger.Printf("Size of this chunk: %v\n", size) if len(d.audio.EncodedSamples) > 0 { n := len(d.audio.EncodedSamples) if n > 20 { n = 20 } d.logger.Printf("Sample data: % x...\n", d.audio.EncodedSamples[:n]) } return nil }
audio/dsf/data.go
0.657318
0.545225
data.go
starcoder
package native import ( "bytes" "github.com/anthonynsimon/bild/clone" "github.com/anthonynsimon/bild/effect" "github.com/anthonynsimon/bild/transform" "github.com/gojek/darkroom/pkg/processor" "image" "image/color" "image/draw" ) // BildProcessor uses bild library to process images using native Golang image.Image interface type BildProcessor struct { encoders *Encoders } // Crop takes an input image, width, height and a CropPoint and returns the cropped image func (bp *BildProcessor) Crop(img image.Image, width, height int, point processor.CropPoint) image.Image { w, h := getResizeWidthAndHeightForCrop(width, height, img.Bounds().Dx(), img.Bounds().Dy()) img = transform.Resize(img, w, h, transform.Linear) x0, y0 := getStartingPointForCrop(w, h, width, height, point) rect := image.Rect(x0, y0, width+x0, height+y0) img = (clone.AsRGBA(img)).SubImage(rect) return img } // Resize takes an input image, width and height and returns the re-sized image func (bp *BildProcessor) Resize(img image.Image, width, height int) image.Image { initW := img.Bounds().Dx() initH := img.Bounds().Dy() w, h := getResizeWidthAndHeight(width, height, initW, initH) if w != initW || h != initH { img = transform.Resize(img, w, h, transform.Linear) } return img } // Watermark takes an input byte array, overlay byte array and opacity value // and returns the watermarked image bytes or error func (bp *BildProcessor) Watermark(base []byte, overlay []byte, opacity uint8) ([]byte, error) { baseImg, f, err := bp.Decode(base) if err != nil { return nil, err } overlayImg, _, err := bp.Decode(overlay) if err != nil { return nil, err } ratio := float64(overlayImg.Bounds().Dy()) / float64(overlayImg.Bounds().Dx()) dWidth := float64(baseImg.Bounds().Dx()) / 2.0 // Resizing overlay image according to base image overlayImg = transform.Resize(overlayImg, int(dWidth), int(dWidth*ratio), transform.Linear) // Anchor point for overlaying x := (baseImg.Bounds().Dx() - overlayImg.Bounds().Dx()) / 2 y := (baseImg.Bounds().Dy() - overlayImg.Bounds().Dy()) / 2 offset := image.Pt(int(x), int(y)) // Mask image (that is just a solid light gray image) mask := image.NewUniform(color.Alpha{A: opacity}) // Performing overlay draw.DrawMask(baseImg.(draw.Image), overlayImg.Bounds().Add(offset), overlayImg, image.ZP, mask, image.ZP, draw.Over) return bp.Encode(baseImg, f) } // GrayScale takes an input image and returns the grayscaled image func (bp *BildProcessor) GrayScale(img image.Image) image.Image { // Rec. 601 Luma formula (https://en.wikipedia.org/wiki/Luma_%28video%29#Rec._601_luma_versus_Rec._709_luma_coefficients) return effect.GrayscaleWithWeights(img, 0.299, 0.587, 0.114) } // Decode takes a byte array and returns the decoded image, format, or the error func (bp *BildProcessor) Decode(data []byte) (image.Image, string, error) { img, f, err := image.Decode(bytes.NewReader(data)) return img, f, err } // Encode takes an image and the preferred format (extension) of the output // Current supported format are "png", "jpg" and "jpeg" func (bp *BildProcessor) Encode(img image.Image, fmt string) ([]byte, error) { enc := bp.encoders.GetEncoder(img, fmt) data, err := enc.Encode(img) return data, err } // NewBildProcessor creates a new BildProcessor with default compression func NewBildProcessor() *BildProcessor { return &BildProcessor{ encoders: NewEncoders(DefaultCompressionOptions), } } // NewBildProcessorWithCompression takes an input of encoding options // and creates a newBildProcessor with custom compression options func NewBildProcessorWithCompression(opts *CompressionOptions) *BildProcessor { return &BildProcessor{ encoders: NewEncoders(opts), } }
pkg/processor/native/processor.go
0.832407
0.454351
processor.go
starcoder
package openapi import ( "encoding/json" "fmt" "net/url" "strings" ) // Optional parameters for the method 'CreatePayments' type CreatePaymentsParams struct { // The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource. PathAccountSid *string `json:"PathAccountSid,omitempty"` // Type of bank account if payment source is ACH. One of `consumer-checking`, `consumer-savings`, or `commercial-checking`. The default value is `consumer-checking`. BankAccountType *string `json:"BankAccountType,omitempty"` // A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. ChargeAmount *float32 `json:"ChargeAmount,omitempty"` // The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the <Pay> Connector are accepted. Currency *string `json:"Currency,omitempty"` // The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. Description *string `json:"Description,omitempty"` // A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. IdempotencyKey *string `json:"IdempotencyKey,omitempty"` // A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. Input *string `json:"Input,omitempty"` // A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. MinPostalCodeLength *int `json:"MinPostalCodeLength,omitempty"` // A single level JSON string that is required when accepting certain information specific only to ACH payments. The information that has to be included here depends on the <Pay> Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). Parameter *map[string]interface{} `json:"Parameter,omitempty"` // This is the unique name corresponding to the Payment Gateway Connector installed in the Twilio Add-ons. Learn more about [<Pay> Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. PaymentConnector *string `json:"PaymentConnector,omitempty"` // Type of payment being captured. One of `credit-card` or `ach-debit`. The default value is `credit-card`. PaymentMethod *string `json:"PaymentMethod,omitempty"` // Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. PostalCode *bool `json:"PostalCode,omitempty"` // Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. SecurityCode *bool `json:"SecurityCode,omitempty"` // Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) StatusCallback *string `json:"StatusCallback,omitempty"` // The number of seconds that <Pay> should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. Timeout *int `json:"Timeout,omitempty"` // Indicates whether the payment method should be tokenized as a `one-time` or `reusable` token. The default value is `reusable`. Do not enter a charge amount when tokenizing. If a charge amount is entered, the payment method will be charged and not tokenized. TokenType *string `json:"TokenType,omitempty"` // Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` ValidCardTypes *string `json:"ValidCardTypes,omitempty"` } func (params *CreatePaymentsParams) SetPathAccountSid(PathAccountSid string) *CreatePaymentsParams { params.PathAccountSid = &PathAccountSid return params } func (params *CreatePaymentsParams) SetBankAccountType(BankAccountType string) *CreatePaymentsParams { params.BankAccountType = &BankAccountType return params } func (params *CreatePaymentsParams) SetChargeAmount(ChargeAmount float32) *CreatePaymentsParams { params.ChargeAmount = &ChargeAmount return params } func (params *CreatePaymentsParams) SetCurrency(Currency string) *CreatePaymentsParams { params.Currency = &Currency return params } func (params *CreatePaymentsParams) SetDescription(Description string) *CreatePaymentsParams { params.Description = &Description return params } func (params *CreatePaymentsParams) SetIdempotencyKey(IdempotencyKey string) *CreatePaymentsParams { params.IdempotencyKey = &IdempotencyKey return params } func (params *CreatePaymentsParams) SetInput(Input string) *CreatePaymentsParams { params.Input = &Input return params } func (params *CreatePaymentsParams) SetMinPostalCodeLength(MinPostalCodeLength int) *CreatePaymentsParams { params.MinPostalCodeLength = &MinPostalCodeLength return params } func (params *CreatePaymentsParams) SetParameter(Parameter map[string]interface{}) *CreatePaymentsParams { params.Parameter = &Parameter return params } func (params *CreatePaymentsParams) SetPaymentConnector(PaymentConnector string) *CreatePaymentsParams { params.PaymentConnector = &PaymentConnector return params } func (params *CreatePaymentsParams) SetPaymentMethod(PaymentMethod string) *CreatePaymentsParams { params.PaymentMethod = &PaymentMethod return params } func (params *CreatePaymentsParams) SetPostalCode(PostalCode bool) *CreatePaymentsParams { params.PostalCode = &PostalCode return params } func (params *CreatePaymentsParams) SetSecurityCode(SecurityCode bool) *CreatePaymentsParams { params.SecurityCode = &SecurityCode return params } func (params *CreatePaymentsParams) SetStatusCallback(StatusCallback string) *CreatePaymentsParams { params.StatusCallback = &StatusCallback return params } func (params *CreatePaymentsParams) SetTimeout(Timeout int) *CreatePaymentsParams { params.Timeout = &Timeout return params } func (params *CreatePaymentsParams) SetTokenType(TokenType string) *CreatePaymentsParams { params.TokenType = &TokenType return params } func (params *CreatePaymentsParams) SetValidCardTypes(ValidCardTypes string) *CreatePaymentsParams { params.ValidCardTypes = &ValidCardTypes return params } // create an instance of payments. This will start a new payments session func (c *ApiService) CreatePayments(CallSid string, params *CreatePaymentsParams) (*ApiV2010Payments, error) { path := "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Payments.json" if params != nil && params.PathAccountSid != nil { path = strings.Replace(path, "{"+"AccountSid"+"}", *params.PathAccountSid, -1) } else { path = strings.Replace(path, "{"+"AccountSid"+"}", c.requestHandler.Client.AccountSid(), -1) } path = strings.Replace(path, "{"+"CallSid"+"}", CallSid, -1) data := url.Values{} headers := make(map[string]interface{}) if params != nil && params.BankAccountType != nil { data.Set("BankAccountType", *params.BankAccountType) } if params != nil && params.ChargeAmount != nil { data.Set("ChargeAmount", fmt.Sprint(*params.ChargeAmount)) } if params != nil && params.Currency != nil { data.Set("Currency", *params.Currency) } if params != nil && params.Description != nil { data.Set("Description", *params.Description) } if params != nil && params.IdempotencyKey != nil { data.Set("IdempotencyKey", *params.IdempotencyKey) } if params != nil && params.Input != nil { data.Set("Input", *params.Input) } if params != nil && params.MinPostalCodeLength != nil { data.Set("MinPostalCodeLength", fmt.Sprint(*params.MinPostalCodeLength)) } if params != nil && params.Parameter != nil { v, err := json.Marshal(params.Parameter) if err != nil { return nil, err } data.Set("Parameter", string(v)) } if params != nil && params.PaymentConnector != nil { data.Set("PaymentConnector", *params.PaymentConnector) } if params != nil && params.PaymentMethod != nil { data.Set("PaymentMethod", *params.PaymentMethod) } if params != nil && params.PostalCode != nil { data.Set("PostalCode", fmt.Sprint(*params.PostalCode)) } if params != nil && params.SecurityCode != nil { data.Set("SecurityCode", fmt.Sprint(*params.SecurityCode)) } if params != nil && params.StatusCallback != nil { data.Set("StatusCallback", *params.StatusCallback) } if params != nil && params.Timeout != nil { data.Set("Timeout", fmt.Sprint(*params.Timeout)) } if params != nil && params.TokenType != nil { data.Set("TokenType", *params.TokenType) } if params != nil && params.ValidCardTypes != nil { data.Set("ValidCardTypes", *params.ValidCardTypes) } resp, err := c.requestHandler.Post(c.baseURL+path, data, headers) if err != nil { return nil, err } defer resp.Body.Close() ps := &ApiV2010Payments{} if err := json.NewDecoder(resp.Body).Decode(ps); err != nil { return nil, err } return ps, err } // Optional parameters for the method 'UpdatePayments' type UpdatePaymentsParams struct { // The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will update the resource. PathAccountSid *string `json:"PathAccountSid,omitempty"` // The piece of payment information that you wish the caller to enter. Must be one of `payment-card-number`, `expiration-date`, `security-code`, `postal-code`, `bank-routing-number`, or `bank-account-number`. Capture *string `json:"Capture,omitempty"` // A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. IdempotencyKey *string `json:"IdempotencyKey,omitempty"` // Indicates whether the current payment session should be cancelled or completed. When `cancel` the payment session is cancelled. When `complete`, Twilio sends the payment information to the selected <Pay> connector for processing. Status *string `json:"Status,omitempty"` // Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. StatusCallback *string `json:"StatusCallback,omitempty"` } func (params *UpdatePaymentsParams) SetPathAccountSid(PathAccountSid string) *UpdatePaymentsParams { params.PathAccountSid = &PathAccountSid return params } func (params *UpdatePaymentsParams) SetCapture(Capture string) *UpdatePaymentsParams { params.Capture = &Capture return params } func (params *UpdatePaymentsParams) SetIdempotencyKey(IdempotencyKey string) *UpdatePaymentsParams { params.IdempotencyKey = &IdempotencyKey return params } func (params *UpdatePaymentsParams) SetStatus(Status string) *UpdatePaymentsParams { params.Status = &Status return params } func (params *UpdatePaymentsParams) SetStatusCallback(StatusCallback string) *UpdatePaymentsParams { params.StatusCallback = &StatusCallback return params } // update an instance of payments with different phases of payment flows. func (c *ApiService) UpdatePayments(CallSid string, Sid string, params *UpdatePaymentsParams) (*ApiV2010Payments, error) { path := "/2010-04-01/Accounts/{AccountSid}/Calls/{CallSid}/Payments/{Sid}.json" if params != nil && params.PathAccountSid != nil { path = strings.Replace(path, "{"+"AccountSid"+"}", *params.PathAccountSid, -1) } else { path = strings.Replace(path, "{"+"AccountSid"+"}", c.requestHandler.Client.AccountSid(), -1) } path = strings.Replace(path, "{"+"CallSid"+"}", CallSid, -1) path = strings.Replace(path, "{"+"Sid"+"}", Sid, -1) data := url.Values{} headers := make(map[string]interface{}) if params != nil && params.Capture != nil { data.Set("Capture", *params.Capture) } if params != nil && params.IdempotencyKey != nil { data.Set("IdempotencyKey", *params.IdempotencyKey) } if params != nil && params.Status != nil { data.Set("Status", *params.Status) } if params != nil && params.StatusCallback != nil { data.Set("StatusCallback", *params.StatusCallback) } resp, err := c.requestHandler.Post(c.baseURL+path, data, headers) if err != nil { return nil, err } defer resp.Body.Close() ps := &ApiV2010Payments{} if err := json.NewDecoder(resp.Body).Decode(ps); err != nil { return nil, err } return ps, err }
rest/api/v2010/accounts_calls_payments.go
0.786869
0.480905
accounts_calls_payments.go
starcoder
package requirements import ( "fmt" "strings" "github.com/aquasecurity/tfsec/cmd/tfsec-skeleton/examples" ) func AttributeMustHaveValue(blockType string, blockLabel string, dotPath string, expectedValue interface{}, failCheckForDefaultValue bool, exampleCode string) Requirement { return NewAttributeRequirement(blockType, blockLabel, dotPath, expectedValue, failCheckForDefaultValue, exampleCode, ComparisonEquals) } func AttributeMustNotHaveValue(blockType string, blockLabel string, dotPath string, expectedValue interface{}, failCheckForDefaultValue bool, exampleCode string) Requirement { return NewAttributeRequirement(blockType, blockLabel, dotPath, expectedValue, failCheckForDefaultValue, exampleCode, ComparisonNotEquals) } type attributeBase struct { dotPath string value interface{} comparison Comparison failCheckForDefaultValue bool blockType string blockLabel string exampleCode string } func NewAttributeRequirement(blockType string, blockLabel string, dotPath string, value interface{}, failCheckForDefaultValue bool, exampleCode string, comparison Comparison) Requirement { var req attributeBase req.dotPath = dotPath req.value = value req.comparison = comparison req.failCheckForDefaultValue = failCheckForDefaultValue req.blockType = blockType req.blockLabel = blockLabel req.exampleCode = exampleCode return &req } func (a *attributeBase) makeGoodValue() interface{} { switch a.comparison { case ComparisonEquals: return a.value case ComparisonNotEquals, ComparisonNotAnyOf: return flipValue(a.value) case ComparisonAnyOf: if strs, ok := a.value.([]string); ok && len(strs) > 0 { return strs[0] } panic("only non-zero length list of strings are supported") case ComparisonGreaterThan, ComparisonGreaterThanOrEqual: if i, ok := a.value.(int); ok { return i + 1 } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) case ComparisonLessThan, ComparisonLessThanOrEqual: if i, ok := a.value.(int); ok { return i - 1 } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) case ComparisonContains: if s, ok := a.value.(string); ok { return []string{s} } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) case ComparisonNotContains: if _, ok := a.value.(string); ok { return []string{} } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) default: panic(fmt.Sprintf("comparison '%s' is not supported", a.comparison)) } } func (a *attributeBase) GenerateGoodExample() string { value := a.makeGoodValue() if a.exampleCode != "" { return examples.SetAttribute(a.exampleCode, fmt.Sprintf("%s.%s.*.%s", a.blockType, a.blockLabel, a.dotPath), value, "good_example") } return fmt.Sprintf(` %s "%s" "%s" { %s} `, a.blockType, a.blockLabel, "good_example", createTerraformFromDotPath(a.dotPath, value)) } func (a *attributeBase) makeBadValue() interface{} { switch a.comparison { case ComparisonEquals, ComparisonAnyOf: return flipValue(a.value) case ComparisonNotEquals: return a.value case ComparisonNotAnyOf: if strs, ok := a.value.([]string); ok && len(strs) > 0 { return strs[0] } panic("only non-zero length list of strings are supported") case ComparisonGreaterThan, ComparisonGreaterThanOrEqual: if i, ok := a.value.(int); ok { return i - 1 } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) case ComparisonLessThan, ComparisonLessThanOrEqual: if i, ok := a.value.(int); ok { return i + 1 } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) case ComparisonContains: if _, ok := a.value.(string); ok { return []string{} } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) case ComparisonNotContains: if s, ok := a.value.(string); ok { return []string{s} } panic(fmt.Sprintf("comparison '%s' cannot support value %#v", a.comparison, a.value)) default: panic(fmt.Sprintf("comparison'%s' is not supported", a.comparison)) } } func (a *attributeBase) GenerateBadExample() string { value := a.makeBadValue() if a.exampleCode != "" { return examples.SetAttribute(a.exampleCode, fmt.Sprintf("%s.%s.*.%s", a.blockType, a.blockLabel, a.dotPath), value, "bad_example") } return fmt.Sprintf(` %s "%s" "%s" { %s} `, a.blockType, a.blockLabel, "bad_example", createTerraformFromDotPath(a.dotPath, value)) } func (a *attributeBase) GenerateRuleCode() string { var code string lowestBlock := "resourceBlock" parts := strings.Split(a.dotPath, ".") getBlockCode := lowestBlock for i, part := range parts { if i == len(parts)-1 { break } getBlockCode = fmt.Sprintf(`%s.GetBlock("%s")`, getBlockCode, part) } attrName := parts[len(parts)-1] attrVarName := snakeToCamel(attrName) + "Attr" code += fmt.Sprintf(`if %s := %s.GetAttribute("%s"); `, attrVarName, getBlockCode, attrName) if a.failCheckForDefaultValue { code += fmt.Sprintf(`%s.IsNil() { // alert on use of default value set.AddResult(). WithDescription("Resource '%%s' uses default value for %s", resourceBlock.FullName()) } else if `, attrVarName, a.dotPath) } var messageTemplate string switch a.comparison { case ComparisonEquals: messageTemplate = fmt.Sprintf("Resource '%%s' does not have %s set to %v", a.dotPath, a.value) case ComparisonNotEquals: messageTemplate = fmt.Sprintf("Resource '%%s' has %s set to %v", a.dotPath, a.value) case ComparisonAnyOf: messageTemplate = fmt.Sprintf("Resource '%%s' does not have %s set to one of %s", a.dotPath, a.value) case ComparisonNotAnyOf: messageTemplate = fmt.Sprintf("Resource '%%s' has %s set to one of %s", a.dotPath, a.value) case ComparisonGreaterThan: messageTemplate = fmt.Sprintf("Resource '%%s' does not have %s set to greater than %d", a.dotPath, a.value) case ComparisonLessThan: messageTemplate = fmt.Sprintf("Resource '%%s' does not have %s set to less than %d", a.dotPath, a.value) case ComparisonGreaterThanOrEqual: messageTemplate = fmt.Sprintf("Resource '%%s' does not have %s set to greater than or equal to %d", a.dotPath, a.value) case ComparisonLessThanOrEqual: messageTemplate = fmt.Sprintf("Resource '%%s' does not have %s set to greater than or equal to %d", a.dotPath, a.value) case ComparisonContains: messageTemplate = fmt.Sprintf("Resource '%%s' should have %s in %s", a.value, a.dotPath) case ComparisonNotContains: messageTemplate = fmt.Sprintf("Resource '%%s' has %s in %s", a.value, a.dotPath) default: panic(fmt.Sprintf("comparison '%s' is not supported", a.comparison)) } code += fmt.Sprintf(`%s.%s { set.AddResult(). WithDescription("%s", resourceBlock.FullName()). WithAttribute(%s) }`, attrVarName, buildComparisonForValue(a.value, a.comparison.Reverse()), messageTemplate, attrVarName) return code } func (a *attributeBase) RequirementType() RequirementType { return RequirementType(AttributeRequirement) }
cmd/tfsec-skeleton/requirements/attributes.go
0.645902
0.46393
attributes.go
starcoder
package game import ( "image/color" "github.com/hajimehoshi/ebiten/v2" ) const ( maxMovingCount = 5 maxPoppingCount = 6 ) var ( tileSize = 40 tileMargin = 3 tileImage = ebiten.NewImage(tileSize, tileSize) ) func init() { tileImage.Fill(color.White) } // TilePosition represents a tile position. type TilePosition struct { x int y int } // Tile represents a tile information including Tetromino shape, position and animation states. type Tile struct { x, y int tetro *Tetromino poppingCount int } // Pos returns the tile's current position. func (t *Tile) Pos() (int, int) { return t.x, t.y } // IsMoving returns a boolean value indicating if the tile is animating. func (t *Tile) IsMoving() bool { return 0 < t.poppingCount } func (t *Tile) stopAnimation() { t.poppingCount = 0 } // Update updates the tile's animation states. func (t *Tile) Update() error { switch { case 0 < t.poppingCount: t.poppingCount-- } return nil } func colorToScale(clr color.Color) (float64, float64, float64, float64) { r, g, b, a := clr.RGBA() rf := float64(r) / 0xffff gf := float64(g) / 0xffff bf := float64(b) / 0xffff af := float64(a) / 0xffff // Convert to non-premultiplied alpha components. if 0 < af { rf /= af gf /= af bf /= af } return rf, gf, bf, af } func mean(a, b int, rate float64) int { return int(float64(a)*(1-rate) + float64(b)*rate) } func meanF(a, b float64, rate float64) float64 { return a*(1-rate) + b*rate } // Draw draws the current tile to the given boardImage. func (t *Tile) Draw(boardImage *ebiten.Image) { // get board height to render origin coordinate at bottom left instead of top left _, bh := boardImage.Size() op := &ebiten.DrawImageOptions{} x := t.x*tileSize + (t.x+1)*tileMargin y := bh - ((t.y+1)*tileSize + (t.y+1)*tileMargin) switch { case 0 < t.poppingCount: const maxScale = 1.2 rate := 0.0 if maxPoppingCount*2/3 <= t.poppingCount { // 0 to 1 rate = 1 - float64(t.poppingCount-2*maxPoppingCount/3)/float64(maxPoppingCount/3) } else { // 1 to 0 rate = float64(t.poppingCount) / float64(maxPoppingCount*2/3) } scale := meanF(1.0, maxScale, rate) op.GeoM.Translate(float64(-tileSize/2), float64(-tileSize/2)) op.GeoM.Scale(scale, scale) op.GeoM.Translate(float64(tileSize/2), float64(tileSize/2)) } op.GeoM.Translate(float64(x), float64(y)) r, g, b, a := colorToScale(t.tetro.color) op.ColorM.Scale(r, g, b, a) boardImage.DrawImage(tileImage, op) }
game/tile.go
0.830457
0.422266
tile.go
starcoder
package density import ( "image" "image/color" "math" "github.com/lucasb-eyer/go-colorful" ) const TileSize = 256 func TileXY(zoom int, lat, lng float64) (x, y int) { fx, fy := TileFloatXY(zoom, lat, lng) x = int(math.Floor(fx)) y = int(math.Floor(fy)) return } func TileFloatXY(zoom int, lat, lng float64) (x, y float64) { lat_rad := lat * math.Pi / 180 n := math.Pow(2, float64(zoom)) x = (lng + 180) / 360 * n y = (1 - math.Log(math.Tan(lat_rad)+(1/math.Cos(lat_rad)))/math.Pi) / 2 * n return } func TileLatLng(zoom, x, y int) (lat, lng float64) { n := math.Pow(2, float64(zoom)) lng = float64(x)/n*360 - 180 lat = math.Atan(math.Sinh(math.Pi*(1-2*float64(y)/n))) * 180 / math.Pi return } type IntPoint struct { X, Y int } type Tile struct { Zoom, X, Y int Grid map[IntPoint]float64 Points int } func NewTile(zoom, x, y int) *Tile { grid := make(map[IntPoint]float64) return &Tile{zoom, x, y, grid, 0} } func (tile *Tile) Add(lat, lng float64) { u, v := TileFloatXY(tile.Zoom, lat, lng) u -= float64(tile.X) v -= float64(tile.Y) v = 1 - v u *= TileSize v *= TileSize x := int(math.Floor(u)) y := int(math.Floor(v)) u = u - math.Floor(u) v = v - math.Floor(v) tile.Grid[IntPoint{x + 0, y + 0}] += (1 - u) * (1 - v) tile.Grid[IntPoint{x + 0, y + 1}] += (1 - u) * v tile.Grid[IntPoint{x + 1, y + 0}] += u * (1 - v) tile.Grid[IntPoint{x + 1, y + 1}] += u * v tile.Points++ } func (tile *Tile) Render(kernel Kernel, scale float64) (image.Image, bool) { im := image.NewNRGBA(image.Rect(0, 0, TileSize, TileSize)) ok := false for y := 0; y < TileSize; y++ { for x := 0; x < TileSize; x++ { var t, tw float64 for _, k := range kernel { nx := x + k.Dx ny := y + k.Dy t += tile.Grid[IntPoint{nx, ny}] * k.Weight tw += k.Weight } if t == 0 { continue } t *= scale t /= tw t = t / (t + 1) a := uint8(255 * math.Pow(t, 0.5)) c := colorful.Hsv(215.0, 1-t*t, 1) r, g, b := c.RGB255() im.SetNRGBA(x, TileSize-1-y, color.NRGBA{r, g, b, a}) ok = true } } return im, ok }
vendor/github.com/fogleman/density/tile.go
0.629205
0.403097
tile.go
starcoder
package lute func (t *Tree) parseInlineHTML(ctx *InlineContext) (ret *Node) { tokens := ctx.tokens startPos := ctx.pos ret = &Node{typ: NodeText, tokens: []byte{tokens[ctx.pos]}} if 3 > ctx.tokensLen || ctx.tokensLen <= startPos+1 { ctx.pos++ return } var tags []byte tags = append(tags, tokens[startPos]) if itemSlash == tokens[startPos+1] { // a closing tag tags = append(tags, tokens[startPos+1]) remains, tagName := t.parseTagName(tokens[ctx.pos+2:]) if 1 > len(tagName) { ctx.pos++ return } tags = append(tags, tagName...) tokens = remains } else if remains, tagName := t.parseTagName(tokens[ctx.pos+1:]); 0 < len(tagName) { tags = append(tags, tagName...) tokens = remains for { valid, remains, attr := t.parseTagAttr(tokens) if !valid { ctx.pos++ return } tokens = remains tags = append(tags, attr...) if 1 > len(attr) { break } } } else if valid, remains, comment := t.parseHTMLComment(tokens[ctx.pos+1:]); valid { tags = append(tags, comment...) tokens = remains ctx.pos += len(tags) ret = &Node{typ: NodeInlineHTML, tokens: tags} return } else if valid, remains, ins := t.parseProcessingInstruction(tokens[ctx.pos+1:]); valid { tags = append(tags, ins...) tokens = remains ctx.pos += len(tags) ret = &Node{typ: NodeInlineHTML, tokens: tags} return } else if valid, remains, decl := t.parseDeclaration(tokens[ctx.pos+1:]); valid { tags = append(tags, decl...) tokens = remains ctx.pos += len(tags) ret = &Node{typ: NodeInlineHTML, tokens: tags} return } else if valid, remains, cdata := t.parseCDATA(tokens[ctx.pos+1:]); valid { tags = append(tags, cdata...) tokens = remains ctx.pos += len(tags) ret = &Node{typ: NodeInlineHTML, tokens: tags} return } else { ctx.pos++ return } length := len(tokens) if 1 > length { ctx.pos = startPos + 1 return } whitespaces, tokens := trimLeft(tokens) if (itemGreater == tokens[0]) || (1 < ctx.tokensLen && itemSlash == tokens[0] && itemGreater == tokens[1]) { tags = append(tags, whitespaces...) tags = append(tags, tokens[0]) if itemSlash == tokens[0] { tags = append(tags, tokens[1]) } ctx.pos += len(tags) ret = &Node{typ: NodeInlineHTML, tokens: tags} return } ctx.pos = startPos + 1 return } func (t *Tree) parseCDATA(tokens []byte) (valid bool, remains, content []byte) { remains = tokens if itemBang != tokens[0] { return } if itemOpenBracket != tokens[1] { return } if 'C' != tokens[2] || 'D' != tokens[3] || 'A' != tokens[4] || 'T' != tokens[5] || 'A' != tokens[6] { return } if itemOpenBracket != tokens[7] { return } content = append(content, tokens[:7]...) tokens = tokens[7:] var token byte var i int length := len(tokens) for ; i < length; i++ { token = tokens[i] content = append(content, token) if i <= length-3 && itemCloseBracket == token && itemCloseBracket == tokens[i+1] && itemGreater == tokens[i+2] { break } } tokens = tokens[i:] if itemCloseBracket != tokens[0] || itemCloseBracket != tokens[1] || itemGreater != tokens[2] { return } content = append(content, tokens[1], tokens[2]) valid = true remains = tokens[3:] return } func (t *Tree) parseDeclaration(tokens []byte) (valid bool, remains, content []byte) { remains = tokens if itemBang != tokens[0] { return } var token byte var i int for _, token = range tokens[1:] { if isWhitespace(token) { break } if !('A' <= token && 'Z' >= token) { return } } content = append(content, tokens[0], tokens[1]) tokens = tokens[2:] length := len(tokens) for ; i < length; i++ { token = tokens[i] content = append(content, token) if itemGreater == token { break } } tokens = tokens[i:] if itemGreater != tokens[0] { return } valid = true remains = tokens[1:] return } func (t *Tree) parseProcessingInstruction(tokens []byte) (valid bool, remains, content []byte) { remains = tokens if itemQuestion != tokens[0] { return } content = append(content, tokens[0]) tokens = tokens[1:] var token byte var i int length := len(tokens) for ; i < length; i++ { token = tokens[i] content = append(content, token) if i <= length-2 && itemQuestion == token && itemGreater == tokens[i+1] { break } } tokens = tokens[i:] if 1 > len(tokens) { return } if itemQuestion != tokens[0] || itemGreater != tokens[1] { return } content = append(content, tokens[1]) valid = true remains = tokens[2:] return } func (t *Tree) parseHTMLComment(tokens []byte) (valid bool, remains, comment []byte) { remains = tokens if itemBang != tokens[0] || itemHyphen != tokens[1] || itemHyphen != tokens[2] { return } comment = append(comment, tokens[0], tokens[1], tokens[2]) tokens = tokens[3:] if itemGreater == tokens[0] { return } if itemHyphen == tokens[0] && itemGreater == tokens[1] { return } var token byte var i int length := len(tokens) for ; i < length; i++ { token = tokens[i] comment = append(comment, token) if i <= length-2 && itemHyphen == token && itemHyphen == tokens[i+1] { break } if i <= length-3 && itemHyphen == token && itemHyphen == tokens[i+1] && itemGreater == tokens[i+2] { break } } tokens = tokens[i:] if itemHyphen != tokens[0] || itemHyphen != tokens[1] || itemGreater != tokens[2] { return } comment = append(comment, tokens[1], tokens[2]) valid = true remains = tokens[3:] return } func (t *Tree) parseTagAttr(tokens []byte) (valid bool, remains, attr []byte) { valid = true remains = tokens var whitespaces []byte var i int var token byte for i, token = range tokens { if !isWhitespace(token) { break } whitespaces = append(whitespaces, token) } if 1 > len(whitespaces) { return } tokens = tokens[i:] var attrName []byte tokens, attrName = t.parseAttrName(tokens) if 1 > len(attrName) { return } var valSpec []byte valid, tokens, valSpec = t.parseAttrValSpec(tokens) if !valid { return } remains = tokens attr = append(attr, whitespaces...) attr = append(attr, attrName...) attr = append(attr, valSpec...) return } func (t *Tree) parseAttrValSpec(tokens []byte) (valid bool, remains, valSpec []byte) { valid = true remains = tokens var i int var token byte for i, token = range tokens { if !isWhitespace(token) { break } valSpec = append(valSpec, token) } if itemEqual != token { valSpec = nil return } valSpec = append(valSpec, token) tokens = tokens[i+1:] for i, token = range tokens { if !isWhitespace(token) { break } valSpec = append(valSpec, token) } token = tokens[i] valSpec = append(valSpec, token) tokens = tokens[i+1:] closed := false if itemDoublequote == token { // A double-quoted attribute value consists of ", zero or more characters not including ", and a final ". for i, token = range tokens { valSpec = append(valSpec, token) if itemDoublequote == token { closed = true break } } } else if itemSinglequote == token { // A single-quoted attribute value consists of ', zero or more characters not including ', and a final '. for i, token = range tokens { valSpec = append(valSpec, token) if itemSinglequote == token { closed = true break } } } else { // An unquoted attribute value is a nonempty string of characters not including whitespace, ", ', =, <, >, or `. for i, token = range tokens { if itemGreater == token { i-- // 大于字符 > 不计入 valSpec break } valSpec = append(valSpec, token) if isWhitespace(token) { // 属性使用空白分隔 break } if itemDoublequote == token || itemSinglequote == token || itemEqual == token || itemLess == token || itemGreater == token || itemBacktick == token { closed = false break } closed = true } } if !closed { valid = false valSpec = nil return } remains = tokens[i+1:] return } func (t *Tree) parseAttrName(tokens []byte) (remains, attrName []byte) { remains = tokens if !isASCIILetter(tokens[0]) && itemUnderscore != tokens[0] && itemColon != tokens[0] { return } attrName = append(attrName, tokens[0]) tokens = tokens[1:] var i int var token byte for i, token = range tokens { if !isASCIILetterNumHyphen(token) && itemUnderscore != token && itemDot != token && itemColon != token { break } attrName = append(attrName, token) } if 1 > len(attrName) { return } remains = tokens[i:] return } func (t *Tree) parseTagName(tokens []byte) (remains, tagName []byte) { i := 0 token := tokens[i] if !isASCIILetter(token) { return tokens, nil } tagName = append(tagName, token) for i = 1; i < len(tokens); i++ { token = tokens[i] if !isASCIILetterNumHyphen(token) { break } tagName = append(tagName, token) } remains = tokens[i:] return }
inline_html.go
0.515864
0.469642
inline_html.go
starcoder
package tsuki import ( "sync" ) type ExpectAction int const ( ExpectActionNothing = ExpectAction(0) ExpectActionRead = ExpectAction(1) ExpectActionWrite = ExpectAction(2) ) var strToExpectAction = map[string]ExpectAction { "read": ExpectActionRead, "write": ExpectActionWrite, } // token -> chunkId -> ExpectAction // Putting token first makes it more cache-friendly, since there much less // tokens than chunks. //type TokenExpectations map[string]map[string]ExpectAction type TokenExpectation struct { action ExpectAction processedChunks map[string]bool pendingCount int mu sync.RWMutex } type ExpectationDB struct { mu sync.RWMutex index map[string]*TokenExpectation expectsPerChunk map[string]int purgeChunk map[string]struct{} } func NewExpectationDB() *ExpectationDB { return &ExpectationDB { index: make(map[string]*TokenExpectation), expectsPerChunk: make(map[string]int), purgeChunk: make(map[string]struct{}), } } func (e *ExpectationDB) Get(token string) *TokenExpectation { e.mu.RLock() defer e.mu.RUnlock() return e.index[token] } func (e *ExpectationDB) Set(token string, exp *TokenExpectation) { e.mu.Lock() defer e.mu.Unlock() e.index[token] = exp for k := range exp.processedChunks { e.expectsPerChunk[k]++ } } func (e *ExpectationDB) Remove(token string) []string { e.mu.Lock() defer e.mu.Unlock() toPurge := make([]string, 0, len(e.purgeChunk)) for id := range e.index[token].processedChunks { e.expectsPerChunk[id]-- if e.expectsPerChunk[id] == 0 { delete(e.expectsPerChunk, id) _, obsolete := e.purgeChunk[id] if obsolete { toPurge = append(toPurge, id) delete(e.purgeChunk, id) } } } delete(e.index, token) return toPurge } func (e *ExpectationDB) MakeObsolete(chunks ...string) (toPurge []string) { e.mu.Lock() defer e.mu.Unlock() for _, id := range chunks { expCount := e.expectsPerChunk[id] if expCount == 0 { // Note that there's no `id` in the e.purgeChunk if we've entered // this if. The only way to make chunk obsolete is to call this // function. Hence, if MakeObsolete didn't remove it the first // call, there was at least one expect action associated with // this chunk. And because of this, the Remove will return it // and clear e.purgeChunk. toPurge = append(toPurge, id) continue } e.purgeChunk[id] = struct{}{} } return }
expectation_db.go
0.588653
0.454048
expectation_db.go
starcoder
package it import ( "math" "gonum.org/v1/gonum/mat" ) // Entropy calculates the entropy of a probability distribution. // H(X) = -\sum_x p(x) log(p(x)) func Entropy(p mat.Vector) float64 { var r float64 for i := 0; i < p.Len(); i++ { v := p.AtVec(i) if v > 0.0 { r -= v * math.Log(v) } } return r } // EntropyMLBC is maximum likelihood estimator with bias correction // It takes discretised data as input. // Implemented from // <NAME> and <NAME>. Nonparametric estimation of Shannon’s // index of diversity when there are unseen species in sample. // Environmental and Ecological Statistics, 10(4):429–443, 2003. func EntropyMLBC(data []int) float64 { p := Emperical1D(data) n := float64(len(data)) S := float64(p.Len()) r := 0.0 for i := 0; i < p.Len(); i++ { v := p.AtVec(i) if v > 0.0 { r -= v * math.Log(v) } } return r + (S-1.0)/(2.0*n) } // EntropyHorvitzThompson is the Horvitz-Thompson entropy estimator. // It takes discretised data as input. // Implemented from // <NAME> and <NAME>. Nonparametric estimation of shannon’s // index of diversity when there are unseen species in sample. // Environmental and Ecological Statistics, 10(4):429–443, 2003. func EntropyHorvitzThompson(data []int) float64 { p := Emperical1D(data) n := float64(len(data)) r := 0.0 for i := 0; i < p.Len(); i++ { v := p.AtVec(i) if v > 0.0 { N := v * math.Log(v) D := 1.0 - math.Pow(1.0-v, n) r -= N / D } } return r } // EntropyChaoShen is the Chao-Shen entropy estimator. It take discretised data // and the log-function as input // Implemented from // <NAME> and <NAME>. Nonparametric estimation of shannon’s // index of diversity when there are unseen species in sample. // Environmental and Ecological Statistics, 10(4):429–443, 2003. func EntropyChaoShen(data []int) float64 { n := float64(len(data)) nrOfSingletons := 0.0 histogram := map[int]float64{} for _, v := range data { histogram[v] += 1.0 } p := make([]float64, len(histogram), len(histogram)) var keys []int for k, v := range histogram { keys = append(keys, k) if v == 1.0 { nrOfSingletons += 1.0 } } if nrOfSingletons == n { nrOfSingletons -= 1.0 } for i := range histogram { p[i] = histogram[keys[i]] / n } C := 1.0 - nrOfSingletons/n for i := range p { p[i] = p[i] * C } var z float64 var r float64 for i := range p { if p[i] > 0.0 { z = math.Pow((1.0 - p[i]), n) z = (1.0 - z) r -= p[i] * math.Log(p[i]) / z } } return r }
stat/it/entropy.go
0.765681
0.564399
entropy.go
starcoder
package mos65c02 import ( "fmt" "reflect" "runtime" "strings" "github.com/pevans/erc/pkg/asmrec" "github.com/pevans/erc/pkg/disasm" "github.com/pevans/erc/pkg/trace" ) // An Instruction is a function that performs an operation on the CPU. type Instruction func(c *CPU) // Below is a table of instructions that are mapped to opcodes. For // corresponding address modes, see addr.go. // 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F var instructions = [256]Instruction{ Brk, Ora, Np2, Nop, Tsb, Ora, Asl, Nop, Php, Ora, Asl, Nop, Tsb, Ora, Asl, Nop, // 0x Bpl, Ora, Ora, Nop, Trb, Ora, Asl, Nop, Clc, Ora, Inc, Nop, Trb, Ora, Asl, Nop, // 1x Jsr, And, Np2, Nop, Bit, And, Rol, Nop, Plp, And, Rol, Nop, Bit, And, Rol, Nop, // 2x Bmi, And, And, Nop, Bit, And, Rol, Nop, Sec, And, Dec, Nop, Bit, And, Rol, Nop, // 3x Rti, Eor, Np2, Nop, Np2, Eor, Lsr, Nop, Pha, Eor, Lsr, Nop, Jmp, Eor, Lsr, Nop, // 4x Bvc, Eor, Eor, Nop, Np2, Eor, Lsr, Nop, Cli, Eor, Phy, Nop, Np3, Eor, Lsr, Nop, // 5x Rts, Adc, Np2, Nop, Stz, Adc, Ror, Nop, Pla, Adc, Ror, Nop, Jmp, Adc, Ror, Nop, // 6x Bvs, Adc, Adc, Nop, Stz, Adc, Ror, Nop, Sei, Adc, Ply, Nop, Jmp, Adc, Ror, Nop, // 7x Bra, Sta, Np2, Nop, Sty, Sta, Stx, Nop, Dey, Bim, Txa, Nop, Sty, Sta, Stx, Nop, // 8x Bcc, Sta, Sta, Nop, Sty, Sta, Stx, Nop, Tya, Sta, Txs, Nop, Stz, Sta, Stz, Nop, // 9x Ldy, Lda, Ldx, Nop, Ldy, Lda, Ldx, Nop, Tay, Lda, Tax, Nop, Ldy, Lda, Ldx, Nop, // Ax Bcs, Lda, Lda, Nop, Ldy, Lda, Ldx, Nop, Clv, Lda, Tsx, Nop, Ldy, Lda, Ldx, Nop, // Bx Cpy, Cmp, Np2, Nop, Cpy, Cmp, Dec, Nop, Iny, Cmp, Dex, Nop, Cpy, Cmp, Dec, Nop, // Cx Bne, Cmp, Cmp, Nop, Np2, Cmp, Dec, Nop, Cld, Cmp, Phx, Nop, Np3, Cmp, Dec, Nop, // Dx Cpx, Sbc, Np2, Nop, Cpx, Sbc, Inc, Nop, Inx, Sbc, Nop, Nop, Cpx, Sbc, Inc, Nop, // Ex Beq, Sbc, Sbc, Nop, Np2, Sbc, Inc, Nop, Sed, Sbc, Plx, Nop, Np3, Sbc, Inc, Nop, // Fx } /* // 0 1 2 3 4 5 6 7 8 9 A B C D E F var cycles = [256]uint8{ 7, 6, 2, 1, 5, 3, 5, 1, 3, 2, 2, 1, 6, 4, 6, 1, // 0x 2, 5, 5, 1, 5, 4, 6, 1, 2, 4, 2, 1, 6, 4, 6, 1, // 1x 6, 6, 2, 1, 3, 3, 5, 1, 4, 2, 2, 1, 4, 4, 6, 1, // 2x 2, 5, 5, 1, 4, 4, 6, 1, 2, 4, 2, 1, 4, 4, 6, 1, // 3x 6, 6, 2, 1, 3, 3, 5, 1, 3, 2, 2, 1, 3, 4, 6, 1, // 4x 2, 5, 5, 1, 4, 4, 6, 1, 2, 4, 3, 1, 8, 4, 6, 1, // 5x 6, 6, 2, 1, 3, 3, 5, 1, 4, 2, 2, 1, 5, 4, 6, 1, // 6x 2, 5, 5, 1, 4, 4, 6, 1, 2, 4, 4, 1, 6, 4, 6, 1, // 7x 3, 6, 2, 1, 3, 3, 3, 1, 2, 2, 2, 1, 4, 4, 4, 1, // 8x 2, 6, 5, 1, 4, 4, 4, 1, 2, 5, 2, 1, 4, 5, 5, 1, // 9x 2, 6, 2, 1, 3, 3, 3, 1, 2, 2, 2, 1, 4, 4, 4, 1, // Ax 2, 5, 5, 1, 4, 4, 4, 1, 2, 4, 2, 1, 4, 4, 4, 1, // Bx 2, 6, 2, 1, 3, 3, 5, 1, 2, 2, 2, 1, 4, 4, 3, 1, // Cx 2, 5, 5, 1, 4, 4, 6, 1, 2, 4, 3, 1, 4, 4, 7, 1, // Dx 2, 6, 2, 1, 3, 3, 5, 1, 2, 2, 2, 1, 4, 4, 6, 1, // Ex 2, 5, 5, 1, 4, 4, 6, 1, 2, 4, 4, 1, 4, 4, 7, 1, // Fx } */ // String composes an instruction function into a string and returns // that func (i Instruction) String() string { var ( funcName = runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() parts = strings.Split(funcName, ".") ) return strings.ToUpper(parts[len(parts)-1]) } // Execute will process through one instruction and return. While doing // so, the CPU state will update such that it moves to the next // instruction. Note that the MOS 65C02 processor can execute // indefinitely; while there are definitely parts of memory that don't // really house opcodes (the zero page being one such part), the // processor would absolutely try to execute those if the PC register // pointed at those parts. And technically, if PC incremented beyond the // 0xFFFF address, it would simply overflow back to the zero page. func (c *CPU) Execute() error { var ( inst Instruction mode AddrMode tr trace.Trace ) c.counter++ c.Opcode = c.Get(c.PC) mode = addrModes[c.Opcode] inst = instructions[c.Opcode] // NOTE: neither the address mode resolver nor the instruction // handler have any error conditions. This is by design: they DO NOT // error out. They handle whatever situation comes up. // Resolve the values of EffAddr and EffVal by executing the address // mode handler. mode(c) disAvail := disasm.Available() asmAvail := asmrec.Available() if disAvail || asmAvail { writeTrace(c, &tr) } if disAvail { disasm.Map(int(c.PC), tr.String()) } if asmAvail { writeState(c, &tr) asmrec.Record(tr.String()) } // Now execute the instruction inst(c) // Adjust the program counter to beyond the expected instruction // sequence (1 byte for the opcode, + N bytes for the operand, based // on address mode). c.PC += offsets[c.Opcode] // We always apply BREAK and UNUSED after each execution, mostly in // observance for how other emulators have handled this step. c.P |= UNUSED | BREAK return nil } func writeTrace(c *CPU, tr *trace.Trace) { tr.Location = fmt.Sprintf(`%04X`, c.PC) tr.Counter = c.counter tr.Instruction = instructions[c.Opcode].String() tr.Operand = formatOperand(c.AddrMode, c.Operand, c.PC) } func writeState(c *CPU, tr *trace.Trace) { tr.State = fmt.Sprintf( `A:%02X X:%02X Y:%02X P:%02X S:%02X (%s) EA:%04X EV:%02X`, c.A, c.X, c.Y, c.P, c.S, formatStatus(c.P), c.EffAddr, c.EffVal, ) } func formatOperand(mode int, operand uint16, pc uint16) string { switch mode { case amAcc, amImp, amBy2, amBy3: return "" case amAbs: return fmt.Sprintf("$%04X", operand) case amAbx: return fmt.Sprintf("$%04X,X", operand) case amAby: return fmt.Sprintf("$%04X,Y", operand) case amIdx: return fmt.Sprintf("($%02X,X)", operand) case amIdy: return fmt.Sprintf("($%02X),Y", operand) case amInd: return fmt.Sprintf("($%04X)", operand) case amImm: return fmt.Sprintf("#$%02X", operand) case amRel: newAddr := pc + operand + 2 // It's signed, so the effect of the operand should be negative w/r/t // two's complement. if operand >= 0x80 { newAddr -= 256 } return fmt.Sprintf("$%04X", newAddr) case amZpg: return fmt.Sprintf("$%02X", operand) case amZpx: return fmt.Sprintf("$%02X,X", operand) case amZpy: return fmt.Sprintf("$%02X,Y", operand) } return "" } func formatStatus(p uint8) string { pstatus := []rune("NVUBDIZC") for i := 7; i >= 0; i-- { bit := (p >> uint(i)) & 1 if bit == 0 { pstatus[7-i] = '.' } } return string(pstatus) }
pkg/mos65c02/instruction.go
0.508544
0.478529
instruction.go
starcoder
package main import ( "image" "image/color" "math" "math/rand" ) // Given a source value and a stddev, return a mutated number // - insure that the abs val of the delta is at least 1 // - insure that the returned value is clamped to [mn,mx] func mutateNorm(src float64, sd float64, mn float64, mx float64) float64 { d := rand.NormFloat64() * sd if math.Abs(d) < 1.0 { if d < 0.0 { d = -1.0 } else { d = 1.0 } } newval := src + d if newval < mn { newval = mn } else if newval > mx { newval = mx } return newval } // Given a color coord (RGB), return a mutated coord func mutateColorCoord(c uint8) uint8 { return uint8(mutateNorm(float64(c), 5.0, 0.0, 255.0)) } // Mutation returns a mutated individual: WHICH IS CURRENTLY INPLACE func Mutation(ind *Individual, rate float64) *Individual { var clr *color.NRGBA // We can precompute these lim := ind.target.imageData.Bounds() mnx, mny := float64(lim.Min.X), float64(lim.Min.Y) mxx, mxy := float64(lim.Max.X), float64(lim.Max.Y) mutatePoint := func(p image.Point) image.Point { p.X = int(mutateNorm(float64(p.X), 6.0, mnx, mxx)) p.Y = int(mutateNorm(float64(p.Y), 6.0, mny, mxy)) return p } for _, curr := range ind.genes { // colors clr = curr.destColor if rand.Float64() <= rate { clr.R = mutateColorCoord(clr.R) } if rand.Float64() <= rate { clr.G = mutateColorCoord(clr.G) } if rand.Float64() <= rate { clr.B = mutateColorCoord(clr.B) } if rand.Float64() <= rate { clr.A = mutateColorCoord(clr.A) } // vertices for idx := range curr.destVertices { if rand.Float64() <= rate { curr.destVertices[idx] = mutatePoint(curr.destVertices[idx]) } } } return ind } // Shuffle provides a complete shuffle of the genome (since order matters) func Shuffle(ind *Individual) *Individual { clone := NewIndividual(ind.target, len(ind.genes)) for write, read := range rand.Perm(len(clone.genes)) { clone.genes[write] = ind.genes[read].Copy() } return clone }
mutation.go
0.754734
0.506774
mutation.go
starcoder
package iso20022 // Specifies rates. type CorporateActionRate74 struct { // Cash dividend amount per equity before deductions or allowances have been made. GrossDividendRate []*GrossDividendRateFormat23Choice `xml:"GrssDvddRate,omitempty"` // Cash dividend amount per equity after deductions or allowances have been made. NetDividendRate []*NetDividendRateFormat25Choice `xml:"NetDvddRate,omitempty"` // Public index rate applied to the amount paid to adjust it to inflation. IndexFactor *RateAndAmountFormat43Choice `xml:"IndxFctr,omitempty"` // Actual interest rate used for the payment of the interest for the specified interest period. InterestRateUsedForPayment []*InterestRateUsedForPaymentFormat9Choice `xml:"IntrstRateUsdForPmt,omitempty"` // A maximum percentage of shares available through the over subscription privilege, usually a percentage of the basic subscription shares, for example, an account owner subscribing to 100 shares may over subscribe to a maximum of 50 additional shares when the over subscription maximum is 50 percent. MaximumAllowedOversubscriptionRate *PercentageRate `xml:"MaxAllwdOvrsbcptRate,omitempty"` // Proportionate allocation used for the offer. ProrationRate *PercentageRate `xml:"PrratnRate,omitempty"` // Percentage of a cash distribution that will be withheld by the tax authorities of the jurisdiction of the issuer, for which a relief at source and/or reclaim may be possible. WithholdingTaxRate []*RateAndAmountFormat45Choice `xml:"WhldgTaxRate,omitempty"` // Rate at which the income will be withheld by a jurisdiction other than the jurisdiction of the issuer’s country of tax incorporation, for which a relief at source and/or reclaim may be possible. It is levied in complement or offset of the withholding tax rate (TAXR) levied by the jurisdiction of the issuer’s tax domicile. SecondLevelTax []*RateAndAmountFormat45Choice `xml:"ScndLvlTax,omitempty"` // Rate used for additional tax that cannot be categorised. AdditionalTax *RateAndAmountFormat43Choice `xml:"AddtlTax,omitempty"` // Amount included in the dividend/NAV that is identified as gains directly or indirectly derived from interest payments, for example, in the context of the EU Savings directive. TaxableIncomePerDividendShare []*RateTypeAndAmountAndStatus33 `xml:"TaxblIncmPerDvddShr,omitempty"` } func (c *CorporateActionRate74) AddGrossDividendRate() *GrossDividendRateFormat23Choice { newValue := new (GrossDividendRateFormat23Choice) c.GrossDividendRate = append(c.GrossDividendRate, newValue) return newValue } func (c *CorporateActionRate74) AddNetDividendRate() *NetDividendRateFormat25Choice { newValue := new (NetDividendRateFormat25Choice) c.NetDividendRate = append(c.NetDividendRate, newValue) return newValue } func (c *CorporateActionRate74) AddIndexFactor() *RateAndAmountFormat43Choice { c.IndexFactor = new(RateAndAmountFormat43Choice) return c.IndexFactor } func (c *CorporateActionRate74) AddInterestRateUsedForPayment() *InterestRateUsedForPaymentFormat9Choice { newValue := new (InterestRateUsedForPaymentFormat9Choice) c.InterestRateUsedForPayment = append(c.InterestRateUsedForPayment, newValue) return newValue } func (c *CorporateActionRate74) SetMaximumAllowedOversubscriptionRate(value string) { c.MaximumAllowedOversubscriptionRate = (*PercentageRate)(&value) } func (c *CorporateActionRate74) SetProrationRate(value string) { c.ProrationRate = (*PercentageRate)(&value) } func (c *CorporateActionRate74) AddWithholdingTaxRate() *RateAndAmountFormat45Choice { newValue := new (RateAndAmountFormat45Choice) c.WithholdingTaxRate = append(c.WithholdingTaxRate, newValue) return newValue } func (c *CorporateActionRate74) AddSecondLevelTax() *RateAndAmountFormat45Choice { newValue := new (RateAndAmountFormat45Choice) c.SecondLevelTax = append(c.SecondLevelTax, newValue) return newValue } func (c *CorporateActionRate74) AddAdditionalTax() *RateAndAmountFormat43Choice { c.AdditionalTax = new(RateAndAmountFormat43Choice) return c.AdditionalTax } func (c *CorporateActionRate74) AddTaxableIncomePerDividendShare() *RateTypeAndAmountAndStatus33 { newValue := new (RateTypeAndAmountAndStatus33) c.TaxableIncomePerDividendShare = append(c.TaxableIncomePerDividendShare, newValue) return newValue }
CorporateActionRate74.go
0.836755
0.610599
CorporateActionRate74.go
starcoder
package bls12381 import ( "errors" "github.com/cloudflare/circl/ecc/bls12381/ff" ) // Scalar represents positive integers in the range 0 <= x < Order. type Scalar = ff.Scalar const ScalarSize = ff.ScalarSize // Order returns the order of the pairing groups, returned as a big-endian slice. // Order = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001 func Order() []byte { return ff.ScalarOrder() } var ( bls12381 struct { // Let z be the BLS12 parameter. minusZ [8]byte // (-z), (integer big-endian). oneMinusZ [8]byte // (1-z), (integer big-endian). g1Check [16]byte // (z^2-1)/3, (integer big-endian). } g1Params struct{ b, _3b, genX, genY ff.Fp } g2Params struct{ b, _3b, genX, genY ff.Fp2 } // g1Isog11 is an isogeny of degree 11 from g1Iso(a,b) to G1 and is given // by rational maps: // g1Iso(a,b) --> G1 // (x,y,z) |-> (x,y,1) // (xNum/xDen, y * yNum/yDen, 1) // (xNum*yDen, y * yNum*xDen, z*xDen*yDen) // such that // xNum = \sum ai * x^i * z^(n-1-i), for 0 <= i < n, and n=12. // xDen = \sum bi * x^i * z^(n-1-i), for 0 <= i < n, and n=11. // yNum = \sum ci * x^i * z^(n-1-i), for 0 <= i < n, and n=16. // yDen = \sum di * x^i * z^(n-1-i), for 0 <= i < n, and n=16. g1Isog11 struct { a, b ff.Fp xNum [12]ff.Fp xDen [11]ff.Fp yNum [16]ff.Fp yDen [16]ff.Fp } // g2Isog3 is an isogeny of degree 3 from g2Iso(a,b) to G2 and is given // by rational maps: // g2Iso(a,b) --> G2 // (x,y,z) |-> (x,y,1) // (xNum/xDen, y * yNum/yDen, 1) // (xNum*yDen, y * yNum*xDen, z*xDen*yDen) // such that // xNum = \sum ai * x^i * z^(n-1-i), for 0 <= i < n, and n=4. // xDen = \sum bi * x^i * z^(n-1-i), for 0 <= i < n, and n=3. // yNum = \sum ci * x^i * z^(n-1-i), for 0 <= i < n, and n=4. // yDen = \sum di * x^i * z^(n-1-i), for 0 <= i < n, and n=4. g2Isog3 struct { a, b ff.Fp2 xNum [4]ff.Fp2 xDen [3]ff.Fp2 yNum [4]ff.Fp2 yDen [4]ff.Fp2 } g1sswu struct { Z ff.Fp // Z = 11. c1 [48]byte // integer c1 = (p - 3) / 4 (big-endian) c2 ff.Fp } g2sswu struct { Z ff.Fp2 // -(2 + I) c1 [95]byte // integer c1 = (p^2 - 9) / 16 (big-endian) c2 ff.Fp2 // sqrt(-1) c3 ff.Fp2 // sqrt(c2) c4 ff.Fp2 // sqrt(Z^3 / c3) c5 ff.Fp2 // sqrt(Z^3 / (c2 * c3)) } g1Sigma struct { beta0 ff.Fp // beta0 = F(2)^(2*(p-1)/3) where F = GF(p). beta1 ff.Fp // beta1 = F(2)^(1*(p-1)/3) where F = GF(p). } g2Psi struct { alpha ff.Fp2 // alpha = w^2/Frob(w^2) beta ff.Fp2 // beta = w^3/Frob(w^3) } ) var ( errInputLength = errors.New("incorrect input length") errEncoding = errors.New("incorrect encoding") ) func headerEncoding(isCompressed, isInfinity, isBigYCoord byte) byte { return (isBigYCoord&0x1)<<5 | (isInfinity&0x1)<<6 | (isCompressed&0x1)<<7 } func err(e error) { if e != nil { panic(e) } } func init() { bls12381.oneMinusZ = [8]byte{ // (big-endian) 0xd2, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, } bls12381.minusZ = [8]byte{ // (big-endian) 0xd2, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, } bls12381.g1Check = [16]byte{ // (big-endian) 0x39, 0x6c, 0x8c, 0x00, 0x55, 0x55, 0xe1, 0x56, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, 0x55, 0x55, } initG1Params() initG2Params() initG1Isog11() initG2Isog3() initG1sswu() initG2sswu() initSigma() initPsi() } func initG1Params() { g1Params.b.SetUint64(4) g1Params._3b.SetUint64(12) err(g1Params.genX.SetString("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb")) err(g1Params.genY.SetString("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")) } func initG2Params() { g2Params.b[0].SetUint64(4) g2Params.b[1].SetUint64(4) g2Params._3b[0].SetUint64(12) g2Params._3b[1].SetUint64(12) err(g2Params.genX[0].SetString("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8")) err(g2Params.genX[1].SetString("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")) err(g2Params.genY[0].SetString("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801")) err(g2Params.genY[1].SetString("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")) } func initG1Isog11() { err(g1Isog11.a.SetString("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")) err(g1Isog11.b.SetString("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")) err(g1Isog11.xNum[0].SetString("0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7")) err(g1Isog11.xNum[1].SetString("0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb")) err(g1Isog11.xNum[2].SetString("0x0d54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0")) err(g1Isog11.xNum[3].SetString("0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861")) err(g1Isog11.xNum[4].SetString("0x0e99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9")) err(g1Isog11.xNum[5].SetString("0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983")) err(g1Isog11.xNum[6].SetString("0x0d6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84")) err(g1Isog11.xNum[7].SetString("0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e")) err(g1Isog11.xNum[8].SetString("0x080d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317")) err(g1Isog11.xNum[9].SetString("0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e")) err(g1Isog11.xNum[10].SetString("0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b")) err(g1Isog11.xNum[11].SetString("0x06e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229")) err(g1Isog11.xDen[0].SetString("0x08ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c")) err(g1Isog11.xDen[1].SetString("0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff")) err(g1Isog11.xDen[2].SetString("0x0b2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19")) err(g1Isog11.xDen[3].SetString("0x03425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8")) err(g1Isog11.xDen[4].SetString("0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e")) err(g1Isog11.xDen[5].SetString("0x0e7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5")) err(g1Isog11.xDen[6].SetString("0x0772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a")) err(g1Isog11.xDen[7].SetString("0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e")) err(g1Isog11.xDen[8].SetString("0x0a10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641")) err(g1Isog11.xDen[9].SetString("0x095fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a")) g1Isog11.xDen[10].SetOne() err(g1Isog11.yNum[0].SetString("0x090d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33")) err(g1Isog11.yNum[1].SetString("0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696")) err(g1Isog11.yNum[2].SetString("0x00cc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6")) err(g1Isog11.yNum[3].SetString("0x01f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb")) err(g1Isog11.yNum[4].SetString("0x08cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb")) err(g1Isog11.yNum[5].SetString("0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0")) err(g1Isog11.yNum[6].SetString("0x04ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2")) err(g1Isog11.yNum[7].SetString("0x0987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29")) err(g1Isog11.yNum[8].SetString("0x09fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587")) err(g1Isog11.yNum[9].SetString("0x0e1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30")) err(g1Isog11.yNum[10].SetString("0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132")) err(g1Isog11.yNum[11].SetString("0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e")) err(g1Isog11.yNum[12].SetString("0x0b182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8")) err(g1Isog11.yNum[13].SetString("0x0245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133")) err(g1Isog11.yNum[14].SetString("0x05c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b")) err(g1Isog11.yNum[15].SetString("0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604")) err(g1Isog11.yDen[0].SetString("0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1")) err(g1Isog11.yDen[1].SetString("0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d")) err(g1Isog11.yDen[2].SetString("0x058df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2")) err(g1Isog11.yDen[3].SetString("0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416")) err(g1Isog11.yDen[4].SetString("0x0be0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d")) err(g1Isog11.yDen[5].SetString("0x08d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac")) err(g1Isog11.yDen[6].SetString("0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c")) err(g1Isog11.yDen[7].SetString("0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9")) err(g1Isog11.yDen[8].SetString("0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a")) err(g1Isog11.yDen[9].SetString("0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55")) err(g1Isog11.yDen[10].SetString("0x04d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8")) err(g1Isog11.yDen[11].SetString("0x0accbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092")) err(g1Isog11.yDen[12].SetString("0x0ad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc")) err(g1Isog11.yDen[13].SetString("0x02660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7")) err(g1Isog11.yDen[14].SetString("0x0e0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f")) g1Isog11.yDen[15].SetOne() } func initG2Isog3() { err(g2Isog3.a.SetString("0x00", "0xF0")) err(g2Isog3.b.SetString("0x03F4", "0x03F4")) err(g2Isog3.xNum[0].SetString( "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6", "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6", )) err(g2Isog3.xNum[1].SetString( "0x00", "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a", )) err(g2Isog3.xNum[2].SetString( "0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e", "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d", )) err(g2Isog3.xNum[3].SetString( "0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1", "0x00", )) err(g2Isog3.xDen[0].SetString( "0x00", "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63", )) err(g2Isog3.xDen[1].SetString( "0x0c", "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f", )) g2Isog3.xDen[2].SetOne() err(g2Isog3.yNum[0].SetString( "<KEY>", "<KEY>", )) err(g2Isog3.yNum[1].SetString( "0x00", "0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be", )) err(g2Isog3.yNum[2].SetString( "<KEY>", "0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f", )) err(g2Isog3.yNum[3].SetString( "0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10", "0x00", )) err(g2Isog3.yDen[0].SetString( "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb", "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb", )) err(g2Isog3.yDen[1].SetString( "0x00", "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3", )) err(g2Isog3.yDen[2].SetString( "0x12", "0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99", )) g2Isog3.yDen[3].SetOne() } func initG1sswu() { g1sswu.Z.SetUint64(11) g1sswu.c1 = [48]byte{ // (big-endian) 0x06, 0x80, 0x44, 0x7a, 0x8e, 0x5f, 0xf9, 0xa6, 0x92, 0xc6, 0xe9, 0xed, 0x90, 0xd2, 0xeb, 0x35, 0xd9, 0x1d, 0xd2, 0xe1, 0x3c, 0xe1, 0x44, 0xaf, 0xd9, 0xcc, 0x34, 0xa8, 0x3d, 0xac, 0x3d, 0x89, 0x07, 0xaa, 0xff, 0xff, 0xac, 0x54, 0xff, 0xff, 0xee, 0x7f, 0xbf, 0xff, 0xff, 0xff, 0xea, 0xaa, } err(g1sswu.c2.SetString("0x3d689d1e0e762cef9f2bec6130316806b4c80eda6fc10ce77ae83eab1ea8b8b8a407c9c6db195e06f2dbeabc2baeff5")) } func initG2sswu() { g2sswu.Z[1].SetUint64(1) g2sswu.Z[0].SetUint64(2) g2sswu.Z.Neg() g2sswu.c1 = [95]byte{ // (big-endian) 0x2a, 0x43, 0x7a, 0x4b, 0x8c, 0x35, 0xfc, 0x74, 0xbd, 0x27, 0x8e, 0xaa, 0x22, 0xf2, 0x5e, 0x9e, 0x2d, 0xc9, 0x0e, 0x50, 0xe7, 0x04, 0x6b, 0x46, 0x6e, 0x59, 0xe4, 0x93, 0x49, 0xe8, 0xbd, 0x05, 0x0a, 0x62, 0xcf, 0xd1, 0x6d, 0xdc, 0xa6, 0xef, 0x53, 0x14, 0x93, 0x30, 0x97, 0x8e, 0xf0, 0x11, 0xd6, 0x86, 0x19, 0xc8, 0x61, 0x85, 0xc7, 0xb2, 0x92, 0xe8, 0x5a, 0x87, 0x09, 0x1a, 0x04, 0x96, 0x6b, 0xf9, 0x1e, 0xd3, 0xe7, 0x1b, 0x74, 0x31, 0x62, 0xc3, 0x38, 0x36, 0x21, 0x13, 0xcf, 0xd7, 0xce, 0xd6, 0xb1, 0xd7, 0x63, 0x82, 0xea, 0xb2, 0x6a, 0xa0, 0x00, 0x01, 0xc7, 0x18, 0xe3, } err(g2sswu.c2.SetString("0x00", "0x01")) err(g2sswu.c3.SetString( "0x135203e60180a68ee2e9c448d77a2cd91c3dedd930b1cf60ef396489f61eb45e304466cf3e67fa0af1ee7b04121bdea2", "0x6af0e0437ff400b6831e36d6bd17ffe48395dabc2d3435e77f76e17009241c5ee67992f72ec05f4c81084fbede3cc09", )) err(g2sswu.c4.SetString( "0x699be3b8c6870965e5bf892ad5d2cc7b0e85a117402dfd83b7f4a947e02d978498255a2aaec0ac627b5afbdf1bf1c90", "0x8157cd83046453f5dd0972b6e3949e4288020b5b8a9cc99ca07e27089a2ce2436d965026adad3ef7baba37f2183e9b5", )) err(g2sswu.c5.SetString( "0xf5d0d63d2797471e6d39f306cc0dc0ab85de3bd9f39ce46f3649ac0de9e844417cc8de88716c1fd323fa68040801aea", "0xab1c2ffdd6c253ca155231eb3e71ba044fd562f6f72bc5bad5ec46a0b7a3b0247cf08ce6c6317f40edbc653a72dee17", )) } func initSigma() { err(g1Sigma.beta0.SetString("0x1a0111ea397fe699ec02408663d4de85aa0d857d89759ad4897d29650fb85f9b409427eb4f49fffd8bfd00000000aaac")) err(g1Sigma.beta1.SetString("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe")) } func initPsi() { // ratioKummer sets z = t/Frob(t) if it falls in Fp2, panics otherwise. ratioKummer := func(z *ff.Fp2, t *ff.Fp12) { var r ff.Fp12 r.Frob(t) r.Inv(&r) r.Mul(t, &r) if r[1].IsZero() != 1 || r[0][1].IsZero() != 1 || r[0][2].IsZero() != 1 { err(errors.New("failure of result to be in Fp2")) } *z = r[0][0] } w := &ff.Fp12{} w[1].SetOne() wsq := &ff.Fp12{} wsq.Sqr(w) ratioKummer(&g2Psi.alpha, wsq) wcube := &ff.Fp12{} wcube.Mul(wsq, w) ratioKummer(&g2Psi.beta, wcube) }
ecc/bls12381/constants.go
0.521959
0.457561
constants.go
starcoder
package formula import ( "fmt" "go/ast" "go/parser" "go/token" "math" "reflect" "runtime" "strconv" "strings" ) // astParser handles the parsing of the AST produced by parsing the formula passed into the astParser as an // AST expression. It 'links' functions and variables when they are encountered. type astParser struct { // formula is the formula that ought to be parsed. formula string // functions is a map of functions added to the formula which may be executed by the formula. The // functions are indexed by their names. functions map[string]availableFunc } // availableFunc represents a function that was made available to the function to use. type availableFunc struct { // function is the function that is called when the formula calls the function. function func(args ...float64) float64 // paramCount is the minimum parameter count that must be passed to this function. If the amount of // parameters passed is lower than paramCount, the function above is not called. paramCount int } // parse parses the formula in the astParser into a function that may be executed by passing a vars map into // it. If the parsing was not successful, an error is returned. func (p *astParser) parse() (eval func(vars vars) (float64, error), err error) { expr, err := parser.ParseExpr(p.formula) if err != nil { return nil, fmt.Errorf("error parsing expression: %v", err) } return p.parseExpr(expr) } // parseExpr parses the expression passed by checking what type it is and applying the correct parser. An // error is returned if the expression parsed returned one or if the expression was not one of the allowed // types. func (p *astParser) parseExpr(e ast.Expr) (eval func(vars vars) (float64, error), err error) { switch expr := e.(type) { case *ast.BasicLit: eval, err = p.parseBasicLit(expr) case *ast.Ident: eval, err = p.parseIdent(expr) case *ast.BinaryExpr: eval, err = p.parseBinaryExpr(expr) case *ast.ParenExpr: eval, err = p.parseParenExpr(expr) case *ast.CallExpr: eval, err = p.parseCallExpr(expr) default: return nil, fmt.Errorf("cannot parse unknown expression %v", reflect.TypeOf(e).Elem().String()) } return } // parseBinaryExpr parses a binary expression. This is an expression that has an operator in it to add, // subtract, multiply etc. Each binary expression only has one operator and 2 expressions. The AST package // splits the formula up correctly itself. func (p *astParser) parseBinaryExpr(expr *ast.BinaryExpr) (eval func(vars vars) (float64, error), err error) { x, err := p.parseExpr(expr.X) if err != nil { return nil, fmt.Errorf("cannot parse binary expression X: %v", err) } y, err := p.parseExpr(expr.Y) if err != nil { return nil, fmt.Errorf("cannot parse binary expression Y: %v", err) } switch expr.Op { case token.ADD: eval = func(vars vars) (float64, error) { x, err := x(vars) if err != nil { return x, err } y, err := y(vars) if err != nil { return y, err } return x + y, nil } case token.SUB: eval = func(vars vars) (float64, error) { x, err := x(vars) if err != nil { return x, err } y, err := y(vars) if err != nil { return y, err } return x - y, nil } case token.MUL: eval = func(vars vars) (float64, error) { x, err := x(vars) if err != nil { return x, err } y, err := y(vars) if err != nil { return y, err } return x * y, nil } case token.QUO: eval = func(vars vars) (float64, error) { x, err := x(vars) if err != nil { return x, err } y, err := y(vars) if err != nil { return y, err } return x / y, nil } case token.REM: eval = func(vars vars) (float64, error) { x, err := x(vars) if err != nil { return x, err } y, err := y(vars) if err != nil { return y, err } return math.Mod(x, y), nil } default: return nil, fmt.Errorf("unknown mathematical operation '%v'", expr.Op) } return } // parseBasicLit parses a basic literal, provided the literal is a numeric one, like a float or an integer. // Both integers and floats are parsed as a float64. func (p *astParser) parseBasicLit(lit *ast.BasicLit) (func(vars vars) (float64, error), error) { switch lit.Kind { case token.INT: val, err := strconv.Atoi(lit.Value) if err != nil { return nil, fmt.Errorf("invalid value for token.INT %v: %v", lit.Value, err) } value := float64(val) return wrapFunc(value), nil case token.FLOAT: val, err := strconv.ParseFloat(lit.Value, 64) if err != nil { return nil, fmt.Errorf("invalid value for token.FLOAT %v: %v", lit.Value, err) } return wrapFunc(val), nil default: return nil, fmt.Errorf("literal must be of type token.INT or token.FLOAT, got %v", lit.Kind) } } // parseIdent parses an identifier. (generally a variable that needs to be substituted with what is found in // the vars map passed) func (p *astParser) parseIdent(ident *ast.Ident) (func(vars vars) (float64, error), error) { return func(vars vars) (float64, error) { name := ident.Name value, ok := vars[name] if !ok { err := &ErrUnknownVariable{ Var: name, Pos: int(ident.NamePos) - 1, } return math.NaN(), err } return value, nil }, nil } // parseParenExpr parses an expression within parentheses and returns the function returned by the expression // within those parentheses. func (p *astParser) parseParenExpr(expr *ast.ParenExpr) (func(vars vars) (float64, error), error) { return p.parseExpr(expr.X) } // parseCallExpr parses a call expression. It parses all parameters inside of the function and evaluates them // when the function is evaluated. func (p *astParser) parseCallExpr(expr *ast.CallExpr) (func(vars vars) (float64, error), error) { args := make([]func(vars vars) (float64, error), len(expr.Args)) for i, arg := range expr.Args { f, err := p.parseExpr(arg) if err != nil { return nil, fmt.Errorf("error parsing function parameter: %v", err) } args[i] = f } return func(vars vars) (_ float64, rerr error) { funcName := expr.Fun.(*ast.Ident).Name // Catch panics within a registered function. defer func() { if r := recover(); r != nil { _, f, line, _ := runtime.Caller(3) err := &ErrPanic{ Func: funcName, Pos: int(expr.Lparen) - len(funcName) - 1, Reason: strings.TrimPrefix(fmt.Sprintf("%v", r), "runtime error: "), File: f, Line: line, } rerr = err } }() f, ok := p.functions[funcName] if !ok { err := &ErrUnknownFunc{ Func: funcName, Pos: int(expr.Lparen) - len(funcName) - 1, } return math.NaN(), err } if len(expr.Args) < f.paramCount { // Too few arguments supplied to the function. err := &ErrInsufficientArgs{ Func: funcName, Pos: int(expr.Lparen) - len(funcName) - 1, Actual: len(expr.Args), Expected: f.paramCount, } return math.NaN(), err } argValues := make([]float64, len(expr.Args)) for i, argValue := range args { av, err := argValue(vars) if err != nil { return av, err } argValues[i] = av } return f.function(argValues...), nil }, nil } // wrapFunc returns a function that wraps around the value passed and returns it. func wrapFunc(value float64) func(vars vars) (float64, error) { return func(vars vars) (float64, error) { return value, nil } }
v2/parser.go
0.617974
0.578805
parser.go
starcoder
package ahrs import ( "github.com/chewxy/math32" "github.com/itohio/EasyRobot/pkg/core/math/vec" ) type MadgwickAHRS struct { Options accel, gyro, mag vec.Vector3D q vec.Quaternion SamplePeriod float32 } func NewMadgwick(opts ...Option) AHRS { m := MadgwickAHRS{ Options: defaultOptions(), q: vec.Quaternion{1, 0, 0, 0}, } applyOptions(&m.Options, opts...) return &m } func (m *MadgwickAHRS) Acceleration() vec.Vector { return m.accel[:] } func (m *MadgwickAHRS) Gyroscope() vec.Vector { return m.gyro[:] } func (m *MadgwickAHRS) Magnetometer() vec.Vector { return m.mag[:] } func (m *MadgwickAHRS) Orientation() vec.Vector { return m.q[:] } func (m *MadgwickAHRS) Reset() AHRS { m.q.Vector().FillC(0) m.q[0] = 1 return m } func (m *MadgwickAHRS) Update(samplePeriod float32) AHRS { m.SamplePeriod = samplePeriod return m } func (m *MadgwickAHRS) Calculate() AHRS { if !(m.Options.HasAccelerator && m.Options.HasGyroscope) { panic(-1) } if !m.Options.HasMagnetometer { return m.calculateWOMag() } q1, q2, q3, q4 := m.q[0], m.q[1], m.q[2], m.q[3] // short name local variable for readability // Auxiliary variables to avoid repeated arithmetic _2q1 := 2 * q1 _2q2 := 2 * q2 _2q3 := 2 * q3 _2q4 := 2 * q4 _2q1q3 := 2 * q1 * q3 _2q3q4 := 2 * q3 * q4 q1q1 := q1 * q1 q1q2 := q1 * q2 q1q3 := q1 * q3 q1q4 := q1 * q4 q2q2 := q2 * q2 q2q3 := q2 * q3 q2q4 := q2 * q4 q3q3 := q3 * q3 q3q4 := q3 * q4 q4q4 := q4 * q4 // Normalise accelerometer measurement ax, ay, az := m.accel.Clone().NormalFast().XYZ() // Normalise magnetometer measurement mx, my, mz := m.mag.Clone().NormalFast().XYZ() // Reference direction of Earth's magnetic field _2q1mx := 2 * q1 * mx _2q1my := 2 * q1 * my _2q1mz := 2 * q1 * mz _2q2mx := 2 * q2 * mx hx := mx*q1q1 - _2q1my*q4 + _2q1mz*q3 + mx*q2q2 + _2q2*my*q3 + _2q2*mz*q4 - mx*q3q3 - mx*q4q4 hy := _2q1mx*q4 + my*q1q1 - _2q1mz*q2 + _2q2mx*q3 - my*q2q2 + my*q3q3 + _2q3*mz*q4 - my*q4q4 _2bx := math32.Sqrt(hx*hx + hy*hy) _2bz := -_2q1mx*q3 + _2q1my*q2 + mz*q1q1 + _2q2mx*q4 - mz*q2q2 + _2q3*my*q4 - mz*q3q3 + mz*q4q4 _4bx := 2 * _2bx _4bz := 2 * _2bz // Gradient decent algorithm corrective step s := vec.Quaternion{ -_2q3*(2*q2q4-_2q1q3-ax) + _2q2*(2*q1q2+_2q3q4-ay) - _2bz*q3*(_2bx*(0.5-q3q3-q4q4)+_2bz*(q2q4-q1q3)-mx) + (-_2bx*q4+_2bz*q2)*(_2bx*(q2q3-q1q4)+_2bz*(q1q2+q3q4)-my) + _2bx*q3*(_2bx*(q1q3+q2q4)+_2bz*(0.5-q2q2-q3q3)-mz), _2q4*(2*q2q4-_2q1q3-ax) + _2q1*(2*q1q2+_2q3q4-ay) - 4*q2*(1-2*q2q2-2*q3q3-az) + _2bz*q4*(_2bx*(0.5-q3q3-q4q4)+_2bz*(q2q4-q1q3)-mx) + (_2bx*q3+_2bz*q1)*(_2bx*(q2q3-q1q4)+_2bz*(q1q2+q3q4)-my) + (_2bx*q4-_4bz*q2)*(_2bx*(q1q3+q2q4)+_2bz*(0.5-q2q2-q3q3)-mz), -_2q1*(2*q2q4-_2q1q3-ax) + _2q4*(2*q1q2+_2q3q4-ay) - 4*q3*(1-2*q2q2-2*q3q3-az) + (-_4bx*q3-_2bz*q1)*(_2bx*(0.5-q3q3-q4q4)+_2bz*(q2q4-q1q3)-mx) + (_2bx*q2+_2bz*q4)*(_2bx*(q2q3-q1q4)+_2bz*(q1q2+q3q4)-my) + (_2bx*q1-_4bz*q3)*(_2bx*(q1q3+q2q4)+_2bz*(0.5-q2q2-q3q3)-mz), _2q2*(2*q2q4-_2q1q3-ax) + _2q3*(2*q1q2+_2q3q4-ay) + (-_4bx*q4+_2bz*q2)*(_2bx*(0.5-q3q3-q4q4)+_2bz*(q2q4-q1q3)-mx) + (-_2bx*q1+_2bz*q3)*(_2bx*(q2q3-q1q4)+_2bz*(q1q2+q3q4)-my) + _2bx*q2*(_2bx*(q1q3+q2q4)+_2bz*(0.5-q2q2-q3q3)-mz), } s.NormalFast() // Compute rate of change of quaternion m.q[0] = 0.5 * (-q2*m.gyro[0] - q3*m.gyro[1] - q4*m.gyro[2]) m.q[1] = 0.5 * (q1*m.gyro[0] + q3*m.gyro[2] - q4*m.gyro[1]) m.q[2] = 0.5 * (q1*m.gyro[1] - q2*m.gyro[2] + q4*m.gyro[0]) m.q[3] = 0.5 * (q1*m.gyro[2] + q2*m.gyro[1] - q3*m.gyro[0]) m.q.MulCSub(m.GainP, s) // Integrate to yield quaternion m.q.MulCAdd(m.SamplePeriod, m.q) m.q.NormalFast() return m } func (m *MadgwickAHRS) calculateWOMag() AHRS { q1, q2, q3, q4 := m.q[0], m.q[1], m.q[2], m.q[3] // short name local variable for readability // Auxiliary variables to avoid repeated arithmetic _2q1 := 2 * q1 _2q2 := 2 * q2 _2q3 := 2 * q3 _2q4 := 2 * q4 _4q1 := 4 * q1 _4q2 := 4 * q2 _4q3 := 4 * q3 _8q2 := 8 * q2 _8q3 := 8 * q3 q1q1 := q1 * q1 q2q2 := q2 * q2 q3q3 := q3 * q3 q4q4 := q4 * q4 // Normalise accelerometer measurement a := m.accel.Clone().NormalFast() // Gradient decent algorithm corrective step s := vec.Quaternion{ _4q1*q3q3 + _2q3*a[0] + _4q1*q2q2 - _2q2*a[1], _4q2*q4q4 - _2q4*a[0] + 4*q1q1*q2 - _2q1*a[1] - _4q2 + _8q2*q2q2 + _8q2*q3q3 + _4q2*a[2], 4*q1q1*q3 + _2q1*a[0] + _4q3*q4q4 - _2q4*a[1] - _4q3 + _8q3*q2q2 + _8q3*q3q3 + _4q3*a[2], 4*q2q2*q4 - _2q2*a[0] + 4*q3q3*q4 - _2q3*a[1], } s.NormalFast() // Compute rate of change of quaternion m.q[0] = 0.5 * (-q2*m.gyro[0] - q3*m.gyro[1] - q4*m.gyro[2]) m.q[1] = 0.5 * (q1*m.gyro[0] + q3*m.gyro[2] - q4*m.gyro[1]) m.q[2] = 0.5 * (q1*m.gyro[1] - q2*m.gyro[2] + q4*m.gyro[0]) m.q[3] = 0.5 * (q1*m.gyro[2] + q2*m.gyro[1] - q3*m.gyro[0]) m.q.MulCSub(m.GainP, s) // Integrate to yield quaternion m.q.MulCAdd(m.SamplePeriod, m.q) m.q.NormalFast() return m }
pkg/core/math/filter/ahrs/madgwick.go
0.7237
0.432003
madgwick.go
starcoder
package ode // #include <ode/ode.h> // extern int callTriCallback(dGeomID mesh, dGeomID other, int index); // extern int callTriRayCallback(dGeomID mesh, dGeomID ray, int index, dReal u, dReal v); import "C" import ( "unsafe" ) var ( triCallbacks = map[TriMesh]TriCallback{} triRayCallbacks = map[TriMesh]TriRayCallback{} ) // TriMeshData represents triangle mesh data. type TriMeshData uintptr func cToTriMeshData(c C.dTriMeshDataID) TriMeshData { return TriMeshData(unsafe.Pointer(c)) } func (t TriMeshData) c() C.dTriMeshDataID { return C.dTriMeshDataID(unsafe.Pointer(t)) } var ( vertexListMap = map[int]VertexList{} indexListMap = map[int]TriVertexIndexList{} ) // NewTriMeshData returns a new TriMeshData instance. func NewTriMeshData() TriMeshData { return cToTriMeshData(C.dGeomTriMeshDataCreate()) } // Destroy destroys the triangle mesh data. func (t TriMeshData) Destroy() { delete(vertexListMap, int(t)) delete(indexListMap, int(t)) C.dGeomTriMeshDataDestroy(t.c()) } // Build builds a triangle mesh from the given data. func (t TriMeshData) Build(verts VertexList, tris TriVertexIndexList) { delete(vertexListMap, int(t)) delete(indexListMap, int(t)) C.dGeomTriMeshDataBuildSimple(t.c(), (*C.dReal)(&verts[0][0]), C.int(len(verts)), (*C.dTriIndex)(&tris[0][0]), C.int(len(tris)*3)) vertexListMap[int(t)] = verts // avoid GC mark and sweep indexListMap[int(t)] = tris // avoid GC mark and sweep } // Preprocess preprocesses the triangle mesh data. func (t TriMeshData) Preprocess() { C.dGeomTriMeshDataPreprocess(t.c()) } // Update updates the triangle mesh data. func (t TriMeshData) Update() { C.dGeomTriMeshDataUpdate(t.c()) } // TriMesh is a geometry representing a triangle mesh. type TriMesh struct { GeomBase } // TriCallback is called to determine whether to collide a triangle with // another geometry. type TriCallback func(mesh TriMesh, other Geom, index int) bool //export triCallback func triCallback(c C.dGeomID, other C.dGeomID, index C.int) C.int { mesh := cToGeom(c).(TriMesh) cb, ok := triCallbacks[mesh] if !ok { return 0 } return C.int(btoi(cb(mesh, cToGeom(other), int(index)))) } // TriRayCallback is called to determine whether to collide a triangle with a // ray at a given point. type TriRayCallback func(mesh TriMesh, ray Ray, index int, u, v float64) bool //export triRayCallback func triRayCallback(c C.dGeomID, ray C.dGeomID, index C.int, u, v C.dReal) C.int { mesh := cToGeom(c).(TriMesh) cb, ok := triRayCallbacks[mesh] if !ok { return 0 } return C.int(btoi(cb(mesh, cToGeom(ray).(Ray), int(index), float64(u), float64(v)))) } // SetLastTransform sets the last transform. func (t TriMesh) SetLastTransform(xform Matrix4) { C.dGeomTriMeshSetLastTransform(t.c(), (*C.dReal)(&xform[0][0])) } // LastTransform returns the last transform. func (t TriMesh) LastTransform() Matrix4 { xform := NewMatrix4() c := C.dGeomTriMeshGetLastTransform(t.c()) Matrix(xform).fromC(c) return xform } // SetTriCallback sets the triangle collision callback. func (t TriMesh) SetTriCallback(cb TriCallback) { if cb == nil { C.dGeomTriMeshSetCallback(t.c(), nil) // clear callback delete(triCallbacks, t) } else { triCallbacks[t] = cb C.dGeomTriMeshSetCallback(t.c(), (*C.dTriCallback)(C.callTriCallback)) } } // TriCallback returns the triangle collision callback. func (t TriMesh) TriCallback() TriCallback { return triCallbacks[t] } // SetTriRayCallback sets the triangle/ray collision callback. func (t TriMesh) SetTriRayCallback(cb TriRayCallback) { if cb == nil { C.dGeomTriMeshSetCallback(t.c(), nil) // clear callback delete(triRayCallbacks, t) } else { triRayCallbacks[t] = cb C.dGeomTriMeshSetRayCallback(t.c(), (*C.dTriRayCallback)(C.callTriRayCallback)) } } // TriRayCallback returns the triangle/ray collision callback. func (t TriMesh) TriRayCallback() TriRayCallback { return triRayCallbacks[t] } // SetMeshData sets the mesh data. func (t TriMesh) SetMeshData(data TriMeshData) { C.dGeomTriMeshSetData(t.c(), data.c()) } // MeshData returns the mesh data. func (t TriMesh) MeshData() TriMeshData { return cToTriMeshData(C.dGeomTriMeshGetData(t.c())) } // SetTCEnabled sets whether temporal coherence is enabled for the given // geometry class. func (t TriMesh) SetTCEnabled(class int, isEnabled bool) { C.dGeomTriMeshEnableTC(t.c(), C.int(class), C.int(btoi(isEnabled))) } // TCEnabled returns whether temporal coherence is enabled for the given // geometry class. func (t TriMesh) TCEnabled(class int) bool { return C.dGeomTriMeshIsTCEnabled(t.c(), C.int(class)) != 0 } // ClearTCCache clears the temporal coherence cache. func (t TriMesh) ClearTCCache() { C.dGeomTriMeshClearTCCache(t.c()) } // Triangle returns a triangle in the mesh by index. func (t TriMesh) Triangle(index int) (Vector3, Vector3, Vector3) { c0, c1, c2 := &C.dVector3{}, &C.dVector3{}, &C.dVector3{} v0, v1, v2 := NewVector3(), NewVector3(), NewVector3() C.dGeomTriMeshGetTriangle(t.c(), C.int(index), c0, c1, c2) Vector(v0).fromC(&c0[0]) Vector(v1).fromC(&c1[0]) Vector(v2).fromC(&c2[0]) return v0, v1, v2 } // Point returns a point on the specified triangle at the given barycentric coordinates. func (t TriMesh) Point(index int, u, v float64) Vector3 { pt := NewVector3() C.dGeomTriMeshGetPoint(t.c(), C.int(index), C.dReal(u), C.dReal(v), (*C.dReal)(&pt[0])) return pt } // TriangleCount returns the number of triangles in the mesh. func (t TriMesh) TriangleCount() int { return int(C.dGeomTriMeshGetTriangleCount(t.c())) }
trimesh.go
0.745028
0.611295
trimesh.go
starcoder
package holidays import ( "errors" "fmt" "time" ) type Region string const ( Bangkok Region = "Bangkok" Berlin Region = "Berlin" Bulgaria Region = "Bulgaria" California Region = "California" NewYork Region = "New York" ) var ( NoHoliday = errors.New("No holiday") orthodoxEaster = map[int]time.Time{ 2013: time.Date(2013, 5, 5, 0, 0, 0, 0, time.UTC), 2014: time.Date(2013, 4, 20, 0, 0, 0, 0, time.UTC), 2015: time.Date(2013, 4, 12, 0, 0, 0, 0, time.UTC), 2016: time.Date(2013, 5, 1, 0, 0, 0, 0, time.UTC), 2017: time.Date(2013, 4, 16, 0, 0, 0, 0, time.UTC), 2018: time.Date(2013, 4, 8, 0, 0, 0, 0, time.UTC), } ) type holiday struct { Name string } func Holiday(t time.Time, r Region) (holiday, error) { day := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) switch r { case Bangkok: return holidayBangkok(day) case Berlin: return holidayBerlin(day) case Bulgaria: return holidayBulgaria(day) case California: return holidayUSA(day) case NewYork: return holidayUSA(day) } return holiday{}, errors.New("Region not supported") } func holidayBangkok(t time.Time) (holiday, error) { return holiday{}, NoHoliday } func holidayBerlin(t time.Time) (holiday, error) { // fixed if t.Day() == 1 && t.Month() == time.January { return holiday{Name: "New Year's Day"}, nil } if t.Day() == 1 && t.Month() == time.May { return holiday{Name: "Labour Day"}, nil } if t.Day() == 3 && t.Month() == time.October { return holiday{Name: "German Unity Day"}, nil } if t.Day() == 25 && t.Month() == time.December { return holiday{Name: "Christmas Day"}, nil } if t.Day() == 26 && t.Month() == time.December { return holiday{Name: "St. Stephen's Day"}, nil } // dynamic eastern := Easter(t) if t.Equal(eastern) { return holiday{Name: "Easter"}, nil } if t.Equal(eastern.AddDate(0, 0, -2)) { return holiday{Name: "Good Friday"}, nil } if t.Equal(eastern.AddDate(0, 0, 1)) { return holiday{Name: "Easter Monday"}, nil } if t.Equal(eastern.AddDate(0, 0, 39)) { return holiday{Name: "Ascension Day"}, nil } if t.Equal(eastern.AddDate(0, 0, 50)) { return holiday{Name: "Whit Monday"}, nil } return holiday{}, NoHoliday } func holidayUSA(t time.Time) (holiday, error) { // US-wide if t.Day() == 1 && t.Month() == time.January { return holiday{Name: "New Year's Day"}, nil } if t.Day() == 4 && t.Month() == time.July { return holiday{Name: "Independence Day"}, nil } if t.Day() == 25 && t.Month() == time.December { return holiday{Name: "Christmas Day"}, nil } // US-wide/dynamic if t.Weekday() == time.Monday && t.Month() == time.September && nthDay(t) == 1 { return holiday{Name: "Labor Day"}, nil } if t.Weekday() == time.Thursday && t.Month() == time.November && nthDay(t) == 4 { return holiday{Name: "Thanksgiving Day"}, nil } if t.Weekday() == time.Friday && t.Month() == time.November && nthDay(t.AddDate(0, 0, -1)) == 4 { // "Friday after 4th Thursday in November" return holiday{Name: "Day after Thanksgiving"}, nil } if t.Weekday() == time.Monday && t.Month() == time.May && nthDayRev(t) == 1 { return holiday{Name: "Memorial Day"}, nil } if t.Weekday() == time.Monday && t.Month() == time.January && nthDay(t) == 3 { return holiday{Name: "<NAME> Jr. Day"}, nil } return holiday{}, NoHoliday } func holidayBulgaria(t time.Time) (holiday, error) { easter, ok := orthodoxEaster[t.Year()] if !ok { return holiday{}, fmt.Errorf("Don't know orthodox easter for year %d", t.Year()) } if t.Equal(easter) { return holiday{Name: "Easter"}, nil } if t.Equal(easter.AddDate(0, 0, -2)) { return holiday{Name: "Good Friday"}, nil } if t.Equal(easter.AddDate(0, 0, -1)) { return holiday{Name: "Easter Saturday"}, nil } if t.Equal(easter.AddDate(0, 0, 1)) { return holiday{Name: "Easter Monday"}, nil } if t.Day() == 1 && t.Month() == time.January { return holiday{Name: "New Year's Day"}, nil } if t.Day() == 2 && t.Month() == time.January { return holiday{Name: "Day after New Year's Day"}, nil } if t.Day() == 3 && t.Month() == time.March { return holiday{Name: "Liberation Day"}, nil } if t.Day() == 1 && t.Month() == time.May { return holiday{Name: "Labour Day"}, nil } if t.Day() == 6 && t.Month() == time.May { return holiday{Name: "St. George's Day"}, nil } if t.Day() == 24 && t.Month() == time.May { return holiday{Name: "Bulgarian Education and Culture and Slavonic Literature Day"}, nil } if t.Day() == 6 && t.Month() == time.September { return holiday{Name: "Unification Day"}, nil } if t.Day() == 22 && t.Month() == time.September { return holiday{Name: "Independence Day"}, nil } if t.Day() == 1 && t.Month() == time.November { return holiday{Name: "Day of the Bulgarian Enlighteners"}, nil } if t.Day() == 24 && t.Month() == time.December { return holiday{Name: "Christmas Eve"}, nil } if t.Day() == 25 && t.Month() == time.December { return holiday{Name: "Christmas Day"}, nil } if t.Day() == 26 && t.Month() == time.December { return holiday{Name: "Second Day of Christmas"}, nil } return holiday{}, NoHoliday } //returns the number of the weekday in a month (is it the 1th, 2th.. Monday) func nthDay(t time.Time) (n int) { cDay := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) for cDay.Before(t) || cDay.Equal(t) { if cDay.Weekday() == t.Weekday() { n++ } cDay = cDay.AddDate(0, 0, 1) } return } func nthDayRev(t time.Time) (n int) { cDay := time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, t.Location()).AddDate(0, 0, -1) // last day in Month for cDay.After(t) || cDay.Equal(t) { if cDay.Weekday() == t.Weekday() { n++ } cDay = cDay.AddDate(0, 0, -1) } return } // -- http://rosettacode.org/wiki/Holidays_related_to_Easter#Goa func mod(a, n int) int { r := a % n if r < 0 { return r + n } return r } func Easter(t time.Time) time.Time { y := t.Year() c := y / 100 n := mod(y, 19) i := mod(c-c/4-(c-(c-17)/25)/3+19*n+15, 30) i -= (i / 28) * (1 - (i/28)*(29/(i+1))*((21-n)/11)) l := i - mod(y+y/4+i+2-c+c/4, 7) m := 3 + (l+40)/44 d := l + 28 - 31*(m/4) return time.Date(y, time.Month(m), d, 0, 0, 0, 0, t.Location()) } // --
holidays/holidays.go
0.553264
0.618896
holidays.go
starcoder
package model import ( "container/heap" "encoding/json" "fmt" "strings" ) // Heap is a min heap that implements heap.Interface. // It provides the methods PushHeap and PopHeap, so that clients don't need to use the heap package. // It also provides methods for cloning the heap, deleting items from the heap based on a condition function, and peeking at the head of the heap. type Heap struct { arr []interface{} value func(a interface{}) float64 } // NewHeap creates a new, empty, min Heap with the supplied function for computing the value used to order the heap. func NewHeap(valueFunc func(a interface{}) float64) *Heap { return &Heap{ arr: []interface{}{}, value: valueFunc, } } // AnyMatch checks if any items in the heap match the supplied predicate, and returns true if any item does. // This method will return true as soon as any matching item is found. // If the heap is empty, this method will return false. // The complexity is O(n) due to needing to potentially check all the items in the heap. func (h *Heap) AnyMatch(predicate func(x interface{}) bool) bool { for _, item := range h.arr { if predicate(item) { return true } } return false } // Clone creates a copy of the Heap, so that items can be added or removed from one heap without affecting the other heap. // The complexity is O(n) due to needing to copy all the items in the heap. func (h *Heap) Clone() *Heap { arrCopy := make([]interface{}, len(h.arr)) copy(arrCopy, h.arr) return &Heap{ arr: arrCopy, value: h.value, } } // Delete cleans up this heap by: unsetting the value function (since it may reference the object containing the heap), // deleting all entries in the heap that implement Deletable, and clearing the backing array. func (h *Heap) Delete() { h.value = nil for i, entry := range h.arr { if del, okay := entry.(Deletable); okay { del.Delete() } h.arr[i] = nil } h.arr = []interface{}{} } // DeleteAll creates a copy of the heap, only containing items that match the supplied condition; this modifies the original heap. // This returns all items that were deleted in an array. // "shouldDelete" needs to return true if the item should be deleted, false if it should be included in the copy. // The complexity is O(n) due to needing to check each entry for inclusion, then re-heapifying the remaining data. func (h *Heap) DeleteAll(shouldDelete func(x interface{}) bool) []interface{} { updated := make([]interface{}, 0, h.Len()) deleted := []interface{}{} for _, v := range h.arr { if shouldDelete(v) { deleted = append(deleted, v) } else { updated = append(updated, v) } } h.arr = updated heap.Init(h) return deleted } // GetValues returns all items in the heap. If any of the items in the heap (or the array) are modified, Heapify() should be called on this heap. func (h *Heap) GetValues() []interface{} { return h.arr } // Heapify ensures that the heap is ordered correctly. // The complexity is O(n) per heap.Init(). func (h *Heap) Heapify() { heap.Init(h) } // Push is required by heap.Interface, and is used by the heap package. // PushHeap or PushAll should be used instead of Push to add a new item to the heap, since this will not update the location of the new item to the correct position in the heap. func (h *Heap) Push(x interface{}) { h.arr = append(h.arr, x) } // PushAll adds all the supplied elements to the heap. // The complexity is O(n), where n is the number elements already in the heap + the number of elements in the supplied array. func (h *Heap) PushAll(x ...interface{}) { h.arr = append(h.arr, x...) heap.Init(h) } // PushAllFrom adds all the entries in the supplied heap to this heap. // The complexity is O(n), where n is the number elements already in the heap + the number of elements in the supplied array. func (h *Heap) PushAllFrom(other *Heap) { h.PushAll(other.arr...) } // PushHeap adds the supplied item to the heap at the correct location. // This wraps heap.Push so that clients don't need to be familiar with the heap package, and only need to use this class. // The complexity is O(log n). func (h *Heap) PushHeap(x interface{}) { heap.Push(h, x) } // Pop is required by heap.Interface, and is used by the heap package. // PopHeap should be used instead of Pop to remove an item from the heap, since this will not re-order the remaining heap. func (h *Heap) Pop() interface{} { lastIndex := h.Len() - 1 if lastIndex < 0 { return nil } toReturn := h.arr[lastIndex] h.arr = h.arr[:lastIndex] return toReturn } // PopHeap removes the next item from the heap (based the minimum value of any item when the configured value function is applied). // This wraps heap.Pop so that clients don't need to be familiar with the heap package, and only need to use this class. // The complexity is O(log n). func (h *Heap) PopHeap() interface{} { return heap.Pop(h) } // Peek retrieves the minimum value from the heap, without modifying the heap. The complexity is O(1). func (h *Heap) Peek() interface{} { if h.Len() <= 0 { return nil } return h.arr[0] } // Len retrieves the number of items, without modifying the heap. The complexity is O(1). func (h *Heap) Len() int { return len(h.arr) } // Less is required by heap.Interface and is used to compare items in the heap when sorting the heap. The complexity is O(1). func (h *Heap) Less(i int, j int) bool { return h.value(h.arr[i]) < h.value(h.arr[j]) } // ReplaceAll creates a copy of the heap, using the supplied function to replace items in the heap; this modifies the original heap. // "replaceFunction" should return one of the following: // - nil or an empty array if the item should be excluded, // - the original item if it should be retained unchanged, // - a single item that should replace the original item, or // - an array with one or more items that should replace the original item. // The complexity is O(n) due to needing to check each entry for replacement, then re-heapifying the updated data. func (h *Heap) ReplaceAll(replaceFunction func(x interface{}) interface{}) { updated := make([]interface{}, 0, h.Len()) for _, x := range h.arr { replacement := replaceFunction(x) if replacementArray, okay := replacement.([]interface{}); okay { updated = append(updated, replacementArray...) } else if replacement != nil { updated = append(updated, replacement) } } h.arr = updated heap.Init(h) } // Swap is required by heap.Interface and is used swap items in the heap when sorting the heap. The complexity is O(1). func (h *Heap) Swap(i int, j int) { if i >= 0 && j >= 0 { h.arr[i], h.arr[j] = h.arr[j], h.arr[i] } } // TrimN keeps the N minmimum entries in this heap and discards the rest. The complexity is O(numberToRetain * log(n)). func (h *Heap) TrimN(numberToRetain int) { if numberToRetain >= h.Len() || numberToRetain < 0 { return } updated := make([]interface{}, numberToRetain) for i := 0; i < numberToRetain; i++ { updated[i] = h.PopHeap() } h.arr = updated heap.Init(h) } func (h *Heap) String() string { str := "{" for i, entry := range h.arr { if i == 0 { str += entryString(entry) } else { str += "," + entryString(entry) } } return str + "}" } // entryString converts an entry in the heap to a string. func entryString(value interface{}) string { if p, okay := value.(fmt.Stringer); okay { return p.String() } else if jsonBytes, err := json.Marshal(value); err == nil && strings.Compare("null", string(jsonBytes)) != 0 { return string(jsonBytes) } else { return fmt.Sprintf("%v", value) } } var _ heap.Interface = (*Heap)(nil) var _ Deletable = (*Heap)(nil)
model/heap.go
0.801237
0.403714
heap.go
starcoder
package expression import ( "gopkg.in/src-d/go-errors.v1" "github.com/dolthub/go-mysql-server/sql" ) var ErrInvalidOffset = errors.NewKind("offset must be a non-negative integer; found: %v") // IsUnary returns whether the expression is unary or not. func IsUnary(e sql.Expression) bool { return len(e.Children()) == 1 } // IsBinary returns whether the expression is binary or not. func IsBinary(e sql.Expression) bool { return len(e.Children()) == 2 } // UnaryExpression is an expression that has only one children. type UnaryExpression struct { Child sql.Expression } // Children implements the Expression interface. func (p *UnaryExpression) Children() []sql.Expression { return []sql.Expression{p.Child} } // Resolved implements the Expression interface. func (p *UnaryExpression) Resolved() bool { return p.Child.Resolved() } // IsNullable returns whether the expression can be null. func (p *UnaryExpression) IsNullable() bool { return p.Child.IsNullable() } // BinaryExpression is an expression that has two children. type BinaryExpression struct { Left sql.Expression Right sql.Expression } // Children implements the Expression interface. func (p *BinaryExpression) Children() []sql.Expression { return []sql.Expression{p.Left, p.Right} } // Resolved implements the Expression interface. func (p *BinaryExpression) Resolved() bool { return p.Left.Resolved() && p.Right.Resolved() } // IsNullable returns whether the expression can be null. func (p *BinaryExpression) IsNullable() bool { return p.Left.IsNullable() || p.Right.IsNullable() } type NaryExpression struct { ChildExpressions []sql.Expression } // Children implements the Expression interface. func (n *NaryExpression) Children() []sql.Expression { return n.ChildExpressions } // Resolved implements the Expression interface. func (n *NaryExpression) Resolved() bool { for _, child := range n.Children() { if !child.Resolved() { return false } } return true } // IsNullable returns whether the expression can be null. func (n *NaryExpression) IsNullable() bool { for _, child := range n.Children() { if child.IsNullable() { return true } } return false } // ExpressionsResolve returns whether all the expressions in the slice given are resolved func ExpressionsResolved(exprs ...sql.Expression) bool { for _, e := range exprs { if !e.Resolved() { return false } } return true } func Dispose(e sql.Expression) { sql.Inspect(e, func(e sql.Expression) bool { sql.Dispose(e) return true }) } // LiteralToInt extracts a non-negative integer from an expression.Literal, or errors func LiteralToInt(e sql.Expression) (int, error) { lit, ok := e.(*Literal) if !ok { return 0, ErrInvalidOffset.New(e) } val := lit.Value() var offset int switch e := val.(type) { case int: offset = e case int8: offset = int(e) case int16: offset = int(e) case int32: offset = int(e) case int64: offset = int(e) default: return 0, ErrInvalidOffset.New(e) } if offset < 0 { return 0, ErrInvalidOffset.New(e) } return offset, nil }
sql/expression/common.go
0.821295
0.4165
common.go
starcoder
package dbtest import ( "context" "fmt" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" beaconlib "github.com/scionproto/scion/go/cs/beacon" dbtest "github.com/scionproto/scion/go/cs/beacon/beacondbtest" "github.com/scionproto/scion/go/lib/addr" "github.com/scionproto/scion/go/lib/slayers/path" "github.com/scionproto/scion/go/pkg/storage" "github.com/scionproto/scion/go/pkg/storage/beacon" ) var ( timeout = time.Second ) // TestableDB extends the beacon db interface with methods that are needed for testing. type TestableDB interface { storage.BeaconDB // We force all test implementations to implement cleanable. This ensures that we // explicitly have to opt-out of testing the clean-up functionality. This is a lot // safer than opting-in to testing it via interface smuggling. // To opt-out, simply define a "IgnoreCleanup" method on the type under test. beacon.Cleanable // Prepare should reset the internal state so that the db is empty and is ready to be tested. Prepare(*testing.T, context.Context) } // Run should be used to test any implementation of the storage.BeaconDB // interface. An implementation interface should at least have one test method // that calls this test-suite. func Run(t *testing.T, db TestableDB) { dbtest.Test(t, db) run(t, db) } func run(t *testing.T, db TestableDB) { t.Run("GetBeacons", func(t *testing.T) { testGetBeacons(t, db) }) t.Run("DeleteExpired should delete expired segments", func(t *testing.T) { if _, ok := db.(interface{ IgnoreCleanable() }); ok { t.Skip("Ignoring beacon cleaning test") } ctx, cancelF := context.WithTimeout(context.Background(), 2*time.Second) defer cancelF() db.Prepare(t, ctx) ts1 := uint32(10) ts2 := uint32(20) // defaultExp is the default expiry of the hopfields. defaultExp := path.ExpTimeToDuration(63) dbtest.InsertBeacon(t, db, dbtest.Info3, 12, ts1, beaconlib.UsageProp) dbtest.InsertBeacon(t, db, dbtest.Info2, 13, ts2, beaconlib.UsageProp) // No expired beacon deleted, err := db.DeleteExpiredBeacons(ctx, time.Unix(10, 0).Add(defaultExp)) require.NoError(t, err) assert.Equal(t, 0, deleted, "Deleted") // 1 expired deleted, err = db.DeleteExpiredBeacons(ctx, time.Unix(20, 0).Add(defaultExp)) require.NoError(t, err) assert.Equal(t, 1, deleted, "Deleted") // 1 expired deleted, err = db.DeleteExpiredBeacons(ctx, time.Unix(30, 0).Add(defaultExp)) require.NoError(t, err) assert.Equal(t, 1, deleted, "Deleted") }) } func testGetBeacons(t *testing.T, db TestableDB) { // Beacons in results are sorted from newest (3) to oldest (1). usages := []beaconlib.Usage{ beaconlib.UsageDownReg, beaconlib.UsageUpReg, beaconlib.UsageCoreReg | beaconlib.UsageUpReg, } var results []beacon.Beacon for i, info := range [][]dbtest.IfInfo{dbtest.Info4, dbtest.Info2, dbtest.Info3} { b, _ := dbtest.AllocBeacon(t, info, uint16(i), uint32(i+1)) results = append(results, beacon.Beacon{Beacon: b, Usage: usages[i]}) } insertBeacons := func(t *testing.T, db beaconlib.DB) { // reverse order because GetBeacons returns values LIFO by default for i := len(results) - 1; i >= 0; i-- { ctx, cancelF := context.WithTimeout(context.Background(), timeout) defer cancelF() _, err := db.InsertBeacon(ctx, results[i].Beacon, results[i].Usage) require.NoError(t, err) } } tests := map[string]struct { PrepareDB func(t *testing.T, ctx context.Context, db beaconlib.DB) Params beacon.QueryParams Expected []beacon.Beacon }{ "Empty result on empty DB": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) {}, Expected: []beacon.Beacon{}, }, "Returns all with zero params": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Expected: results, }, "Empty result for non-existing SegID": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ SegIDs: [][]byte{[]byte("I don't existz")}, }, Expected: []beacon.Beacon{}, }, "Filter by existing SegID": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ SegIDs: [][]byte{results[0].Beacon.Segment.ID()}, }, Expected: results[:1], }, "Filter by SegID prefixes": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ SegIDs: [][]byte{ results[0].Beacon.Segment.ID()[:4], results[1].Beacon.Segment.ID()[:1], }, }, Expected: results[:2], }, "Empty result for non-existing start IA": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ StartsAt: []addr.IA{addr.MustIAFrom(addr.MaxISD, 0)}, }, Expected: []beacon.Beacon{}, }, "Filter by existing start IA": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ StartsAt: []addr.IA{results[0].Beacon.Segment.FirstIA()}, }, Expected: results[:1], }, "Filter by start IA with wildcard AS": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ StartsAt: []addr.IA{addr.MustIAFrom(results[0].Beacon.Segment.FirstIA().ISD(), 0)}, }, Expected: results[:1], }, "Filter by start IA with wildcard ISD": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ StartsAt: []addr.IA{addr.MustIAFrom(0, results[0].Beacon.Segment.FirstIA().AS())}, }, Expected: results[:1], }, "Filter by start IA with wildcards": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ StartsAt: []addr.IA{addr.MustIAFrom(0, 0)}, }, Expected: results, }, "Filter by non-existing ingress interface ID": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ IngressInterfaces: []uint16{42}, }, Expected: []beacon.Beacon{}, }, "Filter by existing ingress interface ID": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ IngressInterfaces: []uint16{0}, }, Expected: results[:1], }, "Filter by non-existing Usage": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ Usages: []beaconlib.Usage{beaconlib.UsageProp}, }, Expected: []beacon.Beacon{}, }, "Filter by existing Usage": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ Usages: []beaconlib.Usage{beaconlib.UsageUpReg}, }, Expected: results[1:], }, "Filter by multiple Usages (intersection)": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ Usages: []beaconlib.Usage{beaconlib.UsageCoreReg | beaconlib.UsageUpReg}, }, Expected: results[2:], }, "Filter by multiple Usages (union)": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ Usages: []beaconlib.Usage{beaconlib.UsageDownReg, beaconlib.UsageCoreReg}, }, Expected: []beacon.Beacon{results[0], results[2]}, }, "Filter by ValidAt before creation": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ ValidAt: time.Unix(0, 0), }, Expected: []beacon.Beacon{}, }, "Filter by ValidAt after expiration": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ ValidAt: time.Unix(24*60*60, 0), }, Expected: []beacon.Beacon{}, }, "Filter by ValidAt": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{ ValidAt: time.Unix(2, 0), }, Expected: results[:2], }, "ValidAt ignored if Zero": { PrepareDB: func(t *testing.T, ctx context.Context, db beaconlib.DB) { insertBeacons(t, db) }, Params: beacon.QueryParams{}, Expected: results, }, } checkEqual := func(t *testing.T, expected []beacon.Beacon, actual []beacon.Beacon) { assert.Equal(t, len(expected), len(actual), "Results lengths") for i := range expected { dbtest.CheckResults(t, []beaconlib.Beacon{expected[i].Beacon}, []beaconlib.Beacon{actual[i].Beacon}, ) assert.Equal(t, expected[i].Usage, actual[i].Usage, fmt.Sprint("Usage of index ", i)) // Ignore differences in lastUpdated. } } for name, test := range tests { t.Run(name, func(t *testing.T) { ctx, cancelF := context.WithTimeout(context.Background(), timeout) defer cancelF() db.Prepare(t, ctx) test.PrepareDB(t, ctx, db) results, err := db.GetBeacons(ctx, &test.Params) require.NoError(t, err) checkEqual(t, test.Expected, results) }) } }
go/pkg/storage/beacon/dbtest/dbtest.go
0.598195
0.401717
dbtest.go
starcoder
package image import ( "image" "image/color" ) type Translate struct { image.Image Point image.Point } var _ image.Image = &Translate{} func (t *Translate) Bounds() image.Rectangle { return t.Image.Bounds().Add(t.Point) } func (t *Translate) At(x, y int) color.Color { return t.Image.At(x-t.Point.X, y-t.Point.Y) } type Flip struct { image.Image X bool Y bool } var _ image.Image = &Flip{} func (t *Flip) At(x, y int) color.Color { min := t.Bounds().Min max := t.Bounds().Max if t.X { x = max.X - (x - min.X) - 1 } if t.Y { y = max.Y - (y - min.Y) - 1 } return t.Image.At(x, y) } type Rotate struct { image.Image Count int } var _ image.Image = &Rotate{} func (t *Rotate) Bounds() image.Rectangle { if t.Count%2 == 0 { return t.Image.Bounds() } b := t.Image.Bounds() b.Max.X, b.Max.Y = b.Max.Y-b.Min.Y+b.Min.X, b.Max.X-b.Min.X+b.Min.Y return b } func (t *Rotate) At(x, y int) color.Color { min := t.Image.Bounds().Min max := t.Image.Bounds().Max switch t.Count % 4 { case 0: case 1: x, y = y-min.Y+min.X, max.Y-1-(x-min.X) case 2: x, y = max.X-1-(x-min.X), max.Y-1-(y-min.Y) case 3: x, y = max.X-1-(y-min.Y), (x-min.X)+min.Y } return t.Image.At(x, y) } type Group struct { images []image.Image bounds image.Rectangle model color.Model } type Blank struct { bounds image.Rectangle model color.Model } var _ image.Image = &Blank{} func BlankFromImage(img image.Image) *Blank { return &Blank{ bounds: img.Bounds(), model: img.ColorModel(), } } func (b *Blank) ColorModel() color.Model { return b.model } func (b *Blank) Bounds() image.Rectangle { return b.bounds } func (b *Blank) At(x, y int) color.Color { return color.Transparent } var _ image.Image = &Group{} func NewGroup(x ...image.Image) *Group { if len(x) == 0 { return nil } g := &Group{ images: x, model: x[0].ColorModel(), } size := image.Point{} for _, v := range x { s := v.Bounds().Size() if size.Y < s.Y { size.Y = s.Y } size.X += s.X } g.bounds.Max = size return g } func (g *Group) ColorModel() color.Model { return g.model } func (g *Group) Bounds() image.Rectangle { return g.bounds } func (g *Group) At(x, y int) color.Color { for _, v := range g.images { s := v.Bounds().Size() if x < s.X { min := v.Bounds().Min return v.At(min.X+x, min.Y+y) } x -= s.X } return nil } func Transform(img image.Image, rotate int, flip bool) image.Image { if flip { img = &Flip{Image: img, Y: true} } if rotate > 0 { img = &Rotate{Image: img, Count: rotate} } return img }
pkg/image/transform.go
0.732879
0.46217
transform.go
starcoder
package ewallet import ( "context" "github.com/ianeinser/xendit-go" ) // CreatePayment creates new payment func CreatePayment(data *CreatePaymentParams) (*xendit.EWallet, *xendit.Error) { return CreatePaymentWithContext(context.Background(), data) } // CreatePaymentWithContext creates new payment func CreatePaymentWithContext(ctx context.Context, data *CreatePaymentParams) (*xendit.EWallet, *xendit.Error) { client, err := getClient() if err != nil { return nil, err } return client.CreatePaymentWithContext(ctx, data) } // GetPaymentStatus gets one payment with its status func GetPaymentStatus(data *GetPaymentStatusParams) (*xendit.EWallet, *xendit.Error) { return GetPaymentStatusWithContext(context.Background(), data) } // GetPaymentStatusWithContext gets one payment with its status func GetPaymentStatusWithContext(ctx context.Context, data *GetPaymentStatusParams) (*xendit.EWallet, *xendit.Error) { client, err := getClient() if err != nil { return nil, err } return client.GetPaymentStatusWithContext(ctx, data) } // CreateEWalletCharge creates new e-wallet charge func CreateEWalletCharge(data *CreateEWalletChargeParams) (*xendit.EWalletCharge, *xendit.Error) { return CreateEWalletChargeWithContext(context.Background(), data) } // CreateEWalletChargeWithContext creates new e-wallet charge func CreateEWalletChargeWithContext(ctx context.Context, data *CreateEWalletChargeParams) (*xendit.EWalletCharge, *xendit.Error) { client, err := getClient() if err != nil { return nil, err } return client.CreateEWalletChargeWithContext(ctx, data) } // GetEWalletChargeStatus gets one e-wallet charge with its status func GetEWalletChargeStatus(data *GetEWalletChargeStatusParams) (*xendit.EWalletCharge, *xendit.Error) { return GetEWalletChargeStatusWithContext(context.Background(), data) } // GetEWalletChargeStatusWithContext gets one e-wallet with its status func GetEWalletChargeStatusWithContext(ctx context.Context, data *GetEWalletChargeStatusParams) (*xendit.EWalletCharge, *xendit.Error) { client, err := getClient() if err != nil { return nil, err } return client.GetEWalletChargeStatusWithContext(ctx, data) } func getClient() (*Client, *xendit.Error) { return &Client{ Opt: &xendit.Opt, APIRequester: xendit.GetAPIRequester(), }, nil }
ewallet/ewallet.go
0.527317
0.413892
ewallet.go
starcoder
package processor import ( "crypto/sha1" "crypto/sha256" "crypto/sha512" "fmt" "strconv" "time" "github.com/Jeffail/benthos/lib/log" "github.com/Jeffail/benthos/lib/metrics" "github.com/Jeffail/benthos/lib/response" "github.com/Jeffail/benthos/lib/types" "github.com/OneOfOne/xxhash" "github.com/opentracing/opentracing-go" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeHash] = TypeSpec{ constructor: NewHash, description: ` Hashes messages according to the selected algorithm. Supported algorithms are: sha256, sha512, sha1, xxhash64. This processor is mostly useful when combined with the ` + "[`process_field`](#process_field)" + ` processor as it allows you to hash a specific field of a document like this: ` + "``` yaml" + ` # Hash the contents of 'foo.bar' process_field: path: foo.bar processors: - hash: algorithm: sha256 ` + "```" + ``, } } //------------------------------------------------------------------------------ // HashConfig contains configuration fields for the Hash processor. type HashConfig struct { Parts []int `json:"parts" yaml:"parts"` Algorithm string `json:"algorithm" yaml:"algorithm"` } // NewHashConfig returns a HashConfig with default values. func NewHashConfig() HashConfig { return HashConfig{ Parts: []int{}, Algorithm: "sha256", } } //------------------------------------------------------------------------------ type hashFunc func(bytes []byte) ([]byte, error) func sha1Hash(b []byte) ([]byte, error) { hasher := sha1.New() hasher.Write(b) return hasher.Sum(nil), nil } func sha256Hash(b []byte) ([]byte, error) { hasher := sha256.New() hasher.Write(b) return hasher.Sum(nil), nil } func sha512Hash(b []byte) ([]byte, error) { hasher := sha512.New() hasher.Write(b) return hasher.Sum(nil), nil } func xxhash64Hash(b []byte) ([]byte, error) { h := xxhash.New64() h.Write(b) return []byte(strconv.FormatUint(h.Sum64(), 10)), nil } func strToHashr(str string) (hashFunc, error) { switch str { case "sha1": return sha1Hash, nil case "sha256": return sha256Hash, nil case "sha512": return sha512Hash, nil case "xxhash64": return xxhash64Hash, nil } return nil, fmt.Errorf("hash algorithm not recognised: %v", str) } //------------------------------------------------------------------------------ // Hash is a processor that can selectively hash parts of a message following a // chosen algorithm. type Hash struct { conf HashConfig fn hashFunc log log.Modular stats metrics.Type mCount metrics.StatCounter mErr metrics.StatCounter mSent metrics.StatCounter mBatchSent metrics.StatCounter } // NewHash returns a Hash processor. func NewHash( conf Config, mgr types.Manager, log log.Modular, stats metrics.Type, ) (Type, error) { cor, err := strToHashr(conf.Hash.Algorithm) if err != nil { return nil, err } return &Hash{ conf: conf.Hash, fn: cor, log: log, stats: stats, mCount: stats.GetCounter("count"), mErr: stats.GetCounter("error"), mSent: stats.GetCounter("sent"), mBatchSent: stats.GetCounter("batch.sent"), }, nil } //------------------------------------------------------------------------------ // ProcessMessage applies the processor to a message, either creating >0 // resulting messages or a response to be sent back to the message source. func (c *Hash) ProcessMessage(msg types.Message) ([]types.Message, types.Response) { c.mCount.Incr(1) newMsg := msg.Copy() proc := func(index int, span opentracing.Span, part types.Part) error { newPart, err := c.fn(part.Get()) if err == nil { newMsg.Get(index).Set(newPart) } else { c.log.Debugf("Failed to hash message part: %v\n", err) c.mErr.Incr(1) } return err } if newMsg.Len() == 0 { return nil, response.NewAck() } IteratePartsWithSpan(TypeHash, c.conf.Parts, newMsg, proc) c.mBatchSent.Incr(1) c.mSent.Incr(int64(newMsg.Len())) msgs := [1]types.Message{newMsg} return msgs[:], nil } // CloseAsync shuts down the processor and stops processing requests. func (c *Hash) CloseAsync() { } // WaitForClose blocks until the processor has closed down. func (c *Hash) WaitForClose(timeout time.Duration) error { return nil } //------------------------------------------------------------------------------
lib/processor/hash.go
0.739705
0.623062
hash.go
starcoder
package xex import ( "fmt" "strings" ) //Set up built-in string functions func registerStringBuiltins() { RegisterFunction( NewFunction( "string", FunctionDocumentation{ Text: `Converts an input into a string using fmt.Sprint`, Parameters: map[string]string{ "in": "The value to convert to a string.", }, }, func(in interface{}) string { return fmt.Sprint(in) }, ), ) RegisterFunction( NewFunction( "concat", FunctionDocumentation{ Text: `concatenates any number of strings returning a single string result`, Parameters: map[string]string{ "strs": "variadic - the strings to concatentate.", }, }, func(strs ...string) string { sb := strings.Builder{} for _, s := range strs { sb.WriteString(s) } return sb.String() }, ), ) RegisterFunction( NewFunction( "len", FunctionDocumentation{ Text: `returns the length of a string`, Parameters: map[string]string{ "in": "The string to measure.", }, }, func(in string) int { return len(in) }, ), ) RegisterFunction( NewFunction( "substring", FunctionDocumentation{ Text: `returns the substring of the input string from index1 to index2 -1. If index2 is zero, everything to the end of the string is returned`, Parameters: map[string]string{ "input": "The string take take a substring from.", "start": "The start index (counting from 0).", "end": "The end index. If this is less than 1, defaults to the end of the string.", }, }, func(input string, start, end int) string { if end < 1 { end = len(input) } return input[start:end] }, ), ) RegisterFunction( NewFunction( "instring", FunctionDocumentation{ Text: `returns the start position in the input string of the search string or -1 if the search string is not found`, Parameters: map[string]string{ "input": "The string to search.", "search": "The string to find in the input.", }, }, func(input, search string) int { return strings.Index(input, search) }, ), ) }
builtins_strings.go
0.630116
0.430447
builtins_strings.go
starcoder
package geometry import ( "errors" "fmt" pm_geojson "github.com/paulmach/go.geojson" "github.com/skelterjohn/geom" "github.com/tidwall/gjson" "github.com/whosonfirst/go-whosonfirst-geojson-v2" _ "log" _ "time" ) type Polygon struct { geojson.Polygon `json:",omitempty"` Exterior geom.Polygon `json:"exterior"` Interior []geom.Polygon `json:"interior"` } func (p Polygon) ExteriorRing() geom.Polygon { return p.Exterior } func (p Polygon) InteriorRings() []geom.Polygon { return p.Interior } func (p Polygon) ContainsCoord(c geom.Coord) bool { ext := p.ExteriorRing() if !ext.ContainsCoord(c) { return false } for _, int := range p.InteriorRings() { if int.ContainsCoord(c) { return false } } return true } func GeometryForFeature(f geojson.Feature) (*pm_geojson.Geometry, error) { geom_rsp := gjson.GetBytes(f.Bytes(), "geometry") return pm_geojson.UnmarshalGeometry([]byte(geom_rsp.String())) } func PolygonsForFeature(f geojson.Feature) ([]geojson.Polygon, error) { g, err := GeometryForFeature(f) if err != nil { return nil, err } polys := make([]geojson.Polygon, 0) switch g.Type { case "LineString": exterior_ring := newRing(g.LineString) polygon := Polygon{ Exterior: exterior_ring, } polys = []geojson.Polygon{polygon} case "Polygon": polygon := newPolygon(g.Polygon) polys = []geojson.Polygon{polygon} case "MultiPolygon": for _, poly := range g.MultiPolygon { polygon := newPolygon(poly) polys = append(polys, polygon) } case "Point": lat := g.Point[1] lon := g.Point[0] pt := []float64{ lon, lat, } coords := [][]float64{ pt, pt, pt, pt, pt, } exterior_ring := newRing(coords) if err != nil { return nil, err } interior_rings := make([]geom.Polygon, 0) polygon := Polygon{ Exterior: exterior_ring, Interior: interior_rings, } polys = []geojson.Polygon{polygon} return polys, nil case "MultiPoint": exterior_ring := newRing(g.MultiPoint) polygon := Polygon{ Exterior: exterior_ring, } polys = []geojson.Polygon{polygon} default: msg := fmt.Sprintf("Invalid geometry type '%s'", g.Type) return nil, errors.New(msg) } return polys, nil } func newRing(coords [][]float64) geom.Polygon { poly := geom.Polygon{} for _, pt := range coords { poly.AddVertex(geom.Coord{X: pt[0], Y: pt[1]}) } return poly } func newPolygon(rings [][][]float64) Polygon { exterior := newRing(rings[0]) interior := make([]geom.Polygon, 0) if len(rings) > 1 { for _, coords := range rings[1:] { interior = append(interior, newRing(coords)) } } polygon := Polygon{ Exterior: exterior, Interior: interior, } return polygon }
vendor/github.com/whosonfirst/go-whosonfirst-geojson-v2/geometry/polygon.go
0.762778
0.472623
polygon.go
starcoder
package perlin import ( "math" "math/rand" ) const ( defaultOctaves = 8 defaultPersistence = 0.5 ) var defaultNoise = New(0, defaultOctaves, defaultPersistence) func Noise1D(x float64) float64 { return defaultNoise.Noise1D(x) } func Noise2D(x, y float64) float64 { return defaultNoise.Noise2D(x, y) } func Noise3D(x, y, z float64) float64 { return defaultNoise.Noise3D(x, y, z) } type Perlin struct { p []int Octaves int Persistence float64 } func New(seed int64, octaves int, persistence float64) *Perlin { src := rand.NewSource(seed) rng := rand.New(src) p := make([]int, 512) copy(p, rng.Perm(256)) for i := 0; i < 0; i++ { p[256+i] = p[i] } return &Perlin{ p: p, Octaves: octaves, Persistence: persistence, } } func (perlin *Perlin) Noise1D(x float64) float64 { return perlin.Noise3D(x, 0, 0) } func (perlin *Perlin) Noise2D(x, y float64) float64 { return perlin.Noise3D(x, y, 0) } func (perlin *Perlin) Noise3D(x, y, z float64) float64 { var ( total float64 maxValue float64 frequency float64 = 1 amplitude float64 = 1 ) for i := 0; i < perlin.Octaves; i++ { total += perlin.noise(x*frequency, y*frequency, z*frequency) * amplitude maxValue += amplitude amplitude *= perlin.Persistence frequency *= 2 } return total / maxValue } func (perlin *Perlin) noise(x, y, z float64) float64 { xi := int(x) & 255 yi := int(y) & 255 zi := int(z) & 255 xf := x - math.Floor(x) yf := y - math.Floor(y) zf := z - math.Floor(z) u := fade(xf) v := fade(yf) w := fade(zf) p := perlin.p a := p[xi] + yi aa := p[a] + zi ab := p[a+1] + zi b := p[xi+1] + yi ba := p[b] + zi bb := p[b+1] + zi x1 := lerp(u, grad(p[aa], xf, yf, zf), grad(p[ba], xf-1, yf, zf)) x2 := lerp(u, grad(p[ab], xf, yf-1, zf), grad(p[bb], xf-1, yf-1, zf)) y1 := lerp(v, x1, x2) x3 := lerp(u, grad(p[aa+1], xf, yf, zf-1), grad(p[ba+1], xf-1, yf, zf-1)) x4 := lerp(u, grad(p[ab+1], xf, yf-1, zf-1), grad(p[bb+1], xf-1, yf-1, zf-1)) y2 := lerp(v, x3, x4) return (lerp(w, y1, y2) + 1) / 2 } func fade(t float64) float64 { // 6t^5 - 15t^4 + 10t^3x return t * t * t * (t*(t*6-15) + 10) } func lerp(t, a, b float64) float64 { return a + t*(b-a) } func grad(hash int, x, y, z float64) float64 { var u, v float64 h := hash & 15 if h < 8 { u = x } else { u = y } if h < 4 { v = y } else if h == 12 || h == 14 { v = x } else { v = z } var g float64 if (h & 1) == 0 { g += u } else { g -= u } if (h & 2) == 0 { g += v } else { g -= v } return g }
perlin.go
0.600657
0.442094
perlin.go
starcoder
package digraph import () // Nodes is a convenience wrapper aroung NodeItr for chained methods type Nodes struct { NodeIterator } // All returns all remaining nodes func (n Nodes) All() []Node { ret := make([]Node, 0) for n.HasNext() { ret = append(ret, n.Next()) } return ret } // NodeIterator iterates through a list of nodes type NodeIterator interface { // Returns if there are more nodes to go through HasNext() bool // If HasNext is true, returns the next node and advances. Otherwise, panics Next() Node } type nodeSliceIterator struct { Nodes []Node } func (a *nodeSliceIterator) HasNext() bool { return len(a.Nodes) > 0 } func (a *nodeSliceIterator) Next() Node { ret := a.Nodes[0]; a.Nodes = a.Nodes[1:]; return ret } type filterNodes struct { source NodeIterator filter func(Node) bool nextReady bool next Node } func (a *filterNodes) adv() { if a.nextReady { return } a.nextReady = true a.next = nil for a.source.HasNext() { node := a.source.Next() if a.filter(node) { a.next = node return } } } func (a *filterNodes) HasNext() bool { a.adv() return a.next != nil } func (a *filterNodes) Next() Node { a.adv() if a.next == nil { panic("Next node not available") } a.nextReady = false return a.next } // Select returns a subset of the given nodes containing only those nodes selected by the predicate func (n Nodes) Select(predicate func(Node) bool) Nodes { return Nodes{&filterNodes{source: n, filter: predicate}} } // NewNodeSliceIterator returns a Nodes for the given array of nodes func NewNodeSliceIterator(nodes ...Node) Nodes { return Nodes{&nodeSliceIterator{Nodes: nodes}} } // nodeWalkIterator walk through the nodes by following edges type nodeWalkIterator struct { seen map[Node]struct{} queue []Node } func (n *nodeWalkIterator) HasNext() bool { for { if len(n.queue) == 0 { return false } if _, seen := n.seen[n.queue[0]]; seen { n.queue = n.queue[1:] } else { // First element of the queue was not seen, return true return true } } } func (n *nodeWalkIterator) Next() Node { for { if _, seen := n.seen[n.queue[0]]; seen { n.queue = n.queue[1:] } else { break } } // queue[0] is not seen node := n.queue[0] n.queue = n.queue[1:] n.seen[node] = struct{}{} for edges := node.Out(); edges.HasNext(); { edge := edges.Next() next := edge.GetTo() if _, s := n.seen[next]; !s { n.queue = append(n.queue, next) } } return node } // NewNodeWalkIterator returns a Nodes that walks through all the // nodes accessible from the given nodes func NewNodeWalkIterator(nodes ...Node) Nodes { return Nodes{&nodeWalkIterator{seen: make(map[Node]struct{}), queue: nodes}} } // Unique filters the nodes so only unique nodes are returned func (n Nodes) Unique() Nodes { seen := make(map[Node]struct{}) return n.Select(func(node Node) bool { _, ok := seen[node] if !ok { seen[node] = struct{}{} } return !ok }) } // NodesByLabelPredicate returns a predicate that select nodes by label. This is to be used in Nodes.Select func NodesByLabelPredicate(id interface{}) func(Node) bool { return func(n Node) bool { return n.GetLabel() == id } } // Edges is a wrapper around edge iterator type Edges struct { EdgeIterator } // All returns all remaining edges func (e Edges) All() []Edge { ret := make([]Edge, 0) for e.HasNext() { ret = append(ret, e.Next()) } return ret } type edgeNodeSelector struct { source EdgeIterator selectNode func(Edge) Node } func (e *edgeNodeSelector) HasNext() bool { return e.source.HasNext() } func (e *edgeNodeSelector) Next() Node { return e.selectNode(e.source.Next()) } // Targets returns a node iterator that goes through the target nodes func (e Edges) Targets() Nodes { return Nodes{&edgeNodeSelector{source: e, selectNode: func(e Edge) Node { return e.GetTo() }}}.Unique() } // EdgeIterator iterates through a list of edges type EdgeIterator interface { // Returns if there are more edges to go through HasNext() bool // If HasNext is true, returns the next edge and advances. Otherwise panics Next() Edge } type edgeSliceIterator struct { Edges []Edge } func (e *edgeSliceIterator) HasNext() bool { return len(e.Edges) > 0 } func (e *edgeSliceIterator) Next() Edge { ret := e.Edges[0]; e.Edges = e.Edges[1:]; return ret } // NewEdges returns an edge iterator for the edges func NewEdges(edge ...Edge) Edges { return Edges{&edgeSliceIterator{Edges: edge}} } type filterEdges struct { source EdgeIterator filter func(Edge) bool nextReady bool next Edge } func (a *filterEdges) adv() { if a.nextReady { return } a.nextReady = true a.next = nil for a.source.HasNext() { edge := a.source.Next() if a.filter(edge) { a.next = edge return } } } func (a *filterEdges) HasNext() bool { a.adv() return a.next != nil } func (a *filterEdges) Next() Edge { a.adv() if a.next == nil { panic("Next edge not available") } a.nextReady = false return a.next } // Select returns a subset of the given edges containing only those edges selected by the predicate func (e Edges) Select(predicate func(Edge) bool) Edges { return Edges{&filterEdges{source: e, filter: predicate}} }
itr.go
0.754192
0.473414
itr.go
starcoder
package Example import ( flatbuffers "github.com/google/flatbuffers/go" MyGame "MyGame" ) /// an example documentation comment: "monster object" type MonsterT struct { Pos *Vec3T Mana int16 Hp int16 Name string Inventory []byte Color Color Test *AnyT Test4 []*TestT Testarrayofstring []string Testarrayoftables []*MonsterT Enemy *MonsterT Testnestedflatbuffer []byte Testempty *StatT Testbool bool Testhashs32Fnv1 int32 Testhashu32Fnv1 uint32 Testhashs64Fnv1 int64 Testhashu64Fnv1 uint64 Testhashs32Fnv1a int32 Testhashu32Fnv1a uint32 Testhashs64Fnv1a int64 Testhashu64Fnv1a uint64 Testarrayofbools []bool Testf float32 Testf2 float32 Testf3 float32 Testarrayofstring2 []string Testarrayofsortedstruct []*AbilityT Flex []byte Test5 []*TestT VectorOfLongs []int64 VectorOfDoubles []float64 ParentNamespaceTest *MyGame.InParentNamespaceT VectorOfReferrables []*ReferrableT SingleWeakReference uint64 VectorOfWeakReferences []uint64 VectorOfStrongReferrables []*ReferrableT CoOwningReference uint64 VectorOfCoOwningReferences []uint64 NonOwningReference uint64 VectorOfNonOwningReferences []uint64 AnyUnique *AnyUniqueAliasesT AnyAmbiguous *AnyAmbiguousAliasesT VectorOfEnums []Color SignedEnum Race Testrequirednestedflatbuffer []byte ScalarKeySortedTables []*StatT } func (t *MonsterT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { if t == nil { return 0 } nameOffset := builder.CreateString(t.Name) inventoryOffset := flatbuffers.UOffsetT(0) if t.Inventory != nil { inventoryOffset = builder.CreateByteString(t.Inventory) } testOffset := t.Test.Pack(builder) test4Offset := flatbuffers.UOffsetT(0) if t.Test4 != nil { test4Length := len(t.Test4) MonsterStartTest4Vector(builder, test4Length) for j := test4Length - 1; j >= 0; j-- { t.Test4[j].Pack(builder) } test4Offset = builder.EndVector(test4Length) } testarrayofstringOffset := flatbuffers.UOffsetT(0) if t.Testarrayofstring != nil { testarrayofstringLength := len(t.Testarrayofstring) testarrayofstringOffsets := make([]flatbuffers.UOffsetT, testarrayofstringLength) for j := 0; j < testarrayofstringLength; j++ { testarrayofstringOffsets[j] = builder.CreateString(t.Testarrayofstring[j]) } MonsterStartTestarrayofstringVector(builder, testarrayofstringLength) for j := testarrayofstringLength - 1; j >= 0; j-- { builder.PrependUOffsetT(testarrayofstringOffsets[j]) } testarrayofstringOffset = builder.EndVector(testarrayofstringLength) } testarrayoftablesOffset := flatbuffers.UOffsetT(0) if t.Testarrayoftables != nil { testarrayoftablesLength := len(t.Testarrayoftables) testarrayoftablesOffsets := make([]flatbuffers.UOffsetT, testarrayoftablesLength) for j := 0; j < testarrayoftablesLength; j++ { testarrayoftablesOffsets[j] = t.Testarrayoftables[j].Pack(builder) } MonsterStartTestarrayoftablesVector(builder, testarrayoftablesLength) for j := testarrayoftablesLength - 1; j >= 0; j-- { builder.PrependUOffsetT(testarrayoftablesOffsets[j]) } testarrayoftablesOffset = builder.EndVector(testarrayoftablesLength) } enemyOffset := t.Enemy.Pack(builder) testnestedflatbufferOffset := flatbuffers.UOffsetT(0) if t.Testnestedflatbuffer != nil { testnestedflatbufferOffset = builder.CreateByteString(t.Testnestedflatbuffer) } testemptyOffset := t.Testempty.Pack(builder) testarrayofboolsOffset := flatbuffers.UOffsetT(0) if t.Testarrayofbools != nil { testarrayofboolsLength := len(t.Testarrayofbools) MonsterStartTestarrayofboolsVector(builder, testarrayofboolsLength) for j := testarrayofboolsLength - 1; j >= 0; j-- { builder.PrependBool(t.Testarrayofbools[j]) } testarrayofboolsOffset = builder.EndVector(testarrayofboolsLength) } testarrayofstring2Offset := flatbuffers.UOffsetT(0) if t.Testarrayofstring2 != nil { testarrayofstring2Length := len(t.Testarrayofstring2) testarrayofstring2Offsets := make([]flatbuffers.UOffsetT, testarrayofstring2Length) for j := 0; j < testarrayofstring2Length; j++ { testarrayofstring2Offsets[j] = builder.CreateString(t.Testarrayofstring2[j]) } MonsterStartTestarrayofstring2Vector(builder, testarrayofstring2Length) for j := testarrayofstring2Length - 1; j >= 0; j-- { builder.PrependUOffsetT(testarrayofstring2Offsets[j]) } testarrayofstring2Offset = builder.EndVector(testarrayofstring2Length) } testarrayofsortedstructOffset := flatbuffers.UOffsetT(0) if t.Testarrayofsortedstruct != nil { testarrayofsortedstructLength := len(t.Testarrayofsortedstruct) MonsterStartTestarrayofsortedstructVector(builder, testarrayofsortedstructLength) for j := testarrayofsortedstructLength - 1; j >= 0; j-- { t.Testarrayofsortedstruct[j].Pack(builder) } testarrayofsortedstructOffset = builder.EndVector(testarrayofsortedstructLength) } flexOffset := flatbuffers.UOffsetT(0) if t.Flex != nil { flexOffset = builder.CreateByteString(t.Flex) } test5Offset := flatbuffers.UOffsetT(0) if t.Test5 != nil { test5Length := len(t.Test5) MonsterStartTest5Vector(builder, test5Length) for j := test5Length - 1; j >= 0; j-- { t.Test5[j].Pack(builder) } test5Offset = builder.EndVector(test5Length) } vectorOfLongsOffset := flatbuffers.UOffsetT(0) if t.VectorOfLongs != nil { vectorOfLongsLength := len(t.VectorOfLongs) MonsterStartVectorOfLongsVector(builder, vectorOfLongsLength) for j := vectorOfLongsLength - 1; j >= 0; j-- { builder.PrependInt64(t.VectorOfLongs[j]) } vectorOfLongsOffset = builder.EndVector(vectorOfLongsLength) } vectorOfDoublesOffset := flatbuffers.UOffsetT(0) if t.VectorOfDoubles != nil { vectorOfDoublesLength := len(t.VectorOfDoubles) MonsterStartVectorOfDoublesVector(builder, vectorOfDoublesLength) for j := vectorOfDoublesLength - 1; j >= 0; j-- { builder.PrependFloat64(t.VectorOfDoubles[j]) } vectorOfDoublesOffset = builder.EndVector(vectorOfDoublesLength) } parentNamespaceTestOffset := t.ParentNamespaceTest.Pack(builder) vectorOfReferrablesOffset := flatbuffers.UOffsetT(0) if t.VectorOfReferrables != nil { vectorOfReferrablesLength := len(t.VectorOfReferrables) vectorOfReferrablesOffsets := make([]flatbuffers.UOffsetT, vectorOfReferrablesLength) for j := 0; j < vectorOfReferrablesLength; j++ { vectorOfReferrablesOffsets[j] = t.VectorOfReferrables[j].Pack(builder) } MonsterStartVectorOfReferrablesVector(builder, vectorOfReferrablesLength) for j := vectorOfReferrablesLength - 1; j >= 0; j-- { builder.PrependUOffsetT(vectorOfReferrablesOffsets[j]) } vectorOfReferrablesOffset = builder.EndVector(vectorOfReferrablesLength) } vectorOfWeakReferencesOffset := flatbuffers.UOffsetT(0) if t.VectorOfWeakReferences != nil { vectorOfWeakReferencesLength := len(t.VectorOfWeakReferences) MonsterStartVectorOfWeakReferencesVector(builder, vectorOfWeakReferencesLength) for j := vectorOfWeakReferencesLength - 1; j >= 0; j-- { builder.PrependUint64(t.VectorOfWeakReferences[j]) } vectorOfWeakReferencesOffset = builder.EndVector(vectorOfWeakReferencesLength) } vectorOfStrongReferrablesOffset := flatbuffers.UOffsetT(0) if t.VectorOfStrongReferrables != nil { vectorOfStrongReferrablesLength := len(t.VectorOfStrongReferrables) vectorOfStrongReferrablesOffsets := make([]flatbuffers.UOffsetT, vectorOfStrongReferrablesLength) for j := 0; j < vectorOfStrongReferrablesLength; j++ { vectorOfStrongReferrablesOffsets[j] = t.VectorOfStrongReferrables[j].Pack(builder) } MonsterStartVectorOfStrongReferrablesVector(builder, vectorOfStrongReferrablesLength) for j := vectorOfStrongReferrablesLength - 1; j >= 0; j-- { builder.PrependUOffsetT(vectorOfStrongReferrablesOffsets[j]) } vectorOfStrongReferrablesOffset = builder.EndVector(vectorOfStrongReferrablesLength) } vectorOfCoOwningReferencesOffset := flatbuffers.UOffsetT(0) if t.VectorOfCoOwningReferences != nil { vectorOfCoOwningReferencesLength := len(t.VectorOfCoOwningReferences) MonsterStartVectorOfCoOwningReferencesVector(builder, vectorOfCoOwningReferencesLength) for j := vectorOfCoOwningReferencesLength - 1; j >= 0; j-- { builder.PrependUint64(t.VectorOfCoOwningReferences[j]) } vectorOfCoOwningReferencesOffset = builder.EndVector(vectorOfCoOwningReferencesLength) } vectorOfNonOwningReferencesOffset := flatbuffers.UOffsetT(0) if t.VectorOfNonOwningReferences != nil { vectorOfNonOwningReferencesLength := len(t.VectorOfNonOwningReferences) MonsterStartVectorOfNonOwningReferencesVector(builder, vectorOfNonOwningReferencesLength) for j := vectorOfNonOwningReferencesLength - 1; j >= 0; j-- { builder.PrependUint64(t.VectorOfNonOwningReferences[j]) } vectorOfNonOwningReferencesOffset = builder.EndVector(vectorOfNonOwningReferencesLength) } anyUniqueOffset := t.AnyUnique.Pack(builder) anyAmbiguousOffset := t.AnyAmbiguous.Pack(builder) vectorOfEnumsOffset := flatbuffers.UOffsetT(0) if t.VectorOfEnums != nil { vectorOfEnumsLength := len(t.VectorOfEnums) MonsterStartVectorOfEnumsVector(builder, vectorOfEnumsLength) for j := vectorOfEnumsLength - 1; j >= 0; j-- { builder.PrependByte(byte(t.VectorOfEnums[j])) } vectorOfEnumsOffset = builder.EndVector(vectorOfEnumsLength) } testrequirednestedflatbufferOffset := flatbuffers.UOffsetT(0) if t.Testrequirednestedflatbuffer != nil { testrequirednestedflatbufferOffset = builder.CreateByteString(t.Testrequirednestedflatbuffer) } scalarKeySortedTablesOffset := flatbuffers.UOffsetT(0) if t.ScalarKeySortedTables != nil { scalarKeySortedTablesLength := len(t.ScalarKeySortedTables) scalarKeySortedTablesOffsets := make([]flatbuffers.UOffsetT, scalarKeySortedTablesLength) for j := 0; j < scalarKeySortedTablesLength; j++ { scalarKeySortedTablesOffsets[j] = t.ScalarKeySortedTables[j].Pack(builder) } MonsterStartScalarKeySortedTablesVector(builder, scalarKeySortedTablesLength) for j := scalarKeySortedTablesLength - 1; j >= 0; j-- { builder.PrependUOffsetT(scalarKeySortedTablesOffsets[j]) } scalarKeySortedTablesOffset = builder.EndVector(scalarKeySortedTablesLength) } MonsterStart(builder) posOffset := t.Pos.Pack(builder) MonsterAddPos(builder, posOffset) MonsterAddMana(builder, t.Mana) MonsterAddHp(builder, t.Hp) MonsterAddName(builder, nameOffset) MonsterAddInventory(builder, inventoryOffset) MonsterAddColor(builder, t.Color) if t.Test != nil { MonsterAddTestType(builder, t.Test.Type) } MonsterAddTest(builder, testOffset) MonsterAddTest4(builder, test4Offset) MonsterAddTestarrayofstring(builder, testarrayofstringOffset) MonsterAddTestarrayoftables(builder, testarrayoftablesOffset) MonsterAddEnemy(builder, enemyOffset) MonsterAddTestnestedflatbuffer(builder, testnestedflatbufferOffset) MonsterAddTestempty(builder, testemptyOffset) MonsterAddTestbool(builder, t.Testbool) MonsterAddTesthashs32Fnv1(builder, t.Testhashs32Fnv1) MonsterAddTesthashu32Fnv1(builder, t.Testhashu32Fnv1) MonsterAddTesthashs64Fnv1(builder, t.Testhashs64Fnv1) MonsterAddTesthashu64Fnv1(builder, t.Testhashu64Fnv1) MonsterAddTesthashs32Fnv1a(builder, t.Testhashs32Fnv1a) MonsterAddTesthashu32Fnv1a(builder, t.Testhashu32Fnv1a) MonsterAddTesthashs64Fnv1a(builder, t.Testhashs64Fnv1a) MonsterAddTesthashu64Fnv1a(builder, t.Testhashu64Fnv1a) MonsterAddTestarrayofbools(builder, testarrayofboolsOffset) MonsterAddTestf(builder, t.Testf) MonsterAddTestf2(builder, t.Testf2) MonsterAddTestf3(builder, t.Testf3) MonsterAddTestarrayofstring2(builder, testarrayofstring2Offset) MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstructOffset) MonsterAddFlex(builder, flexOffset) MonsterAddTest5(builder, test5Offset) MonsterAddVectorOfLongs(builder, vectorOfLongsOffset) MonsterAddVectorOfDoubles(builder, vectorOfDoublesOffset) MonsterAddParentNamespaceTest(builder, parentNamespaceTestOffset) MonsterAddVectorOfReferrables(builder, vectorOfReferrablesOffset) MonsterAddSingleWeakReference(builder, t.SingleWeakReference) MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferencesOffset) MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrablesOffset) MonsterAddCoOwningReference(builder, t.CoOwningReference) MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferencesOffset) MonsterAddNonOwningReference(builder, t.NonOwningReference) MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferencesOffset) if t.AnyUnique != nil { MonsterAddAnyUniqueType(builder, t.AnyUnique.Type) } MonsterAddAnyUnique(builder, anyUniqueOffset) if t.AnyAmbiguous != nil { MonsterAddAnyAmbiguousType(builder, t.AnyAmbiguous.Type) } MonsterAddAnyAmbiguous(builder, anyAmbiguousOffset) MonsterAddVectorOfEnums(builder, vectorOfEnumsOffset) MonsterAddSignedEnum(builder, t.SignedEnum) MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset) MonsterAddScalarKeySortedTables(builder, scalarKeySortedTablesOffset) return MonsterEnd(builder) } func (rcv *Monster) UnPackTo(t *MonsterT) { t.Pos = rcv.Pos(nil).UnPack() t.Mana = rcv.Mana() t.Hp = rcv.Hp() t.Name = string(rcv.Name()) t.Inventory = rcv.InventoryBytes() t.Color = rcv.Color() testTable := flatbuffers.Table{} if rcv.Test(&testTable) { t.Test = rcv.TestType().UnPack(testTable) } test4Length := rcv.Test4Length() t.Test4 = make([]*TestT, test4Length) for j := 0; j < test4Length; j++ { x := Test{} rcv.Test4(&x, j) t.Test4[j] = x.UnPack() } testarrayofstringLength := rcv.TestarrayofstringLength() t.Testarrayofstring = make([]string, testarrayofstringLength) for j := 0; j < testarrayofstringLength; j++ { t.Testarrayofstring[j] = string(rcv.Testarrayofstring(j)) } testarrayoftablesLength := rcv.TestarrayoftablesLength() t.Testarrayoftables = make([]*MonsterT, testarrayoftablesLength) for j := 0; j < testarrayoftablesLength; j++ { x := Monster{} rcv.Testarrayoftables(&x, j) t.Testarrayoftables[j] = x.UnPack() } t.Enemy = rcv.Enemy(nil).UnPack() t.Testnestedflatbuffer = rcv.TestnestedflatbufferBytes() t.Testempty = rcv.Testempty(nil).UnPack() t.Testbool = rcv.Testbool() t.Testhashs32Fnv1 = rcv.Testhashs32Fnv1() t.Testhashu32Fnv1 = rcv.Testhashu32Fnv1() t.Testhashs64Fnv1 = rcv.Testhashs64Fnv1() t.Testhashu64Fnv1 = rcv.Testhashu64Fnv1() t.Testhashs32Fnv1a = rcv.Testhashs32Fnv1a() t.Testhashu32Fnv1a = rcv.Testhashu32Fnv1a() t.Testhashs64Fnv1a = rcv.Testhashs64Fnv1a() t.Testhashu64Fnv1a = rcv.Testhashu64Fnv1a() testarrayofboolsLength := rcv.TestarrayofboolsLength() t.Testarrayofbools = make([]bool, testarrayofboolsLength) for j := 0; j < testarrayofboolsLength; j++ { t.Testarrayofbools[j] = rcv.Testarrayofbools(j) } t.Testf = rcv.Testf() t.Testf2 = rcv.Testf2() t.Testf3 = rcv.Testf3() testarrayofstring2Length := rcv.Testarrayofstring2Length() t.Testarrayofstring2 = make([]string, testarrayofstring2Length) for j := 0; j < testarrayofstring2Length; j++ { t.Testarrayofstring2[j] = string(rcv.Testarrayofstring2(j)) } testarrayofsortedstructLength := rcv.TestarrayofsortedstructLength() t.Testarrayofsortedstruct = make([]*AbilityT, testarrayofsortedstructLength) for j := 0; j < testarrayofsortedstructLength; j++ { x := Ability{} rcv.Testarrayofsortedstruct(&x, j) t.Testarrayofsortedstruct[j] = x.UnPack() } t.Flex = rcv.FlexBytes() test5Length := rcv.Test5Length() t.Test5 = make([]*TestT, test5Length) for j := 0; j < test5Length; j++ { x := Test{} rcv.Test5(&x, j) t.Test5[j] = x.UnPack() } vectorOfLongsLength := rcv.VectorOfLongsLength() t.VectorOfLongs = make([]int64, vectorOfLongsLength) for j := 0; j < vectorOfLongsLength; j++ { t.VectorOfLongs[j] = rcv.VectorOfLongs(j) } vectorOfDoublesLength := rcv.VectorOfDoublesLength() t.VectorOfDoubles = make([]float64, vectorOfDoublesLength) for j := 0; j < vectorOfDoublesLength; j++ { t.VectorOfDoubles[j] = rcv.VectorOfDoubles(j) } t.ParentNamespaceTest = rcv.ParentNamespaceTest(nil).UnPack() vectorOfReferrablesLength := rcv.VectorOfReferrablesLength() t.VectorOfReferrables = make([]*ReferrableT, vectorOfReferrablesLength) for j := 0; j < vectorOfReferrablesLength; j++ { x := Referrable{} rcv.VectorOfReferrables(&x, j) t.VectorOfReferrables[j] = x.UnPack() } t.SingleWeakReference = rcv.SingleWeakReference() vectorOfWeakReferencesLength := rcv.VectorOfWeakReferencesLength() t.VectorOfWeakReferences = make([]uint64, vectorOfWeakReferencesLength) for j := 0; j < vectorOfWeakReferencesLength; j++ { t.VectorOfWeakReferences[j] = rcv.VectorOfWeakReferences(j) } vectorOfStrongReferrablesLength := rcv.VectorOfStrongReferrablesLength() t.VectorOfStrongReferrables = make([]*ReferrableT, vectorOfStrongReferrablesLength) for j := 0; j < vectorOfStrongReferrablesLength; j++ { x := Referrable{} rcv.VectorOfStrongReferrables(&x, j) t.VectorOfStrongReferrables[j] = x.UnPack() } t.CoOwningReference = rcv.CoOwningReference() vectorOfCoOwningReferencesLength := rcv.VectorOfCoOwningReferencesLength() t.VectorOfCoOwningReferences = make([]uint64, vectorOfCoOwningReferencesLength) for j := 0; j < vectorOfCoOwningReferencesLength; j++ { t.VectorOfCoOwningReferences[j] = rcv.VectorOfCoOwningReferences(j) } t.NonOwningReference = rcv.NonOwningReference() vectorOfNonOwningReferencesLength := rcv.VectorOfNonOwningReferencesLength() t.VectorOfNonOwningReferences = make([]uint64, vectorOfNonOwningReferencesLength) for j := 0; j < vectorOfNonOwningReferencesLength; j++ { t.VectorOfNonOwningReferences[j] = rcv.VectorOfNonOwningReferences(j) } anyUniqueTable := flatbuffers.Table{} if rcv.AnyUnique(&anyUniqueTable) { t.AnyUnique = rcv.AnyUniqueType().UnPack(anyUniqueTable) } anyAmbiguousTable := flatbuffers.Table{} if rcv.AnyAmbiguous(&anyAmbiguousTable) { t.AnyAmbiguous = rcv.AnyAmbiguousType().UnPack(anyAmbiguousTable) } vectorOfEnumsLength := rcv.VectorOfEnumsLength() t.VectorOfEnums = make([]Color, vectorOfEnumsLength) for j := 0; j < vectorOfEnumsLength; j++ { t.VectorOfEnums[j] = rcv.VectorOfEnums(j) } t.SignedEnum = rcv.SignedEnum() t.Testrequirednestedflatbuffer = rcv.TestrequirednestedflatbufferBytes() scalarKeySortedTablesLength := rcv.ScalarKeySortedTablesLength() t.ScalarKeySortedTables = make([]*StatT, scalarKeySortedTablesLength) for j := 0; j < scalarKeySortedTablesLength; j++ { x := Stat{} rcv.ScalarKeySortedTables(&x, j) t.ScalarKeySortedTables[j] = x.UnPack() } } func (rcv *Monster) UnPack() *MonsterT { if rcv == nil { return nil } t := &MonsterT{} rcv.UnPackTo(t) return t } type Monster struct { _tab flatbuffers.Table } func GetRootAsMonster(buf []byte, offset flatbuffers.UOffsetT) *Monster { n := flatbuffers.GetUOffsetT(buf[offset:]) x := &Monster{} x.Init(buf, n+offset) return x } func GetSizePrefixedRootAsMonster(buf []byte, offset flatbuffers.UOffsetT) *Monster { n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) x := &Monster{} x.Init(buf, n+offset+flatbuffers.SizeUint32) return x } func (rcv *Monster) Init(buf []byte, i flatbuffers.UOffsetT) { rcv._tab.Bytes = buf rcv._tab.Pos = i } func (rcv *Monster) Table() flatbuffers.Table { return rcv._tab } func (rcv *Monster) Pos(obj *Vec3) *Vec3 { o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) if o != 0 { x := o + rcv._tab.Pos if obj == nil { obj = new(Vec3) } obj.Init(rcv._tab.Bytes, x) return obj } return nil } func (rcv *Monster) Mana() int16 { o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) if o != 0 { return rcv._tab.GetInt16(o + rcv._tab.Pos) } return 150 } func (rcv *Monster) MutateMana(n int16) bool { return rcv._tab.MutateInt16Slot(6, n) } func (rcv *Monster) Hp() int16 { o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) if o != 0 { return rcv._tab.GetInt16(o + rcv._tab.Pos) } return 100 } func (rcv *Monster) MutateHp(n int16) bool { return rcv._tab.MutateInt16Slot(8, n) } func (rcv *Monster) Name() []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(10)) if o != 0 { return rcv._tab.ByteVector(o + rcv._tab.Pos) } return nil } func (rcv *Monster) Inventory(j int) byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) } return 0 } func (rcv *Monster) InventoryLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) InventoryBytes() []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) if o != 0 { return rcv._tab.ByteVector(o + rcv._tab.Pos) } return nil } func (rcv *Monster) MutateInventory(j int, n byte) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) } return false } func (rcv *Monster) Color() Color { o := flatbuffers.UOffsetT(rcv._tab.Offset(16)) if o != 0 { return Color(rcv._tab.GetByte(o + rcv._tab.Pos)) } return 8 } func (rcv *Monster) MutateColor(n Color) bool { return rcv._tab.MutateByteSlot(16, byte(n)) } func (rcv *Monster) TestType() Any { o := flatbuffers.UOffsetT(rcv._tab.Offset(18)) if o != 0 { return Any(rcv._tab.GetByte(o + rcv._tab.Pos)) } return 0 } func (rcv *Monster) MutateTestType(n Any) bool { return rcv._tab.MutateByteSlot(18, byte(n)) } func (rcv *Monster) Test(obj *flatbuffers.Table) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(20)) if o != 0 { rcv._tab.Union(obj, o) return true } return false } func (rcv *Monster) Test4(obj *Test, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(22)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 4 obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *Monster) Test4Length() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(22)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) Testarrayofstring(j int) []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.ByteVector(a + flatbuffers.UOffsetT(j*4)) } return nil } func (rcv *Monster) TestarrayofstringLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } /// an example documentation comment: this will end up in the generated code /// multiline too func (rcv *Monster) Testarrayoftables(obj *Monster, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 4 x = rcv._tab.Indirect(x) obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *Monster) TestarrayoftablesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } /// an example documentation comment: this will end up in the generated code /// multiline too func (rcv *Monster) Enemy(obj *Monster) *Monster { o := flatbuffers.UOffsetT(rcv._tab.Offset(28)) if o != 0 { x := rcv._tab.Indirect(o + rcv._tab.Pos) if obj == nil { obj = new(Monster) } obj.Init(rcv._tab.Bytes, x) return obj } return nil } func (rcv *Monster) Testnestedflatbuffer(j int) byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) } return 0 } func (rcv *Monster) TestnestedflatbufferLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) TestnestedflatbufferBytes() []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) if o != 0 { return rcv._tab.ByteVector(o + rcv._tab.Pos) } return nil } func (rcv *Monster) MutateTestnestedflatbuffer(j int, n byte) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) } return false } func (rcv *Monster) Testempty(obj *Stat) *Stat { o := flatbuffers.UOffsetT(rcv._tab.Offset(32)) if o != 0 { x := rcv._tab.Indirect(o + rcv._tab.Pos) if obj == nil { obj = new(Stat) } obj.Init(rcv._tab.Bytes, x) return obj } return nil } func (rcv *Monster) Testbool() bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(34)) if o != 0 { return rcv._tab.GetBool(o + rcv._tab.Pos) } return false } func (rcv *Monster) MutateTestbool(n bool) bool { return rcv._tab.MutateBoolSlot(34, n) } func (rcv *Monster) Testhashs32Fnv1() int32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(36)) if o != 0 { return rcv._tab.GetInt32(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashs32Fnv1(n int32) bool { return rcv._tab.MutateInt32Slot(36, n) } func (rcv *Monster) Testhashu32Fnv1() uint32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(38)) if o != 0 { return rcv._tab.GetUint32(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashu32Fnv1(n uint32) bool { return rcv._tab.MutateUint32Slot(38, n) } func (rcv *Monster) Testhashs64Fnv1() int64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(40)) if o != 0 { return rcv._tab.GetInt64(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashs64Fnv1(n int64) bool { return rcv._tab.MutateInt64Slot(40, n) } func (rcv *Monster) Testhashu64Fnv1() uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(42)) if o != 0 { return rcv._tab.GetUint64(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashu64Fnv1(n uint64) bool { return rcv._tab.MutateUint64Slot(42, n) } func (rcv *Monster) Testhashs32Fnv1a() int32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(44)) if o != 0 { return rcv._tab.GetInt32(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashs32Fnv1a(n int32) bool { return rcv._tab.MutateInt32Slot(44, n) } func (rcv *Monster) Testhashu32Fnv1a() uint32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(46)) if o != 0 { return rcv._tab.GetUint32(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashu32Fnv1a(n uint32) bool { return rcv._tab.MutateUint32Slot(46, n) } func (rcv *Monster) Testhashs64Fnv1a() int64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(48)) if o != 0 { return rcv._tab.GetInt64(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashs64Fnv1a(n int64) bool { return rcv._tab.MutateInt64Slot(48, n) } func (rcv *Monster) Testhashu64Fnv1a() uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(50)) if o != 0 { return rcv._tab.GetUint64(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateTesthashu64Fnv1a(n uint64) bool { return rcv._tab.MutateUint64Slot(50, n) } func (rcv *Monster) Testarrayofbools(j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(52)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetBool(a + flatbuffers.UOffsetT(j*1)) } return false } func (rcv *Monster) TestarrayofboolsLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(52)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) MutateTestarrayofbools(j int, n bool) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(52)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateBool(a+flatbuffers.UOffsetT(j*1), n) } return false } func (rcv *Monster) Testf() float32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(54)) if o != 0 { return rcv._tab.GetFloat32(o + rcv._tab.Pos) } return 3.14159 } func (rcv *Monster) MutateTestf(n float32) bool { return rcv._tab.MutateFloat32Slot(54, n) } func (rcv *Monster) Testf2() float32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(56)) if o != 0 { return rcv._tab.GetFloat32(o + rcv._tab.Pos) } return 3.0 } func (rcv *Monster) MutateTestf2(n float32) bool { return rcv._tab.MutateFloat32Slot(56, n) } func (rcv *Monster) Testf3() float32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(58)) if o != 0 { return rcv._tab.GetFloat32(o + rcv._tab.Pos) } return 0.0 } func (rcv *Monster) MutateTestf3(n float32) bool { return rcv._tab.MutateFloat32Slot(58, n) } func (rcv *Monster) Testarrayofstring2(j int) []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(60)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.ByteVector(a + flatbuffers.UOffsetT(j*4)) } return nil } func (rcv *Monster) Testarrayofstring2Length() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(60)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) Testarrayofsortedstruct(obj *Ability, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(62)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 8 obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *Monster) TestarrayofsortedstructLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(62)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) Flex(j int) byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) } return 0 } func (rcv *Monster) FlexLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) FlexBytes() []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) if o != 0 { return rcv._tab.ByteVector(o + rcv._tab.Pos) } return nil } func (rcv *Monster) MutateFlex(j int, n byte) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) } return false } func (rcv *Monster) Test5(obj *Test, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(66)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 4 obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *Monster) Test5Length() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(66)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) VectorOfLongs(j int) int64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(68)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetInt64(a + flatbuffers.UOffsetT(j*8)) } return 0 } func (rcv *Monster) VectorOfLongsLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(68)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) MutateVectorOfLongs(j int, n int64) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(68)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateInt64(a+flatbuffers.UOffsetT(j*8), n) } return false } func (rcv *Monster) VectorOfDoubles(j int) float64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(70)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetFloat64(a + flatbuffers.UOffsetT(j*8)) } return 0 } func (rcv *Monster) VectorOfDoublesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(70)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) MutateVectorOfDoubles(j int, n float64) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(70)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateFloat64(a+flatbuffers.UOffsetT(j*8), n) } return false } func (rcv *Monster) ParentNamespaceTest(obj *MyGame.InParentNamespace) *MyGame.InParentNamespace { o := flatbuffers.UOffsetT(rcv._tab.Offset(72)) if o != 0 { x := rcv._tab.Indirect(o + rcv._tab.Pos) if obj == nil { obj = new(MyGame.InParentNamespace) } obj.Init(rcv._tab.Bytes, x) return obj } return nil } func (rcv *Monster) VectorOfReferrables(obj *Referrable, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(74)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 4 x = rcv._tab.Indirect(x) obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *Monster) VectorOfReferrablesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(74)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) SingleWeakReference() uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(76)) if o != 0 { return rcv._tab.GetUint64(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateSingleWeakReference(n uint64) bool { return rcv._tab.MutateUint64Slot(76, n) } func (rcv *Monster) VectorOfWeakReferences(j int) uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(78)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetUint64(a + flatbuffers.UOffsetT(j*8)) } return 0 } func (rcv *Monster) VectorOfWeakReferencesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(78)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) MutateVectorOfWeakReferences(j int, n uint64) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(78)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateUint64(a+flatbuffers.UOffsetT(j*8), n) } return false } func (rcv *Monster) VectorOfStrongReferrables(obj *Referrable, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(80)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 4 x = rcv._tab.Indirect(x) obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *Monster) VectorOfStrongReferrablesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(80)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) CoOwningReference() uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(82)) if o != 0 { return rcv._tab.GetUint64(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateCoOwningReference(n uint64) bool { return rcv._tab.MutateUint64Slot(82, n) } func (rcv *Monster) VectorOfCoOwningReferences(j int) uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(84)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetUint64(a + flatbuffers.UOffsetT(j*8)) } return 0 } func (rcv *Monster) VectorOfCoOwningReferencesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(84)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) MutateVectorOfCoOwningReferences(j int, n uint64) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(84)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateUint64(a+flatbuffers.UOffsetT(j*8), n) } return false } func (rcv *Monster) NonOwningReference() uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(86)) if o != 0 { return rcv._tab.GetUint64(o + rcv._tab.Pos) } return 0 } func (rcv *Monster) MutateNonOwningReference(n uint64) bool { return rcv._tab.MutateUint64Slot(86, n) } func (rcv *Monster) VectorOfNonOwningReferences(j int) uint64 { o := flatbuffers.UOffsetT(rcv._tab.Offset(88)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetUint64(a + flatbuffers.UOffsetT(j*8)) } return 0 } func (rcv *Monster) VectorOfNonOwningReferencesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(88)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) MutateVectorOfNonOwningReferences(j int, n uint64) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(88)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateUint64(a+flatbuffers.UOffsetT(j*8), n) } return false } func (rcv *Monster) AnyUniqueType() AnyUniqueAliases { o := flatbuffers.UOffsetT(rcv._tab.Offset(90)) if o != 0 { return AnyUniqueAliases(rcv._tab.GetByte(o + rcv._tab.Pos)) } return 0 } func (rcv *Monster) MutateAnyUniqueType(n AnyUniqueAliases) bool { return rcv._tab.MutateByteSlot(90, byte(n)) } func (rcv *Monster) AnyUnique(obj *flatbuffers.Table) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(92)) if o != 0 { rcv._tab.Union(obj, o) return true } return false } func (rcv *Monster) AnyAmbiguousType() AnyAmbiguousAliases { o := flatbuffers.UOffsetT(rcv._tab.Offset(94)) if o != 0 { return AnyAmbiguousAliases(rcv._tab.GetByte(o + rcv._tab.Pos)) } return 0 } func (rcv *Monster) MutateAnyAmbiguousType(n AnyAmbiguousAliases) bool { return rcv._tab.MutateByteSlot(94, byte(n)) } func (rcv *Monster) AnyAmbiguous(obj *flatbuffers.Table) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(96)) if o != 0 { rcv._tab.Union(obj, o) return true } return false } func (rcv *Monster) VectorOfEnums(j int) Color { o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) if o != 0 { a := rcv._tab.Vector(o) return Color(rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1))) } return 0 } func (rcv *Monster) VectorOfEnumsLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) VectorOfEnumsBytes() []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) if o != 0 { return rcv._tab.ByteVector(o + rcv._tab.Pos) } return nil } func (rcv *Monster) MutateVectorOfEnums(j int, n Color) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), byte(n)) } return false } func (rcv *Monster) SignedEnum() Race { o := flatbuffers.UOffsetT(rcv._tab.Offset(100)) if o != 0 { return Race(rcv._tab.GetInt8(o + rcv._tab.Pos)) } return -1 } func (rcv *Monster) MutateSignedEnum(n Race) bool { return rcv._tab.MutateInt8Slot(100, int8(n)) } func (rcv *Monster) Testrequirednestedflatbuffer(j int) byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) } return 0 } func (rcv *Monster) TestrequirednestedflatbufferLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func (rcv *Monster) TestrequirednestedflatbufferBytes() []byte { o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) if o != 0 { return rcv._tab.ByteVector(o + rcv._tab.Pos) } return nil } func (rcv *Monster) MutateTestrequirednestedflatbuffer(j int, n byte) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) if o != 0 { a := rcv._tab.Vector(o) return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) } return false } func (rcv *Monster) ScalarKeySortedTables(obj *Stat, j int) bool { o := flatbuffers.UOffsetT(rcv._tab.Offset(104)) if o != 0 { x := rcv._tab.Vector(o) x += flatbuffers.UOffsetT(j) * 4 x = rcv._tab.Indirect(x) obj.Init(rcv._tab.Bytes, x) return true } return false } func (rcv *Monster) ScalarKeySortedTablesLength() int { o := flatbuffers.UOffsetT(rcv._tab.Offset(104)) if o != 0 { return rcv._tab.VectorLen(o) } return 0 } func MonsterStart(builder *flatbuffers.Builder) { builder.StartObject(51) } func MonsterAddPos(builder *flatbuffers.Builder, pos flatbuffers.UOffsetT) { builder.PrependStructSlot(0, flatbuffers.UOffsetT(pos), 0) } func MonsterAddMana(builder *flatbuffers.Builder, mana int16) { builder.PrependInt16Slot(1, mana, 150) } func MonsterAddHp(builder *flatbuffers.Builder, hp int16) { builder.PrependInt16Slot(2, hp, 100) } func MonsterAddName(builder *flatbuffers.Builder, name flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(3, flatbuffers.UOffsetT(name), 0) } func MonsterAddInventory(builder *flatbuffers.Builder, inventory flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(5, flatbuffers.UOffsetT(inventory), 0) } func MonsterStartInventoryVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(1, numElems, 1) } func MonsterAddColor(builder *flatbuffers.Builder, color Color) { builder.PrependByteSlot(6, byte(color), 8) } func MonsterAddTestType(builder *flatbuffers.Builder, testType Any) { builder.PrependByteSlot(7, byte(testType), 0) } func MonsterAddTest(builder *flatbuffers.Builder, test flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(8, flatbuffers.UOffsetT(test), 0) } func MonsterAddTest4(builder *flatbuffers.Builder, test4 flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(9, flatbuffers.UOffsetT(test4), 0) } func MonsterStartTest4Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 2) } func MonsterAddTestarrayofstring(builder *flatbuffers.Builder, testarrayofstring flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(10, flatbuffers.UOffsetT(testarrayofstring), 0) } func MonsterStartTestarrayofstringVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 4) } func MonsterAddTestarrayoftables(builder *flatbuffers.Builder, testarrayoftables flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(11, flatbuffers.UOffsetT(testarrayoftables), 0) } func MonsterStartTestarrayoftablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 4) } func MonsterAddEnemy(builder *flatbuffers.Builder, enemy flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(12, flatbuffers.UOffsetT(enemy), 0) } func MonsterAddTestnestedflatbuffer(builder *flatbuffers.Builder, testnestedflatbuffer flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(13, flatbuffers.UOffsetT(testnestedflatbuffer), 0) } func MonsterStartTestnestedflatbufferVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(1, numElems, 1) } func MonsterAddTestempty(builder *flatbuffers.Builder, testempty flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(14, flatbuffers.UOffsetT(testempty), 0) } func MonsterAddTestbool(builder *flatbuffers.Builder, testbool bool) { builder.PrependBoolSlot(15, testbool, false) } func MonsterAddTesthashs32Fnv1(builder *flatbuffers.Builder, testhashs32Fnv1 int32) { builder.PrependInt32Slot(16, testhashs32Fnv1, 0) } func MonsterAddTesthashu32Fnv1(builder *flatbuffers.Builder, testhashu32Fnv1 uint32) { builder.PrependUint32Slot(17, testhashu32Fnv1, 0) } func MonsterAddTesthashs64Fnv1(builder *flatbuffers.Builder, testhashs64Fnv1 int64) { builder.PrependInt64Slot(18, testhashs64Fnv1, 0) } func MonsterAddTesthashu64Fnv1(builder *flatbuffers.Builder, testhashu64Fnv1 uint64) { builder.PrependUint64Slot(19, testhashu64Fnv1, 0) } func MonsterAddTesthashs32Fnv1a(builder *flatbuffers.Builder, testhashs32Fnv1a int32) { builder.PrependInt32Slot(20, testhashs32Fnv1a, 0) } func MonsterAddTesthashu32Fnv1a(builder *flatbuffers.Builder, testhashu32Fnv1a uint32) { builder.PrependUint32Slot(21, testhashu32Fnv1a, 0) } func MonsterAddTesthashs64Fnv1a(builder *flatbuffers.Builder, testhashs64Fnv1a int64) { builder.PrependInt64Slot(22, testhashs64Fnv1a, 0) } func MonsterAddTesthashu64Fnv1a(builder *flatbuffers.Builder, testhashu64Fnv1a uint64) { builder.PrependUint64Slot(23, testhashu64Fnv1a, 0) } func MonsterAddTestarrayofbools(builder *flatbuffers.Builder, testarrayofbools flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(24, flatbuffers.UOffsetT(testarrayofbools), 0) } func MonsterStartTestarrayofboolsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(1, numElems, 1) } func MonsterAddTestf(builder *flatbuffers.Builder, testf float32) { builder.PrependFloat32Slot(25, testf, 3.14159) } func MonsterAddTestf2(builder *flatbuffers.Builder, testf2 float32) { builder.PrependFloat32Slot(26, testf2, 3.0) } func MonsterAddTestf3(builder *flatbuffers.Builder, testf3 float32) { builder.PrependFloat32Slot(27, testf3, 0.0) } func MonsterAddTestarrayofstring2(builder *flatbuffers.Builder, testarrayofstring2 flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(28, flatbuffers.UOffsetT(testarrayofstring2), 0) } func MonsterStartTestarrayofstring2Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 4) } func MonsterAddTestarrayofsortedstruct(builder *flatbuffers.Builder, testarrayofsortedstruct flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(29, flatbuffers.UOffsetT(testarrayofsortedstruct), 0) } func MonsterStartTestarrayofsortedstructVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(8, numElems, 4) } func MonsterAddFlex(builder *flatbuffers.Builder, flex flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(30, flatbuffers.UOffsetT(flex), 0) } func MonsterStartFlexVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(1, numElems, 1) } func MonsterAddTest5(builder *flatbuffers.Builder, test5 flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(31, flatbuffers.UOffsetT(test5), 0) } func MonsterStartTest5Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 2) } func MonsterAddVectorOfLongs(builder *flatbuffers.Builder, vectorOfLongs flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(32, flatbuffers.UOffsetT(vectorOfLongs), 0) } func MonsterStartVectorOfLongsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(8, numElems, 8) } func MonsterAddVectorOfDoubles(builder *flatbuffers.Builder, vectorOfDoubles flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(33, flatbuffers.UOffsetT(vectorOfDoubles), 0) } func MonsterStartVectorOfDoublesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(8, numElems, 8) } func MonsterAddParentNamespaceTest(builder *flatbuffers.Builder, parentNamespaceTest flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(34, flatbuffers.UOffsetT(parentNamespaceTest), 0) } func MonsterAddVectorOfReferrables(builder *flatbuffers.Builder, vectorOfReferrables flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(35, flatbuffers.UOffsetT(vectorOfReferrables), 0) } func MonsterStartVectorOfReferrablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 4) } func MonsterAddSingleWeakReference(builder *flatbuffers.Builder, singleWeakReference uint64) { builder.PrependUint64Slot(36, singleWeakReference, 0) } func MonsterAddVectorOfWeakReferences(builder *flatbuffers.Builder, vectorOfWeakReferences flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(37, flatbuffers.UOffsetT(vectorOfWeakReferences), 0) } func MonsterStartVectorOfWeakReferencesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(8, numElems, 8) } func MonsterAddVectorOfStrongReferrables(builder *flatbuffers.Builder, vectorOfStrongReferrables flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(38, flatbuffers.UOffsetT(vectorOfStrongReferrables), 0) } func MonsterStartVectorOfStrongReferrablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 4) } func MonsterAddCoOwningReference(builder *flatbuffers.Builder, coOwningReference uint64) { builder.PrependUint64Slot(39, coOwningReference, 0) } func MonsterAddVectorOfCoOwningReferences(builder *flatbuffers.Builder, vectorOfCoOwningReferences flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(40, flatbuffers.UOffsetT(vectorOfCoOwningReferences), 0) } func MonsterStartVectorOfCoOwningReferencesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(8, numElems, 8) } func MonsterAddNonOwningReference(builder *flatbuffers.Builder, nonOwningReference uint64) { builder.PrependUint64Slot(41, nonOwningReference, 0) } func MonsterAddVectorOfNonOwningReferences(builder *flatbuffers.Builder, vectorOfNonOwningReferences flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(42, flatbuffers.UOffsetT(vectorOfNonOwningReferences), 0) } func MonsterStartVectorOfNonOwningReferencesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(8, numElems, 8) } func MonsterAddAnyUniqueType(builder *flatbuffers.Builder, anyUniqueType AnyUniqueAliases) { builder.PrependByteSlot(43, byte(anyUniqueType), 0) } func MonsterAddAnyUnique(builder *flatbuffers.Builder, anyUnique flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(44, flatbuffers.UOffsetT(anyUnique), 0) } func MonsterAddAnyAmbiguousType(builder *flatbuffers.Builder, anyAmbiguousType AnyAmbiguousAliases) { builder.PrependByteSlot(45, byte(anyAmbiguousType), 0) } func MonsterAddAnyAmbiguous(builder *flatbuffers.Builder, anyAmbiguous flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(46, flatbuffers.UOffsetT(anyAmbiguous), 0) } func MonsterAddVectorOfEnums(builder *flatbuffers.Builder, vectorOfEnums flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(47, flatbuffers.UOffsetT(vectorOfEnums), 0) } func MonsterStartVectorOfEnumsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(1, numElems, 1) } func MonsterAddSignedEnum(builder *flatbuffers.Builder, signedEnum Race) { builder.PrependInt8Slot(48, int8(signedEnum), -1) } func MonsterAddTestrequirednestedflatbuffer(builder *flatbuffers.Builder, testrequirednestedflatbuffer flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(49, flatbuffers.UOffsetT(testrequirednestedflatbuffer), 0) } func MonsterStartTestrequirednestedflatbufferVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(1, numElems, 1) } func MonsterAddScalarKeySortedTables(builder *flatbuffers.Builder, scalarKeySortedTables flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(50, flatbuffers.UOffsetT(scalarKeySortedTables), 0) } func MonsterStartScalarKeySortedTablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { return builder.StartVector(4, numElems, 4) } func MonsterEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { return builder.EndObject() }
tests/MyGame/Example/Monster.go
0.656108
0.499023
Monster.go
starcoder
package input import ( "github.com/Jeffail/benthos/lib/input/reader" "github.com/Jeffail/benthos/lib/log" "github.com/Jeffail/benthos/lib/metrics" "github.com/Jeffail/benthos/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeS3] = TypeSpec{ constructor: NewAmazonS3, description: ` Downloads objects in an Amazon S3 bucket, optionally filtered by a prefix. If an SQS queue has been configured then only object keys read from the queue will be downloaded. Otherwise, the entire list of objects found when this input is created will be downloaded. Note that the prefix configuration is only used when downloading objects without SQS configured. If the download manager is enabled this can help speed up file downloads but results in file metadata not being copied. If your bucket is configured to send events directly to an SQS queue then you need to set the ` + "`sqs_body_path`" + ` field to where the object key is found in the payload. However, it is also common practice to send bucket events to an SNS topic which sends enveloped events to SQS, in which case you must also set the ` + "`sqs_envelope_path`" + ` field to where the payload can be found. When using SQS events it's also possible to extract target bucket names from the events by specifying a path in the field ` + "`sqs_bucket_path`" + `. For each SQS event, if that path exists and contains a string it will used as the bucket of the download instead of the ` + "`bucket`" + ` field. Here is a guide for setting up an SQS queue that receives events for new S3 bucket objects: https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html WARNING: When using SQS please make sure you have sensible values for ` + "`sqs_max_messages`" + ` and also the visibility timeout of the queue itself. When Benthos consumes an S3 item as a result of receiving an SQS message the message is not deleted until the S3 item has been sent onwards. This ensures at-least-once crash resiliency, but also means that if the S3 item takes longer to process than the visibility timeout of your queue then the same items might be processed multiple times. ### Metadata This input adds the following metadata fields to each message: ` + "```" + ` - s3_key - s3_bucket - s3_last_modified_unix* - s3_last_modified (RFC3339)* - s3_content_type* - All user defined metadata* * Only added when NOT using download manager ` + "```" + ` You can access these metadata fields using [function interpolation](../config_interpolation.md#metadata).`, } } //------------------------------------------------------------------------------ // NewAmazonS3 creates a new AWS S3 input type. func NewAmazonS3(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) { r, err := reader.NewAmazonS3(conf.S3, log, stats) if err != nil { return nil, err } return NewReader( "s3", reader.NewPreserver(r), log, stats, ) } //------------------------------------------------------------------------------
lib/input/s3.go
0.822153
0.663689
s3.go
starcoder
package normalize import ( "github.com/VKCOM/noverify/src/ir" ) func sideEffectFree(n ir.Node) bool { f := sideEffectsFinder{} n.Walk(&f) return !f.sideEffects } type sideEffectsFinder struct { sideEffects bool } var pureBuiltins = func() map[string]struct{} { list := []string{ `\count`, `\sizeof`, // Array functions. `\array_key_exists`, `\array_keys`, `\array_merge`, `\array_slice`, `\array_values`, `\explode`, `\implode`, `\in_array`, // String functions. `\str_replace`, `\strlen`, `\strpos`, `\strtolower`, `\strtoupper`, `\substr`, `\trim`, // Simple math functions. `\abs`, `\floor`, `\max`, `\min`, // All type converting functions are pure. `\boolval`, `\doubleval`, `\floatval`, `\intval`, `\strval`, // All type predicates are pure. `\is_array`, `\is_bool`, `\is_callable`, `\is_countable`, `\is_double`, `\is_float`, `\is_int`, `\is_integer`, `\is_iterable`, `\is_long`, `\is_null`, `\is_numeric`, `\is_object`, `\is_real`, `\is_resource`, `\is_scalar`, `\is_string`, } set := make(map[string]struct{}, len(list)) for _, nm := range list { set[nm] = struct{}{} } return set }() func (f *sideEffectsFinder) functionCallIsPure(n *ir.FunctionCallExpr) bool { // We allow referencing builtin funcs even before indexing is completed. var funcName string nm, ok := n.Function.(*ir.Name) if ok { if nm.IsFullyQualified() { funcName = nm.Value } else { funcName = `\` + nm.Value } } if funcName != "" { // Might be a builtin. if _, ok := pureBuiltins[funcName]; ok { return true } } return false } func (f *sideEffectsFinder) EnterNode(n ir.Node) bool { if f.sideEffects { return false } // We can get false positives for overloaded operations. // For example, array index can be an offsetGet() call, // which might not be pure. switch n := n.(type) { case *ir.FunctionCallExpr: if f.functionCallIsPure(n) { return true } f.sideEffects = true return false case *ir.MethodCallExpr: f.sideEffects = true return false case *ir.StaticCallExpr: f.sideEffects = true return false case *ir.PrintExpr, *ir.EchoStmt, *ir.UnsetStmt, *ir.ThrowStmt, *ir.GlobalStmt, *ir.ExitExpr, *ir.Assign, *ir.AssignReference, *ir.AssignBitwiseAnd, *ir.AssignBitwiseOr, *ir.AssignBitwiseXor, *ir.AssignConcat, *ir.AssignDiv, *ir.AssignMinus, *ir.AssignMod, *ir.AssignMul, *ir.AssignPlus, *ir.AssignPow, *ir.AssignShiftLeft, *ir.AssignShiftRight, *ir.YieldExpr, *ir.YieldFromExpr, *ir.EvalExpr, *ir.PreIncExpr, *ir.PostIncExpr, *ir.PreDecExpr, *ir.PostDecExpr, *ir.ImportExpr: f.sideEffects = true return false } return true } func (f *sideEffectsFinder) LeaveNode(n ir.Node) {}
src/ir/normalize/side_effects.go
0.671255
0.527256
side_effects.go
starcoder
package numbers import ( "log" "math" //DEBUG: "fmt" ) //LogCanConvert returns true if the input logSpace number can be converted to a number in normal space without overflow or underflow. func LogCanConvert(x float64) bool { return x < 709.4 && x > -745.1 } //AverageLog returns the average of a list of logSpace numbers func AverageLog(x []float64) float64 { var n int = len(x) var sum float64 = x[0] var logN float64 = math.Log(float64(n)) for i := 1; i < len(x); i++ { sum = AddLog(sum, x[i]) } return DivideLog(sum, logN) } //MidpointLog returns a log number that is equidistant from two input logSpace numbers func MidpointLog(x float64, y float64) float64 { return DivideLog(AddLog(x, y), math.Log(2.0)) } //AddLog returns the sum of two numbers in logSpace. func AddLog(x float64, y float64) float64 { if math.IsInf(x, -1) { return y } if math.IsInf(y, -1) { return x } if x >= y { if LogCanConvert(y - x) { return x + math.Log(1+math.Exp(y-x)) } return x } if LogCanConvert(y - x) { return y + math.Log(1+math.Exp(x-y)) } return y } //SubtractLog returns the difference of two numbers in logSpace. func SubtractLog(x float64, y float64) float64 { if x < y { log.Fatalf("Error: Taking the log of a negative number.") return 0 } if x == y { return math.Inf(-1) } if math.IsInf(y, -1) { return x } if LogCanConvert(y - x) { return x + math.Log(1-math.Exp(y-x)) } return x } //MultiplyLog returns the product of two numbers in logSpace. func MultiplyLog(x float64, y float64) float64 { if math.IsInf(x, -1) || math.IsInf(y, -1) { return math.Inf(-1) } return x + y } //DivideLog returns the quotient of two numbers in logSpace. func DivideLog(x float64, y float64) float64 { if math.IsInf(y, -1) { log.Fatalf("Divide by zero error in logSpace. x=%f. y=%f.", x, y) } if math.IsInf(x, -1) { return math.Inf(-1) } return x - y } //LogPow returns log(x**y) where log is the natural logarithm. Safe for large numbers. Support for positive real numbers with integer exponents. func LogPow(x float64, y float64) float64 { if x < 0 { log.Fatalf("LowPowInt does not handle negative x values. x=%e\n", x) } // anything to the zero power is 1, so we return 0 == log(1). 0^0 is what this catches if y == 0.0 { return 0.0 } return y * math.Log(x) } // PowLog returns log(exp(x)**y) where log is the natural logarithm. // This back the log-space answer to x**y where x is already in log-space // In other words, this function returns the log-space answer to x**y where x is already in log-space func PowLog(x float64, y float64) float64 { // anything to the zero power is 1, so we return 0 == log(1). 0^0 is what this catches if y == 0.0 { return 0.0 } return y * x }
numbers/logSpace.go
0.783575
0.604107
logSpace.go
starcoder
package fmom import ( "fmt" "math" ) type IPtCotThPhiM struct { P4 Vec4 } func NewIPtCotThPhiM(pt, eta, phi, m float64) IPtCotThPhiM { return IPtCotThPhiM{P4: Vec4{X: pt, Y: eta, Z: phi, T: m}} } func (p4 IPtCotThPhiM) String() string { return fmt.Sprintf( "fmom.P4{IPt:%v, CotTh:%v, Phi:%v, M:%v}", p4.IPt(), p4.CotTh(), p4.Phi(), p4.M(), ) } func (p4 *IPtCotThPhiM) Clone() P4 { pp := *p4 return &pp } func (p4 *IPtCotThPhiM) IPt() float64 { return p4.P4.X } func (p4 *IPtCotThPhiM) CotTh() float64 { return p4.P4.Y } func (p4 *IPtCotThPhiM) Phi() float64 { return p4.P4.Z } func (p4 *IPtCotThPhiM) M() float64 { return p4.P4.T } func (p4 *IPtCotThPhiM) Pt() float64 { ipt := p4.IPt() return 1 / ipt } func (p4 *IPtCotThPhiM) P() float64 { cotth := p4.CotTh() ipt := p4.IPt() return math.Sqrt(1+cotth*cotth) / ipt } func (p4 *IPtCotThPhiM) P2() float64 { cotth := p4.CotTh() ipt := p4.IPt() return (1 + cotth*cotth) / (ipt * ipt) } func (p4 *IPtCotThPhiM) M2() float64 { m := p4.M() return m * m } func (p4 *IPtCotThPhiM) TanTh() float64 { cotth := p4.CotTh() return 1 / cotth } func (p4 *IPtCotThPhiM) SinTh() float64 { cotth := p4.CotTh() return 1 / math.Sqrt(1+cotth*cotth) } func (p4 *IPtCotThPhiM) CosTh() float64 { cotth := p4.CotTh() cotth2 := cotth * cotth costh := math.Sqrt(cotth2 / (1 + cotth2)) sign := 1.0 if cotth < 0 { sign = -1.0 } return sign * costh } func (p4 *IPtCotThPhiM) E() float64 { m := p4.M() p := p4.P() if m == 0 { return p } return math.Sqrt(p*p + m*m) } func (p4 *IPtCotThPhiM) Et() float64 { cotth := p4.CotTh() e := p4.E() return e / math.Sqrt(1+cotth*cotth) } func (p4 *IPtCotThPhiM) Eta() float64 { cotth := p4.CotTh() aux := math.Sqrt(1 + cotth*cotth) return -0.5 * math.Log((aux-cotth)/(aux+cotth)) } func (p4 *IPtCotThPhiM) Rapidity() float64 { e := p4.E() pz := p4.Pz() return 0.5 * math.Log((e+pz)/(e-pz)) } func (p4 *IPtCotThPhiM) Px() float64 { cosphi := p4.CosPhi() ipt := p4.IPt() pt := 1 / ipt return pt * cosphi } func (p4 *IPtCotThPhiM) Py() float64 { sinphi := p4.SinPhi() ipt := p4.IPt() pt := 1 / ipt return pt * sinphi } func (p4 *IPtCotThPhiM) Pz() float64 { cotth := p4.CotTh() ipt := p4.IPt() pt := 1 / ipt return pt * cotth } func (p4 *IPtCotThPhiM) CosPhi() float64 { phi := p4.Phi() return math.Cos(phi) } func (p4 *IPtCotThPhiM) SinPhi() float64 { phi := p4.Phi() return math.Sin(phi) } func (p4 *IPtCotThPhiM) Set(p P4) { p4.P4.X = p.IPt() p4.P4.Y = p.CotTh() p4.P4.Z = p.Phi() p4.P4.T = p.M() } var ( _ P4 = (*IPtCotThPhiM)(nil) _ fmt.Stringer = (*IPtCotThPhiM)(nil) )
fmom/iptcotthphim.go
0.770594
0.433981
iptcotthphim.go
starcoder
package geometry import ( "github.com/Laughs-In-Flowers/shiva/lib/graphics" "github.com/Laughs-In-Flowers/shiva/lib/math" glm "math" ) type sphere struct { Geometry Radius float64 WidthSegments int HeightSegments int PhiStart float64 PhiLength float64 ThetaStart float64 ThetaLength float64 } func Sphere( radius float64, wSegments, hSegments int, phiStart, phiLength, thetaStart, thetaLength float64, ) *sphere { s := &sphere{ New(), radius, wSegments, hSegments, phiStart, phiLength, thetaStart, thetaLength, } thetaEnd := thetaStart + thetaLength vertexCount := (wSegments + 1) * (hSegments + 1) positions := math.NewAF32(vertexCount*3, vertexCount*3) normals := math.NewAF32(vertexCount*3, vertexCount*3) uvs := math.NewAF32(vertexCount*2, vertexCount*2) indices := math.NewAU32(0, vertexCount) index := 0 vertices := make([][]uint32, 0) var normal math.Vector = math.Vec3(0, 0, 0) for y := 0; y <= hSegments; y++ { verticesRow := make([]uint32, 0) v := float64(y) / float64(hSegments) for x := 0; x <= wSegments; x++ { u := float64(x) / float64(wSegments) px := -radius * glm.Cos(phiStart+u*phiLength) * glm.Sin(thetaStart+v*thetaLength) py := radius * glm.Cos(thetaStart+v*thetaLength) pz := radius * glm.Sin(phiStart+u*phiLength) * glm.Sin(thetaStart+v*thetaLength) normal.Set(0, float32(px)) normal.Set(1, float32(py)) normal.Set(2, float32(pz)) normal.Normalize() positions.Set(index*3, float32(px), float32(py), float32(pz)) normals.Set(index*3, normal.Raw()...) uvs.Set(index*2, float32(u), float32(v)) verticesRow = append(verticesRow, uint32(index)) index++ } vertices = append(vertices, verticesRow) } for y := 0; y < hSegments; y++ { for x := 0; x < wSegments; x++ { v1 := vertices[y][x+1] v2 := vertices[y][x] v3 := vertices[y+1][x] v4 := vertices[y+1][x+1] if y != 0 || thetaStart > 0 { indices.Append(v1, v2, v4) } if y != hSegments-1 || thetaEnd < glm.Pi { indices.Append(v2, v3, v4) } } } s.SetIndices(indices) s.AddVBO(graphics.NewBuff().AddAttrib("VertexPosition", 3).SetBuffer(positions)) s.AddVBO(graphics.NewBuff().AddAttrib("VertexNormal", 3).SetBuffer(normals)) s.AddVBO(graphics.NewBuff().AddAttrib("VertexTexcoord", 2).SetBuffer(uvs)) return s }
lib/graphics/geometry/sphere.go
0.574395
0.564279
sphere.go
starcoder
\brief C implementation of Perlin Simplex Noise over 1,2,3, and 4 dimensions. \author <NAME> (<EMAIL>) Adapted to Go by <NAME> (<EMAIL>) */ /* * This implementation is "Simplex Noise" as presented by * Ken Perlin at a relatively obscure and not often cited course * session "Real-Time Shading" at Siggraph 2001 (before real * time shading actually took on), under the title "hardware noise". * The 3D function is numerically equivalent to his Java reference * code available in the PDF course notes, although I re-implemented * it from scratch to get more readable code. The 1D, 2D and 4D cases * were implemented from scratch by me from Ken Perlin's text. */ package mesh // We don't need to include this. It does no harm, but no use either. func FASTFLOOR(x float64) int { if x > 0 { return int(x) } return int(x) - 1 } //--------------------------------------------------------------------- // Static data /* * Permutation table. This is just a random jumble of all numbers 0-255, * repeated twice to avoid wrapping the index at 255 for each lookup. * This needs to be exactly the same for all instances on all platforms, * so it's easiest to just keep it as static explicit data. * This also removes the need for any initialisation of this class. * * Note that making this an int[] instead of a char[] might make the * code run faster on platforms with a high penalty for unaligned single * byte addressing. Intel x86 is generally single-byte-friendly, but * some other CPUs are faster with 4-aligned reads. * However, a char[] is smaller, which avoids cache trashing, and that * is probably the most important aspect on most architectures. * This array is accessed a *lot* by the noise functions. * A vector-valued noise over 3D accesses it 96 times, and a * float-valued 4D noise 64 times. We want this to fit in the cache! */ var perm = [512]uint8{ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, } //--------------------------------------------------------------------- /* * Helper functions to compute gradients-dot-residualvectors (1D to 4D) * Note that these generate gradients of more than unit length. To make * a close match with the value range of classic Perlin noise, the final * noise values need to be rescaled to fit nicely within [-1,1]. * (The simplex noise functions as such also have different scaling.) * Note also that these noise functions are the most practical and useful * signed version of Perlin noise. To return values according to the * RenderMan specification from the SL noise() and pnoise() functions, * the noise values need to be scaled and offset to [0,1], like this: * float SLnoise = (noise(x,y,z) + 1.0) * 0.5; */ func Q(cond bool, v1 float64, v2 float64) float64 { if cond { return v1 } return v2 } func grad1(hash uint8, x float64) float64 { h := hash & 15 grad := float64(1 + h&7) // Gradient value 1.0, 2.0, ..., 8.0 if h&8 != 0 { grad = -grad // Set a random sign for the gradient } return grad * x // Multiply the gradient with the distance } func grad2(hash uint8, x float64, y float64) float64 { h := hash & 7 // Convert low 3 bits of hash code u := Q(h < 4, x, y) // into 8 simple gradient directions, v := Q(h < 4, y, x) // and compute the dot product with (x,y). return Q(h&1 != 0, -u, u) + Q(h&2 != 0, -2*v, 2*v) } func grad3(hash uint8, x, y, z float64) float64 { h := hash & 15 // Convert low 4 bits of hash code into 12 simple u := Q(h < 8, x, y) // gradient directions, and compute dot product. v := Q(h < 4, y, Q(h == 12 || h == 14, x, z)) // Fix repeats at h = 12 to 15 return Q(h&1 != 0, -u, u) + Q(h&2 != 0, -v, v) } // 1D simplex noise func Noise1(x float64) float64 { i0 := FASTFLOOR(x) i1 := i0 + 1 x0 := x - float64(i0) x1 := x0 - 1 t0 := 1 - x0*x0 t0 *= t0 n0 := t0 * t0 * grad1(perm[i0&0xff], x0) t1 := 1 - x1*x1 t1 *= t1 n1 := t1 * t1 * grad1(perm[i1&0xff], x1) // The maximum value of this noise is 8*(3/4)^4 = 2.53125 // A factor of 0.395 would scale to fit exactly within [-1,1]. // fmt.Printf("Noise1 x %.4f, i0 %v, i1 %v, x0 %.4f, x1 %.4f, perm0 %d, perm1 %d: %.4f,%.4f\n", x, i0, i1, x0, x1, perm[i0&0xff], perm[i1&0xff], n0, n1) // The algorithm isn't perfect, as it is assymetric. The correction will normalize the result to the interval [-1,1], but the average will be off by 3%. return (n0 + n1 + 0.076368899) / 2.45488110001 } // 2D simplex noise func Noise2(x, y float64) float64 { const F2 = 0.366025403 // F2 = 0.5*(sqrt(3.0)-1.0) const G2 = 0.211324865 // G2 = (3.0-Math.sqrt(3.0))/6.0 var n0, n1, n2 float64 // Noise contributions from the three corners // Skew the input space to determine which simplex cell we're in s := (x + y) * F2 // Hairy factor for 2D xs := x + s ys := y + s i := FASTFLOOR(xs) j := FASTFLOOR(ys) t := float64(i+j) * G2 X0 := float64(i) - t // Unskew the cell origin back to (x,y) space Y0 := float64(j) - t x0 := x - X0 // The x,y distances from the cell origin y0 := y - Y0 // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. var i1, j1 int // Offsets for second (middle) corner of simplex in (i,j) coords if x0 > y0 { i1 = 1 j1 = 0 // lower triangle, XY order: (0,0)->(1,0)->(1,1) } else { i1 = 0 j1 = 1 } // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 x1 := x0 - float64(i1) + G2 // Offsets for middle corner in (x,y) unskewed coords y1 := y0 - float64(j1) + G2 x2 := x0 - 1 + 2*G2 // Offsets for last corner in (x,y) unskewed coords y2 := y0 - 1 + 2*G2 // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds ii := i & 0xff jj := j & 0xff // Calculate the contribution from the three corners t0 := 0.5 - x0*x0 - y0*y0 if t0 < 0 { n0 = 0 } else { t0 *= t0 n0 = t0 * t0 * grad2(perm[ii+int(perm[jj])], x0, y0) } t1 := 0.5 - x1*x1 - y1*y1 if t1 < 0 { n1 = 0 } else { t1 *= t1 n1 = t1 * t1 * grad2(perm[ii+i1+int(perm[jj+j1])], x1, y1) } t2 := 0.5 - x2*x2 - y2*y2 if t2 < 0 { n2 = 0 } else { t2 *= t2 n2 = t2 * t2 * grad2(perm[ii+1+int(perm[jj+1])], x2, y2) } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return (n0 + n1 + n2) / 0.022108854818853867 } // 3D simplex noise func Noise3(x, y, z float64) float64 { // Simple skewing factors for the 3D case const F3 = 0.333333333 const G3 = 0.166666667 var n0, n1, n2, n3 float64 // Noise contributions from the four corners // Skew the input space to determine which simplex cell we're in s := (x + y + z) * F3 // Very nice and simple skew factor for 3D xs := x + s ys := y + s zs := z + s i := FASTFLOOR(xs) j := FASTFLOOR(ys) k := FASTFLOOR(zs) t := float64(i+j+k) * G3 X0 := float64(i) - t // Unskew the cell origin back to (x,y,z) space Y0 := float64(j) - t Z0 := float64(k) - t x0 := float64(x) - X0 // The x,y,z distances from the cell origin y0 := float64(y) - Y0 z0 := float64(z) - Z0 // For the 3D case, the simplex shape is a slightly irregular tetrahedron. // Determine which simplex we are in. var i1, j1, k1 int // Offsets for second corner of simplex in (i,j,k) coords var i2, j2, k2 int // Offsets for third corner of simplex in (i,j,k) coords /* This code would benefit from a backport from the GLSL version! */ if x0 >= y0 { if y0 >= z0 { i1 = 1 j1 = 0 k1 = 0 i2 = 1 j2 = 1 k2 = 0 // X Y Z order } else if x0 >= z0 { i1 = 1 j1 = 0 k1 = 0 i2 = 1 j2 = 0 k2 = 1 // X Z Y order } else { i1 = 0 j1 = 0 k1 = 1 i2 = 1 j2 = 0 k2 = 1 // Z X Y order } } else { // x0<y0 if y0 < z0 { i1 = 0 j1 = 0 k1 = 1 i2 = 0 j2 = 1 k2 = 1 // Z Y X order } else if x0 < z0 { i1 = 0 j1 = 1 k1 = 0 i2 = 0 j2 = 1 k2 = 1 // Y Z X order } else { i1 = 0 j1 = 1 k1 = 0 i2 = 1 j2 = 1 k2 = 0 // Y X Z order } } // A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z), // a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and // a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where // c = 1/6. x1 := x0 - float64(i1) + G3 // Offsets for second corner in (x,y,z) coords y1 := y0 - float64(j1) + G3 z1 := z0 - float64(k1) + G3 x2 := x0 - float64(i2) + 2*G3 // Offsets for third corner in (x,y,z) coords y2 := y0 - float64(j2) + 2*G3 z2 := z0 - float64(k2) + 2*G3 x3 := x0 - 1 + 3*G3 // Offsets for last corner in (x,y,z) coords y3 := y0 - 1 + 3*G3 z3 := z0 - 1 + 3*G3 // Wrap the integer indices at 256, to avoid indexing perm[] out of bounds ii := i & 0xff jj := j & 0xff kk := k & 0xff // Calculate the contribution from the four corners t0 := 0.6 - x0*x0 - y0*y0 - z0*z0 if t0 < 0 { n0 = 0 } else { t0 *= t0 n0 = t0 * t0 * grad3(perm[ii+int(perm[jj+int(perm[kk])])], x0, y0, z0) } t1 := 0.6 - x1*x1 - y1*y1 - z1*z1 if t1 < 0 { n1 = 0 } else { t1 *= t1 n1 = t1 * t1 * grad3(perm[ii+i1+int(perm[jj+j1+int(perm[kk+k1])])], x1, y1, z1) } t2 := 0.6 - x2*x2 - y2*y2 - z2*z2 if t2 < 0 { n2 = 0 } else { t2 *= t2 n2 = t2 * t2 * grad3(perm[ii+i2+int(perm[jj+j2+int(perm[kk+k2])])], x2, y2, z2) } t3 := 0.6 - x3*x3 - y3*y3 - z3*z3 if t3 < 0 { n3 = 0 } else { t3 *= t3 n3 = t3 * t3 * grad3(perm[ii+1+int(perm[jj+1+int(perm[kk+1])])], x3, y3, z3) } // Add contributions from each corner to get the final noise value. // The result is scaled to stay just inside [-1,1] return (n0 + n1 + n2 + n3) / 0.030555466710745972 }
examples/mesh/simplexnoise.go
0.74008
0.525734
simplexnoise.go
starcoder
package deluge // IngestorOptionFunc is a function that configures an Ingestor. It is used in // NewIngestor. type IngestorOptionFunc func(*Ingestor) error // SetDocument sets the document type for the ingest. func SetDocument(ctor Constructor) IngestorOptionFunc { return func(i *Ingestor) error { if ctor != nil { i.documentCtor = ctor } return nil } } // SetInput sets the input type for the ingest. func SetInput(input Input) IngestorOptionFunc { return func(i *Ingestor) error { if input != nil { i.input = input } return nil } } // SetClient sets the elasticsearch client. func SetClient(client Client) IngestorOptionFunc { return func(i *Ingestor) error { i.client = client return nil } } // SetErrorThreshold sets the error threshold to stop the ingest at. func SetErrorThreshold(threshold float64) IngestorOptionFunc { return func(i *Ingestor) error { i.threshold = threshold return nil } } // SetActiveConnections sets the number of active connections to elasticsearch // allowed. func SetActiveConnections(numActiveConnections int) IngestorOptionFunc { return func(i *Ingestor) error { i.numActiveConnections = numActiveConnections return nil } } // SetNumReplicas sets the number of replicas to enable upon completion of // the ingest. func SetNumReplicas(numReplicas int) IngestorOptionFunc { return func(i *Ingestor) error { i.numReplicas = numReplicas return nil } } // SetNumWorkers sets the number of workers in the worker pool. func SetNumWorkers(numWorkers int) IngestorOptionFunc { return func(i *Ingestor) error { i.numWorkers = numWorkers return nil } } // ClearExistingIndex clears an existing index if specified. func ClearExistingIndex(clearExisting bool) IngestorOptionFunc { return func(i *Ingestor) error { i.clearExisting = clearExisting return nil } } // SetCompression sets the compression type for the input files. Supports: // "bzip2", "flate", "gzip", "zlib". func SetCompression(compression string) IngestorOptionFunc { return func(i *Ingestor) error { i.compression = compression return nil } } // SetIndex sets the index name to create and ingest into. func SetIndex(index string) IngestorOptionFunc { return func(i *Ingestor) error { i.index = index return nil } } // SetBulkByteSize sets the maximum number of bytes in a bulk index payload. func SetBulkByteSize(numBytes int64) IngestorOptionFunc { return func(i *Ingestor) error { i.bulkByteSize = numBytes return nil } } // SetScanBufferSize sets the maximum number of bytes in the bufio.Scanner // a bulk index payload. func SetScanBufferSize(numBytes int) IngestorOptionFunc { return func(i *Ingestor) error { i.scanBufferSize = numBytes return nil } } // SetBulkSizeOptimiser sets the optimiser to use for bulk sizes. If not // specified, then a static bulk size will be used. func SetBulkSizeOptimiser(bulkSizeOptimiser Optimiser) IngestorOptionFunc { return func(i *Ingestor) error { i.bulkSizeOptimiser = bulkSizeOptimiser return nil } } // SetUpdateMapping sets whether or not to update an index's mapping if it // already exists. func SetUpdateMapping(updateMapping bool) IngestorOptionFunc { return func(i *Ingestor) error { i.updateMapping = updateMapping return nil } } // SetReadOnly sets whether or not to set an index to read only after ingestion. // However, you will be unable to clone the index, since cloning alters metadata. // If you want to be able to clone your index consider `SetBlockWrite(true)` func SetReadOnly(readOnly bool) IngestorOptionFunc { return func(i *Ingestor) error { i.readOnly = readOnly return nil } } // SetBlockWrite sets whether we are able to set the body of the index to read only. // You will still be able to alter the metadata of an index if you use this setting. func SetBlockWrite(blockWrite bool) IngestorOptionFunc { return func(i *Ingestor) error { i.blockWrite = blockWrite return nil } }
options.go
0.655777
0.536981
options.go
starcoder
package p1825 type MKAverage struct { root *Node m int k int nums []int } func Constructor(m int, k int) MKAverage { nums := make([]int, 0, 100010) return MKAverage{nil, m, k, nums} } func (this *MKAverage) AddElement(num int) { this.nums = append(this.nums, num) this.root = Insert(this.root, num) n := len(this.nums) if n > this.m { this.root = Delete(this.root, this.nums[n-this.m-1]) } } func (this *MKAverage) CalculateMKAverage() int { n := len(this.nums) if n < this.m { return -1 } s1 := FirstKSum(this.root, this.k) s2 := FirstKSum(this.root, this.m-this.k) s := int(s2 - s1) return s / (this.m - 2*this.k) } /** * this is a AVL tree */ type Node struct { key int height int cnt int sum int64 sz int left, right *Node } func (node *Node) Height() int { if node == nil { return 0 } return node.height } func (node *Node) Sum() int64 { if node == nil { return 0 } return node.sum } func (node *Node) Size() int { if node == nil { return 0 } return node.sz } func max(a, b int) int { if a >= b { return a } return b } func NewNode(key int) *Node { node := new(Node) node.key = key node.height = 1 node.cnt = 1 node.sum = int64(key) node.sz = 1 return node } func (node *Node) update() { node.height = max(node.left.Height(), node.right.Height()) + 1 node.sum = node.left.Sum() + node.right.Sum() + int64(node.key)*int64(node.cnt) node.sz = node.left.Size() + node.right.Size() + node.cnt } func rightRotate(y *Node) *Node { x := y.left t2 := x.right x.right = y y.left = t2 y.update() x.update() return x } func leftRotate(x *Node) *Node { y := x.right t2 := y.left y.left = x x.right = t2 x.update() y.update() return y } func (node *Node) GetBalance() int { if node == nil { return 0 } return node.left.Height() - node.right.Height() } func Insert(node *Node, key int) *Node { if node == nil { return NewNode(key) } if node.key == key { node.cnt++ node.sz++ node.sum += int64(key) return node } if node.key > key { node.left = Insert(node.left, key) } else { node.right = Insert(node.right, key) } node.update() balance := node.GetBalance() if balance > 1 && key < node.left.key { return rightRotate(node) } if balance < -1 && key > node.right.key { return leftRotate(node) } if balance > 1 && key > node.left.key { node.left = leftRotate(node.left) return rightRotate(node) } if balance < -1 && key < node.right.key { node.right = rightRotate(node.right) return leftRotate(node) } return node } func MinValueNode(root *Node) *Node { cur := root for cur.left != nil { cur = cur.left } return cur } func Delete(root *Node, key int) *Node { if root == nil { return nil } if key < root.key { root.left = Delete(root.left, key) } else if key > root.key { root.right = Delete(root.right, key) } else { root.cnt-- root.sum -= int64(key) root.sz-- if root.cnt > 0 { return root } if root.left == nil || root.right == nil { tmp := root.left if root.left == nil { tmp = root.right } root = tmp } else { tmp := MinValueNode(root.right) root.key = tmp.key root.cnt = tmp.cnt //root.sum = tmp.key // make sure tmp node deleted after call delete on root.right tmp.cnt = 1 root.right = Delete(root.right, tmp.key) } } if root == nil { return root } root.update() balance := root.GetBalance() if balance > 1 && root.left.GetBalance() >= 0 { return rightRotate(root) } if balance > 1 && root.left.GetBalance() < 0 { root.left = leftRotate(root.left) return rightRotate(root) } if balance < -1 && root.right.GetBalance() <= 0 { return leftRotate(root) } if balance < -1 && root.right.GetBalance() > 0 { root.right = rightRotate(root.right) return leftRotate(root) } return root } func FirstKSum(root *Node, k int) int64 { if k == 0 { return 0 } if root.left.Size() >= k { return FirstKSum(root.left, k) } res := root.left.Sum() if root.cnt >= k-root.left.Size() { res += int64(root.key) * int64(k-root.left.Size()) return res } res += int64(root.key) * int64(root.cnt) // need some from right res += FirstKSum(root.right, k-root.left.Size()-root.cnt) return res } /** * Your MKAverage object will be instantiated and called as such: * obj := Constructor(m, k); * obj.AddElement(num); * param_2 := obj.CalculateMKAverage(); */
src/leetcode/set1000/set1000/set1800/set1820/p1825/solution.go
0.627152
0.468608
solution.go
starcoder