code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
package state import "github.com/google/uuid" func getDefaultWorldChangeRoutines() map[string]ChangeRoutine { return map[string]ChangeRoutine{} } func getDefaultWorldStates(states map[string]interface{}) (result map[string]interface{}) { result = map[string]interface{}{ "temperature": float64(20), "humidity": float64(50), "lux": float64(10000), "co-ppm": float64(1.5), } for key, value := range states { result[key] = value } return result } func getDefaultRoomChangeRoutines() (result map[string]ChangeRoutine, err error) { tempId, err := uuid.NewRandom() if err != nil { return result, err } humitId, err := uuid.NewRandom() if err != nil { return result, err } coId, err := uuid.NewRandom() if err != nil { return result, err } return map[string]ChangeRoutine{ tempId.String(): ChangeRoutine{ Id: tempId.String(), Interval: 10, Code: default_room_temp_code, }, humitId.String(): ChangeRoutine{ Id: humitId.String(), Interval: 10, Code: default_room_hum_code, }, coId.String(): ChangeRoutine{ Id: coId.String(), Interval: 10, Code: default_room_co_code, }, }, nil } func getDefaultRoomStates(states map[string]interface{}) (result map[string]interface{}) { result = map[string]interface{}{ "temperature": float64(20), "humidity": float64(50), "lux": float64(50), "co-ppm": float64(1.5), } for key, value := range states { result[key] = value } return result } var defaultTemplates = map[string]RoutineTemplate{ "default_linear": RoutineTemplate{ Name: "linear", Description: `default linear template compareState is for example world compareValue is for example temp changeState is for example world.getRoom("room_1") changeValue is for example temp increment is the value by which the changeValue is incremented ore decremented`, Parameter: []string{"compareState", "compareValue", "changeState", "changeValue", "increment"}, Template: `var targetValue = moses.{{compareState}}.state.get("{{compareValue}}"); var isValue = moses.{{changeState}}.state.get("{{changeValue}}"); if(targetValue > isValue){ isValue = isValue + {{increment}}; }else if(targetValue < isValue){ isValue = isValue - {{increment}}; } isValue = Number(isValue.toFixed(1)); moses.{{changeState}}.state.set("{{changeValue}}", isValue);`, }, } const default_room_temp_code = `var temperature = moses.world.state.get("temperature"); var room_temperature = moses.room.state.get("temperature"); if(temperature > room_temperature){ room_temperature = room_temperature + 1; }else if(temperature < room_temperature){ room_temperature = room_temperature - 1; } room_temperature = Number(room_temperature.toFixed(1)); moses.room.state.set("temperature", room_temperature); ` const default_room_hum_code = `var humidity = moses.world.state.get("humidity"); var room_humidity = moses.room.state.get("humidity"); if(humidity > room_humidity){ room_humidity = room_humidity + 1; }else if(humidity < room_humidity){ room_humidity = room_humidity - 1; } room_humidity = Number(room_humidity.toFixed(1)); moses.room.state.set("humidity", room_humidity); ` const default_room_co_code = `var co = moses.world.state.get("co-ppm"); var room_co = moses.room.state.get("co-ppm"); if(co > room_co){ room_co = room_co + 0.1; }else if(co < room_co){ room_co = room_co - 0.1; } room_co = Number(room_co.toFixed(2)); moses.room.state.set("co-ppm", room_co); `
lib/state/default.go
0.513668
0.404478
default.go
starcoder
Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package jsonpath import "fmt" // NodeType identifies the type of a parse tree node. type NodeType int // Type returns itself and provides an easy default implementation func (t NodeType) Type() NodeType { return t } func (t NodeType) String() string { return NodeTypeName[t] } const ( NodeText NodeType = iota NodeArray NodeList NodeField NodeIdentifier NodeFilter NodeInt NodeFloat NodeWildcard NodeRecursive NodeUnion NodeBool ) var NodeTypeName = map[NodeType]string{ NodeText: "NodeText", NodeArray: "NodeArray", NodeList: "NodeList", NodeField: "NodeField", NodeIdentifier: "NodeIdentifier", NodeFilter: "NodeFilter", NodeInt: "NodeInt", NodeFloat: "NodeFloat", NodeWildcard: "NodeWildcard", NodeRecursive: "NodeRecursive", NodeUnion: "NodeUnion", NodeBool: "NodeBool", } type Node interface { Type() NodeType String() string } // ListNode holds a sequence of nodes. type ListNode struct { NodeType Nodes []Node // The element nodes in lexical order. } func newList() *ListNode { return &ListNode{NodeType: NodeList} } func (l *ListNode) append(n Node) { l.Nodes = append(l.Nodes, n) } func (l *ListNode) String() string { return fmt.Sprintf("%s", l.Type()) } // TextNode holds plain text. type TextNode struct { NodeType Text string // The text; may span newlines. } func newText(text string) *TextNode { return &TextNode{NodeType: NodeText, Text: text} } func (t *TextNode) String() string { return fmt.Sprintf("%s: %s", t.Type(), t.Text) } // FieldNode holds field of struct type FieldNode struct { NodeType Value string } func newField(value string) *FieldNode { return &FieldNode{NodeType: NodeField, Value: value} } func (f *FieldNode) String() string { return fmt.Sprintf("%s: %s", f.Type(), f.Value) } // IdentifierNode holds an identifier type IdentifierNode struct { NodeType Name string } func newIdentifier(value string) *IdentifierNode { return &IdentifierNode{ NodeType: NodeIdentifier, Name: value, } } func (f *IdentifierNode) String() string { return fmt.Sprintf("%s: %s", f.Type(), f.Name) } // ParamsEntry holds param information for ArrayNode type ParamsEntry struct { Value int Known bool // whether the value is known when parse it } // ArrayNode holds start, end, step information for array index selection type ArrayNode struct { NodeType Params [3]ParamsEntry // start, end, step } func newArray(params [3]ParamsEntry) *ArrayNode { return &ArrayNode{ NodeType: NodeArray, Params: params, } } func (a *ArrayNode) String() string { return fmt.Sprintf("%s: %v", a.Type(), a.Params) } // FilterNode holds operand and operator information for filter type FilterNode struct { NodeType Left *ListNode Right *ListNode Operator string } func newFilter(left, right *ListNode, operator string) *FilterNode { return &FilterNode{ NodeType: NodeFilter, Left: left, Right: right, Operator: operator, } } func (f *FilterNode) String() string { return fmt.Sprintf("%s: %s %s %s", f.Type(), f.Left, f.Operator, f.Right) } // IntNode holds integer value type IntNode struct { NodeType Value int } func newInt(num int) *IntNode { return &IntNode{NodeType: NodeInt, Value: num} } func (i *IntNode) String() string { return fmt.Sprintf("%s: %d", i.Type(), i.Value) } // FloatNode holds float value type FloatNode struct { NodeType Value float64 } func newFloat(num float64) *FloatNode { return &FloatNode{NodeType: NodeFloat, Value: num} } func (i *FloatNode) String() string { return fmt.Sprintf("%s: %f", i.Type(), i.Value) } // WildcardNode means a wildcard type WildcardNode struct { NodeType } func newWildcard() *WildcardNode { return &WildcardNode{NodeType: NodeWildcard} } func (i *WildcardNode) String() string { return fmt.Sprintf("%s", i.Type()) } // RecursiveNode means a recursive descent operator type RecursiveNode struct { NodeType } func newRecursive() *RecursiveNode { return &RecursiveNode{NodeType: NodeRecursive} } func (r *RecursiveNode) String() string { return fmt.Sprintf("%s", r.Type()) } // UnionNode is union of ListNode type UnionNode struct { NodeType Nodes []*ListNode } func newUnion(nodes []*ListNode) *UnionNode { return &UnionNode{NodeType: NodeUnion, Nodes: nodes} } func (u *UnionNode) String() string { return fmt.Sprintf("%s", u.Type()) } // BoolNode holds bool value type BoolNode struct { NodeType Value bool } func newBool(value bool) *BoolNode { return &BoolNode{NodeType: NodeBool, Value: value} } func (b *BoolNode) String() string { return fmt.Sprintf("%s: %t", b.Type(), b.Value) }
kubernetes-model/vendor/k8s.io/kubernetes/staging/src/k8s.io/client-go/util/jsonpath/node.go
0.885687
0.542379
node.go
starcoder
package limits import ( "github.com/gophercloud/gophercloud" ) // Limits is a struct that contains the response of a limit query. type Limits struct { // Absolute contains the limits and usage information. // An absolute limit value of -1 indicates that the absolute limit for the item is infinite. Absolute Absolute `json:"absolute"` // Rate contains rate-limit volume copy bandwidth, used to mitigate slow down of data access from the instances. Rate []Rate `json:"rate"` } // Absolute is a struct that contains the current resource usage and limits // of a project. type Absolute struct { // MaxTotalVolumes is the maximum number of volumes. MaxTotalVolumes int `json:"maxTotalVolumes"` // MaxTotalSnapshots is the maximum number of snapshots. MaxTotalSnapshots int `json:"maxTotalSnapshots"` // MaxTotalVolumeGigabytes is the maximum total amount of volumes, in gibibytes (GiB). MaxTotalVolumeGigabytes int `json:"maxTotalVolumeGigabytes"` // MaxTotalBackups is the maximum number of backups. MaxTotalBackups int `json:"maxTotalBackups"` // MaxTotalBackupGigabytes is the maximum total amount of backups, in gibibytes (GiB). MaxTotalBackupGigabytes int `json:"maxTotalBackupGigabytes"` // TotalVolumesUsed is the total number of volumes used. TotalVolumesUsed int `json:"totalVolumesUsed"` // TotalGigabytesUsed is the total number of gibibytes (GiB) used. TotalGigabytesUsed int `json:"totalGigabytesUsed"` // TotalSnapshotsUsed the total number of snapshots used. TotalSnapshotsUsed int `json:"totalSnapshotsUsed"` // TotalBackupsUsed is the total number of backups used. TotalBackupsUsed int `json:"totalBackupsUsed"` // TotalBackupGigabytesUsed is the total number of backups gibibytes (GiB) used. TotalBackupGigabytesUsed int `json:"totalBackupGigabytesUsed"` } // Rate is a struct that contains the // rate-limit volume copy bandwidth, used to mitigate slow down of data access from the instances. type Rate struct { Regex string `json:"regex"` URI string `json:"uri"` Limit []Limit `json:"limit"` } // Limit struct contains Limit values for the Rate struct type Limit struct { Verb string `json:"verb"` NextAvailable string `json:"next-available"` Unit string `json:"unit"` Value int `json:"value"` Remaining int `json:"remaining"` } // Extract interprets a limits result as a Limits. func (r GetResult) Extract() (*Limits, error) { var s struct { Limits *Limits `json:"limits"` } err := r.ExtractInto(&s) return s.Limits, err } // GetResult is the response from a Get operation. Call its Extract // method to interpret it as an Absolute. type GetResult struct { gophercloud.Result }
openstack/blockstorage/extensions/limits/results.go
0.733547
0.446434
results.go
starcoder
package router //go:generate go run generate_rest_tape_player.go import ( "image" "github.com/Postcord/objects" "github.com/Postcord/rest" ) type restTapePlayer struct { t TestingT tape tape index int } func (r *restTapePlayer) AddGuildCommand(a objects.Snowflake, b objects.Snowflake, c *objects.ApplicationCommand) (d *objects.ApplicationCommand, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected AddGuildCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "AddGuildCommand", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) AddGuildMember(a objects.Snowflake, b objects.Snowflake, c *rest.AddGuildMemberParams) (d *objects.GuildMember, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected AddGuildMember at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "AddGuildMember", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) AddGuildMemberRole(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake, d string) (e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected AddGuildMemberRole at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "AddGuildMemberRole", false, 4, a, b, c, d, &e) return } func (r *restTapePlayer) AddPinnedMessage(a objects.Snowflake, b objects.Snowflake) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected AddPinnedMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "AddPinnedMessage", false, 2, a, b, &c) return } func (r *restTapePlayer) AddThreadMember(a objects.Snowflake, b objects.Snowflake) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected AddThreadMember at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "AddThreadMember", false, 2, a, b, &c) return } func (r *restTapePlayer) BatchEditApplicationCommandPermissions(a objects.Snowflake, b objects.Snowflake, c []*objects.GuildApplicationCommandPermissions) (d []*objects.GuildApplicationCommandPermissions, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected BatchEditApplicationCommandPermissions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "BatchEditApplicationCommandPermissions", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) BeginGuildPrune(a objects.Snowflake, b *rest.BeginGuildPruneParams) (c int, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected BeginGuildPrune at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "BeginGuildPrune", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) BulkDeleteMessages(a objects.Snowflake, b *rest.DeleteMessagesParams) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected BulkDeleteMessages at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "BulkDeleteMessages", false, 2, a, b, &c) return } func (r *restTapePlayer) BulkOverwriteGlobalCommands(a objects.Snowflake, b []*objects.ApplicationCommand) (c []*objects.ApplicationCommand, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected BulkOverwriteGlobalCommands at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "BulkOverwriteGlobalCommands", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) BulkOverwriteGuildCommands(a objects.Snowflake, b objects.Snowflake, c []*objects.ApplicationCommand) (d []*objects.ApplicationCommand, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected BulkOverwriteGuildCommands at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "BulkOverwriteGuildCommands", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) CreateBan(a objects.Snowflake, b objects.Snowflake, c *rest.CreateGuildBanParams) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateBan at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateBan", false, 3, a, b, c, &d) return } func (r *restTapePlayer) CreateChannelInvite(a objects.Snowflake, b *rest.CreateInviteParams) (c *objects.Invite, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateChannelInvite at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateChannelInvite", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CreateCommand(a objects.Snowflake, b *objects.ApplicationCommand) (c *objects.ApplicationCommand, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateCommand", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CreateDM(a *rest.CreateDMParams) (b *objects.Channel, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateDM at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateDM", false, 1, a, &b, &c) return } func (r *restTapePlayer) CreateFollowupMessage(a objects.Snowflake, b string, c *rest.CreateFollowupMessageParams) (d *objects.Message, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateFollowupMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateFollowupMessage", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) CreateGroupDM(a *rest.CreateGroupDMParams) (b *objects.Channel, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateGroupDM at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateGroupDM", false, 1, a, &b, &c) return } func (r *restTapePlayer) CreateGuild(a *rest.CreateGuildParams) (b *objects.Guild, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateGuild at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateGuild", false, 1, a, &b, &c) return } func (r *restTapePlayer) CreateGuildChannel(a objects.Snowflake, b *rest.ChannelCreateParams) (c *objects.Channel, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateGuildChannel at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateGuildChannel", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CreateGuildFromTemplate(a string, b string) (c *objects.Guild, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateGuildFromTemplate at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateGuildFromTemplate", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CreateGuildRole(a objects.Snowflake, b *rest.CreateGuildRoleParams) (c *objects.Role, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateGuildRole at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateGuildRole", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CreateGuildTemplate(a objects.Snowflake, b *rest.CreateGuildTemplateParams) (c *objects.Template, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateGuildTemplate at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateGuildTemplate", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CreateInteractionResponse(a objects.Snowflake, b string, c *objects.InteractionResponse) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateInteractionResponse at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateInteractionResponse", false, 3, a, b, c, &d) return } func (r *restTapePlayer) CreateMessage(a objects.Snowflake, b *rest.CreateMessageParams) (c *objects.Message, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateMessage", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CreateReaction(a objects.Snowflake, b objects.Snowflake, c interface {}) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateReaction at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateReaction", false, 3, a, b, c, &d) return } func (r *restTapePlayer) CreateWebhook(a objects.Snowflake, b *rest.CreateWebhookParams) (c *objects.Webhook, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CreateWebhook at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CreateWebhook", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) CrossPostMessage(a objects.Snowflake, b objects.Snowflake) (c *objects.Message, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected CrossPostMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "CrossPostMessage", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) DeleteAllReactions(a objects.Snowflake, b objects.Snowflake) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteAllReactions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteAllReactions", false, 2, a, b, &c) return } func (r *restTapePlayer) DeleteChannel(a objects.Snowflake, b string) (c *objects.Channel, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteChannel at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteChannel", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) DeleteChannelPermission(a objects.Snowflake, b objects.Snowflake, c string) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteChannelPermission at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteChannelPermission", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeleteCommand(a objects.Snowflake, b objects.Snowflake) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteCommand", false, 2, a, b, &c) return } func (r *restTapePlayer) DeleteEmojiReactions(a objects.Snowflake, b objects.Snowflake, c interface {}) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteEmojiReactions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteEmojiReactions", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeleteFollowupMessage(a objects.Snowflake, b string, c objects.Snowflake) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteFollowupMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteFollowupMessage", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeleteGuild(a objects.Snowflake) (b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteGuild at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteGuild", false, 1, a, &b) return } func (r *restTapePlayer) DeleteGuildCommand(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteGuildCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteGuildCommand", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeleteGuildIntegration(a objects.Snowflake, b objects.Snowflake, c string) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteGuildIntegration at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteGuildIntegration", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeleteGuildRole(a objects.Snowflake, b objects.Snowflake, c string) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteGuildRole at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteGuildRole", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeleteGuildTemplate(a objects.Snowflake, b string, c string) (d *objects.Template, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteGuildTemplate at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteGuildTemplate", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) DeleteInvite(a string, b string) (c *objects.Invite, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteInvite at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteInvite", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) DeleteMessage(a objects.Snowflake, b objects.Snowflake) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteMessage", false, 2, a, b, &c) return } func (r *restTapePlayer) DeleteOriginalInteractionResponse(a objects.Snowflake, b string) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteOriginalInteractionResponse at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteOriginalInteractionResponse", false, 2, a, b, &c) return } func (r *restTapePlayer) DeleteOwnReaction(a objects.Snowflake, b objects.Snowflake, c interface {}) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteOwnReaction at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteOwnReaction", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeletePinnedMessage(a objects.Snowflake, b objects.Snowflake) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeletePinnedMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeletePinnedMessage", false, 2, a, b, &c) return } func (r *restTapePlayer) DeleteUserReaction(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake, d interface {}) (e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteUserReaction at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteUserReaction", false, 4, a, b, c, d, &e) return } func (r *restTapePlayer) DeleteWebhook(a objects.Snowflake) (b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteWebhook at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteWebhook", false, 1, a, &b) return } func (r *restTapePlayer) DeleteWebhookMessage(a objects.Snowflake, b objects.Snowflake, c string) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteWebhookMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteWebhookMessage", false, 3, a, b, c, &d) return } func (r *restTapePlayer) DeleteWebhookWithToken(a objects.Snowflake, b string) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected DeleteWebhookWithToken at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "DeleteWebhookWithToken", false, 2, a, b, &c) return } func (r *restTapePlayer) EditApplicationCommandPermissions(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake, d []*objects.ApplicationCommandPermissions) (e *objects.GuildApplicationCommandPermissions, f error) { if r.index == len(r.tape) { r.t.Fatal("unexpected EditApplicationCommandPermissions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "EditApplicationCommandPermissions", false, 4, a, b, c, d, &e, &f) return } func (r *restTapePlayer) EditChannelPermissions(a objects.Snowflake, b objects.Snowflake, c *rest.EditChannelParams) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected EditChannelPermissions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "EditChannelPermissions", false, 3, a, b, c, &d) return } func (r *restTapePlayer) EditFollowupMessage(a objects.Snowflake, b string, c objects.Snowflake, d *rest.EditWebhookMessageParams) (e *objects.Message, f error) { if r.index == len(r.tape) { r.t.Fatal("unexpected EditFollowupMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "EditFollowupMessage", false, 4, a, b, c, d, &e, &f) return } func (r *restTapePlayer) EditMessage(a objects.Snowflake, b objects.Snowflake, c *rest.EditMessageParams) (d *objects.Message, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected EditMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "EditMessage", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) EditOriginalInteractionResponse(a objects.Snowflake, b string, c *rest.EditWebhookMessageParams) (d *objects.Message, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected EditOriginalInteractionResponse at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "EditOriginalInteractionResponse", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) EditWebhookMessage(a objects.Snowflake, b objects.Snowflake, c string, d *rest.EditWebhookMessageParams) (e *objects.Message, f error) { if r.index == len(r.tape) { r.t.Fatal("unexpected EditWebhookMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "EditWebhookMessage", false, 4, a, b, c, d, &e, &f) return } func (r *restTapePlayer) ExecuteWebhook(a objects.Snowflake, b string, c *rest.ExecuteWebhookParams) (d *objects.Message, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ExecuteWebhook at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ExecuteWebhook", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) FollowNewsChannel(a objects.Snowflake) (b *objects.FollowedChannel, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected FollowNewsChannel at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "FollowNewsChannel", false, 1, a, &b, &c) return } func (r *restTapePlayer) Gateway() (a *objects.Gateway, b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected Gateway at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "Gateway", false, 0, &a, &b) return } func (r *restTapePlayer) GatewayBot() (a *objects.Gateway, b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GatewayBot at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GatewayBot", false, 0, &a, &b) return } func (r *restTapePlayer) GetApplicationCommandPermissions(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake) (d *objects.GuildApplicationCommandPermissions, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetApplicationCommandPermissions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetApplicationCommandPermissions", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) GetAuditLogs(a objects.Snowflake, b *rest.GetAuditLogParams) (c *objects.AuditLog, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetAuditLogs at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetAuditLogs", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetChannel(a objects.Snowflake) (b *objects.Channel, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetChannel at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetChannel", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetChannelInvites(a objects.Snowflake) (b []*objects.Invite, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetChannelInvites at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetChannelInvites", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetChannelMessage(a objects.Snowflake, b objects.Snowflake) (c *objects.Message, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetChannelMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetChannelMessage", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetChannelMessages(a objects.Snowflake, b *rest.GetChannelMessagesParams) (c []*objects.Message, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetChannelMessages at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetChannelMessages", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetChannelWebhooks(a objects.Snowflake) (b []*objects.Webhook, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetChannelWebhooks at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetChannelWebhooks", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetCommand(a objects.Snowflake, b objects.Snowflake) (c *objects.ApplicationCommand, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetCommand", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetCommands(a objects.Snowflake) (b []*objects.ApplicationCommand, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetCommands at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetCommands", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetCurrentUser() (a *objects.User, b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetCurrentUser at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetCurrentUser", false, 0, &a, &b) return } func (r *restTapePlayer) GetCurrentUserGuilds(a *rest.CurrentUserGuildsParams) (b []*objects.Guild, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetCurrentUserGuilds at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetCurrentUserGuilds", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetFollowupMessage(a objects.Snowflake, b string, c objects.Snowflake) (d *objects.Message, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetFollowupMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetFollowupMessage", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) GetGuild(a objects.Snowflake) (b *objects.Guild, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuild at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuild", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildApplicationCommandPermissions(a objects.Snowflake, b objects.Snowflake) (c []*objects.GuildApplicationCommandPermissions, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildApplicationCommandPermissions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildApplicationCommandPermissions", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetGuildBan(a objects.Snowflake, b objects.Snowflake) (c *objects.Ban, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildBan at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildBan", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetGuildBans(a objects.Snowflake) (b []*objects.Ban, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildBans at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildBans", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildChannels(a objects.Snowflake) (b []*objects.Channel, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildChannels at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildChannels", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildCommand(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake) (d *objects.ApplicationCommand, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildCommand", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) GetGuildCommands(a objects.Snowflake, b objects.Snowflake) (c []*objects.ApplicationCommand, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildCommands at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildCommands", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetGuildIntegrations(a objects.Snowflake) (b []*objects.Integration, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildIntegrations at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildIntegrations", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildInvites(a objects.Snowflake) (b []*objects.Invite, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildInvites at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildInvites", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildMember(a objects.Snowflake, b objects.Snowflake) (c *objects.GuildMember, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildMember at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildMember", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetGuildPreview(a objects.Snowflake) (b *objects.GuildPreview, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildPreview at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildPreview", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildPruneCount(a objects.Snowflake, b *rest.GetGuildPruneCountParams) (c int, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildPruneCount at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildPruneCount", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetGuildRoles(a objects.Snowflake) (b []*objects.Role, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildRoles at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildRoles", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildTemplates(a objects.Snowflake) (b []*objects.Template, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildTemplates at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildTemplates", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildVanityURL(a objects.Snowflake) (b *objects.Invite, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildVanityURL at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildVanityURL", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildVoiceRegions(a objects.Snowflake) (b []*objects.VoiceRegion, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildVoiceRegions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildVoiceRegions", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildWebhooks(a objects.Snowflake) (b []*objects.Webhook, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildWebhooks at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildWebhooks", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildWelcomeScreen(a objects.Snowflake) (b *objects.MembershipScreening, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildWelcomeScreen at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildWelcomeScreen", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildWidget(a objects.Snowflake) (b *objects.GuildWidgetJSON, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildWidget at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildWidget", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetGuildWidgetImage(a objects.Snowflake, b *rest.GuildWidgetImageParams) (c image.Image, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildWidgetImage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildWidgetImage", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetGuildWidgetSettings(a objects.Snowflake) (b *objects.GuildWidget, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetGuildWidgetSettings at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetGuildWidgetSettings", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetInvite(a string, b *rest.GetInviteParams) (c *objects.Invite, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetInvite at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetInvite", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetOriginalInteractionResponse(a objects.Snowflake, b string) (c *objects.Message, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetOriginalInteractionResponse at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetOriginalInteractionResponse", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) GetPinnedMessages(a objects.Snowflake) (b []*objects.Message, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetPinnedMessages at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetPinnedMessages", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetReactions(a objects.Snowflake, b objects.Snowflake, c interface {}, d *rest.GetReactionsParams) (e []*objects.User, f error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetReactions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetReactions", false, 4, a, b, c, d, &e, &f) return } func (r *restTapePlayer) GetTemplate(a string) (b *objects.Template, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetTemplate at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetTemplate", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetUser(a objects.Snowflake) (b *objects.User, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetUser at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetUser", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetUserConnections() (a []*objects.Connection, b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetUserConnections at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetUserConnections", false, 0, &a, &b) return } func (r *restTapePlayer) GetVoiceRegions() (a []*objects.VoiceRegion, b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetVoiceRegions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetVoiceRegions", false, 0, &a, &b) return } func (r *restTapePlayer) GetWebhook(a objects.Snowflake) (b *objects.Webhook, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetWebhook at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetWebhook", false, 1, a, &b, &c) return } func (r *restTapePlayer) GetWebhookWithToken(a objects.Snowflake, b string) (c *objects.Webhook, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected GetWebhookWithToken at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "GetWebhookWithToken", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) JoinThread(a objects.Snowflake) (b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected JoinThread at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "JoinThread", false, 1, a, &b) return } func (r *restTapePlayer) LeaveGuild(a objects.Snowflake) (b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected LeaveGuild at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "LeaveGuild", false, 1, a, &b) return } func (r *restTapePlayer) LeaveThread(a objects.Snowflake) (b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected LeaveThread at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "LeaveThread", false, 1, a, &b) return } func (r *restTapePlayer) ListActiveThreads(a objects.Snowflake) (b []*rest.ListThreadsResponse, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ListActiveThreads at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ListActiveThreads", false, 1, a, &b, &c) return } func (r *restTapePlayer) ListGuildMembers(a objects.Snowflake, b *rest.ListGuildMembersParams) (c []*objects.GuildMember, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ListGuildMembers at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ListGuildMembers", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ListJoinedPrivateArchivedThreads(a objects.Snowflake, b ...*rest.ListThreadsParams) (c *rest.ListThreadsResponse, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ListJoinedPrivateArchivedThreads at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ListJoinedPrivateArchivedThreads", true, 2, a, b, &c, &d) return } func (r *restTapePlayer) ListPrivateArchivedThreads(a objects.Snowflake, b ...*rest.ListThreadsParams) (c *rest.ListThreadsResponse, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ListPrivateArchivedThreads at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ListPrivateArchivedThreads", true, 2, a, b, &c, &d) return } func (r *restTapePlayer) ListPublicArchivedThreads(a objects.Snowflake, b ...*rest.ListThreadsParams) (c *rest.ListThreadsResponse, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ListPublicArchivedThreads at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ListPublicArchivedThreads", true, 2, a, b, &c, &d) return } func (r *restTapePlayer) ListThreadMembers(a objects.Snowflake) (b []*objects.ThreadMember, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ListThreadMembers at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ListThreadMembers", false, 1, a, &b, &c) return } func (r *restTapePlayer) ModifyChannel(a objects.Snowflake, b *rest.ModifyChannelParams) (c *objects.Channel, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyChannel at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyChannel", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ModifyCurrentUser(a *rest.ModifyCurrentUserParams) (b *objects.User, c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyCurrentUser at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyCurrentUser", false, 1, a, &b, &c) return } func (r *restTapePlayer) ModifyCurrentUserNick(a objects.Snowflake, b *rest.ModifyCurrentUserNickParams) (c *rest.ModifyCurrentUserNickParams, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyCurrentUserNick at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyCurrentUserNick", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ModifyGuild(a objects.Snowflake, b *rest.ModifyGuildParams) (c *objects.Guild, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuild at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuild", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ModifyGuildChannelPositions(a objects.Snowflake, b []*rest.ModifyChannelPositionParams, c string) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuildChannelPositions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuildChannelPositions", false, 3, a, b, c, &d) return } func (r *restTapePlayer) ModifyGuildMember(a objects.Snowflake, b objects.Snowflake, c *rest.ModifyGuildMemberParams) (d *objects.GuildMember, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuildMember at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuildMember", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) ModifyGuildRole(a objects.Snowflake, b objects.Snowflake, c *rest.ModifyGuildRoleParams) (d *objects.Role, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuildRole at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuildRole", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) ModifyGuildRolePositions(a objects.Snowflake, b []*rest.ModifyGuildRolePositionsParams) (c []*objects.Role, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuildRolePositions at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuildRolePositions", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ModifyGuildTemplate(a objects.Snowflake, b string, c *rest.ModifyGuildTemplateParams) (d *objects.Template, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuildTemplate at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuildTemplate", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) ModifyGuildWelcomeScreen(a objects.Snowflake, b *rest.ModifyGuildMembershipScreeningParams) (c *objects.MembershipScreening, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuildWelcomeScreen at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuildWelcomeScreen", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ModifyGuildWidget(a objects.Snowflake, b *rest.GuildWidgetParams) (c *objects.GuildWidget, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyGuildWidget at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyGuildWidget", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ModifyWebhook(a objects.Snowflake, b *rest.ModifyWebhookParams) (c *objects.Webhook, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyWebhook at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyWebhook", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) ModifyWebhookWithToken(a objects.Snowflake, b string, c *rest.ModifyWebhookWithTokenParams) (d *objects.Webhook, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected ModifyWebhookWithToken at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "ModifyWebhookWithToken", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) RemoveGuildBan(a objects.Snowflake, b objects.Snowflake, c string) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected RemoveGuildBan at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "RemoveGuildBan", false, 3, a, b, c, &d) return } func (r *restTapePlayer) RemoveGuildMember(a objects.Snowflake, b objects.Snowflake, c string) (d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected RemoveGuildMember at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "RemoveGuildMember", false, 3, a, b, c, &d) return } func (r *restTapePlayer) RemoveGuildMemberRole(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake, d string) (e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected RemoveGuildMemberRole at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "RemoveGuildMemberRole", false, 4, a, b, c, d, &e) return } func (r *restTapePlayer) RemoveThreadMember(a objects.Snowflake, b objects.Snowflake) (c error) { if r.index == len(r.tape) { r.t.Fatal("unexpected RemoveThreadMember at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "RemoveThreadMember", false, 2, a, b, &c) return } func (r *restTapePlayer) StartThread(a objects.Snowflake, b *rest.StartThreadParams) (c *objects.Channel, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected StartThread at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "StartThread", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) StartThreadWithMessage(a objects.Snowflake, b objects.Snowflake, c *rest.StartThreadParams) (d *objects.Channel, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected StartThreadWithMessage at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "StartThreadWithMessage", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) StartTyping(a objects.Snowflake) (b error) { if r.index == len(r.tape) { r.t.Fatal("unexpected StartTyping at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "StartTyping", false, 1, a, &b) return } func (r *restTapePlayer) SyncGuildTemplate(a objects.Snowflake, b string) (c *objects.Template, d error) { if r.index == len(r.tape) { r.t.Fatal("unexpected SyncGuildTemplate at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "SyncGuildTemplate", false, 2, a, b, &c, &d) return } func (r *restTapePlayer) UpdateCommand(a objects.Snowflake, b objects.Snowflake, c *objects.ApplicationCommand) (d *objects.ApplicationCommand, e error) { if r.index == len(r.tape) { r.t.Fatal("unexpected UpdateCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "UpdateCommand", false, 3, a, b, c, &d, &e) return } func (r *restTapePlayer) UpdateGuildCommand(a objects.Snowflake, b objects.Snowflake, c objects.Snowflake, d *objects.ApplicationCommand) (e *objects.ApplicationCommand, f error) { if r.index == len(r.tape) { r.t.Fatal("unexpected UpdateGuildCommand at end of tape") return // Here for unit tests - in production this will never be hit. } action := r.tape[r.index] r.index++ action.match(r.t, "UpdateGuildCommand", false, 4, a, b, c, d, &e, &f) return }
rest_tape_player_gen.go
0.550366
0.449091
rest_tape_player_gen.go
starcoder
package decisiontrees import ( "code.google.com/p/goprotobuf/proto" pb "github.com/ajtulloch/decisiontrees/protobufs" "github.com/golang/glog" "sync" ) type lossState struct { averageLabel float64 sumSquaredDivergence float64 numExamples int } func constructLoss(e Examples) *lossState { l := &lossState{} for _, ex := range e { l.addExample(ex) } return l } func (l *lossState) addExample(e *pb.Example) { l.numExamples += 1 delta := e.GetWeightedLabel() - l.averageLabel l.averageLabel += delta / float64(l.numExamples) newDelta := e.GetWeightedLabel() - l.averageLabel l.sumSquaredDivergence += delta * newDelta } func (l *lossState) removeExample(e *pb.Example) { l.numExamples -= 1 delta := e.GetWeightedLabel() - l.averageLabel l.averageLabel -= delta / float64(l.numExamples) newDelta := e.GetWeightedLabel() - l.averageLabel l.sumSquaredDivergence -= delta * newDelta } type regressionSplitter struct { leafWeight func(e Examples) float64 featureSelector FeatureSelector splittingConstraints *pb.SplittingConstraints shrinkageConfig *pb.ShrinkageConfig } func (c *regressionSplitter) shouldSplit( examples Examples, bestSplit split, currentLevel int64) bool { if len(examples) <= 1 { glog.Infof("Num examples is %v, terminating", len(examples)) return false } if bestSplit.index == 0 || bestSplit.index == len(examples) { glog.Infof("Empty branch with bestSplit = %v, numExamples = %v, terminating", bestSplit, len(examples)) return false } maximumLevels := c.splittingConstraints.MaximumLevels if maximumLevels != nil && *maximumLevels < currentLevel { glog.Infof("Maximum levels is %v < %v currentLevel", *maximumLevels, currentLevel) return false } minAverageGain := c.splittingConstraints.MinimumAverageGain if minAverageGain != nil && *minAverageGain > bestSplit.gain/float64(len(examples)) { return false } minSamplesAtLeaf := c.splittingConstraints.MinimumSamplesAtLeaf if minSamplesAtLeaf != nil && *minSamplesAtLeaf > int64(len(examples)) { return false } return true } type split struct { feature int index int gain float64 } func getBestSplit(examples Examples, feature int) split { examplesCopy := make([]*pb.Example, len(examples)) if copy(examplesCopy, examples) != len(examples) { glog.Fatal("Failed copying all examples for sorting") } by(func(e1, e2 *pb.Example) bool { return e1.Features[feature] < e2.Features[feature] }).Sort(Examples(examplesCopy)) leftLoss := constructLoss(Examples{}) rightLoss := constructLoss(examplesCopy) totalLoss := constructLoss(examplesCopy) bestSplit := split{ feature: feature, } for index, example := range examplesCopy { func() { if index == 0 { return } previousValue := examplesCopy[index-1].Features[feature] currentValue := example.Features[feature] if previousValue == currentValue { return } gain := totalLoss.sumSquaredDivergence - leftLoss.sumSquaredDivergence - rightLoss.sumSquaredDivergence if gain > bestSplit.gain { bestSplit.gain = gain bestSplit.index = index } }() leftLoss.addExample(example) rightLoss.removeExample(example) } return bestSplit } func (c *regressionSplitter) generateTree(examples Examples, currentLevel int64) *pb.TreeNode { glog.Infof("Generating tree at level %v with %v examples", currentLevel, len(examples)) glog.V(2).Infof("Generating with examples %+v", currentLevel, examples) features := c.featureSelector.getFeatures(examples) candidateSplits := make(chan split, len(features)) for _, feature := range features { go func(feature int) { candidateSplits <- getBestSplit(examples, feature) }(feature) } bestSplit := split{} for _ = range features { candidateSplit := <-candidateSplits if candidateSplit.gain > bestSplit.gain { bestSplit = candidateSplit } } if c.shouldSplit(examples, bestSplit, currentLevel) { glog.Infof("Splitting at level %v with split %v", currentLevel, bestSplit) by(func(e1, e2 *pb.Example) bool { return e1.Features[bestSplit.feature] < e2.Features[bestSplit.feature] }).Sort(examples) bestValue := 0.5 * (examples[bestSplit.index-1].Features[bestSplit.feature] + examples[bestSplit.index].Features[bestSplit.feature]) tree := &pb.TreeNode{ Feature: proto.Int64(int64(bestSplit.feature)), SplitValue: proto.Float64(bestValue), Annotation: &pb.Annotation{ NumExamples: proto.Int64(int64(len(examples))), AverageGain: proto.Float64(bestSplit.gain / float64(len(examples))), LeftFraction: proto.Float64(float64(bestSplit.index) / float64(len(examples))), }, } // Recur down the left and right branches in parallel w := sync.WaitGroup{} recur := func(child **pb.TreeNode, e Examples) { w.Add(1) go func() { *child = c.generateTree(e, currentLevel+1) w.Done() }() } recur(&tree.Left, examples[bestSplit.index:]) recur(&tree.Right, examples[:bestSplit.index]) w.Wait() return tree } glog.Infof("Terminating at level %v with %v examples", currentLevel, len(examples)) glog.V(2).Infof("Terminating with examples: %v", examples) // Otherwise, return the leaf leafWeight := c.leafWeight(examples) shrinkage := 1.0 if c.shrinkageConfig != nil && c.shrinkageConfig.Shrinkage != nil { shrinkage = c.shrinkageConfig.GetShrinkage() } glog.Infof("Leaf weight: %v, shrinkage: %v", leafWeight, shrinkage) return &pb.TreeNode{ LeafValue: proto.Float64(leafWeight * shrinkage), Annotation: &pb.Annotation{ NumExamples: proto.Int64(int64(len(examples))), }, } } // GenerateTree generates a regression tree on the examples given func (c *regressionSplitter) GenerateTree(examples Examples) *pb.TreeNode { return c.generateTree(examples, 0) }
regression_splitter.go
0.804098
0.455744
regression_splitter.go
starcoder
package biquad import ( "math" ) // Chebyshev filter. May represent Lowpass and other // Chebyshev filter implementations. type Chebyshev struct { blt } // From wikipedia: // Chebyshev type I Transfer function: // H(s) = (1/(2*e)) / ( s^2 - s*(sp_1+sp_2) + sp_1*sp_2) // where sp_m = j*cosh(asinh(1/e)/n)*cos(theta_m) - sinh(asinh(1/e)/n)*sin(theta_m) // where theta_m = pi*(2*m - 1) / (2*n) // We apply bilinear transformation as seen in butterworth file (and take into account non unity frequncy cutoff wc) // H(z) = (wc^2/ (2*e) * (1+2z^-1+z^-2) / (1-2z^{-1}+z^{-2} - wc*(sp1+sp2)*(1-z^{-2}) +wc^2*sp1*sp2*(1+2*z^{-1}+z^{-2})) // where wc is the pre-warped (analog) cutoff frequency. // H(z)_denominator = 1-wc(sp1+sp2)+wc^2*sp1*sp2 + z^{-1}*(-2+2*wc^2*sp1*sp2) + z^{-2}*(1+wc*(sp1+sp2)+wc^2*sp1*sp2) // We may now construct the BLT after applying frequency warp correction. // NewChebyshevLPType1 creates a low pass Chebyshev Type I filter from // Fs: sampling frequency // fh: -3dB attenuation frequency. This frequency is lower than the cutoff in Chebyshev lowpass filters. // Not guaranteed to have peak unity gain. func newChebyshevLPType1(Fs, fh, e float64) (*Chebyshev, error) { const n = 2. // Filter order. switch { case fh >= Fs: return nil, ErrBadWorkingFreq case fh <= 0 || Fs <= 0: return nil, ErrBadFreq } // The -3dB stopband start wh is related to wc by: // wh = wc * cosh(acosh(1/e)/n) // thus wc = wh / cosh(acosh(1/e)/n) wc := 2 * math.Pi * fh / math.Cosh(math.Acosh(1/e)/n) td := math.Tan(wc / (2 * Fs)) // wc_a = 2/Ts * tan(wc_d * Ts / 2) sp1 := sparametric1(2, 1, true, e) sp2 := sparametric1(2, 2, true, e) tdc := complex(td, 0) var ( // TODO fix whatever dont work here b0 = td * td / (2 * e) b1 = 2 * b0 b2 = b0 a0 = real(1 - tdc*sp1 + sp2 + tdc*tdc*sp1*sp2) a1 = real(-2 + 2*tdc*tdc*sp1*sp2) a2 = real(1 + tdc*(sp1+sp2) + tdc*tdc*sp1*sp2) ) return &Chebyshev{ blt: newBLT(a0, a1, a2, b0, b1, b2), // Do I need a new complex valued BLT type? }, nil } // calculate parametric pole of chebyshev type 1 transfer function. func sparametric1(n, m int, neg bool, e float64) complex128 { N := float64(n) M := float64(m) tm := math.Pi * (2*M - 1) / (2 * N) imagpart := math.Cosh(math.Asinh(1/e)/N) * math.Cos(tm) realpart := math.Sinh(math.Asinh(1/e)/N) * math.Sin(tm) if neg { realpart *= -1 } return complex(realpart, imagpart) }
chebyshev.go
0.669961
0.526891
chebyshev.go
starcoder
package seeds import "math/rand" //RandDummyURL return a dummy url func RandDummyURL() string { URL := [1000]string{ "http://www.example.com/behavior", "https://www.example.com/?berry=approval#boy", "http://www.example.net/", "https://www.example.org/back.html#bird", "http://blow.example.org/", "https://www.example.com/?bone=back", "http://www.example.com/?arithmetic=breath&behavior=bite", "http://www.example.com/", "https://www.example.net/addition", "http://www.example.com/battle/belief", "https://example.com/beds.html", "https://www.example.com/ball", "http://example.com/beginner/bell.php", "https://aunt.example.edu/#babies", "https://aftermath.example.com/", "http://baby.example.org/", "https://www.example.net/", "https://www.example.com/", "http://www.example.com/#air", "https://www.example.com/", "https://www.example.com/belief.htm", "https://www.example.com/achiever/arm#bell", "https://www.example.org/bells.html", "http://example.com/airport/animal.aspx", "http://www.example.com/", "https://babies.example.com/authority/bee.html", "http://www.example.com/", "https://example.net/army", "https://example.net/aunt/bead?blow=attraction&actor=baseball", "http://www.example.com/", "https://www.example.com/bat/adjustment.html", "http://www.example.com/", "https://www.example.com/amusement", "https://example.com/?airport=account&agreement=adjustment#believe", "http://www.example.com/", "http://www.example.com/", "http://example.com/", "http://brake.example.com/", "https://www.example.net/", "http://www.example.com/account", "http://example.com/#boy", "https://www.example.com/", "https://example.org/#balance", "http://www.example.com/basin/basketball#aftermath", "https://brother.example.com/", "https://bear.example.com/beginner/achiever.php", "http://www.example.com/bells.php", "https://www.example.net/", "http://bike.example.com/", "https://www.example.net/", "http://www.example.org/", "https://example.net/?books=bit&aftermath=blow", "http://www.example.com/attack/bite", "http://www.example.com/", "http://example.com/#acoustics", "http://example.net/bath.php", "https://www.example.edu/", "https://www.example.com/border", "https://example.com/", "https://www.example.com/bike/berry", "https://example.com/#animal", "https://www.example.net/?basket=berry&amusement=argument#bedroom", "http://www.example.org/?berry=advice&books=action", "https://example.com/", "https://example.com/", "https://basketball.example.edu/box.php?back=arm", "http://birth.example.net/", "http://www.example.com/", "http://www.example.edu/", "http://example.com/actor/argument.html", "https://example.net/ball.aspx?beginner=attraction", "http://bed.example.org/", "http://example.com/", "http://example.com/blow", "http://example.com/bikes/ball.aspx?animal=birth#afternoon", "http://example.com/actor/brick#basin", "https://www.example.com/birth/argument.html", "http://example.org/", "http://example.net/?badge=blade&bat=apparatus", "http://www.example.com/", "https://arm.example.net/bell/basketball.html", "http://www.example.com/book", "https://www.example.com/boat.html", "https://www.example.com/bells/boot", "http://www.example.com/", "http://www.example.net/?belief=brick#base", "https://www.example.com/", "https://www.example.com/aftermath/birth#activity", "https://www.example.com/", "https://airplane.example.com/brass/acoustics", "http://example.edu/birthday", "https://example.net/", "https://example.com/", "https://example.com/", "http://example.com/bath/brother.html?basketball=animal&attraction=addition", "https://www.example.org/boy.aspx", "https://www.example.com/?argument=blow", "https://www.example.com/#action", "http://www.example.com/#bottle", "https://arithmetic.example.com/bridge#acoustics", "https://example.net/bells.htm", "https://example.com/bait?attack=acoustics&behavior=adjustment", "https://example.com/advice.html?blade=arch&arm=bite", "http://example.com/bell?bedroom=afternoon&boot=books#battle", "https://example.com/", "http://www.example.com/?battle=amusement&babies=amount#anger", "http://afternoon.example.com/", "https://www.example.com/", "https://www.example.com/#bone", "https://www.example.com/#bed", "http://www.example.com/birds.htm", "http://www.example.edu/arithmetic.html", "https://www.example.org/", "https://amount.example.com/", "http://www.example.com/approval.html", "http://www.example.com/art/bike#alarm", "http://example.org/birthday.php", "http://www.example.com/?birds=breath&branch=act", "http://www.example.org/", "https://www.example.com/", "http://example.net/?bath=bikes", "http://example.com/", "https://basketball.example.com/?base=action", "http://www.example.net/bell.aspx", "http://brother.example.com/babies/baseball.aspx", "https://approval.example.com/bottle.php", "http://example.com/", "https://www.example.net/", "http://www.example.com/activity.aspx", "http://www.example.com/bee", "https://art.example.org/afternoon", "https://www.example.com/", "https://www.example.net/?basketball=bottle&advertisement=bag", "https://www.example.net/", "http://basketball.example.com/", "https://www.example.com/", "https://example.com/", "https://www.example.com/?bear=boot&bee=breath", "https://www.example.com/base?army=bath", "http://www.example.com/", "http://example.com/account.html", "http://animal.example.com/", "http://example.com/baseball?birds=brother&base=army", "http://blood.example.com/brass.html", "http://www.example.net/apparel.php", "https://example.net/", "http://www.example.com/bear", "https://www.example.org/", "http://example.com/", "http://example.com/", "http://www.example.net/ball.aspx", "http://www.example.com/amusement?behavior=advertisement&battle=berry#box", "http://example.com/branch?blade=brass&basketball=birthday", "https://www.example.net/baby/bikes.php#bike", "http://example.com/#beginner", "https://example.net/", "http://attack.example.com/baseball.php", "http://www.example.com/activity/book.php?badge=apparel&branch=bomb#bomb", "http://www.example.com/", "https://example.com/", "https://www.example.net/", "https://www.example.com/board/bottle.php", "https://birthday.example.com/", "http://www.example.com/brick/bag.php", "http://example.com/afternoon/base.htm?art=brass", "https://badge.example.org/", "https://example.com/appliance/agreement.php", "http://example.com/box.php", "https://example.com/beds.aspx", "https://baby.example.com/#action", "https://www.example.com/advice.aspx", "http://addition.example.com/approval.htm", "http://www.example.com/afterthought/amusement?bridge=account", "http://example.com/bath.html", "https://www.example.com/", "http://birthday.example.org/amusement?addition=balance", "https://example.com/bubble/behavior", "http://www.example.com/", "http://example.com/apparatus", "https://approval.example.edu/", "http://bikes.example.com/", "https://bead.example.com/", "http://www.example.com/", "http://www.example.com/?bait=angle", "http://example.com/?amount=beds", "https://actor.example.com/", "http://bottle.example.com/ball", "https://www.example.com/", "https://example.net/", "http://www.example.com/action/airplane", "https://www.example.com/advertisement/birds?box=advice&airplane=birth", "https://example.com/", "https://example.com/?blade=attack", "http://example.org/", "http://www.example.com/", "https://example.com/?bottle=bells", "https://www.example.com/?battle=account", "https://example.com/", "http://example.com/", "http://www.example.com/appliance.aspx", "https://example.com/?bridge=bath", "https://example.com/bikes/army?birthday=bedroom&brick=baseball#advertisement", "http://example.org/bee", "https://example.com/", "http://example.com/bedroom.php", "http://back.example.com/", "https://www.example.com/", "https://example.net/animal/afternoon.html", "http://example.com/ants.php", "http://www.example.com/", "http://example.com/bird/anger.php?bomb=branch&angle=aftermath", "https://www.example.com/", "https://example.com/?bedroom=actor&aunt=attraction", "https://example.edu/", "https://www.example.com/bike.html#basket", "https://www.example.org/air/badge.htm", "https://example.com/?beginner=attraction&appliance=alarm", "http://boat.example.com/border.aspx?board=action", "https://bedroom.example.com/arm.html?attack=advice#army", "https://www.example.org/achiever.html?bottle=boat&boundary=anger", "http://www.example.org/", "http://www.example.com/bedroom/alarm", "http://example.com/airport?branch=box&afterthought=arithmetic", "http://www.example.net/blade.php", "http://board.example.com/", "http://example.org/", "https://example.com/birth/blood", "http://www.example.com/", "https://blade.example.com/berry/baby", "https://www.example.com/amusement", "https://www.example.com/", "http://www.example.com/bee.php#boot", "https://afterthought.example.com/?birds=angle", "https://example.com/", "http://www.example.com/bee", "http://brake.example.com/art", "http://www.example.com/", "https://bridge.example.com/birds/amusement", "http://example.com/battle", "http://amount.example.com/", "https://www.example.org/", "http://www.example.com/", "http://example.com/acoustics/activity.php", "https://berry.example.net/", "https://www.example.com/", "http://www.example.com/border?bells=amusement&airport=bit", "http://example.com/army#apparel", "http://www.example.edu/bag.html", "http://approval.example.com/bikes/boat", "https://belief.example.com/", "https://example.com/", "http://example.org/", "https://bells.example.com/", "http://example.com/belief/arch.html", "https://www.example.com/", "https://www.example.com/air.php", "https://birds.example.com/", "http://example.org/#arithmetic", "https://www.example.com/bomb.htm", "https://example.com/?bell=advertisement&art=believe", "https://example.org/", "https://example.com/", "https://www.example.com/aunt.php", "http://example.com/", "http://example.com/agreement/brick.aspx", "https://adjustment.example.com/", "https://example.com/babies", "http://www.example.com/basket", "https://example.net/#afterthought", "https://example.com/alarm", "http://www.example.com/badge/animal.aspx", "http://www.example.org/boot/addition.php#birds", "https://blow.example.com/", "http://www.example.com/anger/border.php", "http://example.com/bag.html", "http://example.org/angle?angle=badge&birth=bubble", "https://example.com/bone/airport", "https://www.example.com/air/beds", "https://www.example.org/basketball", "https://example.com/amount.php", "https://www.example.com/", "https://example.com/base/bell.php#basketball", "http://example.net/?baby=approval", "http://www.example.com/approval?beds=amount&beginner=action", "https://www.example.com/", "https://back.example.net/birthday/agreement", "https://www.example.com/ants/bed", "https://www.example.com/", "https://arm.example.org/", "http://brick.example.com/?achiever=account#bear", "http://www.example.edu/?bite=ball", "http://www.example.com/", "http://www.example.com/army/basin.html", "https://www.example.com/bird", "http://example.com/", "http://example.com/", "https://battle.example.com/", "https://example.com/bead.aspx?authority=bath", "http://example.com/bell?agreement=books", "http://example.com/", "http://www.example.org/basketball/actor.html", "http://example.com/arm.html", "https://arithmetic.example.com/?bat=baby", "http://example.com/breath", "http://example.edu/#amount", "http://example.edu/balance?arch=aftermath&boat=birthday", "http://example.com/bomb", "http://www.example.net/?bottle=army&authority=arm", "https://www.example.org/?brass=bath&border=belief", "https://example.com/", "http://www.example.com/bag/action#bit", "https://example.com/", "https://afternoon.example.com/", "https://www.example.com/blow", "https://www.example.com/", "http://example.net/?balance=arithmetic&birth=bit", "http://blood.example.com/bubble/bridge.php", "https://www.example.com/book?books=attack&achiever=bite#beds", "http://www.example.com/basket/amount", "http://breath.example.com/brake.php", "https://www.example.net/", "http://blood.example.com/brick/boy.aspx?beef=blade", "http://www.example.com/", "http://example.com/basin", "http://back.example.com/", "https://www.example.com/", "http://www.example.com/boat.htm", "http://www.example.com/account.htm?acoustics=angle&apparel=blood", "http://www.example.net/?army=beds&bear=air", "http://aftermath.example.com/", "https://adjustment.example.com/", "https://argument.example.com/activity.php", "http://example.com/base#bridge", "http://example.com/?boot=bedroom&authority=actor", "http://www.example.com/", "http://apparatus.example.com/", "http://www.example.com/?agreement=breath", "http://example.com/", "https://www.example.org/achiever/attraction", "http://example.com/basin", "http://example.com/#action", "http://example.com/bat/airport.aspx#bedroom", "https://www.example.com/alarm.php", "https://badge.example.com/amount.php", "http://www.example.org/", "http://boy.example.com/?afterthought=battle", "https://example.com/amusement/basket", "https://www.example.com/", "https://www.example.com/believe/airport", "http://www.example.com/box.php", "https://example.com/?agreement=actor&bikes=boundary", "https://example.com/ball/boat.html", "https://army.example.com/", "https://www.example.org/", "https://example.com/?base=adjustment", "http://www.example.com/bridge", "http://example.com/", "https://example.com/#bead", "http://example.org/bite.htm", "https://www.example.org/?brother=approval", "https://example.com/alarm.html", "https://example.com/bear/back.php", "https://www.example.com/adjustment/box.htm", "http://branch.example.com/brake/authority.html", "https://example.com/authority/box?birth=aftermath&argument=bat", "https://www.example.com/afterthought.html", "https://www.example.com/", "https://example.com/act/beef.php", "http://acoustics.example.net/", "http://box.example.com/attack.aspx", "http://www.example.com/", "http://example.net/beef/apparel", "https://example.com/", "https://www.example.com/", "http://www.example.com/?bomb=attack&brother=bridge", "http://www.example.com/breath.php?balance=advice&agreement=blood", "http://www.example.com/bead/ball.html", "http://www.example.com/", "http://animal.example.com/brake/boy.php", "https://www.example.com/", "http://www.example.com/art.php", "https://example.com/?adjustment=aftermath", "https://www.example.com/arm.aspx", "http://www.example.com/angle#ants", "https://www.example.com/", "http://beds.example.org/", "http://www.example.com/", "http://bat.example.com/behavior/bells.aspx", "https://www.example.com/baby/beds", "https://example.org/", "http://bed.example.com/", "https://example.com/?bikes=basin&beds=act#arch", "https://example.com/bikes?bell=brother&art=achiever", "http://www.example.com/adjustment", "http://www.example.com/", "http://example.com/baby", "http://example.org/bee.aspx", "https://example.com/", "https://www.example.com/bikes/adjustment", "http://www.example.net/branch#afternoon", "http://www.example.com/board?boy=action", "https://bell.example.com/", "https://example.net/board.php", "https://example.com/basin.php?bead=actor&birthday=appliance", "http://example.net/advertisement.html?argument=bait#arm", "http://www.example.com/alarm", "https://www.example.edu/?base=aunt&aunt=activity", "http://example.com/brake/bubble.aspx", "https://www.example.com/", "http://www.example.net/", "http://www.example.com/", "https://www.example.com/#afterthought", "https://example.com/bear.php", "https://www.example.com/addition/blade.php?boot=activity&ball=bath#beds", "http://example.com/authority/belief?bird=beef", "https://bite.example.com/acoustics?arithmetic=apparatus&boundary=art", "https://www.example.com/?advice=apparel", "http://example.com/", "https://example.net/", "https://www.example.com/basin?adjustment=bead&arithmetic=birds", "http://www.example.com/", "http://www.example.com/bike/apparatus.aspx", "https://www.example.com/bell/attraction", "http://www.example.org/", "http://example.com/", "http://www.example.org/bite.php", "http://www.example.org/", "http://www.example.com/", "https://bubble.example.org/airplane.htm?ants=bait", "http://www.example.com/behavior/ball#ball", "http://bead.example.com/?activity=blood", "http://bat.example.org/", "http://account.example.com/", "https://bomb.example.com/", "https://example.com/airport.htm", "http://www.example.com/boat/behavior.php", "http://www.example.org/boy.html?actor=bag#belief", "http://www.example.com/amount", "http://example.com/", "https://example.com/?amusement=balance", "http://example.com/#baseball", "https://www.example.com/act", "http://authority.example.com/#account", "http://beginner.example.com/", "https://example.com/?box=aftermath&angle=approval", "http://www.example.com/", "http://www.example.com/argument.html", "https://example.edu/", "http://example.com/?bead=ants", "http://www.example.com/", "https://example.com/birth.php?basket=boundary#bit", "https://example.edu/", "https://anger.example.com/approval/afterthought#account", "https://www.example.com/back.html?bear=border", "http://example.com/", "http://www.example.com/", "http://www.example.com/beef.aspx?aunt=blow", "https://www.example.org/air", "https://birds.example.net/", "https://www.example.com/", "https://border.example.com/advice.php", "http://basket.example.com/believe", "http://example.net/?babies=birds&approval=bat", "http://advertisement.example.com/branch/bells.php", "http://bear.example.com/bubble/bike", "http://example.org/", "https://www.example.com/agreement/aftermath", "http://example.com/balance.html", "https://www.example.edu/#authority", "http://example.org/basket.aspx#baseball", "http://www.example.edu/brass", "https://example.com/", "http://www.example.com/", "https://example.edu/", "http://www.example.com/", "http://www.example.com/bead?bed=berry", "https://www.example.com/", "http://www.example.com/#bat", "http://www.example.org/bee.php", "http://blade.example.net/agreement/badge.html", "http://www.example.com/", "https://www.example.com/boundary/animal.php", "http://example.com/bed?advertisement=air", "http://www.example.net/", "https://www.example.com/", "http://example.net/argument", "http://bat.example.com/?advice=bedroom", "http://example.edu/", "https://example.com/", "http://www.example.com/apparel.php", "https://www.example.com/", "http://example.edu/", "http://bit.example.com/", "https://actor.example.com/book/arm", "https://www.example.com/", "https://www.example.com/brother", "https://www.example.net/battle/bite.aspx", "http://www.example.com/#behavior", "http://example.net/action.html", "http://example.edu/ball/appliance.php", "https://blow.example.com/bike/battle.html", "http://advice.example.com/", "http://www.example.com/border.html", "https://example.org/bomb/bone.php", "https://bit.example.org/border.php", "https://www.example.com/", "https://bat.example.com/advice", "http://www.example.com/", "https://www.example.com/advice", "http://example.com/", "http://www.example.com/base/beds", "http://example.net/", "http://example.com/", "https://www.example.com/", "http://example.com/bat.aspx", "http://www.example.com/?balance=boat#bit", "http://brass.example.edu/bead/aftermath", "http://www.example.com/aftermath/beef.aspx#argument", "https://authority.example.com/", "https://www.example.com/", "https://www.example.com/", "https://www.example.com/", "http://boy.example.com/boundary.html?beds=back&apparatus=bedroom", "https://example.edu/", "https://www.example.com/#air", "http://example.net/", "http://animal.example.com/back/brick?behavior=activity&authority=beds", "http://www.example.com/", "https://www.example.net/", "https://www.example.com/book?bridge=boundary&ants=book", "http://www.example.com/anger", "https://www.example.org/back.php#bells", "http://example.com/actor/bikes#advertisement", "http://example.com/aunt?back=ants&beef=birds", "http://example.edu/beef/amount", "http://www.example.com/afternoon.php?beef=afternoon", "http://example.com/", "https://www.example.com/#bomb", "https://example.edu/", "http://www.example.edu/?afterthought=animal#bat", "http://www.example.net/act/angle.html", "http://example.com/", "http://www.example.com/", "http://beginner.example.com/acoustics", "http://example.com/act", "https://www.example.com/?box=baseball&babies=bikes", "http://advertisement.example.com/bell.html", "http://www.example.net/brick.aspx", "https://www.example.com/", "http://example.edu/", "http://bone.example.com/", "https://www.example.com/believe.php", "http://www.example.com/", "http://www.example.net/brake/afternoon", "https://www.example.com/", "https://www.example.com/#arm", "http://www.example.com/bait/bear", "http://blood.example.com/", "https://www.example.edu/?base=advice&bridge=bed", "http://www.example.com/", "http://www.example.net/", "https://www.example.org/behavior?army=alarm#air", "http://book.example.com/?badge=argument#achiever", "https://angle.example.com/", "http://www.example.com/", "http://example.com/branch.aspx", "https://authority.example.com/boy", "http://example.com/balance?bubble=bed&behavior=amusement", "http://example.com/bedroom/beginner.php", "http://arm.example.net/bells.html", "https://www.example.com/?attack=basin", "https://brother.example.com/#action", "https://example.net/", "http://www.example.com/bomb.php", "https://www.example.com/airplane.aspx", "https://www.example.edu/basin", "https://anger.example.com/bee?afternoon=bear&birthday=basket#account", "http://blow.example.com/#arithmetic", "https://example.com/", "http://bite.example.net/#bee", "http://example.com/bait/behavior.php", "http://example.edu/addition.aspx", "http://example.com/", "http://www.example.net/beds?boat=baseball", "http://www.example.com/ants/bikes", "http://bite.example.com/baseball.php#acoustics", "http://www.example.com/bit/animal", "http://example.com/argument/brick.html?boy=authority&bee=aunt#birthday", "http://agreement.example.com/believe", "https://www.example.net/bait/account.html", "https://behavior.example.com/?bubble=adjustment", "https://board.example.net/", "https://www.example.com/angle.php", "http://www.example.com/", "https://example.edu/acoustics.html", "https://www.example.com/", "https://www.example.com/?ants=aunt", "http://brother.example.com/board/bedroom", "https://www.example.com/", "http://www.example.com/acoustics/account.php", "https://anger.example.com/book.aspx", "http://books.example.edu/", "http://www.example.net/?anger=alarm&airplane=back", "http://www.example.com/", "http://www.example.net/babies", "http://www.example.com/#acoustics", "https://example.com/blow", "http://example.net/?animal=brake&blow=bone", "https://example.com/account.aspx", "http://example.com/", "https://example.com/", "http://example.com/", "https://www.example.net/bottle#books", "https://example.edu/appliance.html", "https://boot.example.com/bridge.html", "https://www.example.com/advertisement/branch", "https://www.example.com/adjustment.php", "http://example.com/", "http://www.example.org/border.php?aftermath=art", "https://www.example.com/argument.php", "http://example.edu/boat", "https://example.com/battle.html", "https://bottle.example.com/account", "https://www.example.org/", "https://www.example.com/", "https://www.example.com/bear/animal", "https://www.example.com/", "http://brick.example.com/?brother=art#bear", "https://example.net/apparel/bead.htm", "http://example.org/bed?bat=air&amusement=approval", "https://example.com/", "https://example.com/act.aspx?angle=base&ball=adjustment", "https://example.edu/babies.php?advice=bridge&blood=brake", "https://example.com/balance.aspx", "https://www.example.com/achiever", "http://www.example.com/", "https://www.example.edu/", "http://example.com/", "https://amusement.example.org/birds/acoustics", "http://example.com/authority", "http://example.com/army", "http://birthday.example.com/arch/book.php", "https://www.example.com/", "http://www.example.com/advice/account", "http://www.example.com/border.htm", "http://www.example.net/attraction/beef", "http://www.example.com/", "http://balance.example.com/advertisement/books.aspx#bird", "https://www.example.com/", "http://www.example.com/bomb.php", "https://www.example.org/", "http://www.example.com/bee/box", "http://base.example.net/border.php", "http://brother.example.com/", "http://arch.example.com/", "https://aunt.example.com/?board=apparatus&brake=bikes", "http://example.com/", "https://www.example.net/?beginner=approval", "https://www.example.com/act", "https://www.example.net/adjustment.php", "https://baby.example.com/", "http://bead.example.org/", "http://www.example.edu/basin/bell", "http://battle.example.net/", "https://example.com/", "http://www.example.com/boy.html#belief", "http://amount.example.com/bee", "http://www.example.com/", "https://www.example.com/bat", "https://www.example.com/basin?bike=army&bird=aunt", "https://www.example.com/#afternoon", "http://www.example.com/brother", "https://www.example.com/blow.php", "http://www.example.com/", "http://aunt.example.com/#boot", "http://www.example.com/", "http://www.example.com/bear", "https://example.net/?boy=behavior&border=bear", "https://example.com/", "https://www.example.com/baby", "http://example.com/?art=acoustics#bells", "https://www.example.com/behavior", "http://balance.example.edu/bit", "http://www.example.com/", "https://www.example.org/", "http://boundary.example.com/?argument=achiever", "http://www.example.com/", "http://www.example.com/bottle/baby.html", "http://www.example.com/", "https://www.example.com/?arch=afternoon", "http://www.example.com/", "https://example.com/", "https://www.example.com/afternoon?amount=apparatus&addition=bath", "https://basin.example.com/", "http://www.example.com/apparatus/argument?bomb=brick&afterthought=adjustment", "http://example.net/", "http://www.example.com/addition.html?boat=board#art", "http://example.com/", "https://www.example.com/attack.html", "https://www.example.com/branch/arm.html", "https://www.example.com/", "http://alarm.example.com/", "http://example.com/", "http://example.edu/afterthought", "https://example.net/", "https://example.com/", "https://example.org/animal?agreement=book&attraction=books", "https://bear.example.com/?apparel=back#activity", "https://bottle.example.org/bear/bait", "https://www.example.com/", "http://www.example.com/?badge=airport&aunt=boy", "https://example.com/airplane/animal.htm?boy=beds&aftermath=back", "http://approval.example.com/", "https://www.example.com/", "http://example.com/berry?boot=breath&berry=birthday", "http://www.example.com/brick/basin", "http://www.example.net/advice#afternoon", "http://www.example.com/book?brick=board", "https://example.com/bit?boot=amount&action=army", "https://anger.example.com/behavior/birthday.html#bells", "http://www.example.com/", "http://www.example.com/", "https://example.com/air?advice=adjustment", "https://example.com/bridge/basketball.php", "https://example.com/", "http://www.example.com/air.aspx?berry=bag&boat=boundary", "http://army.example.com/", "http://www.example.edu/bite.html", "https://example.edu/boat/bat", "http://www.example.net/brother.aspx", "https://example.com/bedroom.php", "http://www.example.com/", "http://activity.example.edu/#boy", "https://achiever.example.com/", "https://www.example.com/arithmetic/bait.htm", "http://www.example.com/", "https://example.org/book", "http://www.example.edu/anger", "https://www.example.com/", "http://www.example.com/achiever/babies", "https://animal.example.com/", "https://actor.example.com/addition", "http://attack.example.net/", "https://www.example.com/achiever", "http://www.example.com/#anger", "https://www.example.com/", "http://example.net/?animal=alarm", "https://www.example.com/", "https://arm.example.org/boat/bikes", "http://bridge.example.com/", "https://example.com/", "https://www.example.com/birth/bells?basketball=appliance&bed=adjustment", "https://www.example.com/?apparatus=anger&base=animal", "https://www.example.com/bat/army.html", "https://www.example.com/", "https://www.example.com/basin/brick?brake=base#birds", "http://example.com/", "https://amusement.example.edu/animal", "http://example.com/authority", "http://www.example.org/", "https://www.example.com/", "https://www.example.com/books.html", "https://www.example.net/border/bee.html", "https://www.example.com/?angle=bike#behavior", "https://bike.example.com/", "http://www.example.com/angle", "http://example.com/bear/bubble.html", "http://www.example.org/", "https://example.com/basketball.aspx", "https://www.example.net/activity/apparatus.aspx", "https://www.example.net/", "https://www.example.net/", "https://www.example.com/?believe=animal&bit=birthday", "https://www.example.com/?amount=apparatus", "http://www.example.com/argument", "http://boy.example.com/berry", "http://example.com/brake#border", "https://basin.example.com/bath?boat=aunt", "http://www.example.com/bikes", "https://www.example.com/boundary.html", "http://argument.example.com/", "https://example.com/", "https://www.example.edu/bubble/approval.php", "http://example.com/", "http://boot.example.net/basketball.htm", "https://www.example.com/?animal=birthday", "https://www.example.com/boy?bead=behavior&bite=balance", "https://example.net/", "https://bead.example.com/", "http://www.example.edu/", "http://www.example.edu/airport.html?act=books#beginner", "http://www.example.com/", "https://example.com/", "http://bait.example.org/balance.html", "http://achiever.example.org/", "https://www.example.com/?aftermath=aunt&apparel=book", "https://www.example.com/beds?babies=birth&achiever=book", "http://example.com/", "http://www.example.com/army", "http://www.example.org/", "https://www.example.com/airport.php?behavior=alarm", "https://www.example.net/bikes/agreement", "http://www.example.com/", "http://www.example.com/", "https://www.example.org/#bottle", "https://bridge.example.com/ants?actor=branch", "http://www.example.org/?bells=attraction", "https://www.example.com/bottle/bone.php", "https://example.org/", "https://www.example.com/", "https://www.example.org/", "https://brick.example.org/behavior/basin?afternoon=acoustics", "https://example.com/", "http://www.example.com/bells", "http://www.example.com/", "https://www.example.com/boot/blow#boot", "https://example.com/birds.html", "http://www.example.com/", "https://www.example.edu/board.htm", "http://example.org/army", "http://breath.example.com/", "http://www.example.com/", "https://example.com/badge.html", "https://example.com/amusement.php", "http://www.example.com/book", "https://example.com/bomb.aspx?brick=bear&behavior=animal", "https://www.example.com/advertisement", "http://www.example.com/appliance", "https://www.example.com/", "http://www.example.com/", "https://example.com/", "http://www.example.com/", "https://blade.example.com/bikes.html", "http://www.example.com/attraction/ball.php#basket", "https://example.com/?books=beginner", "https://example.com/bat.html#animal", "https://www.example.edu/", "http://appliance.example.org/", "https://www.example.com/", "https://example.org/", "https://attack.example.org/bath", "https://aftermath.example.com/balance/bell#activity", "https://www.example.com/bait.aspx", "https://example.org/beef/afternoon", "http://www.example.com/bait/apparatus", "https://www.example.com/achiever", "https://appliance.example.com/apparel/battle.php", "http://example.com/", "http://www.example.com/appliance/acoustics?bomb=approval&act=bite#acoustics", "http://example.com/apparel", "https://www.example.com/arch/baseball.php", "https://www.example.net/bear/action.htm", "http://example.com/airplane/advertisement", "http://www.example.edu/?afternoon=bottle&badge=border", "https://bubble.example.com/brick.php", "https://afternoon.example.com/action/brick?boot=argument&bone=brake", "https://www.example.com/?advice=action&angle=blow", "http://www.example.com/?bottle=arch&actor=apparatus", "https://example.com/?basket=afterthought&birth=activity", "https://bomb.example.com/arm/battle.html", "https://www.example.com/bat.html#balance", "https://amount.example.edu/", "http://example.com/", "https://example.edu/actor/beef", "http://example.org/balance.html", "https://believe.example.com/bedroom.php", "https://www.example.com/", "http://example.com/apparel/baseball.php?acoustics=book", "http://www.example.com/?bone=agreement&arm=bike", "https://airplane.example.com/bite/ants.php", "https://www.example.com/apparel.php", "http://example.net/bike.php?brick=achiever&action=argument", "https://www.example.com/boundary/angle.aspx?bite=act", "https://account.example.com/blood/acoustics.aspx?activity=apparel&belief=afternoon", "http://www.example.net/?afterthought=baby", "https://www.example.com/", "https://www.example.net/?basket=aunt", "https://www.example.net/", "https://example.com/argument", "https://www.example.edu/?bite=bite", "https://bell.example.com/", "http://www.example.com/account/bit", "https://www.example.com/bells/border.htm#birds", "https://www.example.com/birth", "http://www.example.com/", "http://www.example.com/basket.php?blow=bells", "http://example.com/base/bird", "http://www.example.org/#act", "https://www.example.com/?brother=authority#book", "https://example.com/basket/bed", "http://example.edu/air.php", "http://example.org/babies.html", "https://argument.example.com/bubble/bells.aspx", "https://actor.example.com/bone", "http://www.example.com/aftermath/agreement.php", "http://www.example.com/alarm", "https://www.example.edu/", "http://example.com/", "https://example.com/activity", "https://www.example.com/", "https://www.example.com/arithmetic/air.php", "https://example.org/box#anger", "http://www.example.com/bomb/bikes?arch=breath&arithmetic=brake", "https://www.example.net/", "https://www.example.com/", "https://example.com/", "http://example.org/bells/bikes", "https://www.example.net/", "https://advice.example.com/bomb.aspx", "https://www.example.com/?beef=brother", "http://example.com/branch", "http://example.com/", "https://www.example.com/believe.php", "https://bomb.example.com/", "https://www.example.com/babies/animal.php", "http://www.example.net/alarm/angle", "http://www.example.com/?blow=bat&bike=activity", "https://www.example.com/?back=border", "http://www.example.com/", "http://www.example.org/ants?board=act&bite=art", "https://example.com/baseball", "https://www.example.com/behavior/advertisement.php", "https://example.com/", "http://air.example.com/", "http://www.example.com/blow.aspx", "http://amusement.example.net/acoustics", "http://www.example.com/arm/boy.aspx", "http://www.example.com/", "https://bath.example.com/", "http://approval.example.com/", "http://www.example.com/arch", "http://belief.example.org/bell.aspx", "http://www.example.com/babies", "http://action.example.net/bubble.html", "https://example.com/", "https://aftermath.example.com/", "http://aunt.example.net/base/bedroom", "http://example.com/art", "http://www.example.com/account.php", "https://www.example.com/?brake=behavior&behavior=brake", "https://www.example.org/act.htm", "http://www.example.com/bath", "http://www.example.org/", "http://example.org/#ball", "http://example.com/bridge#boot", "http://example.com/", "https://amount.example.com/baseball.php#bat", "https://authority.example.net/", "http://example.com/", "http://boot.example.com/bat/back?bone=bomb&afternoon=basketball", "http://example.com/", "https://angle.example.net/?beginner=boat", "https://www.example.com/", "https://www.example.org/belief", "https://www.example.com/apparel/belief.html", "https://example.com/believe/appliance.php", "http://example.net/?bottle=activity", "http://www.example.com/authority", "https://www.example.com/brass/berry?air=bear", "http://www.example.com/", "http://www.example.net/", "http://box.example.com/?airplane=blood&blood=amusement", "https://example.com/", "https://www.example.com/", "https://example.com/bee.aspx#baby", "https://www.example.com/beef/bite.html#bubble", "http://example.com/", "http://basin.example.com/blow", "http://example.com/brake/alarm.aspx?acoustics=brake&border=border", "https://www.example.com/action/anger.php", "https://example.com/army.aspx", "http://www.example.net/#arithmetic", "https://www.example.org/bit/bird.aspx", "http://www.example.com/bird.php", "https://www.example.com/amount", "http://www.example.com/blow/bed.php", "https://bead.example.com/?acoustics=airport", "https://www.example.com/beef/babies", "https://www.example.com/basket.aspx?apparel=agreement&actor=bag", "http://www.example.com/?baseball=boot&bite=airplane", "https://www.example.com/", "http://animal.example.com/bomb.php", "https://example.com/beds", "https://example.com/aunt/bird", "https://bikes.example.org/", "http://www.example.com/arithmetic.php", "http://example.com/beds/babies.php#basketball", "http://authority.example.com/", "http://www.example.com/?bird=advertisement&bite=acoustics", "http://example.com/bee", "https://babies.example.com/baseball.php", "http://www.example.com/acoustics", "https://authority.example.com/", "https://www.example.com/", "https://www.example.com/", "https://www.example.com/", "https://www.example.com/account.htm", "http://www.example.com/beef.php", "https://birth.example.com/", "https://www.example.com/bottle/argument ", } rand := rand.Intn(1000) return URL[rand] } //RandDummyImageURL return a dummy image url func RandDummyImageURL() string { URL := [1000]string{ "http://dummyimage.com/583x317.jpg/cc0000/ffffff", "http://dummyimage.com/586x251.jpg/cc0000/ffffff", "http://dummyimage.com/667x385.jpg/5fa2dd/ffffff", "http://dummyimage.com/715x450.jpg/5fa2dd/ffffff", "http://dummyimage.com/449x378.jpg/5fa2dd/ffffff", "http://dummyimage.com/567x350.jpg/5fa2dd/ffffff", "http://dummyimage.com/454x336.jpg/ff4444/ffffff", "http://dummyimage.com/508x283.jpg/cc0000/ffffff", "http://dummyimage.com/786x400.jpg/dddddd/000000", "http://dummyimage.com/529x335.jpg/ff4444/ffffff", "http://dummyimage.com/735x264.jpg/5fa2dd/ffffff", "http://dummyimage.com/528x398.jpg/5fa2dd/ffffff", "http://dummyimage.com/379x418.jpg/5fa2dd/ffffff", "http://dummyimage.com/438x359.jpg/cc0000/ffffff", "http://dummyimage.com/511x414.jpg/cc0000/ffffff", "http://dummyimage.com/503x367.jpg/5fa2dd/ffffff", "http://dummyimage.com/738x417.jpg/5fa2dd/ffffff", "http://dummyimage.com/595x286.jpg/5fa2dd/ffffff", "http://dummyimage.com/528x261.jpg/ff4444/ffffff", "http://dummyimage.com/398x289.jpg/ff4444/ffffff", "http://dummyimage.com/332x345.jpg/dddddd/000000", "http://dummyimage.com/715x285.jpg/dddddd/000000", "http://dummyimage.com/777x430.jpg/5fa2dd/ffffff", "http://dummyimage.com/642x273.jpg/ff4444/ffffff", "http://dummyimage.com/637x363.jpg/ff4444/ffffff", "http://dummyimage.com/798x260.jpg/dddddd/000000", "http://dummyimage.com/335x415.jpg/dddddd/000000", "http://dummyimage.com/354x337.jpg/cc0000/ffffff", "http://dummyimage.com/502x331.jpg/cc0000/ffffff", "http://dummyimage.com/485x358.jpg/cc0000/ffffff", "http://dummyimage.com/376x258.jpg/ff4444/ffffff", "http://dummyimage.com/623x385.jpg/cc0000/ffffff", "http://dummyimage.com/783x376.jpg/dddddd/000000", "http://dummyimage.com/665x365.jpg/ff4444/ffffff", "http://dummyimage.com/713x403.jpg/cc0000/ffffff", "http://dummyimage.com/600x425.jpg/5fa2dd/ffffff", "http://dummyimage.com/780x343.jpg/ff4444/ffffff", "http://dummyimage.com/412x442.jpg/cc0000/ffffff", "http://dummyimage.com/330x423.jpg/cc0000/ffffff", "http://dummyimage.com/463x446.jpg/dddddd/000000", "http://dummyimage.com/596x393.jpg/5fa2dd/ffffff", "http://dummyimage.com/593x419.jpg/cc0000/ffffff", "http://dummyimage.com/588x347.jpg/5fa2dd/ffffff", "http://dummyimage.com/545x269.jpg/cc0000/ffffff", "http://dummyimage.com/422x342.jpg/cc0000/ffffff", "http://dummyimage.com/751x343.jpg/ff4444/ffffff", "http://dummyimage.com/513x351.jpg/cc0000/ffffff", "http://dummyimage.com/564x319.jpg/cc0000/ffffff", "http://dummyimage.com/445x384.jpg/dddddd/000000", "http://dummyimage.com/508x330.jpg/cc0000/ffffff", "http://dummyimage.com/300x323.jpg/dddddd/000000", "http://dummyimage.com/649x434.jpg/5fa2dd/ffffff", "http://dummyimage.com/417x438.jpg/ff4444/ffffff", "http://dummyimage.com/770x432.jpg/dddddd/000000", "http://dummyimage.com/610x279.jpg/dddddd/000000", "http://dummyimage.com/496x385.jpg/5fa2dd/ffffff", "http://dummyimage.com/438x306.jpg/5fa2dd/ffffff", "http://dummyimage.com/647x337.jpg/cc0000/ffffff", "http://dummyimage.com/722x282.jpg/ff4444/ffffff", "http://dummyimage.com/735x335.jpg/ff4444/ffffff", "http://dummyimage.com/355x332.jpg/dddddd/000000", "http://dummyimage.com/368x322.jpg/dddddd/000000", "http://dummyimage.com/664x419.jpg/dddddd/000000", "http://dummyimage.com/523x342.jpg/cc0000/ffffff", "http://dummyimage.com/574x340.jpg/5fa2dd/ffffff", "http://dummyimage.com/326x387.jpg/dddddd/000000", "http://dummyimage.com/362x438.jpg/cc0000/ffffff", "http://dummyimage.com/320x287.jpg/cc0000/ffffff", "http://dummyimage.com/656x340.jpg/cc0000/ffffff", "http://dummyimage.com/395x361.jpg/cc0000/ffffff", "http://dummyimage.com/761x377.jpg/ff4444/ffffff", "http://dummyimage.com/500x384.jpg/ff4444/ffffff", "http://dummyimage.com/545x429.jpg/5fa2dd/ffffff", "http://dummyimage.com/711x405.jpg/5fa2dd/ffffff", "http://dummyimage.com/380x391.jpg/cc0000/ffffff", "http://dummyimage.com/730x372.jpg/cc0000/ffffff", "http://dummyimage.com/563x377.jpg/dddddd/000000", "http://dummyimage.com/358x288.jpg/5fa2dd/ffffff", "http://dummyimage.com/407x313.jpg/dddddd/000000", "http://dummyimage.com/371x335.jpg/5fa2dd/ffffff", "http://dummyimage.com/568x269.jpg/5fa2dd/ffffff", "http://dummyimage.com/504x252.jpg/ff4444/ffffff", "http://dummyimage.com/526x318.jpg/ff4444/ffffff", "http://dummyimage.com/619x286.jpg/cc0000/ffffff", "http://dummyimage.com/729x372.jpg/dddddd/000000", "http://dummyimage.com/641x381.jpg/cc0000/ffffff", "http://dummyimage.com/316x351.jpg/cc0000/ffffff", "http://dummyimage.com/788x407.jpg/5fa2dd/ffffff", "http://dummyimage.com/342x444.jpg/5fa2dd/ffffff", "http://dummyimage.com/307x380.jpg/dddddd/000000", "http://dummyimage.com/307x361.jpg/ff4444/ffffff", "http://dummyimage.com/473x264.jpg/ff4444/ffffff", "http://dummyimage.com/411x316.jpg/dddddd/000000", "http://dummyimage.com/732x332.jpg/dddddd/000000", "http://dummyimage.com/797x302.jpg/5fa2dd/ffffff", "http://dummyimage.com/526x260.jpg/5fa2dd/ffffff", "http://dummyimage.com/397x429.jpg/ff4444/ffffff", "http://dummyimage.com/543x301.jpg/5fa2dd/ffffff", "http://dummyimage.com/725x431.jpg/ff4444/ffffff", "http://dummyimage.com/755x344.jpg/5fa2dd/ffffff", "http://dummyimage.com/383x299.jpg/dddddd/000000", "http://dummyimage.com/712x320.jpg/ff4444/ffffff", "http://dummyimage.com/636x348.jpg/5fa2dd/ffffff", "http://dummyimage.com/689x358.jpg/5fa2dd/ffffff", "http://dummyimage.com/628x297.jpg/dddddd/000000", "http://dummyimage.com/345x370.jpg/5fa2dd/ffffff", "http://dummyimage.com/612x393.jpg/cc0000/ffffff", "http://dummyimage.com/348x388.jpg/ff4444/ffffff", "http://dummyimage.com/426x386.jpg/dddddd/000000", "http://dummyimage.com/646x258.jpg/5fa2dd/ffffff", "http://dummyimage.com/491x258.jpg/5fa2dd/ffffff", "http://dummyimage.com/644x382.jpg/ff4444/ffffff", "http://dummyimage.com/596x336.jpg/5fa2dd/ffffff", "http://dummyimage.com/302x272.jpg/ff4444/ffffff", "http://dummyimage.com/714x266.jpg/ff4444/ffffff", "http://dummyimage.com/582x399.jpg/cc0000/ffffff", "http://dummyimage.com/558x325.jpg/cc0000/ffffff", "http://dummyimage.com/519x310.jpg/5fa2dd/ffffff", "http://dummyimage.com/611x441.jpg/dddddd/000000", "http://dummyimage.com/584x409.jpg/5fa2dd/ffffff", "http://dummyimage.com/405x372.jpg/cc0000/ffffff", "http://dummyimage.com/579x255.jpg/dddddd/000000", "http://dummyimage.com/506x316.jpg/5fa2dd/ffffff", "http://dummyimage.com/682x384.jpg/cc0000/ffffff", "http://dummyimage.com/768x408.jpg/5fa2dd/ffffff", "http://dummyimage.com/411x308.jpg/cc0000/ffffff", "http://dummyimage.com/453x255.jpg/cc0000/ffffff", "http://dummyimage.com/485x259.jpg/cc0000/ffffff", "http://dummyimage.com/722x254.jpg/5fa2dd/ffffff", "http://dummyimage.com/336x297.jpg/ff4444/ffffff", "http://dummyimage.com/411x332.jpg/5fa2dd/ffffff", "http://dummyimage.com/483x417.jpg/ff4444/ffffff", "http://dummyimage.com/623x320.jpg/cc0000/ffffff", "http://dummyimage.com/571x371.jpg/dddddd/000000", "http://dummyimage.com/640x259.jpg/5fa2dd/ffffff", "http://dummyimage.com/601x434.jpg/ff4444/ffffff", "http://dummyimage.com/388x362.jpg/cc0000/ffffff", "http://dummyimage.com/409x259.jpg/cc0000/ffffff", "http://dummyimage.com/370x381.jpg/dddddd/000000", "http://dummyimage.com/675x309.jpg/dddddd/000000", "http://dummyimage.com/422x392.jpg/ff4444/ffffff", "http://dummyimage.com/302x259.jpg/dddddd/000000", "http://dummyimage.com/379x391.jpg/dddddd/000000", "http://dummyimage.com/338x295.jpg/cc0000/ffffff", "http://dummyimage.com/729x309.jpg/cc0000/ffffff", "http://dummyimage.com/392x392.jpg/5fa2dd/ffffff", "http://dummyimage.com/479x257.jpg/cc0000/ffffff", "http://dummyimage.com/445x262.jpg/5fa2dd/ffffff", "http://dummyimage.com/608x398.jpg/ff4444/ffffff", "http://dummyimage.com/779x374.jpg/dddddd/000000", "http://dummyimage.com/340x341.jpg/cc0000/ffffff", "http://dummyimage.com/575x319.jpg/cc0000/ffffff", "http://dummyimage.com/303x397.jpg/cc0000/ffffff", "http://dummyimage.com/696x355.jpg/ff4444/ffffff", "http://dummyimage.com/582x286.jpg/dddddd/000000", "http://dummyimage.com/775x386.jpg/cc0000/ffffff", "http://dummyimage.com/741x428.jpg/dddddd/000000", "http://dummyimage.com/366x378.jpg/ff4444/ffffff", "http://dummyimage.com/611x397.jpg/ff4444/ffffff", "http://dummyimage.com/312x319.jpg/ff4444/ffffff", "http://dummyimage.com/333x333.jpg/dddddd/000000", "http://dummyimage.com/386x362.jpg/5fa2dd/ffffff", "http://dummyimage.com/527x327.jpg/5fa2dd/ffffff", "http://dummyimage.com/321x397.jpg/cc0000/ffffff", "http://dummyimage.com/559x259.jpg/ff4444/ffffff", "http://dummyimage.com/426x302.jpg/cc0000/ffffff", "http://dummyimage.com/566x414.jpg/ff4444/ffffff", "http://dummyimage.com/791x399.jpg/5fa2dd/ffffff", "http://dummyimage.com/768x332.jpg/cc0000/ffffff", "http://dummyimage.com/395x258.jpg/cc0000/ffffff", "http://dummyimage.com/663x268.jpg/cc0000/ffffff", "http://dummyimage.com/648x381.jpg/dddddd/000000", "http://dummyimage.com/777x375.jpg/5fa2dd/ffffff", "http://dummyimage.com/775x417.jpg/cc0000/ffffff", "http://dummyimage.com/753x299.jpg/cc0000/ffffff", "http://dummyimage.com/633x367.jpg/ff4444/ffffff", "http://dummyimage.com/452x285.jpg/5fa2dd/ffffff", "http://dummyimage.com/395x373.jpg/cc0000/ffffff", "http://dummyimage.com/671x450.jpg/5fa2dd/ffffff", "http://dummyimage.com/646x429.jpg/dddddd/000000", "http://dummyimage.com/501x375.jpg/5fa2dd/ffffff", "http://dummyimage.com/698x404.jpg/ff4444/ffffff", "http://dummyimage.com/695x359.jpg/dddddd/000000", "http://dummyimage.com/779x446.jpg/5fa2dd/ffffff", "http://dummyimage.com/319x308.jpg/5fa2dd/ffffff", "http://dummyimage.com/493x379.jpg/dddddd/000000", "http://dummyimage.com/570x408.jpg/dddddd/000000", "http://dummyimage.com/353x334.jpg/dddddd/000000", "http://dummyimage.com/384x349.jpg/cc0000/ffffff", "http://dummyimage.com/374x394.jpg/5fa2dd/ffffff", "http://dummyimage.com/793x368.jpg/cc0000/ffffff", "http://dummyimage.com/758x415.jpg/cc0000/ffffff", "http://dummyimage.com/661x268.jpg/dddddd/000000", "http://dummyimage.com/584x303.jpg/5fa2dd/ffffff", "http://dummyimage.com/800x331.jpg/cc0000/ffffff", "http://dummyimage.com/548x369.jpg/dddddd/000000", "http://dummyimage.com/335x390.jpg/ff4444/ffffff", "http://dummyimage.com/649x351.jpg/5fa2dd/ffffff", "http://dummyimage.com/633x436.jpg/dddddd/000000", "http://dummyimage.com/475x279.jpg/cc0000/ffffff", "http://dummyimage.com/512x343.jpg/dddddd/000000", "http://dummyimage.com/460x310.jpg/cc0000/ffffff", "http://dummyimage.com/311x317.jpg/ff4444/ffffff", "http://dummyimage.com/409x256.jpg/cc0000/ffffff", "http://dummyimage.com/517x288.jpg/5fa2dd/ffffff", "http://dummyimage.com/797x265.jpg/cc0000/ffffff", "http://dummyimage.com/727x329.jpg/5fa2dd/ffffff", "http://dummyimage.com/591x406.jpg/dddddd/000000", "http://dummyimage.com/549x267.jpg/ff4444/ffffff", "http://dummyimage.com/761x324.jpg/cc0000/ffffff", "http://dummyimage.com/724x368.jpg/ff4444/ffffff", "http://dummyimage.com/394x297.jpg/5fa2dd/ffffff", "http://dummyimage.com/642x286.jpg/dddddd/000000", "http://dummyimage.com/379x424.jpg/ff4444/ffffff", "http://dummyimage.com/381x284.jpg/dddddd/000000", "http://dummyimage.com/792x295.jpg/cc0000/ffffff", "http://dummyimage.com/772x331.jpg/dddddd/000000", "http://dummyimage.com/455x311.jpg/dddddd/000000", "http://dummyimage.com/546x287.jpg/cc0000/ffffff", "http://dummyimage.com/639x252.jpg/cc0000/ffffff", "http://dummyimage.com/657x319.jpg/cc0000/ffffff", "http://dummyimage.com/361x322.jpg/ff4444/ffffff", "http://dummyimage.com/749x408.jpg/cc0000/ffffff", "http://dummyimage.com/747x342.jpg/cc0000/ffffff", "http://dummyimage.com/493x295.jpg/cc0000/ffffff", "http://dummyimage.com/537x328.jpg/cc0000/ffffff", "http://dummyimage.com/661x445.jpg/dddddd/000000", "http://dummyimage.com/792x380.jpg/dddddd/000000", "http://dummyimage.com/447x257.jpg/dddddd/000000", "http://dummyimage.com/554x251.jpg/cc0000/ffffff", "http://dummyimage.com/653x337.jpg/ff4444/ffffff", "http://dummyimage.com/609x296.jpg/dddddd/000000", "http://dummyimage.com/577x437.jpg/5fa2dd/ffffff", "http://dummyimage.com/312x292.jpg/cc0000/ffffff", "http://dummyimage.com/447x309.jpg/cc0000/ffffff", "http://dummyimage.com/735x365.jpg/cc0000/ffffff", "http://dummyimage.com/686x417.jpg/dddddd/000000", "http://dummyimage.com/483x297.jpg/cc0000/ffffff", "http://dummyimage.com/406x422.jpg/dddddd/000000", "http://dummyimage.com/721x407.jpg/cc0000/ffffff", "http://dummyimage.com/797x438.jpg/dddddd/000000", "http://dummyimage.com/306x362.jpg/ff4444/ffffff", "http://dummyimage.com/563x262.jpg/dddddd/000000", "http://dummyimage.com/573x315.jpg/dddddd/000000", "http://dummyimage.com/421x266.jpg/5fa2dd/ffffff", "http://dummyimage.com/762x426.jpg/cc0000/ffffff", "http://dummyimage.com/622x392.jpg/5fa2dd/ffffff", "http://dummyimage.com/614x404.jpg/dddddd/000000", "http://dummyimage.com/601x261.jpg/ff4444/ffffff", "http://dummyimage.com/500x328.jpg/cc0000/ffffff", "http://dummyimage.com/572x374.jpg/dddddd/000000", "http://dummyimage.com/502x292.jpg/ff4444/ffffff", "http://dummyimage.com/685x425.jpg/dddddd/000000", "http://dummyimage.com/790x418.jpg/dddddd/000000", "http://dummyimage.com/663x264.jpg/5fa2dd/ffffff", "http://dummyimage.com/512x350.jpg/dddddd/000000", "http://dummyimage.com/532x263.jpg/dddddd/000000", "http://dummyimage.com/465x283.jpg/ff4444/ffffff", "http://dummyimage.com/706x335.jpg/ff4444/ffffff", "http://dummyimage.com/623x310.jpg/ff4444/ffffff", "http://dummyimage.com/693x256.jpg/5fa2dd/ffffff", "http://dummyimage.com/532x279.jpg/ff4444/ffffff", "http://dummyimage.com/552x382.jpg/cc0000/ffffff", "http://dummyimage.com/530x439.jpg/5fa2dd/ffffff", "http://dummyimage.com/618x273.jpg/cc0000/ffffff", "http://dummyimage.com/630x295.jpg/dddddd/000000", "http://dummyimage.com/604x389.jpg/cc0000/ffffff", "http://dummyimage.com/609x301.jpg/5fa2dd/ffffff", "http://dummyimage.com/429x291.jpg/ff4444/ffffff", "http://dummyimage.com/495x434.jpg/ff4444/ffffff", "http://dummyimage.com/318x450.jpg/dddddd/000000", "http://dummyimage.com/799x352.jpg/5fa2dd/ffffff", "http://dummyimage.com/768x443.jpg/dddddd/000000", "http://dummyimage.com/736x380.jpg/cc0000/ffffff", "http://dummyimage.com/364x338.jpg/ff4444/ffffff", "http://dummyimage.com/449x338.jpg/dddddd/000000", "http://dummyimage.com/354x370.jpg/dddddd/000000", "http://dummyimage.com/415x280.jpg/5fa2dd/ffffff", "http://dummyimage.com/345x399.jpg/dddddd/000000", "http://dummyimage.com/625x407.jpg/5fa2dd/ffffff", "http://dummyimage.com/535x444.jpg/ff4444/ffffff", "http://dummyimage.com/563x341.jpg/dddddd/000000", "http://dummyimage.com/435x362.jpg/dddddd/000000", "http://dummyimage.com/785x276.jpg/ff4444/ffffff", "http://dummyimage.com/411x312.jpg/dddddd/000000", "http://dummyimage.com/646x383.jpg/dddddd/000000", "http://dummyimage.com/600x257.jpg/cc0000/ffffff", "http://dummyimage.com/389x368.jpg/ff4444/ffffff", "http://dummyimage.com/732x255.jpg/dddddd/000000", "http://dummyimage.com/489x359.jpg/dddddd/000000", "http://dummyimage.com/654x430.jpg/ff4444/ffffff", "http://dummyimage.com/444x279.jpg/5fa2dd/ffffff", "http://dummyimage.com/783x338.jpg/ff4444/ffffff", "http://dummyimage.com/445x301.jpg/dddddd/000000", "http://dummyimage.com/520x275.jpg/5fa2dd/ffffff", "http://dummyimage.com/457x281.jpg/ff4444/ffffff", "http://dummyimage.com/589x256.jpg/dddddd/000000", "http://dummyimage.com/324x399.jpg/ff4444/ffffff", "http://dummyimage.com/362x444.jpg/dddddd/000000", "http://dummyimage.com/736x440.jpg/cc0000/ffffff", "http://dummyimage.com/675x356.jpg/5fa2dd/ffffff", "http://dummyimage.com/358x362.jpg/cc0000/ffffff", "http://dummyimage.com/319x311.jpg/ff4444/ffffff", "http://dummyimage.com/741x257.jpg/cc0000/ffffff", "http://dummyimage.com/798x253.jpg/5fa2dd/ffffff", "http://dummyimage.com/398x346.jpg/5fa2dd/ffffff", "http://dummyimage.com/800x407.jpg/ff4444/ffffff", "http://dummyimage.com/718x280.jpg/5fa2dd/ffffff", "http://dummyimage.com/493x280.jpg/5fa2dd/ffffff", "http://dummyimage.com/447x380.jpg/dddddd/000000", "http://dummyimage.com/337x325.jpg/cc0000/ffffff", "http://dummyimage.com/602x407.jpg/ff4444/ffffff", "http://dummyimage.com/319x332.jpg/cc0000/ffffff", "http://dummyimage.com/539x367.jpg/dddddd/000000", "http://dummyimage.com/754x395.jpg/cc0000/ffffff", "http://dummyimage.com/352x273.jpg/ff4444/ffffff", "http://dummyimage.com/760x414.jpg/cc0000/ffffff", "http://dummyimage.com/698x272.jpg/cc0000/ffffff", "http://dummyimage.com/375x419.jpg/dddddd/000000", "http://dummyimage.com/782x251.jpg/dddddd/000000", "http://dummyimage.com/616x348.jpg/ff4444/ffffff", "http://dummyimage.com/408x337.jpg/5fa2dd/ffffff", "http://dummyimage.com/656x308.jpg/cc0000/ffffff", "http://dummyimage.com/342x368.jpg/dddddd/000000", "http://dummyimage.com/709x293.jpg/cc0000/ffffff", "http://dummyimage.com/382x252.jpg/cc0000/ffffff", "http://dummyimage.com/713x263.jpg/5fa2dd/ffffff", "http://dummyimage.com/347x378.jpg/5fa2dd/ffffff", "http://dummyimage.com/701x316.jpg/5fa2dd/ffffff", "http://dummyimage.com/319x288.jpg/5fa2dd/ffffff", "http://dummyimage.com/738x389.jpg/dddddd/000000", "http://dummyimage.com/502x315.jpg/dddddd/000000", "http://dummyimage.com/709x258.jpg/dddddd/000000", "http://dummyimage.com/636x310.jpg/cc0000/ffffff", "http://dummyimage.com/316x435.jpg/cc0000/ffffff", "http://dummyimage.com/707x290.jpg/dddddd/000000", "http://dummyimage.com/567x272.jpg/5fa2dd/ffffff", "http://dummyimage.com/576x386.jpg/dddddd/000000", "http://dummyimage.com/622x307.jpg/ff4444/ffffff", "http://dummyimage.com/552x380.jpg/5fa2dd/ffffff", "http://dummyimage.com/500x438.jpg/dddddd/000000", "http://dummyimage.com/468x357.jpg/ff4444/ffffff", "http://dummyimage.com/698x438.jpg/ff4444/ffffff", "http://dummyimage.com/560x352.jpg/5fa2dd/ffffff", "http://dummyimage.com/717x390.jpg/5fa2dd/ffffff", "http://dummyimage.com/800x447.jpg/cc0000/ffffff", "http://dummyimage.com/330x389.jpg/ff4444/ffffff", "http://dummyimage.com/474x417.jpg/5fa2dd/ffffff", "http://dummyimage.com/438x259.jpg/dddddd/000000", "http://dummyimage.com/371x410.jpg/5fa2dd/ffffff", "http://dummyimage.com/607x307.jpg/cc0000/ffffff", "http://dummyimage.com/638x385.jpg/dddddd/000000", "http://dummyimage.com/423x404.jpg/5fa2dd/ffffff", "http://dummyimage.com/620x300.jpg/ff4444/ffffff", "http://dummyimage.com/649x401.jpg/dddddd/000000", "http://dummyimage.com/346x351.jpg/ff4444/ffffff", "http://dummyimage.com/481x257.jpg/ff4444/ffffff", "http://dummyimage.com/367x446.jpg/dddddd/000000", "http://dummyimage.com/422x303.jpg/dddddd/000000", "http://dummyimage.com/336x259.jpg/dddddd/000000", "http://dummyimage.com/340x310.jpg/5fa2dd/ffffff", "http://dummyimage.com/715x385.jpg/dddddd/000000", "http://dummyimage.com/400x449.jpg/cc0000/ffffff", "http://dummyimage.com/306x412.jpg/cc0000/ffffff", "http://dummyimage.com/641x366.jpg/ff4444/ffffff", "http://dummyimage.com/665x448.jpg/ff4444/ffffff", "http://dummyimage.com/591x431.jpg/5fa2dd/ffffff", "http://dummyimage.com/638x363.jpg/5fa2dd/ffffff", "http://dummyimage.com/407x440.jpg/5fa2dd/ffffff", "http://dummyimage.com/444x303.jpg/cc0000/ffffff", "http://dummyimage.com/554x349.jpg/ff4444/ffffff", "http://dummyimage.com/316x405.jpg/5fa2dd/ffffff", "http://dummyimage.com/427x323.jpg/cc0000/ffffff", "http://dummyimage.com/427x338.jpg/dddddd/000000", "http://dummyimage.com/371x343.jpg/5fa2dd/ffffff", "http://dummyimage.com/434x322.jpg/cc0000/ffffff", "http://dummyimage.com/405x445.jpg/dddddd/000000", "http://dummyimage.com/330x337.jpg/cc0000/ffffff", "http://dummyimage.com/794x400.jpg/cc0000/ffffff", "http://dummyimage.com/385x347.jpg/5fa2dd/ffffff", "http://dummyimage.com/386x401.jpg/ff4444/ffffff", "http://dummyimage.com/451x375.jpg/dddddd/000000", "http://dummyimage.com/712x333.jpg/5fa2dd/ffffff", "http://dummyimage.com/576x286.jpg/cc0000/ffffff", "http://dummyimage.com/529x271.jpg/dddddd/000000", "http://dummyimage.com/663x324.jpg/cc0000/ffffff", "http://dummyimage.com/730x394.jpg/5fa2dd/ffffff", "http://dummyimage.com/693x265.jpg/ff4444/ffffff", "http://dummyimage.com/436x409.jpg/dddddd/000000", "http://dummyimage.com/488x341.jpg/ff4444/ffffff", "http://dummyimage.com/790x324.jpg/5fa2dd/ffffff", "http://dummyimage.com/746x394.jpg/ff4444/ffffff", "http://dummyimage.com/459x360.jpg/dddddd/000000", "http://dummyimage.com/786x387.jpg/ff4444/ffffff", "http://dummyimage.com/552x379.jpg/5fa2dd/ffffff", "http://dummyimage.com/608x389.jpg/dddddd/000000", "http://dummyimage.com/425x257.jpg/5fa2dd/ffffff", "http://dummyimage.com/618x309.jpg/ff4444/ffffff", "http://dummyimage.com/696x262.jpg/dddddd/000000", "http://dummyimage.com/329x302.jpg/dddddd/000000", "http://dummyimage.com/523x410.jpg/5fa2dd/ffffff", "http://dummyimage.com/680x390.jpg/dddddd/000000", "http://dummyimage.com/719x312.jpg/5fa2dd/ffffff", "http://dummyimage.com/750x271.jpg/ff4444/ffffff", "http://dummyimage.com/318x385.jpg/ff4444/ffffff", "http://dummyimage.com/790x320.jpg/dddddd/000000", "http://dummyimage.com/375x397.jpg/ff4444/ffffff", "http://dummyimage.com/479x315.jpg/cc0000/ffffff", "http://dummyimage.com/330x368.jpg/5fa2dd/ffffff", "http://dummyimage.com/374x356.jpg/ff4444/ffffff", "http://dummyimage.com/606x426.jpg/ff4444/ffffff", "http://dummyimage.com/525x270.jpg/ff4444/ffffff", "http://dummyimage.com/419x422.jpg/cc0000/ffffff", "http://dummyimage.com/377x375.jpg/dddddd/000000", "http://dummyimage.com/672x433.jpg/5fa2dd/ffffff", "http://dummyimage.com/344x360.jpg/dddddd/000000", "http://dummyimage.com/394x313.jpg/dddddd/000000", "http://dummyimage.com/730x357.jpg/dddddd/000000", "http://dummyimage.com/429x404.jpg/cc0000/ffffff", "http://dummyimage.com/303x422.jpg/cc0000/ffffff", "http://dummyimage.com/459x320.jpg/cc0000/ffffff", "http://dummyimage.com/485x288.jpg/5fa2dd/ffffff", "http://dummyimage.com/638x281.jpg/ff4444/ffffff", "http://dummyimage.com/466x340.jpg/ff4444/ffffff", "http://dummyimage.com/676x340.jpg/dddddd/000000", "http://dummyimage.com/709x369.jpg/cc0000/ffffff", "http://dummyimage.com/746x369.jpg/dddddd/000000", "http://dummyimage.com/692x309.jpg/dddddd/000000", "http://dummyimage.com/756x422.jpg/5fa2dd/ffffff", "http://dummyimage.com/583x266.jpg/5fa2dd/ffffff", "http://dummyimage.com/460x356.jpg/ff4444/ffffff", "http://dummyimage.com/567x345.jpg/ff4444/ffffff", "http://dummyimage.com/404x333.jpg/ff4444/ffffff", "http://dummyimage.com/578x301.jpg/dddddd/000000", "http://dummyimage.com/402x438.jpg/cc0000/ffffff", "http://dummyimage.com/662x253.jpg/5fa2dd/ffffff", "http://dummyimage.com/345x287.jpg/dddddd/000000", "http://dummyimage.com/789x366.jpg/cc0000/ffffff", "http://dummyimage.com/711x332.jpg/cc0000/ffffff", "http://dummyimage.com/704x322.jpg/cc0000/ffffff", "http://dummyimage.com/544x254.jpg/5fa2dd/ffffff", "http://dummyimage.com/514x371.jpg/dddddd/000000", "http://dummyimage.com/575x298.jpg/5fa2dd/ffffff", "http://dummyimage.com/401x284.jpg/5fa2dd/ffffff", "http://dummyimage.com/410x446.jpg/dddddd/000000", "http://dummyimage.com/747x338.jpg/ff4444/ffffff", "http://dummyimage.com/467x256.jpg/dddddd/000000", "http://dummyimage.com/481x387.jpg/ff4444/ffffff", "http://dummyimage.com/673x336.jpg/5fa2dd/ffffff", "http://dummyimage.com/396x359.jpg/dddddd/000000", "http://dummyimage.com/446x302.jpg/5fa2dd/ffffff", "http://dummyimage.com/560x367.jpg/ff4444/ffffff", "http://dummyimage.com/539x274.jpg/5fa2dd/ffffff", "http://dummyimage.com/407x288.jpg/5fa2dd/ffffff", "http://dummyimage.com/535x323.jpg/5fa2dd/ffffff", "http://dummyimage.com/646x306.jpg/5fa2dd/ffffff", "http://dummyimage.com/322x259.jpg/ff4444/ffffff", "http://dummyimage.com/759x278.jpg/5fa2dd/ffffff", "http://dummyimage.com/563x317.jpg/cc0000/ffffff", "http://dummyimage.com/413x379.jpg/cc0000/ffffff", "http://dummyimage.com/654x250.jpg/5fa2dd/ffffff", "http://dummyimage.com/580x434.jpg/cc0000/ffffff", "http://dummyimage.com/667x353.jpg/dddddd/000000", "http://dummyimage.com/799x348.jpg/ff4444/ffffff", "http://dummyimage.com/440x347.jpg/ff4444/ffffff", "http://dummyimage.com/723x286.jpg/5fa2dd/ffffff", "http://dummyimage.com/523x273.jpg/cc0000/ffffff", "http://dummyimage.com/791x446.jpg/cc0000/ffffff", "http://dummyimage.com/686x422.jpg/cc0000/ffffff", "http://dummyimage.com/694x257.jpg/5fa2dd/ffffff", "http://dummyimage.com/653x421.jpg/5fa2dd/ffffff", "http://dummyimage.com/618x310.jpg/5fa2dd/ffffff", "http://dummyimage.com/499x287.jpg/dddddd/000000", "http://dummyimage.com/674x311.jpg/5fa2dd/ffffff", "http://dummyimage.com/705x265.jpg/cc0000/ffffff", "http://dummyimage.com/341x278.jpg/dddddd/000000", "http://dummyimage.com/577x442.jpg/cc0000/ffffff", "http://dummyimage.com/624x404.jpg/5fa2dd/ffffff", "http://dummyimage.com/580x276.jpg/dddddd/000000", "http://dummyimage.com/434x386.jpg/ff4444/ffffff", "http://dummyimage.com/566x376.jpg/ff4444/ffffff", "http://dummyimage.com/343x288.jpg/dddddd/000000", "http://dummyimage.com/679x401.jpg/5fa2dd/ffffff", "http://dummyimage.com/396x338.jpg/cc0000/ffffff", "http://dummyimage.com/569x313.jpg/dddddd/000000", "http://dummyimage.com/796x419.jpg/ff4444/ffffff", "http://dummyimage.com/585x281.jpg/cc0000/ffffff", "http://dummyimage.com/767x388.jpg/dddddd/000000", "http://dummyimage.com/411x267.jpg/dddddd/000000", "http://dummyimage.com/690x331.jpg/dddddd/000000", "http://dummyimage.com/620x371.jpg/cc0000/ffffff", "http://dummyimage.com/494x402.jpg/cc0000/ffffff", "http://dummyimage.com/392x300.jpg/ff4444/ffffff", "http://dummyimage.com/548x324.jpg/ff4444/ffffff", "http://dummyimage.com/546x256.jpg/cc0000/ffffff", "http://dummyimage.com/495x437.jpg/5fa2dd/ffffff", "http://dummyimage.com/448x404.jpg/cc0000/ffffff", "http://dummyimage.com/673x399.jpg/cc0000/ffffff", "http://dummyimage.com/544x277.jpg/5fa2dd/ffffff", "http://dummyimage.com/622x346.jpg/ff4444/ffffff", "http://dummyimage.com/576x323.jpg/ff4444/ffffff", "http://dummyimage.com/753x350.jpg/dddddd/000000", "http://dummyimage.com/559x350.jpg/5fa2dd/ffffff", "http://dummyimage.com/780x391.jpg/5fa2dd/ffffff", "http://dummyimage.com/776x442.jpg/cc0000/ffffff", "http://dummyimage.com/386x313.jpg/cc0000/ffffff", "http://dummyimage.com/737x421.jpg/cc0000/ffffff", "http://dummyimage.com/336x315.jpg/dddddd/000000", "http://dummyimage.com/758x257.jpg/dddddd/000000", "http://dummyimage.com/528x439.jpg/dddddd/000000", "http://dummyimage.com/376x346.jpg/cc0000/ffffff", "http://dummyimage.com/410x375.jpg/ff4444/ffffff", "http://dummyimage.com/525x421.jpg/5fa2dd/ffffff", "http://dummyimage.com/337x363.jpg/cc0000/ffffff", "http://dummyimage.com/580x371.jpg/cc0000/ffffff", "http://dummyimage.com/703x396.jpg/cc0000/ffffff", "http://dummyimage.com/382x258.jpg/dddddd/000000", "http://dummyimage.com/753x421.jpg/5fa2dd/ffffff", "http://dummyimage.com/782x322.jpg/ff4444/ffffff", "http://dummyimage.com/596x276.jpg/5fa2dd/ffffff", "http://dummyimage.com/523x353.jpg/dddddd/000000", "http://dummyimage.com/625x326.jpg/5fa2dd/ffffff", "http://dummyimage.com/677x402.jpg/ff4444/ffffff", "http://dummyimage.com/750x354.jpg/cc0000/ffffff", "http://dummyimage.com/749x279.jpg/5fa2dd/ffffff", "http://dummyimage.com/705x405.jpg/dddddd/000000", "http://dummyimage.com/400x422.jpg/ff4444/ffffff", "http://dummyimage.com/701x446.jpg/dddddd/000000", "http://dummyimage.com/388x303.jpg/cc0000/ffffff", "http://dummyimage.com/454x297.jpg/dddddd/000000", "http://dummyimage.com/588x288.jpg/ff4444/ffffff", "http://dummyimage.com/410x401.jpg/cc0000/ffffff", "http://dummyimage.com/661x331.jpg/cc0000/ffffff", "http://dummyimage.com/701x426.jpg/dddddd/000000", "http://dummyimage.com/389x362.jpg/ff4444/ffffff", "http://dummyimage.com/493x308.jpg/cc0000/ffffff", "http://dummyimage.com/602x349.jpg/cc0000/ffffff", "http://dummyimage.com/669x419.jpg/ff4444/ffffff", "http://dummyimage.com/480x428.jpg/ff4444/ffffff", "http://dummyimage.com/375x292.jpg/cc0000/ffffff", "http://dummyimage.com/448x430.jpg/5fa2dd/ffffff", "http://dummyimage.com/383x391.jpg/dddddd/000000", "http://dummyimage.com/435x443.jpg/dddddd/000000", "http://dummyimage.com/530x287.jpg/ff4444/ffffff", "http://dummyimage.com/554x425.jpg/5fa2dd/ffffff", "http://dummyimage.com/344x315.jpg/cc0000/ffffff", "http://dummyimage.com/333x334.jpg/5fa2dd/ffffff", "http://dummyimage.com/408x266.jpg/cc0000/ffffff", "http://dummyimage.com/656x387.jpg/dddddd/000000", "http://dummyimage.com/785x376.jpg/5fa2dd/ffffff", "http://dummyimage.com/402x278.jpg/cc0000/ffffff", "http://dummyimage.com/329x331.jpg/5fa2dd/ffffff", "http://dummyimage.com/687x295.jpg/5fa2dd/ffffff", "http://dummyimage.com/741x350.jpg/ff4444/ffffff", "http://dummyimage.com/794x421.jpg/dddddd/000000", "http://dummyimage.com/470x266.jpg/5fa2dd/ffffff", "http://dummyimage.com/596x341.jpg/cc0000/ffffff", "http://dummyimage.com/633x257.jpg/5fa2dd/ffffff", "http://dummyimage.com/447x271.jpg/dddddd/000000", "http://dummyimage.com/480x278.jpg/ff4444/ffffff", "http://dummyimage.com/383x282.jpg/cc0000/ffffff", "http://dummyimage.com/628x280.jpg/ff4444/ffffff", "http://dummyimage.com/320x363.jpg/dddddd/000000", "http://dummyimage.com/761x441.jpg/ff4444/ffffff", "http://dummyimage.com/726x410.jpg/5fa2dd/ffffff", "http://dummyimage.com/419x367.jpg/dddddd/000000", "http://dummyimage.com/643x357.jpg/ff4444/ffffff", "http://dummyimage.com/409x368.jpg/dddddd/000000", "http://dummyimage.com/495x411.jpg/5fa2dd/ffffff", "http://dummyimage.com/626x413.jpg/ff4444/ffffff", "http://dummyimage.com/316x348.jpg/ff4444/ffffff", "http://dummyimage.com/586x340.jpg/5fa2dd/ffffff", "http://dummyimage.com/481x413.jpg/5fa2dd/ffffff", "http://dummyimage.com/361x372.jpg/dddddd/000000", "http://dummyimage.com/582x425.jpg/dddddd/000000", "http://dummyimage.com/758x307.jpg/cc0000/ffffff", "http://dummyimage.com/761x287.jpg/dddddd/000000", "http://dummyimage.com/489x384.jpg/5fa2dd/ffffff", "http://dummyimage.com/372x253.jpg/5fa2dd/ffffff", "http://dummyimage.com/790x420.jpg/ff4444/ffffff", "http://dummyimage.com/669x365.jpg/cc0000/ffffff", "http://dummyimage.com/697x257.jpg/ff4444/ffffff", "http://dummyimage.com/727x333.jpg/5fa2dd/ffffff", "http://dummyimage.com/323x331.jpg/ff4444/ffffff", "http://dummyimage.com/775x380.jpg/5fa2dd/ffffff", "http://dummyimage.com/606x354.jpg/5fa2dd/ffffff", "http://dummyimage.com/574x369.jpg/ff4444/ffffff", "http://dummyimage.com/379x264.jpg/5fa2dd/ffffff", "http://dummyimage.com/571x345.jpg/5fa2dd/ffffff", "http://dummyimage.com/352x258.jpg/ff4444/ffffff", "http://dummyimage.com/585x263.jpg/5fa2dd/ffffff", "http://dummyimage.com/380x356.jpg/ff4444/ffffff", "http://dummyimage.com/523x362.jpg/ff4444/ffffff", "http://dummyimage.com/588x307.jpg/cc0000/ffffff", "http://dummyimage.com/504x291.jpg/ff4444/ffffff", "http://dummyimage.com/606x306.jpg/5fa2dd/ffffff", "http://dummyimage.com/703x410.jpg/5fa2dd/ffffff", "http://dummyimage.com/713x273.jpg/ff4444/ffffff", "http://dummyimage.com/344x387.jpg/dddddd/000000", "http://dummyimage.com/793x392.jpg/ff4444/ffffff", "http://dummyimage.com/551x401.jpg/cc0000/ffffff", "http://dummyimage.com/483x441.jpg/cc0000/ffffff", "http://dummyimage.com/331x315.jpg/dddddd/000000", "http://dummyimage.com/717x429.jpg/cc0000/ffffff", "http://dummyimage.com/461x359.jpg/5fa2dd/ffffff", "http://dummyimage.com/401x334.jpg/5fa2dd/ffffff", "http://dummyimage.com/490x416.jpg/dddddd/000000", "http://dummyimage.com/491x252.jpg/dddddd/000000", "http://dummyimage.com/391x270.jpg/cc0000/ffffff", "http://dummyimage.com/584x383.jpg/5fa2dd/ffffff", "http://dummyimage.com/309x301.jpg/cc0000/ffffff", "http://dummyimage.com/602x372.jpg/cc0000/ffffff", "http://dummyimage.com/552x430.jpg/5fa2dd/ffffff", "http://dummyimage.com/430x282.jpg/5fa2dd/ffffff", "http://dummyimage.com/597x250.jpg/cc0000/ffffff", "http://dummyimage.com/388x265.jpg/cc0000/ffffff", "http://dummyimage.com/759x317.jpg/cc0000/ffffff", "http://dummyimage.com/737x378.jpg/5fa2dd/ffffff", "http://dummyimage.com/789x287.jpg/5fa2dd/ffffff", "http://dummyimage.com/357x308.jpg/ff4444/ffffff", "http://dummyimage.com/631x285.jpg/cc0000/ffffff", "http://dummyimage.com/561x334.jpg/dddddd/000000", "http://dummyimage.com/437x362.jpg/5fa2dd/ffffff", "http://dummyimage.com/651x436.jpg/dddddd/000000", "http://dummyimage.com/624x415.jpg/dddddd/000000", "http://dummyimage.com/631x308.jpg/cc0000/ffffff", "http://dummyimage.com/586x338.jpg/dddddd/000000", "http://dummyimage.com/664x393.jpg/ff4444/ffffff", "http://dummyimage.com/417x344.jpg/5fa2dd/ffffff", "http://dummyimage.com/714x335.jpg/5fa2dd/ffffff", "http://dummyimage.com/312x289.jpg/5fa2dd/ffffff", "http://dummyimage.com/611x444.jpg/5fa2dd/ffffff", "http://dummyimage.com/575x339.jpg/ff4444/ffffff", "http://dummyimage.com/670x372.jpg/ff4444/ffffff", "http://dummyimage.com/502x329.jpg/cc0000/ffffff", "http://dummyimage.com/649x255.jpg/ff4444/ffffff", "http://dummyimage.com/653x393.jpg/5fa2dd/ffffff", "http://dummyimage.com/557x299.jpg/cc0000/ffffff", "http://dummyimage.com/343x428.jpg/dddddd/000000", "http://dummyimage.com/333x356.jpg/ff4444/ffffff", "http://dummyimage.com/349x320.jpg/dddddd/000000", "http://dummyimage.com/713x265.jpg/5fa2dd/ffffff", "http://dummyimage.com/726x334.jpg/cc0000/ffffff", "http://dummyimage.com/685x376.jpg/dddddd/000000", "http://dummyimage.com/778x266.jpg/5fa2dd/ffffff", "http://dummyimage.com/380x313.jpg/5fa2dd/ffffff", "http://dummyimage.com/453x441.jpg/cc0000/ffffff", "http://dummyimage.com/572x263.jpg/cc0000/ffffff", "http://dummyimage.com/722x334.jpg/5fa2dd/ffffff", "http://dummyimage.com/398x330.jpg/cc0000/ffffff", "http://dummyimage.com/600x408.jpg/cc0000/ffffff", "http://dummyimage.com/720x339.jpg/ff4444/ffffff", "http://dummyimage.com/663x335.jpg/cc0000/ffffff", "http://dummyimage.com/644x405.jpg/5fa2dd/ffffff", "http://dummyimage.com/748x364.jpg/5fa2dd/ffffff", "http://dummyimage.com/468x296.jpg/cc0000/ffffff", "http://dummyimage.com/746x350.jpg/5fa2dd/ffffff", "http://dummyimage.com/567x365.jpg/dddddd/000000", "http://dummyimage.com/786x407.jpg/ff4444/ffffff", "http://dummyimage.com/466x276.jpg/5fa2dd/ffffff", "http://dummyimage.com/748x304.jpg/ff4444/ffffff", "http://dummyimage.com/420x436.jpg/dddddd/000000", "http://dummyimage.com/795x323.jpg/5fa2dd/ffffff", "http://dummyimage.com/629x378.jpg/dddddd/000000", "http://dummyimage.com/571x429.jpg/dddddd/000000", "http://dummyimage.com/674x317.jpg/5fa2dd/ffffff", "http://dummyimage.com/765x313.jpg/cc0000/ffffff", "http://dummyimage.com/356x419.jpg/5fa2dd/ffffff", "http://dummyimage.com/665x276.jpg/dddddd/000000", "http://dummyimage.com/383x359.jpg/dddddd/000000", "http://dummyimage.com/737x410.jpg/5fa2dd/ffffff", "http://dummyimage.com/706x258.jpg/cc0000/ffffff", "http://dummyimage.com/326x306.jpg/5fa2dd/ffffff", "http://dummyimage.com/710x423.jpg/dddddd/000000", "http://dummyimage.com/752x405.jpg/dddddd/000000", "http://dummyimage.com/689x274.jpg/5fa2dd/ffffff", "http://dummyimage.com/651x433.jpg/5fa2dd/ffffff", "http://dummyimage.com/445x271.jpg/dddddd/000000", "http://dummyimage.com/549x414.jpg/cc0000/ffffff", "http://dummyimage.com/730x271.jpg/ff4444/ffffff", "http://dummyimage.com/750x326.jpg/dddddd/000000", "http://dummyimage.com/381x408.jpg/5fa2dd/ffffff", "http://dummyimage.com/591x369.jpg/cc0000/ffffff", "http://dummyimage.com/743x446.jpg/dddddd/000000", "http://dummyimage.com/645x371.jpg/ff4444/ffffff", "http://dummyimage.com/603x321.jpg/5fa2dd/ffffff", "http://dummyimage.com/509x383.jpg/ff4444/ffffff", "http://dummyimage.com/384x254.jpg/dddddd/000000", "http://dummyimage.com/350x415.jpg/5fa2dd/ffffff", "http://dummyimage.com/716x323.jpg/ff4444/ffffff", "http://dummyimage.com/565x271.jpg/5fa2dd/ffffff", "http://dummyimage.com/387x441.jpg/ff4444/ffffff", "http://dummyimage.com/786x404.jpg/5fa2dd/ffffff", "http://dummyimage.com/723x390.jpg/5fa2dd/ffffff", "http://dummyimage.com/556x293.jpg/ff4444/ffffff", "http://dummyimage.com/361x405.jpg/dddddd/000000", "http://dummyimage.com/637x440.jpg/ff4444/ffffff", "http://dummyimage.com/341x255.jpg/5fa2dd/ffffff", "http://dummyimage.com/383x376.jpg/5fa2dd/ffffff", "http://dummyimage.com/492x332.jpg/ff4444/ffffff", "http://dummyimage.com/446x332.jpg/ff4444/ffffff", "http://dummyimage.com/565x442.jpg/ff4444/ffffff", "http://dummyimage.com/406x401.jpg/5fa2dd/ffffff", "http://dummyimage.com/754x294.jpg/ff4444/ffffff", "http://dummyimage.com/710x335.jpg/ff4444/ffffff", "http://dummyimage.com/731x429.jpg/ff4444/ffffff", "http://dummyimage.com/690x297.jpg/dddddd/000000", "http://dummyimage.com/729x360.jpg/cc0000/ffffff", "http://dummyimage.com/621x384.jpg/cc0000/ffffff", "http://dummyimage.com/530x268.jpg/dddddd/000000", "http://dummyimage.com/688x329.jpg/5fa2dd/ffffff", "http://dummyimage.com/647x311.jpg/5fa2dd/ffffff", "http://dummyimage.com/314x407.jpg/5fa2dd/ffffff", "http://dummyimage.com/762x343.jpg/ff4444/ffffff", "http://dummyimage.com/696x285.jpg/dddddd/000000", "http://dummyimage.com/361x258.jpg/ff4444/ffffff", "http://dummyimage.com/792x403.jpg/ff4444/ffffff", "http://dummyimage.com/441x298.jpg/ff4444/ffffff", "http://dummyimage.com/520x354.jpg/5fa2dd/ffffff", "http://dummyimage.com/607x332.jpg/dddddd/000000", "http://dummyimage.com/412x344.jpg/ff4444/ffffff", "http://dummyimage.com/726x263.jpg/dddddd/000000", "http://dummyimage.com/677x387.jpg/5fa2dd/ffffff", "http://dummyimage.com/688x424.jpg/ff4444/ffffff", "http://dummyimage.com/549x307.jpg/dddddd/000000", "http://dummyimage.com/609x422.jpg/dddddd/000000", "http://dummyimage.com/305x424.jpg/dddddd/000000", "http://dummyimage.com/540x403.jpg/dddddd/000000", "http://dummyimage.com/743x294.jpg/cc0000/ffffff", "http://dummyimage.com/470x264.jpg/5fa2dd/ffffff", "http://dummyimage.com/316x434.jpg/ff4444/ffffff", "http://dummyimage.com/600x369.jpg/5fa2dd/ffffff", "http://dummyimage.com/497x389.jpg/ff4444/ffffff", "http://dummyimage.com/357x398.jpg/dddddd/000000", "http://dummyimage.com/303x388.jpg/5fa2dd/ffffff", "http://dummyimage.com/587x391.jpg/dddddd/000000", "http://dummyimage.com/735x250.jpg/cc0000/ffffff", "http://dummyimage.com/512x388.jpg/ff4444/ffffff", "http://dummyimage.com/613x357.jpg/5fa2dd/ffffff", "http://dummyimage.com/608x323.jpg/ff4444/ffffff", "http://dummyimage.com/598x333.jpg/ff4444/ffffff", "http://dummyimage.com/572x293.jpg/5fa2dd/ffffff", "http://dummyimage.com/310x437.jpg/dddddd/000000", "http://dummyimage.com/429x264.jpg/ff4444/ffffff", "http://dummyimage.com/545x393.jpg/dddddd/000000", "http://dummyimage.com/328x270.jpg/5fa2dd/ffffff", "http://dummyimage.com/335x450.jpg/ff4444/ffffff", "http://dummyimage.com/645x284.jpg/cc0000/ffffff", "http://dummyimage.com/464x422.jpg/cc0000/ffffff", "http://dummyimage.com/778x357.jpg/cc0000/ffffff", "http://dummyimage.com/701x297.jpg/5fa2dd/ffffff", "http://dummyimage.com/456x365.jpg/dddddd/000000", "http://dummyimage.com/378x440.jpg/cc0000/ffffff", "http://dummyimage.com/313x314.jpg/cc0000/ffffff", "http://dummyimage.com/347x446.jpg/dddddd/000000", "http://dummyimage.com/632x320.jpg/ff4444/ffffff", "http://dummyimage.com/507x348.jpg/cc0000/ffffff", "http://dummyimage.com/566x341.jpg/5fa2dd/ffffff", "http://dummyimage.com/724x378.jpg/ff4444/ffffff", "http://dummyimage.com/687x309.jpg/cc0000/ffffff", "http://dummyimage.com/756x410.jpg/ff4444/ffffff", "http://dummyimage.com/529x419.jpg/5fa2dd/ffffff", "http://dummyimage.com/448x435.jpg/ff4444/ffffff", "http://dummyimage.com/787x413.jpg/5fa2dd/ffffff", "http://dummyimage.com/709x418.jpg/dddddd/000000", "http://dummyimage.com/658x293.jpg/cc0000/ffffff", "http://dummyimage.com/623x362.jpg/dddddd/000000", "http://dummyimage.com/772x279.jpg/dddddd/000000", "http://dummyimage.com/493x317.jpg/dddddd/000000", "http://dummyimage.com/765x395.jpg/ff4444/ffffff", "http://dummyimage.com/384x446.jpg/cc0000/ffffff", "http://dummyimage.com/693x301.jpg/ff4444/ffffff", "http://dummyimage.com/542x334.jpg/5fa2dd/ffffff", "http://dummyimage.com/671x421.jpg/5fa2dd/ffffff", "http://dummyimage.com/501x295.jpg/cc0000/ffffff", "http://dummyimage.com/557x326.jpg/5fa2dd/ffffff", "http://dummyimage.com/431x376.jpg/dddddd/000000", "http://dummyimage.com/794x291.jpg/dddddd/000000", "http://dummyimage.com/738x310.jpg/cc0000/ffffff", "http://dummyimage.com/701x448.jpg/5fa2dd/ffffff", "http://dummyimage.com/787x359.jpg/cc0000/ffffff", "http://dummyimage.com/623x279.jpg/5fa2dd/ffffff", "http://dummyimage.com/692x421.jpg/dddddd/000000", "http://dummyimage.com/523x410.jpg/cc0000/ffffff", "http://dummyimage.com/776x364.jpg/dddddd/000000", "http://dummyimage.com/409x375.jpg/ff4444/ffffff", "http://dummyimage.com/572x399.jpg/5fa2dd/ffffff", "http://dummyimage.com/778x413.jpg/dddddd/000000", "http://dummyimage.com/596x433.jpg/ff4444/ffffff", "http://dummyimage.com/300x312.jpg/cc0000/ffffff", "http://dummyimage.com/509x330.jpg/ff4444/ffffff", "http://dummyimage.com/521x394.jpg/ff4444/ffffff", "http://dummyimage.com/423x292.jpg/5fa2dd/ffffff", "http://dummyimage.com/530x315.jpg/cc0000/ffffff", "http://dummyimage.com/664x359.jpg/5fa2dd/ffffff", "http://dummyimage.com/345x287.jpg/5fa2dd/ffffff", "http://dummyimage.com/730x442.jpg/5fa2dd/ffffff", "http://dummyimage.com/696x408.jpg/dddddd/000000", "http://dummyimage.com/337x399.jpg/ff4444/ffffff", "http://dummyimage.com/758x268.jpg/dddddd/000000", "http://dummyimage.com/708x306.jpg/dddddd/000000", "http://dummyimage.com/759x411.jpg/ff4444/ffffff", "http://dummyimage.com/603x320.jpg/ff4444/ffffff", "http://dummyimage.com/424x254.jpg/ff4444/ffffff", "http://dummyimage.com/688x421.jpg/cc0000/ffffff", "http://dummyimage.com/477x423.jpg/dddddd/000000", "http://dummyimage.com/344x367.jpg/5fa2dd/ffffff", "http://dummyimage.com/572x256.jpg/ff4444/ffffff", "http://dummyimage.com/356x309.jpg/5fa2dd/ffffff", "http://dummyimage.com/556x423.jpg/cc0000/ffffff", "http://dummyimage.com/767x301.jpg/5fa2dd/ffffff", "http://dummyimage.com/421x258.jpg/5fa2dd/ffffff", "http://dummyimage.com/762x369.jpg/cc0000/ffffff", "http://dummyimage.com/356x263.jpg/cc0000/ffffff", "http://dummyimage.com/444x401.jpg/cc0000/ffffff", "http://dummyimage.com/472x353.jpg/ff4444/ffffff", "http://dummyimage.com/539x377.jpg/dddddd/000000", "http://dummyimage.com/381x365.jpg/dddddd/000000", "http://dummyimage.com/515x371.jpg/cc0000/ffffff", "http://dummyimage.com/314x417.jpg/5fa2dd/ffffff", "http://dummyimage.com/754x435.jpg/cc0000/ffffff", "http://dummyimage.com/383x423.jpg/5fa2dd/ffffff", "http://dummyimage.com/302x411.jpg/5fa2dd/ffffff", "http://dummyimage.com/795x340.jpg/5fa2dd/ffffff", "http://dummyimage.com/331x387.jpg/cc0000/ffffff", "http://dummyimage.com/370x333.jpg/dddddd/000000", "http://dummyimage.com/599x359.jpg/ff4444/ffffff", "http://dummyimage.com/611x450.jpg/cc0000/ffffff", "http://dummyimage.com/417x251.jpg/cc0000/ffffff", "http://dummyimage.com/346x386.jpg/5fa2dd/ffffff", "http://dummyimage.com/750x369.jpg/dddddd/000000", "http://dummyimage.com/504x276.jpg/ff4444/ffffff", "http://dummyimage.com/400x384.jpg/dddddd/000000", "http://dummyimage.com/499x341.jpg/ff4444/ffffff", "http://dummyimage.com/522x385.jpg/dddddd/000000", "http://dummyimage.com/752x419.jpg/5fa2dd/ffffff", "http://dummyimage.com/793x373.jpg/cc0000/ffffff", "http://dummyimage.com/521x288.jpg/cc0000/ffffff", "http://dummyimage.com/612x400.jpg/5fa2dd/ffffff", "http://dummyimage.com/531x309.jpg/5fa2dd/ffffff", "http://dummyimage.com/741x443.jpg/ff4444/ffffff", "http://dummyimage.com/305x335.jpg/ff4444/ffffff", "http://dummyimage.com/386x369.jpg/cc0000/ffffff", "http://dummyimage.com/546x374.jpg/5fa2dd/ffffff", "http://dummyimage.com/470x295.jpg/ff4444/ffffff", "http://dummyimage.com/334x362.jpg/cc0000/ffffff", "http://dummyimage.com/570x305.jpg/dddddd/000000", "http://dummyimage.com/578x287.jpg/5fa2dd/ffffff", "http://dummyimage.com/793x376.jpg/dddddd/000000", "http://dummyimage.com/504x316.jpg/dddddd/000000", "http://dummyimage.com/360x358.jpg/ff4444/ffffff", "http://dummyimage.com/334x356.jpg/dddddd/000000", "http://dummyimage.com/402x354.jpg/5fa2dd/ffffff", "http://dummyimage.com/365x290.jpg/dddddd/000000", "http://dummyimage.com/628x370.jpg/ff4444/ffffff", "http://dummyimage.com/339x431.jpg/ff4444/ffffff", "http://dummyimage.com/324x398.jpg/5fa2dd/ffffff", "http://dummyimage.com/555x367.jpg/ff4444/ffffff", "http://dummyimage.com/601x312.jpg/dddddd/000000", "http://dummyimage.com/533x254.jpg/cc0000/ffffff", "http://dummyimage.com/718x449.jpg/cc0000/ffffff", "http://dummyimage.com/413x309.jpg/5fa2dd/ffffff", "http://dummyimage.com/597x442.jpg/dddddd/000000", "http://dummyimage.com/461x250.jpg/ff4444/ffffff", "http://dummyimage.com/630x279.jpg/5fa2dd/ffffff", "http://dummyimage.com/477x321.jpg/5fa2dd/ffffff", "http://dummyimage.com/645x373.jpg/cc0000/ffffff", "http://dummyimage.com/651x449.jpg/5fa2dd/ffffff", "http://dummyimage.com/688x361.jpg/5fa2dd/ffffff", "http://dummyimage.com/324x391.jpg/5fa2dd/ffffff", "http://dummyimage.com/726x313.jpg/5fa2dd/ffffff", "http://dummyimage.com/446x328.jpg/5fa2dd/ffffff", "http://dummyimage.com/337x386.jpg/cc0000/ffffff", "http://dummyimage.com/662x379.jpg/dddddd/000000", "http://dummyimage.com/789x291.jpg/ff4444/ffffff", "http://dummyimage.com/684x376.jpg/cc0000/ffffff", "http://dummyimage.com/573x392.jpg/dddddd/000000", "http://dummyimage.com/325x345.jpg/5fa2dd/ffffff", "http://dummyimage.com/431x284.jpg/ff4444/ffffff", "http://dummyimage.com/519x445.jpg/ff4444/ffffff", "http://dummyimage.com/429x252.jpg/5fa2dd/ffffff", "http://dummyimage.com/379x447.jpg/5fa2dd/ffffff", "http://dummyimage.com/640x411.jpg/cc0000/ffffff", "http://dummyimage.com/681x430.jpg/cc0000/ffffff", "http://dummyimage.com/549x295.jpg/dddddd/000000", "http://dummyimage.com/623x291.jpg/ff4444/ffffff", "http://dummyimage.com/354x414.jpg/5fa2dd/ffffff", "http://dummyimage.com/557x444.jpg/5fa2dd/ffffff", "http://dummyimage.com/703x300.jpg/5fa2dd/ffffff", "http://dummyimage.com/499x388.jpg/5fa2dd/ffffff", "http://dummyimage.com/484x370.jpg/ff4444/ffffff", "http://dummyimage.com/681x366.jpg/ff4444/ffffff", "http://dummyimage.com/578x331.jpg/ff4444/ffffff", "http://dummyimage.com/748x326.jpg/cc0000/ffffff", "http://dummyimage.com/706x449.jpg/dddddd/000000", "http://dummyimage.com/766x260.jpg/ff4444/ffffff", "http://dummyimage.com/616x434.jpg/ff4444/ffffff", "http://dummyimage.com/697x267.jpg/ff4444/ffffff", "http://dummyimage.com/511x445.jpg/dddddd/000000", "http://dummyimage.com/589x267.jpg/cc0000/ffffff", "http://dummyimage.com/420x318.jpg/5fa2dd/ffffff", "http://dummyimage.com/404x331.jpg/cc0000/ffffff", "http://dummyimage.com/736x431.jpg/dddddd/000000", "http://dummyimage.com/793x299.jpg/5fa2dd/ffffff", "http://dummyimage.com/423x351.jpg/cc0000/ffffff", "http://dummyimage.com/446x421.jpg/cc0000/ffffff", "http://dummyimage.com/557x276.jpg/5fa2dd/ffffff", "http://dummyimage.com/549x335.jpg/5fa2dd/ffffff", "http://dummyimage.com/615x258.jpg/cc0000/ffffff", "http://dummyimage.com/422x270.jpg/ff4444/ffffff", "http://dummyimage.com/653x308.jpg/dddddd/000000", "http://dummyimage.com/315x314.jpg/cc0000/ffffff", "http://dummyimage.com/330x364.jpg/cc0000/ffffff", "http://dummyimage.com/704x349.jpg/5fa2dd/ffffff", "http://dummyimage.com/622x402.jpg/cc0000/ffffff", "http://dummyimage.com/721x431.jpg/dddddd/000000", "http://dummyimage.com/649x352.jpg/dddddd/000000", "http://dummyimage.com/510x336.jpg/dddddd/000000", "http://dummyimage.com/500x325.jpg/ff4444/ffffff", "http://dummyimage.com/396x337.jpg/cc0000/ffffff", "http://dummyimage.com/753x439.jpg/cc0000/ffffff", "http://dummyimage.com/613x267.jpg/cc0000/ffffff", "http://dummyimage.com/475x273.jpg/ff4444/ffffff", "http://dummyimage.com/663x302.jpg/5fa2dd/ffffff", "http://dummyimage.com/714x317.jpg/ff4444/ffffff", "http://dummyimage.com/635x405.jpg/cc0000/ffffff", "http://dummyimage.com/794x397.jpg/5fa2dd/ffffff", "http://dummyimage.com/737x308.jpg/5fa2dd/ffffff", "http://dummyimage.com/400x386.jpg/5fa2dd/ffffff", "http://dummyimage.com/521x271.jpg/dddddd/000000", "http://dummyimage.com/732x394.jpg/ff4444/ffffff", "http://dummyimage.com/660x365.jpg/dddddd/000000", "http://dummyimage.com/603x368.jpg/5fa2dd/ffffff", "http://dummyimage.com/618x393.jpg/cc0000/ffffff", "http://dummyimage.com/698x378.jpg/cc0000/ffffff", "http://dummyimage.com/553x371.jpg/5fa2dd/ffffff", "http://dummyimage.com/775x416.jpg/cc0000/ffffff", "http://dummyimage.com/362x405.jpg/dddddd/000000", "http://dummyimage.com/489x443.jpg/dddddd/000000", "http://dummyimage.com/686x399.jpg/cc0000/ffffff", "http://dummyimage.com/497x380.jpg/5fa2dd/ffffff", "http://dummyimage.com/653x422.jpg/ff4444/ffffff", "http://dummyimage.com/507x351.jpg/dddddd/000000", "http://dummyimage.com/405x276.jpg/cc0000/ffffff", "http://dummyimage.com/309x343.jpg/dddddd/000000", "http://dummyimage.com/447x328.jpg/ff4444/ffffff", "http://dummyimage.com/360x388.jpg/dddddd/000000", "http://dummyimage.com/633x331.jpg/cc0000/ffffff", "http://dummyimage.com/346x268.jpg/cc0000/ffffff", "http://dummyimage.com/666x345.jpg/dddddd/000000", "http://dummyimage.com/768x256.jpg/ff4444/ffffff", "http://dummyimage.com/692x269.jpg/5fa2dd/ffffff", "http://dummyimage.com/610x362.jpg/dddddd/000000", "http://dummyimage.com/354x402.jpg/dddddd/000000", "http://dummyimage.com/448x381.jpg/ff4444/ffffff", "http://dummyimage.com/440x399.jpg/dddddd/000000", "http://dummyimage.com/466x371.jpg/cc0000/ffffff", "http://dummyimage.com/316x385.jpg/5fa2dd/ffffff", "http://dummyimage.com/768x371.jpg/ff4444/ffffff", "http://dummyimage.com/472x359.jpg/5fa2dd/ffffff", "http://dummyimage.com/536x443.jpg/dddddd/000000", "http://dummyimage.com/521x291.jpg/5fa2dd/ffffff", "http://dummyimage.com/654x384.jpg/dddddd/000000", "http://dummyimage.com/614x332.jpg/5fa2dd/ffffff", "http://dummyimage.com/503x271.jpg/ff4444/ffffff", "http://dummyimage.com/360x276.jpg/cc0000/ffffff", "http://dummyimage.com/437x443.jpg/cc0000/ffffff", "http://dummyimage.com/670x447.jpg/cc0000/ffffff", "http://dummyimage.com/376x445.jpg/ff4444/ffffff", "http://dummyimage.com/611x435.jpg/5fa2dd/ffffff", "http://dummyimage.com/513x304.jpg/cc0000/ffffff", "http://dummyimage.com/553x386.jpg/dddddd/000000", "http://dummyimage.com/429x365.jpg/ff4444/ffffff", "http://dummyimage.com/636x320.jpg/ff4444/ffffff", "http://dummyimage.com/627x443.jpg/5fa2dd/ffffff", "http://dummyimage.com/435x300.jpg/dddddd/000000", "http://dummyimage.com/714x304.jpg/ff4444/ffffff", "http://dummyimage.com/544x264.jpg/dddddd/000000", "http://dummyimage.com/589x265.jpg/dddddd/000000", "http://dummyimage.com/582x278.jpg/dddddd/000000", "http://dummyimage.com/397x404.jpg/5fa2dd/ffffff", "http://dummyimage.com/580x317.jpg/cc0000/ffffff", "http://dummyimage.com/762x364.jpg/dddddd/000000", "http://dummyimage.com/380x253.jpg/5fa2dd/ffffff", "http://dummyimage.com/455x318.jpg/ff4444/ffffff", "http://dummyimage.com/685x422.jpg/5fa2dd/ffffff", "http://dummyimage.com/490x403.jpg/ff4444/ffffff", "http://dummyimage.com/417x349.jpg/ff4444/ffffff", "http://dummyimage.com/399x302.jpg/ff4444/ffffff", "http://dummyimage.com/711x353.jpg/cc0000/ffffff", "http://dummyimage.com/496x427.jpg/ff4444/ffffff", "http://dummyimage.com/486x399.jpg/5fa2dd/ffffff", "http://dummyimage.com/493x362.jpg/cc0000/ffffff", "http://dummyimage.com/514x383.jpg/cc0000/ffffff", "http://dummyimage.com/539x417.jpg/5fa2dd/ffffff", "http://dummyimage.com/413x303.jpg/cc0000/ffffff", "http://dummyimage.com/666x410.jpg/5fa2dd/ffffff", "http://dummyimage.com/416x412.jpg/cc0000/ffffff", "http://dummyimage.com/536x301.jpg/ff4444/ffffff", "http://dummyimage.com/402x354.jpg/dddddd/000000"} rand := rand.Intn(1000) return URL[rand] }
util/seeds/dummyseeds.go
0.514644
0.656493
dummyseeds.go
starcoder
package geom import ( "github.com/water-vapor/euclidea-solver/configs" "github.com/water-vapor/euclidea-solver/pkg/hashset" "math" "math/rand" ) // HalfLine is determined uniquely by its starting point and normalized direction vector type HalfLine struct { hashset.Serializable point *Point direction *Vector2D } // NewHalfLineFromTwoPoints creates a half line from two points, with source as end point func NewHalfLineFromTwoPoints(source *Point, direction *Point) *HalfLine { v := NewVector2D(direction.x-source.x, direction.y-source.y) v.Normalize() return &HalfLine{point: source, direction: v} } // NewHalfLineFromDirection creates a half line from its end point and a direction func NewHalfLineFromDirection(pt *Point, direction *Vector2D) *HalfLine { direction.Normalize() return &HalfLine{point: pt, direction: direction} } // GetEndPoint returns its end point func (h *HalfLine) GetEndPoint() *Point { return h.point } // Serialize returns the hash of the half line func (h *HalfLine) Serialize() interface{} { cx := int64(math.Round(h.direction.x * configs.HashPrecision)) cy := int64(math.Round(h.direction.y * configs.HashPrecision)) cx0 := int64(math.Round(h.point.x * configs.HashPrecision)) cy0 := int64(math.Round(h.point.y * configs.HashPrecision)) return ((cx*configs.Prime+cy)*configs.Prime+cx0)*configs.Prime + cy0 } // PointInRange checks if a point is in the coordinates of a half line func (h *HalfLine) PointInRange(pt *Point) bool { if math.Abs(h.direction.x) < configs.Tolerance { // line is vertical if h.direction.y < 0 && pt.y-h.point.y-configs.Tolerance > 0 { return false } if h.direction.y > 0 && pt.y-h.point.y+configs.Tolerance < 0 { return false } } else { if h.direction.x < 0 && pt.x-h.point.x-configs.Tolerance > 0 { return false } if h.direction.x > 0 && pt.x-h.point.x+configs.Tolerance < 0 { return false } } return true } // ContainsPoint checks if a point is on the half line func (h *HalfLine) ContainsPoint(pt *Point) bool { if !h.PointInRange(pt) { return false } return NewLineFromHalfLine(h).ContainsPoint(pt) } // IntersectLine returns intersections with a line func (h *HalfLine) IntersectLine(l *Line) *Intersection { return l.IntersectHalfLine(h) } // IntersectHalfLine returns intersections with another half line func (h *HalfLine) IntersectHalfLine(h2 *HalfLine) *Intersection { // intersect as if it is a line intersection := h.IntersectLine(NewLineFromHalfLine(h2)) // parallel, no solution, just return if intersection.SolutionNumber == 0 { return intersection } // checks whether the intersection is on h2, since we've extended it pt := intersection.Solutions[0] if pt.OnHalfLine(h2) { return intersection } return NewIntersection() } // IntersectSegment returns intersections with a segment func (h *HalfLine) IntersectSegment(s *Segment) *Intersection { // intersect as if it is a line intersection := h.IntersectLine(NewLineFromSegment(s)) // parallel, no solution, just return if intersection.SolutionNumber == 0 { return intersection } // checks whether the intersection is on s, since we've extended it pt := intersection.Solutions[0] if pt.OnSegment(s) { return intersection } return NewIntersection() } // IntersectCircle returns intersections with a circle func (h *HalfLine) IntersectCircle(c *Circle) *Intersection { return c.IntersectHalfLine(h) } // GetRandomPoint returns a random point on the half line func (h *HalfLine) GetRandomPoint() *Point { v := h.direction.Clone() v.SetLength(rand.Float64() * configs.RandomPointRange) return NewPoint(h.point.x+v.x, h.point.y+v.y) }
pkg/geom/halfline.go
0.860721
0.502258
halfline.go
starcoder
package datemath_parser // built-in format var builtInFormat = map[string][]string{ // A formatter for the number of milliseconds since the epoch. // Note, that this timestamp is subject to the limits of a Java Long.MIN_VALUE and Long.MAX_VALUE. "epoch_millis": {"epoch_millis"}, // A formatter for the number of seconds since the epoch. // Note, that this timestamp is subject to the limits of a Java Long.MIN_VALUE and Long. // MAX_VALUE divided by 1000 (the number of milliseconds in a second). "epoch_second": {"epoch_second"}, // A generic ISO datetime parser, where the date must include the year at a minimum, and the time (separated by T), is optional. Examples: yyyy-MM-dd'T'HH:mm:ss.SSSZ or yyyy-MM-dd. "date_optional_time": {"yyyy-MM-ddTHH:mm:ss.SSSZ", "yyyy-MM-dd"}, "strict_date_optional_time": {"yyyy-MM-ddTHH:mm:ss.SSSZ", "yyyy-MM-dd"}, // A generic ISO datetime parser, where the date must include the year at a minimum, and the time (separated by T), is optional. The fraction of a second part has a nanosecond resolution. Examples: yyyy-MM-ddTHH:mm:ss.SSSSSSZ or yyyy-MM-dd. "strict_date_optional_time_nanos": {"yyyy-MM-ddTHH:mm:ss.SSSSSSZ", "yyyy-MM-dd"}, // A basic formatter for a full date as four digit year, two digit month of year, and two digit day of month: yyyyMMdd. "basic_date": {"yyyyMMdd"}, // A basic formatter that combines a basic date and time, separated by a T: . "basic_date_time": {"yyyyMMddTHHmmss.SSSZ"}, // A basic formatter that combines a basic date and time without millis, separated by a T: yyyyMMddTHHmmssZ. "basic_date_time_no_millis": {"yyyyMMddTHHmmssZ"}, // A formatter for a full ordinal date, using a four digit year and three digit dayOfYear: yyyyDDD. "basic_ordinal_date": {"yyyyDDD"}, // A formatter for a full ordinal date and time, using a four digit year and three digit dayOfYear: yyyyDDDTHHmmss.SSSZ. "basic_ordinal_date_time": {"yyyyDDDTHHmmss.SSSZ"}, // A formatter for a full ordinal date and time without millis, using a four digit year and three digit dayOfYear: yyyyDDDTHHmmssZ. "basic_ordinal_date_time_no_millis": {"yyyyDDDTHHmmssZ"}, // A basic formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, three digit millis, and time zone offset: HHmmss.SSSZ. "basic_time": {"HHmmss.SSSZ"}, // A basic formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, and time zone offset: HHmmssZ. "basic_time_no_millis": {"HHmmssZ"}, // A basic formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, three digit millis, and time zone off set prefixed by T: THHmmss.SSSZ. "basic_t_time": {"THHmmss.SSSZ"}, // A basic formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, and time zone offset prefixed by T: THHmmssZ. "basic_t_time_no_millis": {"THHmmssZ"}, // A basic formatter for a full date as four digit weekyear, two digit week of weekyear, and one digit day of week: xxxxWwwe. "basic_week_date": {"xxxxWwwe"}, "strict_basic_week_date": {"xxxxWwwe"}, // A basic formatter that combines a basic weekyear date and time, separated by a T: xxxxWwweTHHmmss.SSSZ. "basic_week_date_time": {"xxxxWwweTHHmmss.SSSZ"}, "strict_basic_week_date_time": {"xxxxWwweTHHmmss.SSSZ"}, // A basic formatter that combines a basic weekyear date and time without millis, separated by a T: xxxxWwweTHHmmssZ. "basic_week_date_time_no_millis": {"xxxxWwweTHHmmssZ"}, "strict_basic_week_date_time_no_millis": {"xxxxWwweTHHmmssZ"}, // A formatter for a full date as four digit year, two digit month of year, and two digit day of month: yyyy-MM-dd. "date": {"yyyy-MM-dd"}, "strict_date": {"yyyy-MM-dd"}, // A formatter that combines a full date and two digit hour of day: yyyy-MM-ddTHH. "date_hour": {"yyyy-MM-ddTHH"}, "strict_date_hour": {"yyyy-MM-ddTHH"}, // A formatter that combines a full date, two digit hour of day, and two digit minute of hour: yyyy-MM-ddTHH:mm. "date_hour_minute": {"yyyy-MM-ddTHH:mm"}, "strict_date_hour_minute": {"yyyy-MM-ddTHH:mm"}, // A formatter that combines a full date, two digit hour of day, two digit minute of hour, and two digit second of minute: yyyy-MM-ddTHH:mm:ss. "date_hour_minute_second": {"yyyy-MM-ddTHH:mm:ss"}, "strict_date_hour_minute_second": {"yyyy-MM-ddTHH:mm:ss"}, // A formatter that combines a full date, two digit hour of day, two digit minute of hour, two digit second of minute, and three digit fraction of second: yyyy-MM-ddTHH:mm:ss.SSS. "date_hour_minute_second_fraction": {"yyyy-MM-ddTHH:mm:ss.SSS"}, "strict_date_hour_minute_second_fraction": {"yyyy-MM-ddTHH:mm:ss.SSS"}, // A formatter that combines a full date, two digit hour of day, two digit minute of hour, two digit second of minute, and three digit fraction of second: yyyy-MM-ddTHH:mm:ss.SSS. "date_hour_minute_second_millis": {"yyyy-MM-ddTHH:mm:ss.SSS"}, "strict_date_hour_minute_second_millis": {"yyyy-MM-ddTHH:mm:ss.SSS"}, // A formatter that combines a full date and time, separated by a T: yyyy-MM-ddTHH:mm:ss.SSSZ. "date_time": {"yyyy-MM-ddTHH:mm:ss.SSSZ"}, "strict_date_time": {"yyyy-MM-ddTHH:mm:ss.SSSZ"}, // A formatter that combines a full date and time without millis, separated by a T: yyyy-MM-ddTHH:mm:ssZ. "date_time_no_millis": {"yyyy-MM-ddTHH:mm:ssZ"}, "strict_date_time_no_millis": {"yyyy-MM-ddTHH:mm:ssZ"}, // A formatter for a two digit hour of day: HH "hour": {"HH"}, "strict_hour": {"HH"}, // A formatter for a two digit hour of day and two digit minute of hour: HH:mm. "hour_minute": {"HH:mm"}, "strict_hour_minute": {"HH:mm"}, // A formatter for a two digit hour of day, two digit minute of hour, and two digit second of minute: HH:mm:ss. "hour_minute_second": {"HH:mm:ss"}, "strict_hour_minute_second": {"HH:mm:ss"}, // A formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, and three digit fraction of second: HH:mm:ss.SSS. "hour_minute_second_fraction": {"HH:mm:ss.SSS"}, "strict_hour_minute_second_fraction": {"HH:mm:ss.SSS"}, // A formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, and three digit fraction of second: HH:mm:ss.SSS. "hour_minute_second_millis": {"HH:mm:ss.SSS"}, "strict_hour_minute_second_millis": {"HH:mm:ss.SSS"}, // A formatter for a full ordinal date, using a four digit year and three digit dayOfYear: yyyy-DDD. "ordinal_date": {"yyyy-DDD"}, "strict_ordinal_date": {"yyyy-DDD"}, // A formatter for a full ordinal date and time, using a four digit year and three digit dayOfYear: yyyy-DDDTHH:mm:ss.SSSZ. "ordinal_date_time": {"yyyy-DDDTHH:mm:ss.SSSZ"}, "strict_ordinal_date_time": {"yyyy-DDDTHH:mm:ss.SSSZ"}, // A formatter for a full ordinal date and time without millis, using a four digit year and three digit dayOfYear: yyyy-DDDTHH:mm:ssZ. "ordinal_date_time_no_millis": {"yyyy-DDDTHH:mm:ssZ"}, "strict_ordinal_date_time_no_millis": {"yyyy-DDDTHH:mm:ssZ"}, // A formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, three digit fraction of second, and time zone offset: HH:mm:ss.SSSZ. "time": {"HH:mm:ss.SSSZ"}, "strict_time": {"HH:mm:ss.SSSZ"}, // A formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, and time zone offset: HH:mm:ssZ. "time_no_millis": {"HH:mm:ssZ"}, "strict_time_no_millis": {"HH:mm:ssZ"}, // A formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, three digit fraction of second, and time zone offset prefixed by T: THH:mm:ss.SSSZ. "t_time": {"THH:mm:ss.SSSZ"}, "strict_t_time": {"THH:mm:ss.SSSZ"}, // A formatter for a two digit hour of day, two digit minute of hour, two digit second of minute, and time zone offset prefixed by T: THH:mm:ssZ. "t_time_no_millis": {"THH:mm:ssZ"}, "strict_t_time_no_millis": {"THH:mm:ssZ"}, // A formatter for a full date as four digit weekyear, two digit week of weekyear, and one digit day of week: xxxx-Www-e. "week_date": {"xxxx-Www-e"}, "strict_week_date": {"xxxx-Www-e"}, // A formatter that combines a full weekyear date and time, separated by a T: xxxx-Www-eTHH:mm:ss.SSSZ. "week_date_time": {"xxxx-Www-eTHH:mm:ss.SSSZ"}, "strict_week_date_time": {"xxxx-Www-eTHH:mm:ss.SSSZ"}, // A formatter that combines a full weekyear date and time without millis, separated by a T: xxxx-Www-eTHH:mm:ssZ. "week_date_time_no_millis": {"xxxx-Www-eTHH:mm:ssZ"}, "strict_week_date_time_no_millis": {"xxxx-Www-eTHH:mm:ssZ"}, // A formatter for a four digit weekyear: xxxx. "weekyear": {"xxxx"}, "strict_weekyear": {"xxxx"}, // A formatter for a four digit weekyear and two digit week of weekyear: xxxx-Www. "weekyear_week": {"xxxx-Www"}, "strict_weekyear_week": {"xxxx-Www"}, // A formatter for a four digit weekyear, two digit week of weekyear, and one digit day of week: xxxx-Www-e. "weekyear_week_day": {"xxxx-Www-e"}, "strict_weekyear_week_day": {"xxxx-Www-e"}, // A formatter for a four digit year and two digit month of year: yyyy-MM. "year_month": {"yyyy-MM"}, "strict_year_month": {"yyyy-MM"}, // A formatter for a four digit year: yyyy. "year": {"yyyy"}, "strict_year": {"yyyy"}, // A formatter for a four digit year, two digit month of year, and two digit day of month: yyyy-MM-dd. "year_month_day": {"yyyy-MM-dd"}, "strict_year_month_day": {"yyyy-MM-dd"}, }
format.go
0.643105
0.534795
format.go
starcoder
package types import ( "encoding/json" "errors" "fmt" "math/big" "strconv" "strings" "<KEY>" cbor "gx/ipfs/QmcZLyosDwMKdB6NLRsiss9HXzDPhVhhRtPy67JFKTDQDX/go-ipld-cbor" "gx/ipfs/QmdBzoMxsBpojBfN1cv5GnKtB7sfYBMoLH7p9qSyEVYXcu/refmt/obj/atlas" ) // NOTE -- ALL *AttoFIL methods must call ensureZeroAmounts with refs to every user-supplied value before use. func init() { cbor.RegisterCborType(attoFILAtlasEntry) ZeroAttoFIL = NewZeroAttoFIL() } var attoPower = 18 var tenToTheEighteen = big.NewInt(10).Exp(big.NewInt(10), big.NewInt(18), nil) // ZeroAttoFIL represents an AttoFIL quantity of 0 var ZeroAttoFIL *AttoFIL // ensureZeroAmounts takes a variable number of refs -- variables holding *AttoFIL -- // and sets their values to the ZeroAttoFIL (the zero value for the type) if their values are nil. func ensureZeroAmounts(refs ...**AttoFIL) { for _, ref := range refs { if *ref == nil { *ref = ZeroAttoFIL } } } var attoFILAtlasEntry = atlas.BuildEntry(AttoFIL{}).Transform(). TransformMarshal(atlas.MakeMarshalTransformFunc( func(a AttoFIL) ([]byte, error) { return a.Bytes(), nil })). TransformUnmarshal(atlas.MakeUnmarshalTransformFunc( func(x []byte) (AttoFIL, error) { return *NewAttoFILFromBytes(x), nil })). Complete() // UnmarshalJSON converts a byte array to an AttoFIL. func (z *AttoFIL) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } token, ok := NewAttoFILFromFILString(s) if !ok { return errors.New("cannot convert string to token amount") } *z = *token return nil } // MarshalJSON converts an AttoFIL to a byte array and returns it. func (z AttoFIL) MarshalJSON() ([]byte, error) { return json.Marshal(z.String()) } // AttoFIL represents a signed multi-precision integer quantity of // attofilecoin (atto is metric for 10**-18). The zero value for // AttoFIL represents the value 0. type AttoFIL struct{ val *big.Int } // NewAttoFIL allocates and returns a new AttoFIL set to x. func NewAttoFIL(x *big.Int) *AttoFIL { return &AttoFIL{val: big.NewInt(0).Set(x)} } // NewZeroAttoFIL returns a new zero quantity of attofilecoin. It is // different from ZeroAttoFIL in that this value may be used/mutated. func NewZeroAttoFIL() *AttoFIL { return NewAttoFIL(big.NewInt(0)) } // NewAttoFILFromFIL returns a new AttoFIL representing a quantity // of attofilecoin equal to x filecoin. func NewAttoFILFromFIL(x uint64) *AttoFIL { xAsBigInt := big.NewInt(0).SetUint64(x) return NewAttoFIL(xAsBigInt.Mul(xAsBigInt, tenToTheEighteen)) } // NewAttoFILFromBytes allocates and returns a new AttoFIL set // to the value of buf as the bytes of a big-endian unsigned integer. func NewAttoFILFromBytes(buf []byte) *AttoFIL { af := NewZeroAttoFIL() af.val = leb128.ToBigInt(buf) return af } // NewAttoFILFromFILString allocates a new AttoFIL set to the value of s filecoin, // interpreted as a decimal in base 10, and returns it and a boolean indicating success. func NewAttoFILFromFILString(s string) (*AttoFIL, bool) { splitNumber := strings.Split(s, ".") // If '.' is absent from string, add an empty string to become the decimal part if len(splitNumber) == 1 { splitNumber = append(splitNumber, "") } intPart := splitNumber[0] decPart := splitNumber[1] // A decimal part longer than 18 digits should be an error if len(decPart) > attoPower || len(splitNumber) > 2 { return nil, false } // The decimal is right padded with 0's if it less than 18 digits long for len(decPart) < attoPower { decPart += "0" } return NewAttoFILFromString(intPart+decPart, 10) } // NewAttoFILFromString allocates a new AttoFIL set to the value of s attofilecoin, // interpreted in the given base, and returns it and a boolean indicating success. func NewAttoFILFromString(s string, base int) (*AttoFIL, bool) { af := NewZeroAttoFIL() _, ok := af.val.SetString(s, base) return af, ok } // Add sets z to the sum x+y and returns z. func (z *AttoFIL) Add(y *AttoFIL) *AttoFIL { ensureZeroAmounts(&z, &y) newVal := big.NewInt(0) newVal.Add(z.val, y.val) newZ := AttoFIL{val: newVal} return &newZ } // Sub sets z to the difference x-y and returns z. func (z *AttoFIL) Sub(y *AttoFIL) *AttoFIL { ensureZeroAmounts(&z, &y) newVal := big.NewInt(0) newVal.Sub(z.val, y.val) newZ := AttoFIL{val: newVal} return &newZ } // MulBigInt multiplies attoFIL by a given big int func (z *AttoFIL) MulBigInt(x *big.Int) *AttoFIL { newVal := big.NewInt(0) newVal.Mul(z.val, x) return &AttoFIL{val: newVal} } // DivCeil returns the minimum number of times this value can be divided into smaller amounts // such that none of the smaller amounts are greater than the given divisor. // Equal to ceil(z/y) if AttoFIL could be fractional. // If y is zero a panic will occur. func (z *AttoFIL) DivCeil(y *AttoFIL) *AttoFIL { value, remainder := big.NewInt(0).DivMod(z.val, y.val, big.NewInt(0)) if remainder.Cmp(big.NewInt(0)) == 0 { return NewAttoFIL(value) } return NewAttoFIL(big.NewInt(0).Add(value, big.NewInt(1))) } // Equal returns true if z = y func (z *AttoFIL) Equal(y *AttoFIL) bool { ensureZeroAmounts(&z, &y) return z.val.Cmp(y.val) == 0 } // LessThan returns true if z < y func (z *AttoFIL) LessThan(y *AttoFIL) bool { ensureZeroAmounts(&z, &y) return z.val.Cmp(y.val) < 0 } // GreaterThan returns true if z > y func (z *AttoFIL) GreaterThan(y *AttoFIL) bool { ensureZeroAmounts(&z, &y) return z.val.Cmp(y.val) > 0 } // LessEqual returns true if z <= y func (z *AttoFIL) LessEqual(y *AttoFIL) bool { ensureZeroAmounts(&z, &y) return z.val.Cmp(y.val) <= 0 } // GreaterEqual returns true if z >= y func (z *AttoFIL) GreaterEqual(y *AttoFIL) bool { ensureZeroAmounts(&z, &y) return z.val.Cmp(y.val) >= 0 } // IsPositive returns true if z is greater than zero. func (z *AttoFIL) IsPositive() bool { ensureZeroAmounts(&z) return z.GreaterThan(ZeroAttoFIL) } // IsNegative returns true if z is less than zero. func (z *AttoFIL) IsNegative() bool { ensureZeroAmounts(&z) return z.LessThan(ZeroAttoFIL) } // IsZero returns true if z equals zero. func (z *AttoFIL) IsZero() bool { ensureZeroAmounts(&z) return z.Equal(ZeroAttoFIL) } // Bytes returns the absolute value of x as a big-endian byte slice. func (z *AttoFIL) Bytes() []byte { ensureZeroAmounts(&z) return leb128.FromBigInt(z.val) } func (z *AttoFIL) String() string { ensureZeroAmounts(&z) attoPadLength := strconv.Itoa(attoPower + 1) paddedStr := fmt.Sprintf("%0"+attoPadLength+"d", z.val) decimaledStr := fmt.Sprintf("%s.%s", paddedStr[:len(paddedStr)-attoPower], paddedStr[len(paddedStr)-attoPower:]) noTrailZeroStr := strings.TrimRight(decimaledStr, "0") return strings.TrimRight(noTrailZeroStr, ".") } // CalculatePrice treats z as a price in AttoFIL/Byte and applies it to numBytes to calculate a total price. func (z *AttoFIL) CalculatePrice(numBytes *BytesAmount) *AttoFIL { ensureZeroAmounts(&z) ensureBytesAmounts(&numBytes) unitPrice := z newVal := big.NewInt(0) newVal.Mul(unitPrice.val, numBytes.val) return &AttoFIL{val: newVal} }
types/atto_fil.go
0.681939
0.577674
atto_fil.go
starcoder
package vector import ( "encoding/binary" "math" "github.com/frenchie-foundation/go-lachesis/inter" "github.com/frenchie-foundation/go-lachesis/inter/idx" ) /* * Use binary form for optimization, to avoid serialization. As a result, DB cache works as elements cache. */ type ( // LowestAfterSeq is a vector of lowest events (their Seq) which do observe the source event LowestAfterSeq []byte // HighestBeforeSeq is a vector of highest events (their Seq + IsForkDetected) which are observed by source event HighestBeforeSeq []byte // HighestBeforeTime is a vector of highest events (their ClaimedTime) which are observed by source event HighestBeforeTime []byte // BranchSeq encodes Seq and MinSeq into 8 bytes BranchSeq struct { Seq idx.Event // maximum observed e.Seq in the branch MinSeq idx.Event // minimum observed e.Seq in the branch } // allVecs is container of all the vector clocks allVecs struct { after LowestAfterSeq beforeSeq HighestBeforeSeq beforeTime HighestBeforeTime } ) // NewLowestAfterSeq creates new LowestAfterSeq vector. func NewLowestAfterSeq(size int) LowestAfterSeq { return make(LowestAfterSeq, size*4) } // NewHighestBeforeTime creates new HighestBeforeTime vector. func NewHighestBeforeTime(size int) HighestBeforeTime { return make(HighestBeforeTime, size*8) } // NewHighestBeforeSeq creates new HighestBeforeSeq vector. func NewHighestBeforeSeq(size int) HighestBeforeSeq { return make(HighestBeforeSeq, size*8) } // Get i's position in the byte-encoded vector clock func (b LowestAfterSeq) Get(i idx.Validator) idx.Event { for int(i) >= b.Size() { return 0 } return idx.Event(binary.LittleEndian.Uint32(b[i*4 : (i+1)*4])) } // Size of the vector clock func (b LowestAfterSeq) Size() int { return len(b) / 4 } // Set i's position in the byte-encoded vector clock func (b *LowestAfterSeq) Set(i idx.Validator, seq idx.Event) { for int(i) >= b.Size() { // append zeros if exceeds size *b = append(*b, []byte{0, 0, 0, 0}...) } binary.LittleEndian.PutUint32((*b)[i*4:(i+1)*4], uint32(seq)) } // Get i's position in the byte-encoded vector clock func (b HighestBeforeTime) Get(i idx.Validator) inter.Timestamp { for int(i) >= b.Size() { return 0 } return inter.Timestamp(binary.LittleEndian.Uint64(b[i*8 : (i+1)*8])) } // Set i's position in the byte-encoded vector clock func (b *HighestBeforeTime) Set(i idx.Validator, time inter.Timestamp) { for int(i) >= b.Size() { // append zeros if exceeds size *b = append(*b, []byte{0, 0, 0, 0, 0, 0, 0, 0}...) } binary.LittleEndian.PutUint64((*b)[i*8:(i+1)*8], uint64(time)) } // Size of the vector clock func (b HighestBeforeTime) Size() int { return len(b) / 8 } // Size of the vector clock func (b HighestBeforeSeq) Size() int { return len(b) / 8 } // Get i's position in the byte-encoded vector clock func (b HighestBeforeSeq) Get(i idx.Validator) BranchSeq { for int(i) >= b.Size() { return BranchSeq{} } seq1 := binary.LittleEndian.Uint32(b[i*8 : i*8+4]) seq2 := binary.LittleEndian.Uint32(b[i*8+4 : i*8+8]) return BranchSeq{ Seq: idx.Event(seq1), MinSeq: idx.Event(seq2), } } // Set i's position in the byte-encoded vector clock func (b *HighestBeforeSeq) Set(i idx.Validator, seq BranchSeq) { for int(i) >= b.Size() { // append zeros if exceeds size *b = append(*b, []byte{0, 0, 0, 0, 0, 0, 0, 0}...) } binary.LittleEndian.PutUint32((*b)[i*8:i*8+4], uint32(seq.Seq)) binary.LittleEndian.PutUint32((*b)[i*8+4:i*8+8], uint32(seq.MinSeq)) } var ( // forkDetectedSeq is a special marker of observed fork by a creator forkDetectedSeq = BranchSeq{ Seq: 0, MinSeq: idx.Event(math.MaxInt32), } ) // IsForkDetected returns true if observed fork by a creator (in combination of branches) func (seq BranchSeq) IsForkDetected() bool { return seq == forkDetectedSeq }
vector/vector.go
0.706292
0.540621
vector.go
starcoder
package pl import "github.com/ContextLogic/cldr" var calendar = cldr.Calendar{ Formats: cldr.CalendarFormats{ Date: cldr.CalendarDateFormat{Full: "EEEE, d MMMM y", Long: "d MMMM y", Medium: "dd.MM.y", Short: "dd.MM.y"}, Time: cldr.CalendarDateFormat{Full: "HH:mm:ss zzzz", Long: "HH:mm:ss z", Medium: "HH:mm:ss", Short: "HH:mm"}, DateTime: cldr.CalendarDateFormat{Full: "{1} {0}", Long: "{1} {0}", Medium: "{1}, {0}", Short: "{1}, {0}"}, }, FormatNames: cldr.CalendarFormatNames{ Months: cldr.CalendarMonthFormatNames{ Abbreviated: cldr.CalendarMonthFormatNameValue{Jan: "sty", Feb: "lut", Mar: "mar", Apr: "kwi", May: "maj", Jun: "cze", Jul: "lip", Aug: "sie", Sep: "wrz", Oct: "paź", Nov: "lis", Dec: "gru"}, Narrow: cldr.CalendarMonthFormatNameValue{Jan: "s", Feb: "l", Mar: "m", Apr: "k", May: "m", Jun: "c", Jul: "l", Aug: "s", Sep: "w", Oct: "p", Nov: "l", Dec: "g"}, Short: cldr.CalendarMonthFormatNameValue{}, Wide: cldr.CalendarMonthFormatNameValue{Jan: "styczeń", Feb: "luty", Mar: "marzec", Apr: "kwiecień", May: "maj", Jun: "czerwiec", Jul: "lipiec", Aug: "sierpień", Sep: "wrzesień", Oct: "październik", Nov: "listopad", Dec: "grudzień"}, }, Days: cldr.CalendarDayFormatNames{ Abbreviated: cldr.CalendarDayFormatNameValue{Sun: "niedz.", Mon: "pon.", Tue: "wt.", Wed: "śr.", Thu: "czw.", Fri: "pt.", Sat: "sob."}, Narrow: cldr.CalendarDayFormatNameValue{Sun: "N", Mon: "P", Tue: "W", Wed: "Ś", Thu: "C", Fri: "P", Sat: "S"}, Short: cldr.CalendarDayFormatNameValue{Sun: "niedz.", Mon: "pon.", Tue: "wt.", Wed: "śr.", Thu: "czw.", Fri: "pt.", Sat: "sob."}, Wide: cldr.CalendarDayFormatNameValue{Sun: "niedziela", Mon: "poniedziałek", Tue: "wtorek", Wed: "środa", Thu: "czwartek", Fri: "piątek", Sat: "sobota"}, }, Periods: cldr.CalendarPeriodFormatNames{ Abbreviated: cldr.CalendarPeriodFormatNameValue{}, Narrow: cldr.CalendarPeriodFormatNameValue{AM: "a", PM: "p"}, Short: cldr.CalendarPeriodFormatNameValue{}, Wide: cldr.CalendarPeriodFormatNameValue{AM: "AM", PM: "PM"}, }, }, }
resources/locales/pl/calendar.go
0.501221
0.437703
calendar.go
starcoder
package tiledb /* #cgo LDFLAGS: -ltiledb #include <tiledb/tiledb.h> #include <stdlib.h> */ import "C" import ( "fmt" "runtime" "unsafe" ) /* Array struct representing a TileDB array object. An Array object represents array data in TileDB at some persisted location, e.g. on disk, in an S3 bucket, etc. Once an array has been opened for reading or writing, interact with the data through Query objects. */ type Array struct { tiledbArray *C.tiledb_array_t context *Context uri string } // NonEmptyDomain contains the non empty dimension bounds and dimension name type NonEmptyDomain struct { DimensionName string Bounds interface{} } // NewArray alloc a new array func NewArray(ctx *Context, uri string) (*Array, error) { curi := C.CString(uri) defer C.free(unsafe.Pointer(curi)) array := Array{context: ctx, uri: uri} ret := C.tiledb_array_alloc(array.context.tiledbContext, curi, &array.tiledbArray) if ret != C.TILEDB_OK { return nil, fmt.Errorf("Error creating tiledb array: %s", array.context.LastError()) } // Set finalizer for free C pointer on gc runtime.SetFinalizer(&array, func(array *Array) { array.Free() }) return &array, nil } // Free tiledb_array_t that was allocated on heap in c func (a *Array) Free() { if a.tiledbArray != nil { a.Close() C.tiledb_array_free(&a.tiledbArray) } } /* Open the array. The array is opened using a query type as input. This is to indicate that queries created for this Array object will inherit the query type. In other words, Array objects are opened to receive only one type of queries. They can always be closed and be re-opened with another query type. Also there may be many different Array objects created and opened with different query types. For instance, one may create and open an array object array_read for reads and another one array_write for writes, and interleave creation and submission of queries for both these array objects. */ func (a *Array) Open(queryType QueryType) error { ret := C.tiledb_array_open(a.context.tiledbContext, a.tiledbArray, C.tiledb_query_type_t(queryType)) if ret != C.TILEDB_OK { return fmt.Errorf("Error opening tiledb array for querying: %s", a.context.LastError()) } return nil } /* OpenWithKey Opens an encrypted array using the given encryption key. This function has the same semantics as tiledb_array_open() but is used for encrypted arrays. An encrypted array must be opened with this function before queries can be issued to it. */ func (a *Array) OpenWithKey(queryType QueryType, encryptionType EncryptionType, key string) error { ckey := unsafe.Pointer(C.CString(key)) defer C.free(ckey) ret := C.tiledb_array_open_with_key(a.context.tiledbContext, a.tiledbArray, C.tiledb_query_type_t(queryType), C.tiledb_encryption_type_t(encryptionType), ckey, C.uint32_t(len(key))) if ret != C.TILEDB_OK { return fmt.Errorf("Error opening tiledb array with key for querying: %s", a.context.LastError()) } return nil } /* OpenAt Similar to tiledb_array_open, but this function takes as input a timestamp, representing time in milliseconds ellapsed since 1970-01-01 00:00:00 +0000 (UTC). Opening the array at a timestamp provides a view of the array with all writes/updates that happened at or before timestamp (i.e., excluding those that occurred after timestamp). This function is useful to ensure consistency at a potential distributed setting, where machines need to operate on the same view of the array. */ func (a *Array) OpenAt(queryType QueryType, timestamp uint64) error { ret := C.tiledb_array_open_at(a.context.tiledbContext, a.tiledbArray, C.tiledb_query_type_t(queryType), C.uint64_t(timestamp)) if ret != C.TILEDB_OK { return fmt.Errorf("Error opening tiledb array at %d for querying: %s", timestamp, a.context.LastError()) } return nil } /* OpenAtWithKey Similar to tiledb_array_open_with_key, but this function takes as input a timestamp, representing time in milliseconds ellapsed since 1970-01-01 00:00:00 +0000 (UTC). Opening the array at a timestamp provides a view of the array with all writes/updates that happened at or before timestamp (i.e., excluding those that occurred after timestamp). This function is useful to ensure consistency at a potential distributed setting, where machines need to operate on the same view of the array. */ func (a *Array) OpenAtWithKey(queryType QueryType, encryptionType EncryptionType, key string, timestamp uint64) error { ckey := unsafe.Pointer(C.CString(key)) defer C.free(ckey) ret := C.tiledb_array_open_at_with_key(a.context.tiledbContext, a.tiledbArray, C.tiledb_query_type_t(queryType), C.tiledb_encryption_type_t(encryptionType), ckey, C.uint32_t(len(key)), C.uint64_t(timestamp)) if ret != C.TILEDB_OK { return fmt.Errorf("Error opening tiledb array with key at %d for querying: %s", timestamp, a.context.LastError()) } return nil } /* Reopen the array (the array must be already open). This is useful when the array got updated after it got opened and the Array object got created. To sync-up with the updates, the user must either close the array and open with open(), or just use reopen() without closing. This function will be generally faster than the former alternative. */ func (a *Array) Reopen() error { ret := C.tiledb_array_reopen(a.context.tiledbContext, a.tiledbArray) if ret != C.TILEDB_OK { return fmt.Errorf("Error reopening tiledb array for querying: %s", a.context.LastError()) } return nil } // Close a tiledb array, this is called on garbage collection automatically func (a *Array) Close() error { ret := C.tiledb_array_close(a.context.tiledbContext, a.tiledbArray) if ret != C.TILEDB_OK { return fmt.Errorf("Error closing tiledb array for querying: %s", a.context.LastError()) } return nil } // Create a new TileDB array given an input schema. func (a *Array) Create(arraySchema *ArraySchema) error { curi := C.CString(a.uri) defer C.free(unsafe.Pointer(curi)) ret := C.tiledb_array_create(a.context.tiledbContext, curi, arraySchema.tiledbArraySchema) if ret != C.TILEDB_OK { return fmt.Errorf("Error creating tiledb array: %s", a.context.LastError()) } return nil } // CreateWithKey a new TileDB array given an input schema. func (a *Array) CreateWithKey(arraySchema *ArraySchema, encryptionType EncryptionType, key string) error { ckey := unsafe.Pointer(C.CString(key)) defer C.free(ckey) curi := C.CString(a.uri) defer C.free(unsafe.Pointer(curi)) ret := C.tiledb_array_create_with_key(a.context.tiledbContext, curi, arraySchema.tiledbArraySchema, C.tiledb_encryption_type_t(encryptionType), ckey, C.uint32_t(len(key))) if ret != C.TILEDB_OK { return fmt.Errorf("Error creating tiledb array with key: %s", a.context.LastError()) } return nil } // Consolidate Consolidates the fragments of an array into a single fragment. // You must first finalize all queries to the array before consolidation can // begin (as consolidation temporarily acquires an exclusive lock on the array). func (a *Array) Consolidate(config *Config) error { if config == nil { return fmt.Errorf("Config must not be nil for Consolidate") } curi := C.CString(a.uri) defer C.free(unsafe.Pointer(curi)) ret := C.tiledb_array_consolidate(a.context.tiledbContext, curi, config.tiledbConfig) if ret != C.TILEDB_OK { return fmt.Errorf("Error consolidating tiledb array: %s", a.context.LastError()) } return nil } // ConsolidateWithKey Consolidates the fragments of an encrypted array // into a single fragment. // You must first finalize all queries to the array before consolidation can // begin (as consolidation temporarily acquires an exclusive lock on the array). func (a *Array) ConsolidateWithKey(encryptionType EncryptionType, key string, config *Config) error { if config == nil { return fmt.Errorf("Config must not be nil for ConsolidateWithKey") } ckey := unsafe.Pointer(C.CString(key)) defer C.free(ckey) curi := C.CString(a.uri) defer C.free(unsafe.Pointer(curi)) ret := C.tiledb_array_consolidate_with_key(a.context.tiledbContext, curi, C.tiledb_encryption_type_t(encryptionType), ckey, C.uint32_t(len(key)), config.tiledbConfig) if ret != C.TILEDB_OK { return fmt.Errorf("Error consolidating tiledb with key array: %s", a.context.LastError()) } return nil } // Schema returns the ArraySchema for the array func (a *Array) Schema() (*ArraySchema, error) { arraySchema := ArraySchema{context: a.context} ret := C.tiledb_array_get_schema(a.context.tiledbContext, a.tiledbArray, &arraySchema.tiledbArraySchema) if ret != C.TILEDB_OK { return nil, fmt.Errorf("Error getting schema for tiledb array: %s", a.context.LastError()) } return &arraySchema, nil } // QueryType return the current query type of an open array func (a *Array) QueryType() (QueryType, error) { var queryType C.tiledb_query_type_t ret := C.tiledb_array_get_query_type(a.context.tiledbContext, a.tiledbArray, &queryType) if ret != C.TILEDB_OK { return -1, fmt.Errorf("Error getting QueryType for tiledb array: %s", a.context.LastError()) } return QueryType(queryType), nil } // NonEmptyDomain retrieves the non-empty domain from an array // This returns the bounding coordinates for each dimension func (a *Array) NonEmptyDomain() ([]NonEmptyDomain, bool, error) { nonEmptyDomains := make([]NonEmptyDomain, 0) schema, err := a.Schema() if err != nil { return nil, false, err } domain, err := schema.Domain() if err != nil { return nil, false, err } domainType, err := domain.Type() if err != nil { return nil, false, err } ndims, err := domain.NDim() if err != nil { return nil, false, err } var ret C.int var isEmpty C.int switch domainType { case TILEDB_INT8: tmpDomain := make([]int8, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []int8{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_INT16: tmpDomain := make([]int16, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []int16{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_INT32: tmpDomain := make([]int32, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []int32{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_INT64: tmpDomain := make([]int64, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []int64{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_UINT8: tmpDomain := make([]uint8, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []uint8{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_UINT16: tmpDomain := make([]uint16, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []uint16{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_UINT32: tmpDomain := make([]uint32, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []uint32{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_UINT64: tmpDomain := make([]uint64, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []uint64{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_FLOAT32: tmpDomain := make([]float32, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []float32{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } case TILEDB_FLOAT64: tmpDomain := make([]float64, 2*ndims) ret = C.tiledb_array_get_non_empty_domain(a.context.tiledbContext, a.tiledbArray, unsafe.Pointer(&tmpDomain[0]), &isEmpty) if ret != C.TILEDB_OK { return nil, false, fmt.Errorf("Error in getting non empty domain for array: %s", a.context.LastError()) } if isEmpty == 0 { for i := uint(0); i < ndims; i++ { dimension, err := domain.DimensionFromIndex(i) if err != nil { return nil, false, err } name, err := dimension.Name() if err != nil { return nil, false, err } nonEmptyDomains = append(nonEmptyDomains, NonEmptyDomain{DimensionName: name, Bounds: []float64{tmpDomain[i*2], tmpDomain[(i*2)+1]}}) } } } return nonEmptyDomains, isEmpty == 1, nil } // MaxBufferSize computes the upper bound on the buffer size (in bytes) // required for a read query for a given fixed attribute and subarray func (a *Array) MaxBufferSize(attributeName string, subarray interface{}) (uint64, error) { // Get Schema schema, err := a.Schema() if err != nil { return 0, err } // Get domain from schema domain, err := schema.Domain() if err != nil { return 0, err } // Get domain type to switch on domainType, err := domain.Type() if err != nil { return 0, err } cAttributeName := C.CString(attributeName) defer C.free(unsafe.Pointer(cAttributeName)) var bufferSize C.uint64_t var ret C.int // Switch on domain type to cast subarray to proper type switch domainType { case TILEDB_INT8: tmpSubArray := subarray.([]int8) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_INT16: tmpSubArray := subarray.([]int16) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_INT32: tmpSubArray := subarray.([]int32) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_INT64: tmpSubArray := subarray.([]int64) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_UINT8: tmpSubArray := subarray.([]uint8) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_UINT16: tmpSubArray := subarray.([]uint16) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_UINT32: tmpSubArray := subarray.([]uint32) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_UINT64: tmpSubArray := subarray.([]uint64) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_FLOAT32: tmpSubArray := subarray.([]float32) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) case TILEDB_FLOAT64: tmpSubArray := subarray.([]float64) ret = C.tiledb_array_max_buffer_size(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferSize) } if ret != C.TILEDB_OK { return 0, fmt.Errorf("Error in getting max buffer size for array: %s", a.context.LastError()) } return uint64(bufferSize), nil } // MaxBufferSizeVar computes the upper bound on the buffer size (in bytes) // required for a read query for a given variable sized attribute and subarray func (a *Array) MaxBufferSizeVar(attributeName string, subarray interface{}) (uint64, uint64, error) { // Get Schema schema, err := a.Schema() if err != nil { return 0, 0, err } // Get domain from schema domain, err := schema.Domain() if err != nil { return 0, 0, err } // Get domain type to switch on domainType, err := domain.Type() if err != nil { return 0, 0, err } cAttributeName := C.CString(attributeName) defer C.free(unsafe.Pointer(cAttributeName)) var bufferValSize C.uint64_t var bufferOffSize C.uint64_t var ret C.int // Switch on domain type to cast subarray to proper type switch domainType { case TILEDB_INT8: tmpSubArray := subarray.([]int8) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_INT16: tmpSubArray := subarray.([]int16) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_INT32: tmpSubArray := subarray.([]int32) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_INT64: tmpSubArray := subarray.([]int64) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_UINT8: tmpSubArray := subarray.([]uint8) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_UINT16: tmpSubArray := subarray.([]uint16) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_UINT32: tmpSubArray := subarray.([]uint32) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_UINT64: tmpSubArray := subarray.([]uint64) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_FLOAT32: tmpSubArray := subarray.([]float32) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) case TILEDB_FLOAT64: tmpSubArray := subarray.([]float64) ret = C.tiledb_array_max_buffer_size_var(a.context.tiledbContext, a.tiledbArray, cAttributeName, unsafe.Pointer(&tmpSubArray[0]), &bufferOffSize, &bufferValSize) } if ret != C.TILEDB_OK { return 0, 0, fmt.Errorf("Error in getting max buffer size variable for array: %s", a.context.LastError()) } return uint64(bufferOffSize), uint64(bufferValSize), nil } /* MaxBufferElements compute an upper bound on the buffer elements needed to read a subarray. Returns A map of attribute name (including TILEDB_COORDS) to the maximum number of elements that can be read in the given subarray. For each attribute, a pair of numbers are returned. The first, for variable-length attributes, is the maximum number of offsets for that attribute in the given subarray. For fixed-length attributes and coordinates, the first is always 0. The second is the maximum number of elements for that attribute in the given subarray. */ func (a *Array) MaxBufferElements(subarray interface{}) (map[string][2]uint64, error) { // Build map ret := make(map[string][2]uint64, 0) // Get schema schema, err := a.Schema() if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } attributes, err := schema.Attributes() if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } // Loop through each attribute for _, attribute := range attributes { // Check if attribute is variable attribute or not cellValNum, err := attribute.CellValNum() if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } // Get datatype size to convert byte lengths to needed buffer sizes dataType, err := attribute.Type() dataTypeSize := uint64(C.tiledb_datatype_size(C.tiledb_datatype_t(dataType))) // Get attribute name name, err := attribute.Name() if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } if cellValNum == TILEDB_VAR_NUM { bufferOffsetSize, bufferValSize, err := a.MaxBufferSizeVar(name, subarray) if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } // Set sizes for attribute in return map ret[name] = [2]uint64{ bufferOffsetSize / uint64(C.TILEDB_OFFSET_SIZE), bufferValSize / dataTypeSize} if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } } else { bufferValSize, err := a.MaxBufferSize(name, subarray) if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } ret[name] = [2]uint64{0, bufferValSize / dataTypeSize} } } // Handle coordinates domain, err := schema.Domain() if err != nil { return nil, fmt.Errorf("Could not get domain for MaxBufferElements: %s", err) } domainType, err := domain.Type() if err != nil { return nil, fmt.Errorf("Could not get domainType for MaxBufferElements: %s", err) } domainTypeSize := uint64(C.tiledb_datatype_size(C.tiledb_datatype_t(domainType))) bufferValSize, err := a.MaxBufferSize(TILEDB_COORDS, subarray) if err != nil { return nil, fmt.Errorf("Error getting MaxBufferElements for array: %s", err) } ret[TILEDB_COORDS] = [2]uint64{0, bufferValSize / domainTypeSize} return ret, nil } // URI returns the array's uri func (a *Array) URI() (string, error) { var curi *C.char defer C.free(unsafe.Pointer(curi)) C.tiledb_array_get_uri(a.context.tiledbContext, a.tiledbArray, &curi) uri := C.GoString(curi) if uri == "" { return uri, fmt.Errorf("Error getting URI for array: uri is empty") } return uri, nil }
array.go
0.630002
0.520984
array.go
starcoder
package influxql import ( "encoding/json" "errors" "github.com/influxdata/influxdb/models" ) // TagSet is a fundamental concept within the query system. It represents a composite series, // composed of multiple individual series that share a set of tag attributes. type TagSet struct { Tags map[string]string Filters []Expr SeriesKeys []string Key []byte } // AddFilter adds a series-level filter to the Tagset. func (t *TagSet) AddFilter(key string, filter Expr) { t.SeriesKeys = append(t.SeriesKeys, key) t.Filters = append(t.Filters, filter) } // Rows represents a list of rows that can be sorted consistently by name/tag. // Result represents a resultset returned from a single statement. type Result struct { // StatementID is just the statement's position in the query. It's used // to combine statement results if they're being buffered in memory. StatementID int `json:"-"` Series models.Rows Err error } // MarshalJSON encodes the result into JSON. func (r *Result) MarshalJSON() ([]byte, error) { // Define a struct that outputs "error" as a string. var o struct { Series []*models.Row `json:"series,omitempty"` Err string `json:"error,omitempty"` } // Copy fields to output struct. o.Series = r.Series if r.Err != nil { o.Err = r.Err.Error() } return json.Marshal(&o) } // UnmarshalJSON decodes the data into the Result struct func (r *Result) UnmarshalJSON(b []byte) error { var o struct { Series []*models.Row `json:"series,omitempty"` Err string `json:"error,omitempty"` } err := json.Unmarshal(b, &o) if err != nil { return err } r.Series = o.Series if o.Err != "" { r.Err = errors.New(o.Err) } return nil } func GetProcessor(expr Expr, startIndex int) (Processor, int) { switch expr := expr.(type) { case *VarRef: return newEchoProcessor(startIndex), startIndex + 1 case *Call: return newEchoProcessor(startIndex), startIndex + 1 case *BinaryExpr: return getBinaryProcessor(expr, startIndex) case *ParenExpr: return GetProcessor(expr.Expr, startIndex) case *NumberLiteral: return newLiteralProcessor(expr.Val), startIndex case *StringLiteral: return newLiteralProcessor(expr.Val), startIndex case *BooleanLiteral: return newLiteralProcessor(expr.Val), startIndex case *TimeLiteral: return newLiteralProcessor(expr.Val), startIndex case *DurationLiteral: return newLiteralProcessor(expr.Val), startIndex } panic("unreachable") } type Processor func(values []interface{}) interface{} func newEchoProcessor(index int) Processor { return func(values []interface{}) interface{} { if index > len(values)-1 { return nil } return values[index] } } func newLiteralProcessor(val interface{}) Processor { return func(values []interface{}) interface{} { return val } } func getBinaryProcessor(expr *BinaryExpr, startIndex int) (Processor, int) { lhs, index := GetProcessor(expr.LHS, startIndex) rhs, index := GetProcessor(expr.RHS, index) return newBinaryExprEvaluator(expr.Op, lhs, rhs), index } func newBinaryExprEvaluator(op Token, lhs, rhs Processor) Processor { switch op { case ADD: return func(values []interface{}) interface{} { l := lhs(values) r := rhs(values) if lf, rf, ok := processorValuesAsFloat64(l, r); ok { return lf + rf } return nil } case SUB: return func(values []interface{}) interface{} { l := lhs(values) r := rhs(values) if lf, rf, ok := processorValuesAsFloat64(l, r); ok { return lf - rf } return nil } case MUL: return func(values []interface{}) interface{} { l := lhs(values) r := rhs(values) if lf, rf, ok := processorValuesAsFloat64(l, r); ok { return lf * rf } return nil } case DIV: return func(values []interface{}) interface{} { l := lhs(values) r := rhs(values) if lf, rf, ok := processorValuesAsFloat64(l, r); ok { return lf / rf } return nil } default: // we shouldn't get here, but give them back nils if it goes this way return func(values []interface{}) interface{} { return nil } } } func processorValuesAsFloat64(lhs interface{}, rhs interface{}) (float64, float64, bool) { var lf float64 var rf float64 var ok bool lf, ok = lhs.(float64) if !ok { var li int64 if li, ok = lhs.(int64); !ok { return 0, 0, false } lf = float64(li) } rf, ok = rhs.(float64) if !ok { var ri int64 if ri, ok = rhs.(int64); !ok { return 0, 0, false } rf = float64(ri) } return lf, rf, true }
vendor/github.com/influxdata/influxdb/influxql/result.go
0.727104
0.477676
result.go
starcoder
package measurement import ( "fmt" "sort" "strings" "sync" "sync/atomic" "time" ) type measurement struct { sync.RWMutex outputCounter int64 opCurMeasurement map[string]*histogram opSumMeasurement map[string]*histogram } func (m *measurement) getHist(op string, err error, current bool) *histogram { opMeasurement := m.opSumMeasurement if current { opMeasurement = m.opCurMeasurement } // Create hist of {op} and {op}_ERR at the same time, or else the TPM would be incorrect opPairedKey := fmt.Sprintf("%s_ERR", op) if err != nil { op, opPairedKey = opPairedKey, op } m.RLock() opM, ok := opMeasurement[op] m.RUnlock() if !ok { opM = newHistogram() opPairedM := newHistogram() m.Lock() opMeasurement[op] = opM opMeasurement[opPairedKey] = opPairedM m.Unlock() } return opM } func (m *measurement) measure(op string, err error, lan time.Duration) { m.getHist(op, err, true).Measure(lan) m.getHist(op, err, false).Measure(lan) } func (m *measurement) takeCurMeasurement() (ret map[string]*histogram) { m.RLock() defer m.RUnlock() ret, m.opCurMeasurement = m.opCurMeasurement, make(map[string]*histogram, 16) return } func outputMeasurement(opMeasurement map[string]*histogram, prefix string) { keys := make([]string, len(opMeasurement)) var i = 0 for k := range opMeasurement { keys[i] = k i += 1 } sort.Strings(keys) for _, op := range keys { hist := opMeasurement[op] if !hist.Empty() { fmt.Printf("%s%-6s - %s\n", prefix, strings.ToUpper(op), hist.Summary()) } } } func (m *measurement) output(summaryReport bool) { // Clear current measure data every time var opCurMeasurement = m.takeCurMeasurement() if summaryReport { m.RLock() defer m.RUnlock() outputMeasurement(m.opSumMeasurement, "[SUM] ") } else { outputMeasurement(opCurMeasurement, "[CUR] ") m.RLock() defer m.RUnlock() m.outputCounter += 1 if m.outputCounter%10 == 0 { outputMeasurement(m.opSumMeasurement, "[SUM] ") } } } func (m *measurement) getOpName() []string { m.RLock() defer m.RUnlock() res := make([]string, 0, len(m.opSumMeasurement)) for op := range m.opSumMeasurement { res = append(res, op) } return res } // Output prints the measurement summary. func Output(summaryReport bool) { globalMeasure.output(summaryReport) } // EnableWarmUp sets whether to enable warm-up. func EnableWarmUp(b bool) { if b { atomic.StoreInt32(&warmUp, 1) } else { atomic.StoreInt32(&warmUp, 0) } } // IsWarmUpFinished returns whether warm-up is finished or not. func IsWarmUpFinished() bool { return atomic.LoadInt32(&warmUp) == 0 } // Measure measures the operation. func Measure(op string, lan time.Duration, err error) { if !IsWarmUpFinished() { return } globalMeasure.measure(op, err, lan) } func newMeasurement() *measurement { return &measurement{ sync.RWMutex{}, 0, make(map[string]*histogram, 16), make(map[string]*histogram, 16), } } var ( globalMeasure *measurement warmUp int32 // use as bool, 1 means in warmup progress, 0 means warmup finished. ) func init() { globalMeasure = newMeasurement() warmUp = 0 }
pkg/measurement/measure.go
0.602529
0.517083
measure.go
starcoder
package window import ( "time" ) // New creates a Window instance which represents a recurring window // between two times of day. If `start` is after `end` then the time // window is assumed to cross over midnight. If `start` and `end` are // the same then the window is always active. func New(start, end time.Time) *Window { start = normaliseTime(start) end = normaliseTime(end) xMidnight := false if end.Before(start) { end = addDay(end) xMidnight = true } return &Window{ Start: start, End: end, Now: time.Now, xMidnight: xMidnight, } } // Window represents a recurring window between two times of day. // The Now field can be use to override the time source (for testing). type Window struct { Start time.Time End time.Time Now func() time.Time xMidnight bool } // Active returns true if the time window is currently active. func (w *Window) Active() bool { return w.Until() == time.Duration(0) } // Until returns the duration until the next time window starts. func (w *Window) Until() time.Duration { if w.Start == w.End { return time.Duration(0) } now := w.nowTimeAfterStart() if w.End.After(now) { // During window. return time.Duration(0) } // After window. return addDay(w.Start).Sub(now) } func addDay(t time.Time) time.Time { return t.Add(24 * time.Hour) } // nowTimeAfterStart to make time calculations easier we choose a date time to represent now // that is on or the next one after the start time func (w *Window) nowTimeAfterStart() time.Time { now := normaliseTime(w.Now()) if now.Before(w.Start) { now = addDay(now) } return now } func normaliseTime(t time.Time) time.Time { return time.Date(1, 1, 1, t.Hour(), t.Minute(), t.Second(), 0, time.UTC) } // UntilEnd returns the duration until the end of the time window. func (w *Window) UntilEnd() time.Duration { if (w.Active()) { return w.End.Sub(w.nowTimeAfterStart()) } return time.Duration(0) } // UntilNextInterval gets when the next interval starts. // Only works when window is currently active. func (w *Window) UntilNextInterval(interval time.Duration) time.Duration { if (w.Active()) { now := w.nowTimeAfterStart() elapsedTime := now.Sub(w.Start) nextInterval := w.Start.Add(elapsedTime.Truncate(interval) + interval) if (w.End.After(nextInterval)) { return nextInterval.Sub(now) } } return time.Duration(-1) }
window.go
0.875588
0.421552
window.go
starcoder
package simplify import "math" func squareDistance(left *MappablePoint, right *MappablePoint) float64 { leftX, leftY, leftZ := (*left).MapPoint() rightX, rightY, rightZ := (*right).MapPoint() return math.Pow(leftX-rightX, 2) + math.Pow(leftY-rightY, 2) + math.Pow(leftZ-rightZ, 2) } func segmentSquareDistance(point *MappablePoint, start *MappablePoint, end *MappablePoint) float64 { x, y, z := (*point).MapPoint() startX, startY, startZ := (*start).MapPoint() endX, endY, endZ := (*end).MapPoint() deltaX := endX - startX deltaY := endY - startY deltaZ := endZ - startZ result := func(rx float64, ry float64, rz float64) float64 { dx := x - rx dy := y - ry dz := z - rz return dx*dx + dy*dy + dz*dz } if deltaX == 0 && deltaY == 0 && deltaZ == 0 { return result(startX, startY, startZ) } t := ((x-startX)*deltaX + (y-startY)*deltaY + (z-startZ)*deltaZ) / (deltaX*deltaX + deltaY*deltaY + deltaZ*deltaZ) if t > 1 { return result(endX, endY, endZ) } return result(startX+deltaX*t, startY+deltaY*t, startZ+deltaZ*t) } func simplifyRadialDistance(points []MappablePoint, tolerance float64) []MappablePoint { if len(points) <= 2 { return points } previous := points[0] var newPoints = []MappablePoint{previous} var selectedPoint MappablePoint for _, point := range points[1:] { selectedPoint = point if squareDistance(&selectedPoint, &previous) < tolerance { continue } newPoints = append(newPoints, selectedPoint) previous = selectedPoint } if selectedPoint != nil && previous != selectedPoint { newPoints = append(newPoints, selectedPoint) } return newPoints } func simplifyDouglasPeucker(points []MappablePoint, tolerance float64) []MappablePoint { if len(points) <= 2 { return points } first := points[0] last := points[len(points)-1] var foundIndex int var bestDistance float64 for index, point := range points { if point == first || point == last { continue } distance := segmentSquareDistance(&point, &first, &last) if distance >= bestDistance { bestDistance = distance foundIndex = index } } if bestDistance > tolerance { leftPart := points[:foundIndex+1] rightPart := points[foundIndex:] left := simplifyDouglasPeucker(leftPart, tolerance) leftR := left[:len(left)-1] right := simplifyDouglasPeucker(rightPart, tolerance) result := append(leftR, right...) return result } return []MappablePoint{first, last} } func Simplify(points []MappablePoint, tolerance float64, highQuality bool) []MappablePoint { if len(points) <= 2 { return points } squaredTolerance := tolerance * tolerance if highQuality { return simplifyDouglasPeucker(points, squaredTolerance) } return simplifyDouglasPeucker(simplifyRadialDistance(points, squaredTolerance), squaredTolerance) }
go/pkg/simplify/simplify.go
0.844281
0.643833
simplify.go
starcoder
package model // Path holds information about a possible path, including edges, current length and current rewards. type Path struct { edges []*Edge length int rewards map[*Reward]int } // Edges returns a list of path edges. func (path *Path) Edges() []*Edge { return path.edges } // AddEdge adds an edge with length and its to node's rewards to the path. func (path *Path) AddEdge(edge *Edge, i int) { path.edges = append(path.edges, edge) path.length += edge.Weights()[i].Time() path.AddRewards(edge.To().Rewards()) } // Length returns the path length. func (path *Path) Length() int { return path.length } // Rewards returns the path rewards. func (path *Path) Rewards() map[*Reward]int { return path.rewards } // AddRewards adds a map of rewards to the path. func (path *Path) AddRewards(rewards map[*Reward]int) { for key, value := range rewards { path.rewards[key] += value } } // CreatePath is the constructor for path pointer. func CreatePath() *Path { path := new(Path) path.rewards = make(map[*Reward]int) return path } // IsLongerThan compares two paths to see which has best potential to be the shortest path. func (path *Path) IsLongerThan(other *Path) bool { pLength := path.Length() + path.Edges()[len(path.Edges())-1].To().MinPathLeft() oLength := other.Length() + other.Edges()[len(other.Edges())-1].To().MinPathLeft() if pLength != oLength { return pLength > oLength } return len(path.Edges()) > len(other.Edges()) } // Copy copies a path values into another path. func (path *Path) Copy() *Path { pathCopy := CreatePath() pathCopy.edges = make([]*Edge, len(path.Edges())) copy(pathCopy.edges, path.Edges()) pathCopy.length = path.Length() for k, v := range path.Rewards() { pathCopy.rewards[k] = v } return pathCopy } // PossibleRoute checks if an edge makes an eligible route to take for the current path. func (path *Path) PossibleRoute(edge *Edge) (isPossible bool, index int) { if path.rewardsAreNotNegativeOrUnique(edge.To()) { return false, -1 } nodeVisited := path.hasBeenVisited(edge) if !edge.To().Revisitable() && nodeVisited { return false, -1 } rewardsChangedSinceLastVisit := path.rewardsChangedSinceLastVisit(edge) if edge.To().Revisitable() && nodeVisited && !rewardsChangedSinceLastVisit { return false, -1 } return path.requirementsMet(edge) } func (path *Path) hasBeenVisited(edge *Edge) bool { node := edge.To() for i := 0; i < len(path.edges); i++ { if path.edges[i].From() == node { return true } } return edge.From() == node } func (path *Path) rewardsChangedSinceLastVisit(edge *Edge) bool { rewards := make(map[*Reward]int) node := edge.To() for k, v := range edge.From().Rewards() { rewards[k] += v } if edge.From() == edge.To() { return checkRewardsNotEmpty(rewards) } for i := len(path.edges) - 1; i >= 0; i-- { for k, v := range path.edges[i].From().Rewards() { rewards[k] += v } if path.edges[i].From() == node { break } } return checkRewardsNotEmpty(rewards) } func checkRewardsNotEmpty(rewards map[*Reward]int) bool { for _, v := range rewards { if v != 0 { return true } } return false } func (path *Path) rewardsAreNotNegativeOrUnique(node *Node) bool { for reward, quantity := range node.Rewards() { rewardCount := path.Rewards()[reward] if rewardCount+quantity < 0 || (reward.Unique() && rewardCount > 0) { return true } } return false } func (path *Path) requirementsMet(edge *Edge) (result bool, index int) { for i, weight := range edge.Weights() { if path.weightRequirementsMet(weight) { return true, i } } return false, -1 } func (path *Path) weightRequirementsMet(weight *Weight) bool { for reward, quantity := range weight.Requirements() { if path.countRewardsIncludingIsA(reward) < quantity { return false } } return true } func (path *Path) countRewardsIncludingIsA(reward *Reward) int { count := path.Rewards()[reward] for _, r := range reward.CanBe() { count += path.countRewardsIncludingIsA(r) } return count } // PrioQueue is a list of Path pointers and implements heap interface. type PrioQueue []*Path // Len returns the length of the PriorityQueue. func (pq PrioQueue) Len() int { return len(pq) } // Less checks if one path is longer than another path in the PriorityQueue. func (pq PrioQueue) Less(i, j int) bool { return pq[j].IsLongerThan(pq[i]) } // Swap switches places of two paths in the PriorityQueue. func (pq PrioQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } // Push adds a Path to the correct place in the PriorityQueue. func (pq *PrioQueue) Push(x interface{}) { *pq = append(*pq, x.(*Path)) } // Pop returns the node with the best potential path for the shortest path. func (pq *PrioQueue) Pop() interface{} { old := *pq n := len(old) x := old[n-1] *pq = old[0 : n-1] return x }
model/path.go
0.855233
0.562717
path.go
starcoder
package mutesting import ( "fmt" "go/ast" "go/types" "strings" "github.com/AlexanderAsmakov/go-mutesting/mutator" ) // CountWalk returns the number of corresponding mutations for a given mutator. // It traverses the AST of the given node and calls the method Check of the given mutator for every node and sums up the returned counts. After completion of the traversal the final counter is returned. func CountWalk(pkg *types.Package, info *types.Info, node ast.Node, m mutator.Mutator) int { w := &countWalk{ count: 0, mutator: m, pkg: pkg, info: info, } ast.Walk(w, node) return w.count } type countWalk struct { count int mutator mutator.Mutator pkg *types.Package info *types.Info } // Visit implements the Visit method of the ast.Visitor interface func (w *countWalk) Visit(node ast.Node) ast.Visitor { if node == nil { return w } w.count += len(w.mutator(w.pkg, w.info, node)) return w } // MutateWalk mutates the given node with the given mutator returning a channel to control the mutation steps. // It traverses the AST of the given node and calls the method Check of the given mutator to verify that a node can be mutated by the mutator. If a node can be mutated the method Mutate of the given mutator is executed with the node and the control channel. After completion of the traversal the control channel is closed. func MutateWalk(pkg *types.Package, info *types.Info, node ast.Node, m mutator.Mutator) chan bool { w := &mutateWalk{ changed: make(chan bool), mutator: m, pkg: pkg, info: info, } go func() { ast.Walk(w, node) close(w.changed) }() return w.changed } type mutateWalk struct { changed chan bool mutator mutator.Mutator pkg *types.Package info *types.Info } // Visit implements the Visit method of the ast.Visitor interface func (w *mutateWalk) Visit(node ast.Node) ast.Visitor { if node == nil { return w } for _, m := range w.mutator(w.pkg, w.info, node) { m.Change() w.changed <- true <-w.changed m.Reset() w.changed <- true <-w.changed } return w } // PrintWalk traverses the AST of the given node and prints every node to STDOUT. func PrintWalk(node ast.Node) { w := &printWalk{ level: 0, } ast.Walk(w, node) } type printWalk struct { level int } // Visit implements the Visit method of the ast.Visitor interface func (w *printWalk) Visit(node ast.Node) ast.Visitor { if node != nil { w.level++ fmt.Printf("%s(%p)%#v\n", strings.Repeat("\t", w.level), node, node) } else { w.level-- } return w }
walk.go
0.777384
0.44746
walk.go
starcoder
package junit import ( "strconv" "time" ) // findSuites performs a depth-first search through the XML document, and // attempts to ingest any "testsuite" tags that are encountered. func findSuites(nodes []xmlNode, suites chan Suite) { for _, node := range nodes { switch node.XMLName.Local { case "testsuite": suites <- ingestSuite(node) default: findSuites(node.Nodes, suites) } } } func ingestSuite(root xmlNode) Suite { suite := Suite{ Name: root.Attr("name"), Package: root.Attr("package"), } for _, node := range root.Nodes { switch node.XMLName.Local { case "testcase": testcase := ingestTestcase(node) suite.Tests = append(suite.Tests, testcase) case "properties": props := ingestProperties(node) suite.Properties = props case "system-out": suite.SystemOut = string(node.Content) case "system-err": suite.SystemErr = string(node.Content) } } suite.Aggregate() return suite } func ingestProperties(root xmlNode) map[string]string { props := make(map[string]string, len(root.Nodes)) for _, node := range root.Nodes { switch node.XMLName.Local { case "property": name := node.Attr("name") value := node.Attr("value") props[name] = value } } return props } func ingestTestcase(root xmlNode) Test { test := Test{ Name: root.Attr("name"), Classname: root.Attr("classname"), Duration: duration(root.Attr("time")), Status: StatusPassed, } for _, node := range root.Nodes { switch node.XMLName.Local { case "skipped": test.Status = StatusSkipped case "failure": test.Error = ingestError(node) test.Status = StatusFailed case "error": test.Error = ingestError(node) test.Status = StatusError } } return test } func ingestError(root xmlNode) Error { return Error{ Body: string(root.Content), Type: root.Attr("type"), Message: root.Attr("message"), } } func duration(t string) time.Duration { // Check if there was a valid decimal value if s, err := strconv.ParseFloat(t, 64); err == nil { return time.Duration(s*1000000) * time.Microsecond } // Check if there was a valid duration string if d, err := time.ParseDuration(t); err == nil { return d } return 0 }
vendor/github.com/joshdk/go-junit/ingest.go
0.681197
0.409752
ingest.go
starcoder
package helpers import ( "math" "math/cmplx" "math/rand" "strconv" "time" ) // Abs abs() func Abs(number float64) float64 { return math.Abs(number) } // Acos - Arc cosine func Acos(x complex128) complex128 { return cmplx.Acos(x) } // Acosh - Inverse hyperbolic cosine func Acosh(x complex128) complex128 { return cmplx.Acosh(x) } // Asin - Arc sine func Asin(x complex128) complex128 { return cmplx.Asin(x) } // Asinh - Inverse hyperbolic sine func Asinh(x complex128) complex128 { return cmplx.Asinh(x) } // Atan2 - Arc tangent of two variables func Atan2(y, x float64) float64 { return math.Atan2(y, x) } // Atan - Arc tangent func Atan(x complex128) complex128 { return cmplx.Atan(x) } // Atanh - Inverse hyperbolic tangent func Atanh(x complex128) complex128 { return cmplx.Atanh(x) } // BaseConvert - Convert a number between arbitrary bases func BaseConvert(num string, frombase, tobase int) (string, error) { i, err := strconv.ParseInt(num, frombase, 0) if err != nil { return "", err } return strconv.FormatInt(i, tobase), nil } // Ceil - Round fractions up func Ceil(x float64) float64 { return math.Ceil(x) } // Cos - Cosine func Cos(x float64) float64 { return math.Cos(x) } // Cosh - Hyperbolic cosine func Cosh(x float64) float64 { return math.Cosh(x) } // Decbin - Decimal to binary func Decbin(x int64) string { return strconv.FormatInt(x, 2) } // Dechex - Decimal to hexadecimal func Dechex(x int64) string { return strconv.FormatInt(x, 16) } // Decoct - Decimal to octal func Decoct(x int64) string { return strconv.FormatInt(x, 8) } // Exp - Calculates the exponent of e func Exp(x float64) float64 { return math.Exp(x) } // Expm1 - Returns exp(number) - 1 // computed in a way that is accurate even when the value of number is close to zero func Expm1(x float64) float64 { return math.Exp(x) - 1 } // Floor - Round fractions down func Floor(x float64) float64 { return math.Floor(x) } // IsFinite - Finds whether a value is a legal finite number func IsFinite(f float64, sign int) bool { return !math.IsInf(f, sign) } // IsInfinite - Finds whether a value is infinite func IsInfinite(f float64, sign int) bool { return math.IsInf(f, sign) } // IsNan - Finds whether a value is not a number func IsNan(f float64) bool { return math.IsNaN(f) } // Log - Natural logarithm func Log(x float64) float64 { return math.Log(x) } // Log10 - Base-10 logarithm func Log10(x float64) float64 { return math.Log10(x) } // Log1p - Returns log(1 + number) // computed in a way that is accurate even when the value of number is close to zero func Log1p(x float64) float64 { return math.Log1p(x) } // Max max() func Max(nums ...float64) float64 { if len(nums) < 2 { panic("nums: the nums length is less than 2") } max := nums[0] for i := 1; i < len(nums); i++ { max = math.Max(max, nums[i]) } return max } // Min min() func Min(nums ...float64) float64 { if len(nums) < 2 { panic("nums: the nums length is less than 2") } min := nums[0] for i := 1; i < len(nums); i++ { min = math.Min(min, nums[i]) } return min } // Pi - Get value of pi func Pi() float64 { return math.Pi } // Pow - Exponential expression func Pow(x, y float64) float64 { return math.Pow(x, y) } // Rand rand() // Range: [0, 2147483647] func Rand(min, max int) int { if min > max { panic("min: min cannot be greater than max") } // PHP: getrandmax() if int31 := 1<<31 - 1; max > int31 { panic("max: max can not be greater than " + strconv.Itoa(int31)) } if min == max { return min } r := rand.New(rand.NewSource(time.Now().UnixNano())) return r.Intn(max+1-min) + min } // Round - Rounds a float func Round(x float64) float64 { return math.Round(x) } // Sin - Sine func Sin(x float64) float64 { return math.Sin(x) } // Sinh - Hyperbolic sine func Sinh(x float64) float64 { return math.Sinh(x) } // Sqrt - Square root func Sqrt(x float64) float64 { return math.Sqrt(x) } // Tan - Tangent func Tan(x float64) float64 { return math.Tan(x) } // Tanh - Hyperbolic tangent func Tanh(x float64) float64 { return math.Tanh(x) }
math.go
0.862656
0.481149
math.go
starcoder
package query /* type FieldType int const ( Blob FieldType = iota Integer VarChar Char DateTime Date Time Float Bit )*/ // NodeType indicates the type of node, which saves us from having to use reflection to determine this type NodeType int const ( UnknownNodeType NodeType = iota TableNodeType ColumnNodeType ReferenceNodeType // forward reference from a foreign key ManyManyNodeType ReverseReferenceNodeType ValueNodeType OperationNodeType AliasNodeType SubqueryNodeType ) type goNamer interface { goName() string } type nodeContainer interface { containedNodes() (nodes []NodeI) } // NodeSorter is the interface a node must satisfy to be able to be used in an OrderBy statement. type NodeSorter interface { Ascending() NodeI Descending() NodeI sortDesc() bool } // Expander is the interface a node must satisfy to be able to be expanded upon, // making a many-* relationship that creates multiple versions of the original object. type Expander interface { Expand() isExpanded() bool isExpander() bool } type Aliaser interface { // SetAlias sets a unique name for the node as used in a database query. SetAlias(string) // GetAlias returns the alias that was used in a database query. GetAlias() string } // Nodes that can have an alias can mix this in type nodeAlias struct { alias string } // SetAlias sets an alias which is an alternate name to use for the node in the result of a query. // Aliases will generally be assigned during the query build process. You only need to assign a manual // alias if func (n *nodeAlias) SetAlias(a string) { n.alias = a } // GetAlias returns the alias name for the node. func (n *nodeAlias) GetAlias() string { return n.alias } type conditioner interface { setCondition(condition NodeI) getCondition() NodeI } // Nodes that can have a condition can mix this in type nodeCondition struct { condition NodeI } func (c *nodeCondition) setCondition(cond NodeI) { c.condition = cond } func (c *nodeCondition) getCondition() NodeI { return c.condition } // NodeI is the interface that all nodes must satisfy. A node is a representation of an object or a relationship // between objects in a database that we use to create a query. It lets us abstract the structure of a database // to be able to query any kind of database. Obviously, this doesn't work for all possible database structures, but // it generally works well enough to solve most of the situations that you will come across. type NodeI interface { // Equals returns true if the given node is equal to this node. Equals(NodeI) bool tableName() string log(level int) nodeType() NodeType databaseKey() string } /** Public Accessors The following functions are designed primarily to be used by the db package to help it unpack queries. They are not given an accessor at the beginning so that they do not show up as a function in editors that provide code hinting when trying to put together a node chain during the code creation process. Essentially they are trying to create exported functions for the db package without broadcasting them to the world. */ // NodeTableName is used internally by the framework to return the table associated with a node. func NodeTableName(n NodeI) string { return n.tableName() } func NodeDbKey(n NodeI) string { return n.databaseKey() } // NodeIsConditioner is used internally by the framework to determine if the node has a join condition. func NodeIsConditioner(n NodeI) bool { if tn, _ := n.(TableNodeI); tn != nil { if c, _ := tn.EmbeddedNode_().(conditioner); c != nil { return true } } return false } // NodeSetCondition is used internally by the framework to set a condition on a node. func NodeSetCondition(n NodeI, condition NodeI) { if condition != nil { if c, ok := n.(conditioner); !ok { panic("cannot set condition on this type of node") } else { c.setCondition(condition) } } } // NodeCondition is used internally by the framework to get a condition node. func NodeCondition(n NodeI) NodeI { if cn, ok := n.(conditioner); ok { return cn.getCondition() } else if tn, ok := n.(TableNodeI); ok { if cn, ok := tn.EmbeddedNode_().(conditioner); ok { return cn.getCondition() } } return nil } // ContainedNodes is used internally by the framework to return the contained nodes. func ContainedNodes(n NodeI) (nodes []NodeI) { if nc, ok := n.(nodeContainer); ok { return nc.containedNodes() } else { return nil } } // LogNode is used internally by the framework to debug node issues. func LogNode(n NodeI, level int) { n.log(level) } // NodeIsExpanded is used internally by the framework to detect if the node is an expanded many-many relationship. func NodeIsExpanded(n NodeI) bool { if tn, ok := n.(TableNodeI); ok { if en, ok := tn.EmbeddedNode_().(Expander); ok { return en.isExpanded() } } return false } // NodeIsExpander is used internally by the framework to detect if the node can be an expanded many-many relationship. func NodeIsExpander(n NodeI) bool { if tn, ok := n.(TableNodeI); ok { if tn.getParent() == nil {return false} if en, ok := tn.EmbeddedNode_().(Expander); ok { return en.isExpander() } } return false } // ExpandNode is used internally by the framework to expand a many-many relationship. func ExpandNode(n NodeI) { if tn, ok := n.(TableNodeI); ok { if en, ok := tn.EmbeddedNode_().(Expander); ok { en.Expand() } else { panic("Cannot expand a node of this type") } } else { panic("Cannot expand a node of this type") } } // NodeGoName is used internally by the framework to return the go name of the item the node refers to. func NodeGoName(n NodeI) string { if gn, ok := n.(goNamer); ok { return gn.goName() } else if tn, ok := n.(TableNodeI); ok { return tn.EmbeddedNode_().(goNamer).goName() } return "" } // NodeSorterSortDesc is used internally by the framework to determine if the NodeSorter is descending. func NodeSorterSortDesc(n NodeSorter) bool { return n.sortDesc() } // NodeGetType is an internal function used to get the node type without casting. This is particularly useful when // dealing with TableNodeI types, because they are embedded in different concrete types by the code // generator, so to get the specific node type involves extracting the embedded type and then doing a type select. func NodeGetType(n NodeI) NodeType { return n.nodeType() } // Convenience method to see if a node is a table type of node, or a leaf node func NodeIsTableNodeI(n NodeI) bool { t := NodeGetType(n) return t == ReferenceNodeType || t == ReverseReferenceNodeType || t == TableNodeType || t == ManyManyNodeType } // Convenience method to see if a node is a reference type node. This is essentially table type nodes // excluding an actual TableNode, since table nodes always start at the top level. func NodeIsReferenceI(n NodeI) bool { t := NodeGetType(n) return t == ReferenceNodeType || t == ReverseReferenceNodeType || t == ManyManyNodeType } // Return the primary key of a node, if it has a primary key. Otherwise return nil. func NodePrimaryKey(n NodeI) NodeI { if tn, ok := n.(TableNodeI); ok { return tn.PrimaryKeyNode() } return nil }
pkg/orm/query/node.go
0.741019
0.406803
node.go
starcoder
package main import ( "fmt" "image/color" "log" "math" "os" "github.com/campoy/goml/iplot/xyer" "github.com/campoy/goml/util" "github.com/campoy/mat" "github.com/campoy/tools/imgcat" "gonum.org/v1/plot" "gonum.org/v1/plot/plotter" "gonum.org/v1/plot/vg/draw" ) func main() { enc, err := imgcat.NewEncoder(os.Stdout, imgcat.Width(imgcat.Cells(100)), imgcat.Inline(true)) if err != nil { fmt.Fprintf(os.Stdout, "images will not be shown: %v\n", err) } data, err := util.ParseMatrix("ex2data1.txt") if err != nil { log.Fatalf("could not parse ex2data1.txt: %v", err) } m, cols := data.Rows(), data.Cols() n := cols - 1 X := mat.ConcatenateCols(mat.New(m, 1).AddScalar(1), data.SliceCols(0, n)) y := data.SliceCols(n, n+1) fmt.Println("Plotting data with + indicating (y=1) examples" + "and o indicating (y = 0) examples.") p := plotDataset(X, y) util.PrintPlot(enc, p, 400, 400) initialTheta := mat.New(n+1, 1) cost, grad := costFunction(initialTheta, X, y) fmt.Printf("Cost at initial theta (zeros): %f\n", cost) fmt.Printf("Expected cost (approx): 0.693\n") fmt.Printf("Gradient at initial theta (zeros): \n") for i := 0; i < grad.Cols(); i++ { fmt.Printf(" %.4f\n", grad.At(0, i)) } fmt.Printf("Expected gradients (approx):\n -0.1000\n -12.0092\n -11.2628\n") testTheta := mat.FromSlice(3, 1, []float64{-24, 0.2, 0.2}) cost, grad = costFunction(testTheta, X, y) fmt.Printf("\nCost at test theta: %f\n", cost) fmt.Printf("Expected cost (approx): 0.218\n") fmt.Printf("Gradient at test theta: \n") for i := 0; i < grad.Cols(); i++ { fmt.Printf(" %.4f\n", grad.At(0, i)) } fmt.Printf("Expected gradients (approx):\n 0.043\n 2.566\n 2.647\n") theta := initialTheta for i := 0; true; i++ { theta = optimize(func(theta mat.Matrix) (float64, mat.Matrix) { return costFunction(theta, X, y) }, theta, 250000) if i == 0 && i%100 != 0 { continue } acc := accuracy(X, theta, y) if acc >= 0.90 { break } fmt.Printf("Train accurracy: %f\n", acc) p := plotDataset(X, y) p.Add(line(theta)) p.X.Min, p.X.Max = 0, 100 p.Y.Min, p.Y.Max = 0, 100 util.PrintPlot(enc, p, 400, 400) } cost, _ = costFunction(theta, X, y) fmt.Printf("Cost at theta found by optimization: %f\n", cost) fmt.Printf("theta: \n") fmt.Printf(" %v \n", theta) p.Add(line(theta)) p.X.Min, p.X.Max = 0, 100 p.Y.Min, p.Y.Max = 0, 100 util.PrintPlot(enc, p, 400, 400) // For a student with scores 45 and 85, we predict an admission probability of 0.776289 prob := sigmoid(mat.Product(mat.FromSlice(1, 3, []float64{1, 45, 85}), theta).At(0, 0)) fmt.Printf("For a student with scores 45 and 85, we predict an admission probability of %f\n", prob) fmt.Println("Expected value: 0.775 +/- 0.002") fmt.Printf("Train accurracy: %f\n", accuracy(X, theta, y)) } func costFunction(theta, X, y mat.Matrix) (float64, mat.Matrix) { h := mat.Map(sigmoid, mat.Product(X, theta)) m := float64(X.Rows()) ones := mat.New(X.Rows(), 1).AddScalar(1) j := -1 / m * mat.Sum(mat.Plus( mat.Dot(y, mat.Map(math.Log, h)), mat.Dot(mat.Minus(ones, y), mat.Map(math.Log, mat.Minus(ones, h))), )) grad := mat.Product(mat.Minus(h, y).T(), X).Scale(1 / m).T() return j, grad } func sigmoid(z float64) float64 { return 1 / (1 + math.Exp(-z)) } func optimize(cost func(theta mat.Matrix) (float64, mat.Matrix), initialTheta mat.Matrix, iters int) mat.Matrix { theta := initialTheta alpha := 0.0001 for i := 0; i < iters; i++ { _, grad := cost(theta) theta = mat.Minus(theta, grad.Scale(alpha)) } return theta } func accuracy(X, theta, y mat.Matrix) float64 { m := X.Rows() preds := mat.Map(sigmoid, mat.Product(X, theta)) correct := 0 for i := 0; i < m; i++ { pred := preds.At(i, 0) switch y.At(i, 0) { case 0: if pred <= 0.5 { correct++ } case 1: if pred > 0.5 { correct++ } } } return float64(correct) / float64(m) } func plotDataset(X, y mat.Matrix) *plot.Plot { p, _ := plot.New() addScatter := func(val float64, shape draw.GlyphDrawer, color color.Color) *plotter.Scatter { values := X.FilterRows(func(i int) bool { return y.At(i, 0) == val }) s, _ := plotter.NewScatter(xyer.FromMatrixCols(values, 1, 2)) s.GlyphStyle = draw.GlyphStyle{Shape: shape, Color: color, Radius: 2} p.Add(s) return s } pos := addScatter(1, draw.CrossGlyph{}, color.Black) neg := addScatter(0, draw.CircleGlyph{}, color.RGBA{255, 255, 0, 255}) max := func(a, b float64) float64 { if a > b { return a } return b } min := func(a, b float64) float64 { if a < b { return a } return b } p.X.Label.Text = "Exam 1 score" p.Y.Label.Text = "Exam 2 score" p.Legend.Add("Admitted", pos) p.Legend.Add("Not admitted", neg) p.Legend.Top = true ex1 := X.SliceCols(0, 0) ex2 := X.SliceCols(1, 1) p.X.Min, p.X.Max = ex1.Reduce(100, min), ex1.Reduce(0, max) p.Y.Min, p.Y.Max = ex2.Reduce(100, min), ex2.Reduce(0, max) return p } func line(theta mat.Matrix) *plotter.Line { equation := func(x float64) float64 { return -(theta.At(1, 0)*x + theta.At(0, 0)) / theta.At(2, 0) } line, _, _ := plotter.NewLinePoints(xyer.FromSliceOfSlices([][]float64{ {0, equation(0)}, {100, equation(100)}, })) line.Color = color.RGBA{255, 0, 0, 255} return line }
logreg/main.go
0.586286
0.450541
main.go
starcoder
package nprand import "fmt" const ( stateLen int = 624 maxUint32 uint32 = 0xffffffff // Magic Mersenne Twister constants mtN int = 624 mtM int = 397 matrixA uint32 = 0x9908b0df upperMask uint32 = 0x80000000 lowerMask uint32 = 0x7fffffff ) // State is the state of the random number generator. type State struct { Key [stateLen]uint32 `json:"key"` Pos int `json:"pos"` } // New creates a new seeded RNG state. func New(seed uint32) *State { state := State{} state.Seed(seed) return &state } // Seed initializes the RNG state. func (state *State) Seed(seed uint32) { for pos := 0; pos < stateLen; pos++ { state.Key[pos] = seed seed = (uint32(1812433253)*(seed^(seed>>uint32(30))) + uint32(pos) + 1) } state.Pos = stateLen } // Bits32 generates 32 bits of randomness. func (state *State) Bits32() uint32 { var y uint32 if state.Pos == stateLen { i := 0 for ; i < mtN-mtM; i++ { y = (state.Key[i] & upperMask) | (state.Key[i+1] & lowerMask) state.Key[i] = state.Key[i+mtM] ^ (y >> 1) ^ (-(y & 1) & matrixA) } for ; i < mtN-1; i++ { y = (state.Key[i] & upperMask) | (state.Key[i+1] & lowerMask) state.Key[i] = state.Key[i+(mtM-mtN)] ^ (y >> 1) ^ (-(y & 1) & matrixA) } y = (state.Key[mtN-1] & upperMask) | (state.Key[0] & lowerMask) state.Key[mtN-1] = state.Key[mtM-1] ^ (y >> 1) ^ (-(y & 1) & matrixA) state.Pos = 0 } y = state.Key[state.Pos] state.Pos++ // Tempering y ^= y >> 11 y ^= (y << 7) & uint32(0x9d2c5680) y ^= (y << 15) & uint32(0xefc60000) y ^= y >> 18 return y } // Bits64 generates 64 bits of randomness. func (state *State) Bits64() uint64 { upper := uint64(state.Bits32()) << 32 lower := uint64(state.Bits32()) return upper | lower } // Read implements the Reader interface, yielding a random stream of bytes. func (state *State) Read(p []byte) (int, error) { pos := 0 var val uint32 for n := 0; n < len(p); n++ { if pos == 0 { val = state.Bits32() pos = 4 } p[n] = byte(val) val >>= 8 pos-- } return len(p), nil } // bitsLimit is an internal utility function to generate bits of randomness in [0, limit]. func (state *State) bitsLimit(limit uint64) uint64 { if limit == 0 { return 0 } // The plan is to generate some random bits, zero out bits above the limit using a mask, and // repeat until we get at or below the limit. // Compute the smallest bit mask >= limit. mask := limit mask |= mask >> 1 mask |= mask >> 2 mask |= mask >> 4 mask |= mask >> 8 mask |= mask >> 16 mask |= mask >> 32 // If we only need 32 bits or less, only generate 32 bits or randomness. if limit <= uint64(maxUint32) { for { if val := uint64(state.Bits32()) & mask; val <= limit { return val } } } // Otherwise generate 64 bits. for { if val := state.Bits64() & mask; val <= limit { return val } } } // Int64 generates a random Int64 in [low, high). It panics if high <= low. func (state *State) Int64(low, high int64) int64 { if high <= low { panic(fmt.Sprintf("nprand Int64: high %v <= low %v", high, low)) } return low + int64(state.bitsLimit(uint64(high)-uint64(low)-1)) } // Int64n generates a random Int64 in [0, n). It panics if n <= 0. func (state *State) Int64n(n int64) int64 { if n < 0 { panic(fmt.Sprintf("nprand Int64n: n %v < 0", n)) } return int64(state.bitsLimit(uint64(n) - 1)) } // Intn generates a random Int in [0, n). It panics if n <= 0. func (state *State) Intn(n int) int { if n < 0 { panic(fmt.Sprintf("nprand Intn: n %v < 0", n)) } return int(state.bitsLimit(uint64(n) - 1)) } // UnitInterval generates a random float64 in [0,1). func (state *State) UnitInterval() float64 { // shifts : 67108864 = 0x4000000, 9007199254740992 = 0x20000000000000 a := float64(state.Bits32() >> 5) b := float64(state.Bits32() >> 6) return (a*(1<<26) + b) / (1 << 53) } // Uniform generates a random float64 uniformly distributed in [low, high). It panics if high <= // low. func (state *State) Uniform(low, high float64) float64 { if high <= low { panic(fmt.Sprintf("nprand Uniform: high %v <= low %v", high, low)) } return low + (high-low)*state.UnitInterval() }
master/pkg/nprand/nprand.go
0.663015
0.490175
nprand.go
starcoder
package profile import ( "net/url" "sort" "strings" ) type Label struct { Key string `json:"key"` Value string `json:"value"` } type Labels []Label func LabelsFromMap(m map[string]interface{}) Labels { if len(m) == 0 { return nil } labels := make(Labels, 0, len(m)) for k, rawVal := range m { if k == "" { continue } val, _ := rawVal.(string) labels = append(labels, Label{k, val}) } sort.Sort(labels) return labels } func (labels Labels) Equal(labels2 Labels) bool { if len(labels) != len(labels2) { return false } labelsSet := make(map[string][]Label, len(labels)) for _, label := range labels { labelsSet[label.Key] = append(labelsSet[label.Key], label) } for _, label := range labels2 { v, ok := labelsSet[label.Key] if !ok { return false } ok = false for _, label2 := range v { if label.Value == label2.Value { ok = true break } } if !ok { return false } } return true } func (labels Labels) Add(labels2 Labels) Labels { if labels == nil { return labels2 } else if labels2 == nil { return labels } labelsIdx := make(map[Label]struct{}, len(labels)) for _, label := range labels { labelsIdx[label] = struct{}{} } ret := make([]Label, len(labels), len(labels)+len(labels2)) copy(ret, labels) for _, label2 := range labels2 { _, ok := labelsIdx[label2] if !ok { ret = append(ret, label2) } } return ret } func (labels *Labels) FromString(s string) (err error) { if s == "" { return nil } var chunk string for s != "" { chunk, s = split2(s, ',') key, val := split2(chunk, '=') key, err = url.QueryUnescape(strings.TrimSpace(key)) if err != nil { return err } if key == "" { continue } val, err = url.QueryUnescape(strings.TrimSpace(val)) if err != nil { return err } *labels = append(*labels, Label{key, val}) } if len(*labels) != 0 { sort.Sort(labels) } return nil } func split2(s string, ch byte) (s1, s2 string) { for i := 0; i < len(s); i++ { if s[i] == ch { return s[:i], s[i+1:] } } return s, "" } func (labels Labels) String() string { var buf strings.Builder for i, label := range labels { if i != 0 { buf.WriteByte(',') } buf.WriteString(label.Key) buf.WriteByte('=') buf.WriteString(label.Value) } return buf.String() } func (labels Labels) Len() int { return len(labels) } func (labels Labels) Less(i, j int) bool { return labels[i].Key < labels[j].Key } func (labels Labels) Swap(i, j int) { labels[i], labels[j] = labels[j], labels[i] }
pkg/profile/labels.go
0.569972
0.445288
labels.go
starcoder
package leetcode // Coorditaion of grid type coord struct { X int Y int } // Context for the calculation type context struct { Width int Height int Grids [][]byte IsMerged [][]byte NumberOfIslands int } func newContext(grid [][]byte) *context { c := context{ Width: len(grid[0]), Height: len(grid), Grids: grid, NumberOfIslands: 0, } isMerged := make([][]byte, c.Height) for i := 0; i < c.Height; i++ { isMerged[i] = make([]byte, c.Width) } c.IsMerged = isMerged return &c } type coordQueue struct { coords []coord } func newCoordQueue() *coordQueue { return &coordQueue{ coords: []coord{}, } } func (q *coordQueue) push(coord coord) { q.coords = append(q.coords, coord) } func (q *coordQueue) pop() coord { c := q.coords[0] q.coords = q.coords[1:] return c } func (q *coordQueue) isEmpty() bool { return len(q.coords) == 0 } func isUnmergedLand(coord coord, c *context) bool { // If is out of range, regard as ocean if coord.X < 0 || coord.X >= c.Width || coord.Y < 0 || coord.Y >= c.Height { return false } // If is ocean, return false if c.Grids[coord.Y][coord.X] == '0' { return false } // If is merged, return false if c.IsMerged[coord.Y][coord.X] == 1 { return false } return true } func mergeLand(coord coord, c *context, q *coordQueue) { // Mark as merged c.IsMerged[coord.Y][coord.X] = 1 // Push into queue q.push(coord) } func isNewIsland(coord coord, c *context) bool { return isUnmergedLand(coord, c) } func maybeMerge(coord coord, c *context, q *coordQueue) { if isUnmergedLand(coord, c) { mergeLand(coord, c, q) } } func mergeAround(co coord, c *context, q *coordQueue) { maybeMerge(coord{co.X + 1, co.Y}, c, q) maybeMerge(coord{co.X - 1, co.Y}, c, q) maybeMerge(coord{co.X, co.Y + 1}, c, q) maybeMerge(coord{co.X, co.Y - 1}, c, q) } func mergeIsland(coord coord, c *context) { q := newCoordQueue() // Merge initial lands mergeLand(coord, c, q) // Expand island for !q.isEmpty() { cur := q.pop() mergeAround(cur, c, q) } } func countIslandByGrid(coord coord, c *context) { if isNewIsland(coord, c) { c.NumberOfIslands++ mergeIsland(coord, c) } } func numIslands(grid [][]byte) int { // Validate input if grid == nil || len(grid) == 0 || grid[0] == nil || len(grid[0]) == 0 { return 0 } // Setup context c := newContext(grid) // Iterate over all grids and count island for y := 0; y < c.Height; y++ { for x := 0; x < c.Width; x++ { countIslandByGrid(coord{x, y}, c) } } // Return result return c.NumberOfIslands }
0200-number-of-islands/0200_number_of_islands.go
0.776708
0.45181
0200_number_of_islands.go
starcoder
package datastructure import ( "math" "github.com/duke-git/lancet/v2/datastructure" "github.com/duke-git/lancet/v2/lancetconstraints" ) // BSTree is a binary search tree data structure in which each node has at most two children, // which are referred to as the left child and the right child. // In BSTree: leftNode < rootNode < rightNode // type T should implements Compare function in lancetconstraints.Comparator interface. type BSTree[T any] struct { root *datastructure.TreeNode[T] } // NewBSTree create a BSTree pointer func NewBSTree[T any](rootData T) *BSTree[T] { root := datastructure.NewTreeNode(rootData) return &BSTree[T]{root} } // InsertNode insert data into BSTree func (t *BSTree[T]) InsertNode(data T, comparator lancetconstraints.Comparator) { root := t.root newNode := datastructure.NewTreeNode(data) if root == nil { t.root = newNode } else { insertTreeNode(root, newNode, comparator) } } // DeletetNode delete data into BSTree func (t *BSTree[T]) DeletetNode(data T, comparator lancetconstraints.Comparator) { deleteTreeNode(t.root, data, comparator) } // NodeLevel get node level in BSTree func (t *BSTree[T]) NodeLevel(node *datastructure.TreeNode[T]) int { if node == nil { return 0 } left := float64(t.NodeLevel(node.Left)) right := float64(t.NodeLevel(node.Right)) return int(math.Max(left, right)) + 1 } // PreOrderTraverse traverse tree node in pre order func (t *BSTree[T]) PreOrderTraverse() []T { return preOrderTraverse(t.root) } // PostOrderTraverse traverse tree node in post order func (t *BSTree[T]) PostOrderTraverse() []T { return postOrderTraverse(t.root) } // InOrderTraverse traverse tree node in mid order func (t *BSTree[T]) InOrderTraverse() []T { return inOrderTraverse(t.root) } // LevelOrderTraverse traverse tree node in level order func (t *BSTree[T]) LevelOrderTraverse() []T { traversal := make([]T, 0) levelOrderTraverse(t.root, &traversal) return traversal } // Depth returns the calculated depth of a binary saerch tree func (t *BSTree[T]) Depth() int { return calculateDepth(t.root, 0) } // Print the bstree structure func (t *BSTree[T]) Print() { maxLevel := t.NodeLevel(t.root) nodes := []*datastructure.TreeNode[T]{t.root} printTreeNodes(nodes, 1, maxLevel) }
datastructure/tree/bstree.go
0.776538
0.636353
bstree.go
starcoder
package model import ( "github.com/aunum/log" g "gorgonia.org/gorgonia" ) // Loss is the loss of a model. type Loss interface { // Comput the loss. Compute(yHat, y *g.Node) (loss *g.Node, err error) // Clone the loss to another graph. CloneTo(graph *g.ExprGraph, opts ...CloneOpt) Loss // Inputs return any inputs the loss function utilizes. Inputs() Inputs } // Reducer is used to reduce tensors to scalar values. type Reducer func(n *g.Node, along ...int) (*g.Node, error) // MSE is standard mean squared error loss. var MSE = &MSELoss{} // MSELoss is mean squared error loss. type MSELoss struct{} // Compute the loss func (m *MSELoss) Compute(yHat, y *g.Node) (loss *g.Node, err error) { loss, err = g.Sub(yHat, y) if err != nil { return nil, err } loss, err = g.Square(loss) if err != nil { return nil, err } loss, err = g.Mean(loss) if err != nil { return nil, err } return } // CloneTo another graph. func (m *MSELoss) CloneTo(graph *g.ExprGraph, opts ...CloneOpt) Loss { return &MSELoss{} } // Inputs returns any inputs the loss function utilizes. func (m *MSELoss) Inputs() Inputs { return Inputs{} } // CrossEntropy loss. var CrossEntropy = &CrossEntropyLoss{} // CrossEntropyLoss is standard cross entropy loss. type CrossEntropyLoss struct{} // Compute the loss. func (c *CrossEntropyLoss) Compute(yHat, y *g.Node) (loss *g.Node, err error) { loss, err = g.Log(yHat) if err != nil { return nil, err } loss, err = g.HadamardProd(y, loss) if err != nil { return nil, err } loss, err = g.Neg(loss) if err != nil { return nil, err } loss, err = g.Mean(loss) if err != nil { return nil, err } return } // CloneTo another graph. func (c *CrossEntropyLoss) CloneTo(graph *g.ExprGraph, opts ...CloneOpt) Loss { return &CrossEntropyLoss{} } // Inputs returns any inputs the loss function utilizes. func (c *CrossEntropyLoss) Inputs() Inputs { return Inputs{} } // PseudoHuberLoss is a loss that is less sensetive to outliers. // Can be thought of as absolute error when large, and quadratic when small. // The larger the Delta param the steeper the loss. type PseudoHuberLoss struct { // Delta determines where the function switches behavior. Delta float32 } // PseudoHuber is the Huber loss function. var PseudoHuber = &PseudoHuberLoss{ Delta: 1.0, } // NewPseudoHuberLoss return a new huber loss. func NewPseudoHuberLoss(delta float32, reducer Reducer) *PseudoHuberLoss { return &PseudoHuberLoss{ Delta: delta, } } // Compute the loss. func (h *PseudoHuberLoss) Compute(yHat, y *g.Node) (loss *g.Node, err error) { loss, err = g.Sub(yHat, y) if err != nil { return nil, err } loss, err = g.Div(loss, g.NewScalar(yHat.Graph(), g.Float32, g.WithValue(float32(h.Delta)))) if err != nil { return nil, err } loss, err = g.Square(loss) if err != nil { return nil, err } loss, err = g.Add(g.NewScalar(yHat.Graph(), g.Float32, g.WithValue(float32(1.0))), loss) if err != nil { return nil, err } loss, err = g.Sqrt(loss) if err != nil { return nil, err } loss, err = g.Sub(loss, g.NewScalar(yHat.Graph(), g.Float32, g.WithValue(float32(1.0)))) if err != nil { return nil, err } deltaSquare, err := g.Square(g.NewScalar(yHat.Graph(), g.Float32, g.WithValue(float32(h.Delta)))) if err != nil { return nil, err } loss, err = g.Mul(deltaSquare, loss) if err != nil { return nil, err } /// arg! https://github.com/gorgonia/gorgonia/issues/373 loss, err = g.Sum(loss, 1) if err != nil { return nil, err } return } // CloneTo another graph. func (h *PseudoHuberLoss) CloneTo(graph *g.ExprGraph, opts ...CloneOpt) Loss { return &PseudoHuberLoss{Delta: h.Delta} } // Inputs returns any inputs the loss function utilizes. func (h *PseudoHuberLoss) Inputs() Inputs { return Inputs{} } // PseudoCrossEntropy loss. var PseudoCrossEntropy = &PseudoCrossEntropyLoss{} // PseudoCrossEntropyLoss is standard cross entropy loss. type PseudoCrossEntropyLoss struct{} // Compute the loss. func (c *PseudoCrossEntropyLoss) Compute(yHat, y *g.Node) (loss *g.Node, err error) { loss, err = g.HadamardProd(yHat, y) if err != nil { log.Fatal(err) } loss, err = g.Mean(loss) if err != nil { log.Fatal(err) } loss, err = g.Neg(loss) if err != nil { log.Fatal(err) } return } // CloneTo another graph. func (c *PseudoCrossEntropyLoss) CloneTo(graph *g.ExprGraph, opts ...CloneOpt) Loss { return &PseudoCrossEntropyLoss{} } // Inputs returns any inputs the loss function utilizes. func (c *PseudoCrossEntropyLoss) Inputs() Inputs { return Inputs{} }
vendor/github.com/aunum/gold/pkg/v1/model/loss.go
0.8339
0.426322
loss.go
starcoder
package observer // Интерфейс работы с измерениями. type measurementsHandler interface { MeasurementsChanged() string SetMeasurements(float64, float64, float64) string } // WeatherDater Интерфейс источника метеоданных, способного быть субъектом. type WeatherDater interface { measurementsHandler subject } // Источник метеоданных. type weatherData struct { changed bool observers map[observer]struct{} temperature float64 humidity float64 pressure float64 } // MeasurementsChanged Вызывается при каждом обновлении показаний датчиков. func (w *weatherData) MeasurementsChanged() string { return w.NotifyObservers(nil) } // SetMeasurements Задать измерения. func (w *weatherData) SetMeasurements(temperature, humidity, pressure float64) string { w.temperature = temperature w.humidity = humidity w.pressure = pressure return w.MeasurementsChanged() } // RegisterObserver Регистрация нового наблюдателя. func (w *weatherData) RegisterObserver(newObserver observer) { w.observers[newObserver] = struct{}{} } // RemoveObserver Удалить наблюдателя из списка. func (w *weatherData) RemoveObserver(removedObserver observer) { delete(w.observers, removedObserver) } // NotifyObservers Оповестить наблюдателей. func (w *weatherData) NotifyObservers(data *Measurements) string { var result string if w.HasChanged() { for currentObserver := range w.observers { result += currentObserver.Update(w, data) } w.ClearChanged() } return result } // SetChanged Зафиксировать изменения. func (w *weatherData) SetChanged() { w.changed = true } // HasChanged Проверить фиксацию изменений. func (w *weatherData) HasChanged() bool { return w.changed } // ClearChanged Снять фиксацию изменений. func (w *weatherData) ClearChanged() { w.changed = false } // GetTemperature Получить текущую температуру. func (w *weatherData) GetTemperature() float64 { return w.temperature } // GetHumidity Получить текущую влажность. func (w *weatherData) GetHumidity() float64 { return w.humidity } // GetPressure Получить текущее давление. func (w *weatherData) GetPressure() float64 { return w.pressure } // NewWeatherData Создать weatherData. func NewWeatherData() WeatherDater { wd := new(weatherData) wd.observers = make(map[observer]struct{}) return wd }
pkg/behavioral/observer/weatherData.go
0.572723
0.527134
weatherData.go
starcoder
package main import ( "fmt" "math/big" ) //C47_2a implements step 2a of Bleichenbacher's attack func C47_2a(c0, B, e, d, n *big.Int) *big.Int { lowerBdDenom := big.NewInt(0).Mul(B, big.NewInt(3)) lowerBd := big.NewRat(0, 1).SetFrac(n, lowerBdDenom) s1 := RatCeil(lowerBd) for { fmt.Printf("Testing s1 = %X\n", s1) ctext := big.NewInt(0).Exp(s1, e, n) ctext.Mul(c0, ctext) ctext.Mod(ctext, n) if C47PaddingOracle(ctext.Bytes(), d, n) { return s1 } s1.Add(s1, big.NewInt(1)) } } //C47_2b implements step 2b of Bleichenbacher's attack func C47_2b(c0, prevS, e, d, n *big.Int) *big.Int { si := big.NewInt(0).Add(prevS, big.NewInt(1)) for { ctext := big.NewInt(0).Exp(si, e, n) ctext.Mul(c0, ctext) ctext.Mod(ctext, n) if C47PaddingOracle(ctext.Bytes(), d, n) { return si } si.Add(si, big.NewInt(1)) } } //C47_2c implements step 2c of Bleichenbacher's attack func C47_2c(c0, prevS, B, e, d, n *big.Int, a, b *big.Rat) (*big.Int, *big.Int) { one := big.NewInt(1) prevSRat := big.NewRat(0, 1).SetInt(prevS) BRat := big.NewRat(0, 1).SetInt(B) numer1 := big.NewRat(0, 1).Mul(b, prevSRat) numer2 := big.NewRat(2, 1) numer2.Mul(numer2, BRat) numer := big.NewRat(0, 1).Sub(numer1, numer2) twoB := big.NewRat(0, 1).Mul(big.NewRat(2, 1), BRat) threeB := big.NewRat(0, 1).Mul(big.NewRat(3, 1), BRat) twoNInv := big.NewRat(0, 1).SetFrac(big.NewInt(2), n) ri := RatCeil(big.NewRat(0, 1).Mul(twoNInv, numer)) for { tmp0 := big.NewInt(0).Mul(ri, n) tmp0Rat := big.NewRat(0, 1).SetInt(tmp0) tmp0Rat.Add(twoB, tmp0Rat) sLowerBd := RatCeil(big.NewRat(0, 1).Quo(tmp0Rat, b)) tmp1 := big.NewInt(0).Mul(ri, n) tmp1Rat := big.NewRat(0, 1).SetInt(tmp1) tmp1Rat.Add(threeB, tmp1Rat) sUpperBd := RatCeil(big.NewRat(0, 1).Quo(tmp1Rat, a)) si := big.NewInt(0).Set(sLowerBd) for si.Cmp(sUpperBd) < 0 { ctext := big.NewInt(0).Exp(si, e, n) ctext.Mul(ctext, c0) ctext.Mod(ctext, n) if C47PaddingOracle(ctext.Bytes(), d, n) { return nil, si } si.Add(si, one) } ri.Add(ri, one) } } //C47GetStep3Interval implements a portion of step 3 of Bleichenbacher's attack func C47GetStep3Interval(a, b *big.Rat, B, r, n, si *big.Int) Interval { rn := big.NewInt(0).Mul(r, n) twoB := big.NewInt(0).Mul(B, big.NewInt(2)) threeBMinusOne := big.NewInt(0).Mul(B, big.NewInt(3)) threeBMinusOne.Sub(threeBMinusOne, big.NewInt(1)) lowerNumer := big.NewInt(0).Add(twoB, rn) upperNumer := big.NewInt(0).Add(threeBMinusOne, rn) lowerRat := big.NewRat(0, 1).SetFrac(lowerNumer, si) upperRat := big.NewRat(0, 1).SetFrac(upperNumer, si) lowerBd := RatMax(a, big.NewRat(0, 1).SetInt(RatCeil(lowerRat))) upperBd := RatMin(b, big.NewRat(0, 1).SetInt(RatFloor(upperRat))) return Interval{lowerBd, upperBd} } //C47_3 implements step 3 of Bleichenbacher's attack func C47_3(prevM []Interval, B, si, n *big.Int) []Interval { one := big.NewInt(1) siRat := big.NewRat(0, 1).SetInt(si) oneOverN := big.NewRat(0, 1).SetFrac(one, n) threeB := big.NewInt(0).Mul(big.NewInt(3), B) twoB := big.NewInt(0).Mul(big.NewInt(2), B) twoBRat := big.NewRat(0, 1).SetInt(twoB) threeBMinusOne := big.NewInt(0).Sub(threeB, one) threeBMinusOneRat := big.NewRat(0, 1).SetInt(threeBMinusOne) newM := make([]Interval, 0) for _, intvl := range prevM { a := intvl.Min b := intvl.Max lowerBd := big.NewRat(0, 1).Mul(a, siRat) lowerBd.Sub(lowerBd, threeBMinusOneRat) lowerBd.Mul(lowerBd, oneOverN) upperBd := big.NewRat(0, 1).Mul(b, siRat) upperBd.Sub(upperBd, twoBRat) upperBd.Mul(upperBd, oneOverN) lowerBdInt := RatCeil(lowerBd) upperBdInt := RatFloor(upperBd) fmt.Printf("Lower %X\nUpper %X\n", lowerBdInt, upperBdInt) r := lowerBdInt for r.Cmp(upperBdInt) <= 0 { newM = append(newM, C47GetStep3Interval(a, b, B, r, n, si)) r.Add(r, one) } } fmt.Printf("Pre-simplification %v\n", newM) return SimplifyIntervalUnion(newM) } //BleichenbacherAttack decrypts msg, given the intended recipient's //public RSA keypair [e,n]. d is passed only for passing on to the padding //oracle. The attack assumes the original plaintext was properly padded //per PKCS#1v1.5 func BleichenbacherAttack(msg []byte, e, d, n *big.Int) []byte { msgNum := big.NewInt(0).SetBytes(msg) zero := big.NewInt(0) one := big.NewInt(1) two := big.NewInt(2) //set B = 2^(8(k-2)) B := big.NewInt(int64(len(msg))) B = B.Sub(B, two) B = B.Mul(B, big.NewInt(8)) B = B.Exp(two, B, zero) //Set initial interval initMinInt := big.NewInt(0).Mul(two, B) initMaxInt := big.NewInt(0).Mul(big.NewInt(3), B) initMaxInt.Sub(initMaxInt, one) initMin := big.NewRat(0, 1).SetFrac(initMinInt, big.NewInt(1)) initMax := big.NewRat(0, 1).SetFrac(initMaxInt, big.NewInt(1)) initInterval := Interval{initMin, initMax} //Set up initial values initM := []Interval{initInterval} initS := big.NewInt(1) initC := big.NewInt(0).Exp(initS, e, n) initC.Mul(initC, msgNum) initC.Mod(initC, n) si := C47_2a(initC, B, e, d, n) fmt.Println("Init s computed") Mi := C47_3(initM, B, si, n) fmt.Println("Init M computed") newS := big.NewInt(0).Set(si) i := 2 for { fmt.Printf("Beginning iteration i=%v\n", i) fmt.Println(Mi) if len(Mi) == 1 && Mi[0].Length().Cmp(one) == 0 { return RatCeil(Mi[0].Max).Bytes() } si = newS if len(Mi) > 1 { newS = C47_2b(initC, si, e, d, n) } else { _, newS = C47_2c(initC, si, B, e, d, n, Mi[0].Min, Mi[0].Max) } Mi = C47_3(Mi, B, newS, n) fmt.Printf("Mi = %v\n", Mi) i++ } } //C47PaddingOracle decrypts m with the RSA private keypair [d, n] //and checks whether the plaintext is properly paddid according to //PKCS#1v1.5 func C47PaddingOracle(m []byte, d, n *big.Int) bool { pText := RSADecryptPad(m, d, n) return RSAPKCS1Validate(pText) }
bleichenbacher.go
0.522689
0.482185
bleichenbacher.go
starcoder
package render import ( "unsafe" "github.com/inkyblackness/hacked/ui/opengl" ) // TextureRenderer is a renderer within which something can be rendered onto a texture. // This texture can then be used to be displayed. type TextureRenderer struct { gl opengl.OpenGL framebuffer uint32 texture uint32 width int32 height int32 } // NewTextureRenderer returns a new instance. func NewTextureRenderer(gl opengl.OpenGL) *TextureRenderer { renderer := &TextureRenderer{ gl: gl, framebuffer: gl.GenFramebuffers(1)[0], texture: gl.GenTextures(1)[0], width: 200, height: 200, } gl.BindTexture(opengl.TEXTURE_2D, renderer.texture) gl.TexParameteri(opengl.TEXTURE_2D, opengl.TEXTURE_MAG_FILTER, opengl.NEAREST) gl.TexParameteri(opengl.TEXTURE_2D, opengl.TEXTURE_MIN_FILTER, opengl.NEAREST) offset := unsafe.Pointer(uintptr(0)) // nolint: govet gl.TexImage2D(opengl.TEXTURE_2D, 0, opengl.RGBA, renderer.width, renderer.height, 0, opengl.RGBA, opengl.UNSIGNED_BYTE, offset) // gl.GenerateMipmap(opengl.TEXTURE_2D) gl.BindTexture(opengl.TEXTURE_2D, 0) renderer.onFramebuffer(func() { gl.BindTexture(opengl.TEXTURE_2D, renderer.texture) gl.FramebufferTexture(opengl.FRAMEBUFFER, opengl.COLOR_ATTACHMENT0, renderer.texture, 0) gl.DrawBuffers([]uint32{opengl.COLOR_ATTACHMENT0}) gl.BindTexture(opengl.TEXTURE_2D, 0) // result := gl.CheckFramebufferStatus(opengl.FRAMEBUFFER) // fmt.Printf("status: 0x%04X\n", result) // result == FRAMEBUFFER_COMPLETE == 0x8CD5 }) return renderer } // Dispose cleans up resources. func (renderer *TextureRenderer) Dispose() { gl := renderer.gl gl.DeleteFramebuffers([]uint32{renderer.framebuffer}) gl.DeleteTextures([]uint32{renderer.texture}) } // Handle returns the texture handle. func (renderer *TextureRenderer) Handle() uint32 { return renderer.texture } // Size returns the dimensions of the texture, in pixels. func (renderer *TextureRenderer) Size() (width, height float32) { return float32(renderer.width), float32(renderer.height) } // Render calls the nested function. All drawing commands within this function will end up in the texture. func (renderer *TextureRenderer) Render(nested func()) { gl := renderer.gl renderer.onFramebuffer(func() { gl.Viewport(0, 0, renderer.width, renderer.height) gl.ClearColor(0.0, 0.0, 0.0, 0.0) gl.Clear(opengl.COLOR_BUFFER_BIT | opengl.DEPTH_BUFFER_BIT) nested() }) } func (renderer *TextureRenderer) onFramebuffer(nested func()) { gl := renderer.gl gl.BindFramebuffer(opengl.FRAMEBUFFER, renderer.framebuffer) nested() gl.BindFramebuffer(opengl.FRAMEBUFFER, 0) }
editor/render/TextureRenderer.go
0.760828
0.415788
TextureRenderer.go
starcoder
package parser import ( "go/ast" "reflect" ) //Function holds the signature of a function with name, Parameters and Return values type Function struct { Name string Parameters []*Field ReturnValues []string PackageName string FullNameReturnValues []string } //SignturesAreEqual Returns true if the two functions have the same signature (parameter names are not checked) func (f *Function) SignturesAreEqual(function *Function) bool { result := true result = result && (function.Name == f.Name) result = result && reflect.DeepEqual(f.FullNameReturnValues, function.FullNameReturnValues) result = result && (len(f.Parameters) == len(function.Parameters)) if result { for i, p := range f.Parameters { if p.FullType != function.Parameters[i].FullType { return false } } } return result } // generate and return a function object from the given Functype. The names must be passed to this // function since the FuncType does not have this information func getFunction(f *ast.FuncType, name string, aliases map[string]string, packageName string) *Function { function := &Function{ Name: name, Parameters: make([]*Field, 0), ReturnValues: make([]string, 0), FullNameReturnValues: make([]string, 0), PackageName: packageName, } params := f.Params if params != nil { for _, pa := range params.List { theType, _ := getFieldType(pa.Type, aliases, packageName) if pa.Names != nil { if pa.Names != nil { for _, fieldName := range pa.Names { function.Parameters = append(function.Parameters, &Field{ Name: fieldName.Name, Type: replacePackageConstant(theType, ""), FullType: replacePackageConstant(theType, packageName), }) } } } else { function.Parameters = append(function.Parameters, &Field{ Name: "", Type: replacePackageConstant(theType, ""), FullType: replacePackageConstant(theType, packageName), }) } } } results := f.Results if results != nil { for _, pa := range results.List { theType, _ := getFieldType(pa.Type, aliases, packageName) function.ReturnValues = append(function.ReturnValues, replacePackageConstant(theType, packageName)) function.FullNameReturnValues = append(function.FullNameReturnValues, replacePackageConstant(theType, packageName)) } } return function }
parser/function.go
0.535098
0.418935
function.go
starcoder
package conv // SliceFloat is alias of Floats. func SliceFloat(i interface{}) []float64 { return Floats(i) } // SliceFloat32 is alias of Float32s. func SliceFloat32(i interface{}) []float32 { return Float32s(i) } // SliceFloat64 is alias of Float64s. func SliceFloat64(i interface{}) []float64 { return Floats(i) } // Floats converts <i> to []float64. func Floats(i interface{}) []float64 { return Float64s(i) } // Float32s converts <i> to []float32. func Float32s(i interface{}) []float32 { if i == nil { return nil } if r, ok := i.([]float32); ok { return r } else { var array []float32 switch value := i.(type) { case []string: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []int: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []int8: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []int16: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []int32: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []int64: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []uint: for _, v := range value { array = append(array, Float32(v)) } case []uint8: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []uint16: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []uint32: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []uint64: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []bool: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []float64: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } case []interface{}: array = make([]float32, len(value)) for k, v := range value { array[k] = Float32(v) } default: return []float32{Float32(i)} } return array } } // Float64s converts <i> to []float64. func Float64s(i interface{}) []float64 { if i == nil { return nil } if r, ok := i.([]float64); ok { return r } else { var array []float64 switch value := i.(type) { case []string: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []int: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []int8: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []int16: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []int32: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []int64: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []uint: for _, v := range value { array = append(array, Float64(v)) } case []uint8: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []uint16: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []uint32: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []uint64: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []bool: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []float32: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } case []interface{}: array = make([]float64, len(value)) for k, v := range value { array[k] = Float64(v) } default: return []float64{Float64(i)} } return array } }
conv_slice_float.go
0.513668
0.441553
conv_slice_float.go
starcoder
package hexgrid import ( "fmt" ) type Coord struct { X int `json:"x"` Y int `json:"y"` } func (c Coord) String() string { return fmt.Sprintf("C(%d, %d)", c.X, c.Y) } type ByXY []Coord func (a ByXY) Len() int { return len(a) } func (a ByXY) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByXY) Less(i, j int) bool { return a[i].Y < a[j].Y || (a[i].Y == a[j].Y && a[i].X < a[j].X) } type HexGrid[T any] struct { xdim int ydim int hexes []T } func (g HexGrid[T]) Dims() (int, int) { return g.xdim, g.ydim } func Generate[T any](xdim int, ydim int, initFn func(coord Coord) T) HexGrid[T] { hexes := make([]T, 0, xdim*ydim) for y := 0; y < ydim; y++ { for x := 0; x < xdim; x++ { val := initFn(Coord{x, y}) hexes = append(hexes, val) } } return HexGrid[T]{ xdim, ydim, hexes, } } func (g HexGrid[T]) MapHexes(hexFn func(coord Coord, hexData *T)) { for y := 0; y < g.ydim; y++ { for x := 0; x < g.xdim; x++ { hexFn(Coord{x, y}, &g.hexes[g.xyToIndex(x, y)]) } } } func (g HexGrid[T]) xyToIndex(x int, y int) int { return y*g.xdim + x } func (g HexGrid[T]) coordToIndex(coord Coord) int { return g.xyToIndex(coord.X, coord.Y) } func (g HexGrid[T]) indexToCoord(i int) Coord { return Coord{i % g.xdim, i / g.xdim} } func (g HexGrid[T]) isInBounds(coord Coord) bool { if coord.X < 0 || coord.X >= g.xdim { return false } if coord.Y < 0 || coord.Y >= g.ydim { return false } return true } func (g HexGrid[T]) GetAt(coord Coord) *T { return g.GetAtXY(coord.X, coord.Y) } func (g HexGrid[T]) GetAtXY(x int, y int) *T { if x < 0 || x >= g.xdim || y < 0 || y >= g.ydim { return nil } index := g.xyToIndex(x, y) return &g.hexes[index] } func (g HexGrid[T]) GetNeighbors(coord Coord) []Coord { return g.GetNeighborsXY(coord.X, coord.Y) } type offset struct { x int y int } func (g HexGrid[T]) GetNeighborsXY(x int, y int) []Coord { var offsets []offset if y%2 == 1 { offsets = []offset{ {+0, -1}, {+1, -1}, {+1, +0}, {+1, +1}, {+0, +1}, {-1, +0}, } } else { offsets = []offset{ {-1, -1}, {+0, -1}, {+1, +0}, {+0, +1}, {-1, +1}, {-1, +0}, } } result := make([]Coord, 0, len(offsets)) for _, offset := range offsets { coord := Coord{x + offset.x, y + offset.y} if g.isInBounds(coord) { result = append(result, coord) } } return result }
hexgrid.go
0.771241
0.46041
hexgrid.go
starcoder
package i6502 import ( "fmt" ) /* The AddressBus contains a list of all attached memory components, like Ram, Rom and IO. It takes care of mapping the global 16-bit address space of the Cpu to the relative memory addressing of each component. */ type AddressBus struct { addressables []*addressable // Different components } type addressable struct { memory Memory // Actual memory start uint16 // First address in address space end uint16 // Last address in address space } func (a *addressable) String() string { return fmt.Sprintf("\t0x%04X-%04X\n", a.start, a.end) } // Creates a new, empty 16-bit AddressBus func NewAddressBus() (*AddressBus, error) { return &AddressBus{addressables: make([]*addressable, 0)}, nil } // Returns a string with details about the AddressBus and attached memory func (a *AddressBus) String() string { output := "Address Bus:\n" for _, addressable := range a.addressables { output += addressable.String() } return output } /* Attach the given Memory at the specified memory offset. To attach 16kB ROM at 0xC000-FFFF, you simple attach the Rom at address 0xC000, the Size of the Memory determines the end-address. rom, _ := i6502.NewRom(0x4000) bus.Attach(rom, 0xC000) */ func (a *AddressBus) Attach(memory Memory, offset uint16) { start := offset end := offset + memory.Size() - 1 addressable := addressable{memory: memory, start: start, end: end} a.addressables = append(a.addressables, &addressable) } /* Read an 8-bit value from Memory attached at the 16-bit address. This will panic if you try to read from an address that has no Memory attached. */ func (a *AddressBus) ReadByte(address uint16) byte { addressable, err := a.addressableForAddress(address) if err != nil { panic(err) } return addressable.memory.ReadByte(address - addressable.start) } /* Convenience method to quickly read a 16-bit value from address and address + 1. Note that we first read the LOW byte from address and then the HIGH byte from address + 1. */ func (a *AddressBus) Read16(address uint16) uint16 { lo := uint16(a.ReadByte(address)) hi := uint16(a.ReadByte(address + 1)) return (hi << 8) | lo } /* Write an 8-bit value to the Memory at the 16-bit address. This will panic if you try to write to an address that has no Memory attached or Memory that is read-only, like Rom. */ func (a *AddressBus) WriteByte(address uint16, data byte) { addressable, err := a.addressableForAddress(address) if err != nil { panic(err) } addressable.memory.WriteByte(address-addressable.start, data) } /* Convenience method to quickly write a 16-bit value to address and address + 1. Note that the LOW byte will be stored in address and the high byte in address + 1. */ func (a *AddressBus) Write16(address uint16, data uint16) { a.WriteByte(address, byte(data)) a.WriteByte(address+1, byte(data>>8)) } // Returns the addressable for the specified address, or an error if no addressable exists. func (a *AddressBus) addressableForAddress(address uint16) (*addressable, error) { for _, addressable := range a.addressables { if addressable.start <= address && addressable.end >= address { return addressable, nil } } return nil, fmt.Errorf("No addressable memory found at 0x%04X", address) }
address_bus.go
0.805058
0.44354
address_bus.go
starcoder
package goja import ( "math" "github.com/powerpuffpenguin/goja/ftoa" ) func (r *Runtime) numberproto_valueOf(call FunctionCall) Value { this := call.This if !isNumber(this) { r.typeErrorResult(true, "Value is not a number") } switch t := this.(type) { case valueInt, valueFloat: return this case *Object: if v, ok := t.self.(*primitiveValueObject); ok { return v.pValue } } panic(r.NewTypeError("Number.prototype.valueOf is not generic")) } func isNumber(v Value) bool { switch t := v.(type) { case valueFloat, valueInt: return true case *Object: switch t := t.self.(type) { case *primitiveValueObject: return isNumber(t.pValue) } } return false } func (r *Runtime) numberproto_toString(call FunctionCall) Value { if !isNumber(call.This) { r.typeErrorResult(true, "Value is not a number") } var radix int if arg := call.Argument(0); arg != _undefined { radix = int(arg.ToInteger()) } else { radix = 10 } if radix < 2 || radix > 36 { panic(r.newError(r.global.RangeError, "toString() radix argument must be between 2 and 36")) } num := call.This.ToFloat() if math.IsNaN(num) { return stringNaN } if math.IsInf(num, 1) { return stringInfinity } if math.IsInf(num, -1) { return stringNegInfinity } if radix == 10 { return asciiString(fToStr(num, ftoa.ModeStandard, 0)) } return asciiString(ftoa.FToBaseStr(num, radix)) } func (r *Runtime) numberproto_toFixed(call FunctionCall) Value { num := r.toNumber(call.This).ToFloat() prec := call.Argument(0).ToInteger() if prec < 0 || prec > 100 { panic(r.newError(r.global.RangeError, "toFixed() precision must be between 0 and 100")) } if math.IsNaN(num) { return stringNaN } return asciiString(fToStr(num, ftoa.ModeFixed, int(prec))) } func (r *Runtime) numberproto_toExponential(call FunctionCall) Value { num := r.toNumber(call.This).ToFloat() precVal := call.Argument(0) var prec int64 if precVal == _undefined { return asciiString(fToStr(num, ftoa.ModeStandardExponential, 0)) } else { prec = precVal.ToInteger() } if math.IsNaN(num) { return stringNaN } if math.IsInf(num, 1) { return stringInfinity } if math.IsInf(num, -1) { return stringNegInfinity } if prec < 0 || prec > 100 { panic(r.newError(r.global.RangeError, "toExponential() precision must be between 0 and 100")) } return asciiString(fToStr(num, ftoa.ModeExponential, int(prec+1))) } func (r *Runtime) numberproto_toPrecision(call FunctionCall) Value { numVal := r.toNumber(call.This) precVal := call.Argument(0) if precVal == _undefined { return numVal.toString() } num := numVal.ToFloat() prec := precVal.ToInteger() if math.IsNaN(num) { return stringNaN } if math.IsInf(num, 1) { return stringInfinity } if math.IsInf(num, -1) { return stringNegInfinity } if prec < 1 || prec > 100 { panic(r.newError(r.global.RangeError, "toPrecision() precision must be between 1 and 100")) } return asciiString(fToStr(num, ftoa.ModePrecision, int(prec))) } func (r *Runtime) number_isFinite(call FunctionCall) Value { switch arg := call.Argument(0).(type) { case valueInt: return valueTrue case valueFloat: f := float64(arg) return r.toBoolean(!math.IsInf(f, 0) && !math.IsNaN(f)) default: return valueFalse } } func (r *Runtime) number_isInteger(call FunctionCall) Value { switch arg := call.Argument(0).(type) { case valueInt: return valueTrue case valueFloat: f := float64(arg) return r.toBoolean(!math.IsNaN(f) && !math.IsInf(f, 0) && math.Floor(f) == f) default: return valueFalse } } func (r *Runtime) number_isNaN(call FunctionCall) Value { if f, ok := call.Argument(0).(valueFloat); ok && math.IsNaN(float64(f)) { return valueTrue } return valueFalse } func (r *Runtime) number_isSafeInteger(call FunctionCall) Value { arg := call.Argument(0) if i, ok := arg.(valueInt); ok && i >= -(maxInt-1) && i <= maxInt-1 { return valueTrue } if arg == _negativeZero { return valueTrue } return valueFalse } func (r *Runtime) initNumber() { r.global.NumberPrototype = r.newPrimitiveObject(valueInt(0), r.global.ObjectPrototype, classNumber) o := r.global.NumberPrototype.self o._putProp("toExponential", r.newNativeFunc(r.numberproto_toExponential, nil, "toExponential", nil, 1), true, false, true) o._putProp("toFixed", r.newNativeFunc(r.numberproto_toFixed, nil, "toFixed", nil, 1), true, false, true) o._putProp("toLocaleString", r.newNativeFunc(r.numberproto_toString, nil, "toLocaleString", nil, 0), true, false, true) o._putProp("toPrecision", r.newNativeFunc(r.numberproto_toPrecision, nil, "toPrecision", nil, 1), true, false, true) o._putProp("toString", r.newNativeFunc(r.numberproto_toString, nil, "toString", nil, 1), true, false, true) o._putProp("valueOf", r.newNativeFunc(r.numberproto_valueOf, nil, "valueOf", nil, 0), true, false, true) r.global.Number = r.newNativeFunc(r.builtin_Number, r.builtin_newNumber, "Number", r.global.NumberPrototype, 1) o = r.global.Number.self o._putProp("EPSILON", _epsilon, false, false, false) o._putProp("isFinite", r.newNativeFunc(r.number_isFinite, nil, "isFinite", nil, 1), true, false, true) o._putProp("isInteger", r.newNativeFunc(r.number_isInteger, nil, "isInteger", nil, 1), true, false, true) o._putProp("isNaN", r.newNativeFunc(r.number_isNaN, nil, "isNaN", nil, 1), true, false, true) o._putProp("isSafeInteger", r.newNativeFunc(r.number_isSafeInteger, nil, "isSafeInteger", nil, 1), true, false, true) o._putProp("MAX_SAFE_INTEGER", valueInt(maxInt-1), false, false, false) o._putProp("MIN_SAFE_INTEGER", valueInt(-(maxInt - 1)), false, false, false) o._putProp("MIN_VALUE", valueFloat(math.SmallestNonzeroFloat64), false, false, false) o._putProp("MAX_VALUE", valueFloat(math.MaxFloat64), false, false, false) o._putProp("NaN", _NaN, false, false, false) o._putProp("NEGATIVE_INFINITY", _negativeInf, false, false, false) o._putProp("parseFloat", r.Get("parseFloat"), true, false, true) o._putProp("parseInt", r.Get("parseInt"), true, false, true) o._putProp("POSITIVE_INFINITY", _positiveInf, false, false, false) r.addToGlobal("Number", r.global.Number) }
builtin_number.go
0.670177
0.421135
builtin_number.go
starcoder
package filtermodule import ( "fmt" "regexp" "strconv" "strings" "time" "../spammodule" bot "../sweetiebot" "github.com/erikmcclure/discordgo" ) // FilterModule implements word filters that allow you to look for spoilers or profanity uses regex matching. type FilterModule struct { spam *spammodule.SpamModule filters map[string]*regexp.Regexp lastmsg int64 // Universal saturation limit on all filter responses } // New instance of FilterModule func New(info *bot.GuildInfo, s *spammodule.SpamModule) *FilterModule { w := &FilterModule{ filters: make(map[string]*regexp.Regexp), lastmsg: 0, spam: s, } for k := range info.Config.Filter.Filters { w.UpdateRegex(k, info) } return w } // Name of the module func (w *FilterModule) Name() string { return "Filter" } // Commands in the module func (w *FilterModule) Commands() []bot.Command { return []bot.Command{ &setFilterCommand{}, &addFilterCommand{w}, &removeFilterCommand{w}, &deleteFilterCommand{w}, &searchFilterCommand{}, } } // Description of the module func (w *FilterModule) Description(info *bot.GuildInfo) string { return "Implements customizable filters that search for forbiddan words or phrases and removes them with a customizable response and excludable channels. Optionally also adds pressure to the user for triggering a filter, and if the response is set to !, doesn't remove the message at all, only adding pressure.\n\nIf you just want a basic case-insensitive word filter that respects spaces, use `!setconfig filter.templates` with your filter name and this template: `(?i)(^| )%%($| )`. \n\nExample usage: \n```!setfilter badwords \"This is a christian server, no swearing allowed.\"\n!setconfig filter.templates badwords (?i)(^| )%%($| )\n!addfilter badwords hell\n!addfilter badwords \"jesus christ\"```" } func (w *FilterModule) matchFilter(info *bot.GuildInfo, m *discordgo.Message) bool { author := bot.DiscordUser(m.Author.ID) if info.UserIsMod(author) || info.UserIsAdmin(author) || m.Author.Bot { return false } timestamp := bot.GetTimestamp(m) for k, v := range w.filters { if v == nil { // skip empty regex continue } if c, ok := info.Config.Filter.Channels[k]; ok { if _, ok := c[bot.DiscordChannel(m.ChannelID)]; ok { continue // This channel is excluded from this filter so skip it } } if v.MatchString(m.Content) { ch, _ := info.Bot.DG.State.Channel(m.ChannelID) if len(info.Config.Filter.Pressure) > 0 && w.spam != nil { if p, ok := info.Config.Filter.Pressure[k]; ok && p > 0.0 { w.spam.AddPressure(info, m, w.spam.TrackUser(author, bot.GetTimestamp(m)), p, "triggering the "+k+" filter") } } if s, _ := info.Config.Filter.Responses[k]; len(s) != 1 || s[0] != '!' { time.Sleep(bot.DelayTime) info.ChannelMessageDelete(ch, m.ID) if len(s) > 0 && bot.RateLimit(&w.lastmsg, 5, timestamp.Unix()) { info.SendMessage(bot.DiscordChannel(m.ChannelID), s) } } return true } } return false } // OnMessageCreate discord hook func (w *FilterModule) OnMessageCreate(info *bot.GuildInfo, m *discordgo.Message) { w.matchFilter(info, m) } // OnMessageUpdate discord hook func (w *FilterModule) OnMessageUpdate(info *bot.GuildInfo, m *discordgo.Message) { w.matchFilter(info, m) } // OnCommand discord hook func (w *FilterModule) OnCommand(info *bot.GuildInfo, m *discordgo.Message) bool { return w.matchFilter(info, m) } var templateregex = regexp.MustCompile("%%") // UpdateRegex updates all filter regexes func (w *FilterModule) UpdateRegex(filter string, info *bot.GuildInfo) (err error) { combine := "" w.filters[filter] = nil if len(info.Config.Filter.Filters[filter]) > 0 { combine = "(" + strings.Join(bot.MapToSlice(info.Config.Filter.Filters[filter]), "|") + ")" } if len(info.Config.Filter.Templates[filter]) > 0 { combine = templateregex.ReplaceAllLiteralString(info.Config.Filter.Templates[filter], combine) } if len(combine) > 0 { w.filters[filter], err = regexp.Compile(combine) } return } func getAllFilters(info *bot.GuildInfo) []string { filters := []string{} for k := range info.Config.Filter.Filters { filters = append(filters, k) } return filters } type setFilterCommand struct{} func (c *setFilterCommand) Info() *bot.CommandInfo { return &bot.CommandInfo{ Name: "SetFilter", Usage: "Creates a new filter or sets the response and excluded channel list for an existing filter.", Sensitive: true, } } func (c *setFilterCommand) Process(args []string, msg *discordgo.Message, indices []int, info *bot.GuildInfo) (string, bool, *discordgo.MessageEmbed) { if len(args) < 1 { return "```\nNo filter given. All filters: " + strings.Join(getAllFilters(info), ", ") + "```", false, nil } filter := args[0] add := "%s response has been set and channels excluded." info.ConfigLock.Lock() m, _ := info.Config.Filter.Filters[filter] if len(m) == 0 { if len(info.Config.Filter.Filters) == 0 { info.Config.Filter.Filters = make(map[string]map[string]bool) } info.Config.Filter.Filters[filter] = make(map[string]bool) add = "%s has been created, the response set, and excluded channels configured." } if len(args) > 1 { if len(info.Config.Filter.Responses) == 0 { info.Config.Filter.Responses = make(map[string]string) } info.Config.Filter.Responses[filter] = args[1] } if len(info.Config.Filter.Channels) == 0 { info.Config.Filter.Channels = make(map[string]map[bot.DiscordChannel]bool) } info.Config.Filter.Channels[filter] = make(map[bot.DiscordChannel]bool) g, _ := info.GetGuild() for i := 2; i < len(args); i++ { if ch, err := bot.ParseChannel(args[i], g); err == nil { info.Config.Filter.Channels[filter][ch] = true } } info.ConfigLock.Unlock() info.SaveConfig() return fmt.Sprintf("```\n"+add+"```", info.Sanitize(filter, bot.CleanCodeBlock)), false, nil } func (c *setFilterCommand) Usage(info *bot.GuildInfo) *bot.CommandUsage { return &bot.CommandUsage{ Desc: "Sets the [filter] response to [response] and it's excluded channel list to [channels]. Creates the filter if it doesn't exist.", Params: []bot.CommandUsageParam{ {Name: "filter", Desc: "The name of a filter.", Optional: false}, {Name: "response", Desc: "The message that will be sent when a message is deleted. Can be left blank, but quotes are mandatory.", Optional: true}, {Name: "channels", Desc: "All additional arguments should be channels to exclude the filter from.", Optional: true}, }, } } type addFilterCommand struct { m *FilterModule } func (c *addFilterCommand) Info() *bot.CommandInfo { return &bot.CommandInfo{ Name: "AddFilter", Usage: "Adds a string to a filter.", Sensitive: true, } } func (c *addFilterCommand) Process(args []string, msg *discordgo.Message, indices []int, info *bot.GuildInfo) (string, bool, *discordgo.MessageEmbed) { if len(args) < 1 { return "```\nNo filter given. All filters: " + strings.Join(getAllFilters(info), ", ") + "```", false, nil } if len(args) < 2 { return "```\nCan't add empty string!```", false, nil } info.ConfigLock.Lock() filter := args[0] m, ok := info.Config.Filter.Filters[filter] if !ok { info.ConfigLock.Unlock() return fmt.Sprintf("```\nThe %s filter does not exist!```", filter), false, nil } if len(m) == 0 { info.Config.Filter.Filters[filter] = make(map[string]bool) } add := "Added %s to %s." arg := msg.Content[indices[1]:] info.Config.Filter.Filters[filter][arg] = true if c.m.UpdateRegex(filter, info) != nil { delete(info.Config.Filter.Filters[filter], arg) add = "Failed to add %s to %s because regex compilation failed." c.m.UpdateRegex(filter, info) } info.ConfigLock.Unlock() info.SaveConfig() filter = info.Sanitize(filter, bot.CleanCodeBlock) return fmt.Sprintf("```\n"+add+" Length of %s: %v```", info.Sanitize(arg, bot.CleanCodeBlock), filter, filter, strconv.Itoa(len(info.Config.Filter.Filters[filter]))), false, nil } func (c *addFilterCommand) Usage(info *bot.GuildInfo) *bot.CommandUsage { return &bot.CommandUsage{ Desc: "Adds [arbitrary string] to [filter] and recompiles the filter regex.", Params: []bot.CommandUsageParam{ {Name: "filter", Desc: "The name of a filter. The filter must exist. Create a new filter by using !setfilter.", Optional: false}, {Name: "arbitrary string", Desc: "Arbitrary string to add to the filter. Quotes aren't necessary, but cannot be empty.", Optional: false}, }, } } type removeFilterCommand struct { m *FilterModule } func (c *removeFilterCommand) Info() *bot.CommandInfo { return &bot.CommandInfo{ Name: "RemoveFilter", Usage: "Removes a term from a filter.", Sensitive: true, } } func (c *removeFilterCommand) Process(args []string, msg *discordgo.Message, indices []int, info *bot.GuildInfo) (string, bool, *discordgo.MessageEmbed) { if len(args) < 1 { return "```\nNo filter given. All filters: " + strings.Join(getAllFilters(info), ", ") + "```", false, nil } if len(args) < 2 { return "```\nCan't remove an empty string!```", false, nil } filter := args[0] cmap, ok := info.Config.Filter.Filters[filter] if !ok { return "```\nThat filter does not exist!```", false, nil } arg := msg.Content[indices[1]:] _, ok = cmap[arg] if !ok { return "```\nCould not find " + arg + "!```", false, nil } delete(info.Config.Filter.Filters[filter], arg) c.m.UpdateRegex(filter, info) filter = info.Sanitize(filter, bot.CleanCodeBlock) retval := fmt.Sprintf("```\nRemoved %s from %s. Length of %s: %v```", info.Sanitize(arg, bot.CleanCodeBlock), filter, filter, len(info.Config.Filter.Filters[filter])) info.SaveConfig() return retval, false, nil } func (c *removeFilterCommand) Usage(info *bot.GuildInfo) *bot.CommandUsage { return &bot.CommandUsage{ Desc: "Removes [arbitrary string] from [filter], then recompiles the regex.", Params: []bot.CommandUsageParam{ {Name: "filter", Desc: "The name of a filter. The filter must exist. Create a new filter by using !setfilter.", Optional: false}, {Name: "arbitrary string", Desc: "Arbitrary string to remove from the filter. Quotes aren't necessary, but cannot be empty.", Optional: false}, }, } } type deleteFilterCommand struct { m *FilterModule } func (c *deleteFilterCommand) Info() *bot.CommandInfo { return &bot.CommandInfo{ Name: "DeleteFilter", Usage: "Deletes an entire filter.", Sensitive: true, } } func (c *deleteFilterCommand) Process(args []string, msg *discordgo.Message, indices []int, info *bot.GuildInfo) (string, bool, *discordgo.MessageEmbed) { if len(args) < 1 { return "```\nNo filter given. All filters: " + strings.Join(getAllFilters(info), ", ") + "```", false, nil } if len(args) > 1 { return "```\nYou specified more than one argument. This command completely removes an entire filter, use " + info.Config.Basic.CommandPrefix + "removefilter to remove a single item.```", false, nil } filter := args[0] _, ok := info.Config.Filter.Filters[filter] if !ok { return "```\nThat filter does not exist!```", false, nil } delete(info.Config.Filter.Filters, filter) delete(info.Config.Filter.Channels, filter) delete(info.Config.Filter.Responses, filter) delete(info.Config.Filter.Templates, filter) delete(c.m.filters, filter) c.m.UpdateRegex(filter, info) filter = info.Sanitize(filter, bot.CleanCodeBlock) info.SaveConfig() return fmt.Sprintf("```\nDeleted the %s filter```", filter), false, nil } func (c *deleteFilterCommand) Usage(info *bot.GuildInfo) *bot.CommandUsage { return &bot.CommandUsage{ Desc: "Deletes a filter and all of its settings.", Params: []bot.CommandUsageParam{ {Name: "filter", Desc: "The name of a filter. The filter must exist. Create a new filter by using !setfilter.", Optional: false}, }, } } type searchFilterCommand struct { } func (c *searchFilterCommand) Info() *bot.CommandInfo { return &bot.CommandInfo{ Name: "SearchFilter", Usage: "Searches a filter.", Sensitive: true, } } func (c *searchFilterCommand) Process(args []string, msg *discordgo.Message, indices []int, info *bot.GuildInfo) (string, bool, *discordgo.MessageEmbed) { if len(args) < 1 { return "```\nNo filter given. All filters: " + strings.Join(getAllFilters(info), ", ") + "```", false, nil } filter := strings.ToLower(args[0]) cmap, ok := info.Config.Filter.Filters[filter] if !ok { return "```\nThat filter doesn't exist!```", false, nil } results := []string{} if len(args) < 2 { results = bot.MapToSlice(cmap) } else { arg := msg.Content[indices[1]:] for k := range cmap { if strings.Contains(k, arg) { results = append(results, k) } } } if len(results) > 0 { return "```\nThe following entries match your query:\n" + info.Sanitize(strings.Join(results, "\n"), bot.CleanCodeBlock) + "```", len(results) > 6, nil } return "```\nNo results found in the " + filter + " filter.```", false, nil } func (c *searchFilterCommand) Usage(info *bot.GuildInfo) *bot.CommandUsage { return &bot.CommandUsage{ Desc: "Returns all terms of the given filter that contain the given string.", Params: []bot.CommandUsageParam{ {Name: "filter", Desc: "The name of the filter. The filter must exist. Create a new filter by using !setfilter.", Optional: false}, {Name: "arbitrary string", Desc: "Arbitrary string to add to filter. If not provided, will simply return entire contents of the filter.", Optional: true}, }, } }
filtermodule/FilterModule.go
0.63409
0.498962
FilterModule.go
starcoder
package termui import ( "image" ) // Cell is a rune with assigned Fg and Bg. type Cell struct { Ch rune Fg Color Bg Color } // Buffer is a renderable rectangle cell data container. type Buffer struct { Area image.Rectangle // selected drawing area CellMap map[image.Point]Cell } // NewCell returne a new Cell given all necessary fields. func NewCell(ch rune, Fg, Bg Color) Cell { return Cell{ch, Fg, Bg} } // NewBuffer returns a new empty Buffer. func NewBuffer() *Buffer { return &Buffer{ CellMap: make(map[image.Point]Cell), Area: image.Rectangle{}, } } // NewFilledBuffer returns a new Buffer filled with the given Cell. func NewFilledBuffer(x0, y0, x1, y1 int, c Cell) *Buffer { buf := NewBuffer() buf.Area.Min = image.Pt(x0, y0) buf.Area.Max = image.Pt(x1, y1) buf.Fill(c) return buf } // SetCell assigns a Cell to (x,y). func (self *Buffer) SetCell(x, y int, c Cell) { self.CellMap[image.Pt(x, y)] = c } // SetString assigns a string to a Buffer starting at (x,y). func (self *Buffer) SetString(x, y int, s string, fg, bg Color) { for i, char := range s { self.SetCell(x+i, y, Cell{char, fg, bg}) } } // At returns the cell at (x,y). func (self *Buffer) At(x, y int) Cell { return self.CellMap[image.Pt(x, y)] } // SetArea assigns a new rect area to self. func (self *Buffer) SetArea(r image.Rectangle) { self.Area.Max = r.Max self.Area.Min = r.Min } // SetAreaXY sets the Buffer bounds from (0,0) to (x,y). func (self *Buffer) SetAreaXY(x, y int) { self.Area.Min.Y = 0 self.Area.Min.X = 0 self.Area.Max.Y = y self.Area.Max.X = x } // Merge merges the given buffers onto the current Buffer. func (self *Buffer) Merge(bs ...*Buffer) { for _, buf := range bs { for p, c := range buf.CellMap { self.SetCell(p.X, p.Y, c) } self.SetArea(self.Area.Union(buf.Area)) } } // MergeWithOffset merges a Buffer onto another with an offset. func (self *Buffer) MergeWithOffset(buf *Buffer, xOffset, yOffset int) { for p, c := range buf.CellMap { self.SetCell(p.X+xOffset, p.Y+yOffset, c) } rect := image.Rect(xOffset, yOffset, buf.Area.Max.X+xOffset, buf.Area.Max.Y+yOffset) self.SetArea(self.Area.Union(rect)) } // Fill fills the Buffer with a Cell. func (self *Buffer) Fill(c Cell) { for x := self.Area.Min.X; x < self.Area.Max.X; x++ { for y := self.Area.Min.Y; y < self.Area.Max.Y; y++ { self.SetCell(x, y, c) } } }
vendor/github.com/cjbassi/termui/buffer.go
0.847999
0.55652
buffer.go
starcoder
package goeval import ( "fmt" "go/token" "reflect" ) // ComputeBinaryOp executes the corresponding binary operation (+, -, etc) on two interfaces. func ComputeBinaryOp(xI, yI interface{}, op token.Token) (interface{}, error) { typeX := reflect.TypeOf(xI) typeY := reflect.TypeOf(yI) if typeX == typeY { switch xI.(type) { case string: x := xI.(string) y := yI.(string) switch op { case token.ADD: return x + y, nil } case int: x := xI.(int) y := yI.(int) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case int8: x := xI.(int8) y := yI.(int8) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case int16: x := xI.(int16) y := yI.(int16) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case int32: x := xI.(int32) y := yI.(int32) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case int64: x := xI.(int64) y := yI.(int64) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case uint: x := xI.(uint) y := yI.(uint) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case uint8: x := xI.(uint8) y := yI.(uint8) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case uint16: x := xI.(uint16) y := yI.(uint16) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case uint32: x := xI.(uint32) y := yI.(uint32) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case uint64: x := xI.(uint64) y := yI.(uint64) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case uintptr: x := xI.(uintptr) y := yI.(uintptr) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.REM: return x % y, nil case token.AND: return x & y, nil case token.OR: return x | y, nil case token.XOR: return x ^ y, nil case token.AND_NOT: return x &^ y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case complex64: x := xI.(complex64) y := yI.(complex64) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil } case complex128: x := xI.(complex128) y := yI.(complex128) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil } case float32: x := xI.(float32) y := yI.(float32) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case float64: x := xI.(float64) y := yI.(float64) switch op { case token.ADD: return x + y, nil case token.SUB: return x - y, nil case token.MUL: return x * y, nil case token.QUO: return x / y, nil case token.LSS: return x < y, nil case token.GTR: return x > y, nil case token.LEQ: return x <= y, nil case token.GEQ: return x >= y, nil } case bool: x := xI.(bool) y := yI.(bool) switch op { // Bool case token.LAND: return x && y, nil case token.LOR: return x || y, nil } } } yUint, isUint := yI.(uint64) if !isUint { isUint = true switch yV := yI.(type) { case int: yUint = uint64(yV) case int8: yUint = uint64(yV) case int16: yUint = uint64(yV) case int32: yUint = uint64(yV) case int64: yUint = uint64(yV) case uint8: yUint = uint64(yV) case uint16: yUint = uint64(yV) case uint32: yUint = uint64(yV) case uint64: yUint = uint64(yV) case float32: yUint = uint64(yV) case float64: yUint = uint64(yV) default: isUint = false } } if isUint { switch xI.(type) { case int: x := xI.(int) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case int8: x := xI.(int8) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case int16: x := xI.(int16) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case int32: x := xI.(int32) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case int64: x := xI.(int64) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case uint: x := xI.(uint) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case uint8: x := xI.(uint8) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case uint16: x := xI.(uint16) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case uint32: x := xI.(uint32) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case uint64: x := xI.(uint64) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } case uintptr: x := xI.(uintptr) switch op { // Num, uint case token.SHL: return x << yUint, nil case token.SHR: return x >> yUint, nil } } } // Anything switch op { case token.EQL: return xI == yI, nil case token.NEQ: return xI != yI, nil } return nil, fmt.Errorf("unknown operation %#v between %#v and %#v", op, xI, yI) } // ComputeUnaryOp computes the corresponding unary (+x, -x) operation on an interface. func ComputeUnaryOp(xI interface{}, op token.Token) (interface{}, error) { switch xI.(type) { case bool: x := xI.(bool) switch op { case token.NOT: return !x, nil } case int: x := xI.(int) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case int8: x := xI.(int8) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case int16: x := xI.(int16) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case int32: x := xI.(int32) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case int64: x := xI.(int64) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case uint: x := xI.(uint) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case uint8: x := xI.(uint8) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case uint16: x := xI.(uint16) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case uint32: x := xI.(uint32) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case uint64: x := xI.(uint64) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case uintptr: x := xI.(uintptr) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case float32: x := xI.(float32) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case float64: x := xI.(float64) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case complex64: x := xI.(complex64) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } case complex128: x := xI.(complex128) switch op { case token.ADD: return +x, nil case token.SUB: return -x, nil } } return nil, fmt.Errorf("unknown unary operation %#v on %#v", op, xI) }
ops.go
0.537284
0.574186
ops.go
starcoder
package main import ( "fmt" "../utils" "strconv" "math" ) type Boat struct { x int y int aim [2]int } func handle_rotation(cur_aim [2]int, rotation float64 ) [2]int { rotation_radians := rotation * (math.Pi/180) new_aim := [2]int{0,0} new_aim[0] = cur_aim[0] * int(math.Cos(rotation_radians)) - cur_aim[1] * int(math.Sin(rotation_radians)) new_aim[1] = cur_aim[0] * int(math.Sin(rotation_radians)) + cur_aim[1] * int(math.Cos(rotation_radians)) return new_aim } func part1(instructions []string) { cur_pos := Boat{0,0, [2]int{1,0}} for _, instruction := range instructions { command := instruction[:1] speed, _ := strconv.Atoi(instruction[1:]) switch command { case "N": cur_pos.y += speed case "S": cur_pos.y -= speed case "E": cur_pos.x += speed case "W": cur_pos.x -= speed case "L": cur_pos.aim = handle_rotation(cur_pos.aim, float64(speed)) case "R": cur_pos.aim = handle_rotation(cur_pos.aim, -float64(speed)) case "F": cur_pos.x += cur_pos.aim[0] * speed cur_pos.y += cur_pos.aim[1] * speed } } fmt.Println(math.Abs(float64(cur_pos.x)) + math.Abs(float64(cur_pos.y))) } func part2(instructions []string) { cur_pos := Boat{0,0, [2]int{1,0}} waypoint := [2]int{10,1} for _, instruction := range instructions { command := instruction[:1] speed, _ := strconv.Atoi(instruction[1:]) switch command { case "N": waypoint[1] += speed case "S": waypoint[1] -= speed case "E": waypoint[0] += speed case "W": waypoint[0] -= speed case "L": waypoint = handle_rotation(waypoint, float64(speed)) case "R": waypoint = handle_rotation(waypoint, -float64(speed)) case "F": cur_pos.x += waypoint[0] * speed cur_pos.y += waypoint[1] * speed } } fmt.Println(math.Abs(float64(cur_pos.x)) + math.Abs(float64(cur_pos.y))) } func main() { instructions := utils.Readlines_as_string_array("input") part1(instructions) part2(instructions) }
2020/day12/puzzle.go
0.707203
0.527377
puzzle.go
starcoder
package render import ( "strings" "github.com/weaveworks/scope/probe/kubernetes" "github.com/weaveworks/scope/report" ) // KubernetesVolumesRenderer is a Renderer which combines all Kubernetes // volumes components such as stateful Pods, Persistent Volume, Persistent Volume Claim, Storage Class. var KubernetesVolumesRenderer = MakeReduce( VolumesRenderer, PodToVolumeRenderer, PVCToStorageClassRenderer, PVToControllerRenderer, SPCToSPRenderer, SPToDiskRenderer, VolumeSnapshotRenderer, ) // VolumesRenderer is a Renderer which produces a renderable kubernetes PV & PVC // graph by merging the pods graph and the Persistent Volume topology. var VolumesRenderer = volumesRenderer{} // volumesRenderer is a Renderer to render PV & PVC nodes. type volumesRenderer struct{} // Render renders PV & PVC nodes along with adjacency func (v volumesRenderer) Render(rpt report.Report) Nodes { nodes := make(report.Nodes) for id, n := range rpt.PersistentVolumeClaim.Nodes { volume, _ := n.Latest.Lookup(kubernetes.VolumeName) for _, p := range rpt.PersistentVolume.Nodes { volumeName, _ := p.Latest.Lookup(kubernetes.Name) if volume == volumeName { n.Adjacency = n.Adjacency.Add(p.ID) n.Children = n.Children.Add(p) } } nodes[id] = n } return Nodes{Nodes: nodes} } // PodToVolumeRenderer is a Renderer which produces a renderable kubernetes Pod // graph by merging the pods graph and the Persistent Volume Claim topology. // Pods having persistent volumes are rendered. var PodToVolumeRenderer = podToVolumesRenderer{} // VolumesRenderer is a Renderer to render Pods & PVCs. type podToVolumesRenderer struct{} // Render renders the Pod nodes having volumes adjacency. func (v podToVolumesRenderer) Render(rpt report.Report) Nodes { nodes := make(report.Nodes) for podID, podNode := range rpt.Pod.Nodes { ClaimName, _ := podNode.Latest.Lookup(kubernetes.VolumeClaim) for _, pvcNode := range rpt.PersistentVolumeClaim.Nodes { pvcName, _ := pvcNode.Latest.Lookup(kubernetes.Name) if pvcName == ClaimName { podNode.Adjacency = podNode.Adjacency.Add(pvcNode.ID) podNode.Children = podNode.Children.Add(pvcNode) } } nodes[podID] = podNode } return Nodes{Nodes: nodes} } // PVCToStorageClassRenderer is a Renderer which produces a renderable kubernetes PVC // & Storage class graph. var PVCToStorageClassRenderer = pvcToStorageClassRenderer{} // pvcToStorageClassRenderer is a Renderer to render PVC & StorageClass. type pvcToStorageClassRenderer struct{} // Render renders the PVC & Storage Class nodes with adjacency. func (v pvcToStorageClassRenderer) Render(rpt report.Report) Nodes { nodes := make(report.Nodes) for scID, scNode := range rpt.StorageClass.Nodes { storageClass, _ := scNode.Latest.Lookup(kubernetes.Name) spcNameFromValue, _ := scNode.Latest.Lookup(kubernetes.Value) for _, pvcNode := range rpt.PersistentVolumeClaim.Nodes { storageClassName, _ := pvcNode.Latest.Lookup(kubernetes.StorageClassName) if storageClassName == storageClass { scNode.Adjacency = scNode.Adjacency.Add(pvcNode.ID) scNode.Children = scNode.Children.Add(pvcNode) } } // Expecting spcName from sc instead obtained a string i.e - name: StoragePoolClaim value: "spcName" . // Hence we are spliting it to get spcName. if strings.Contains(spcNameFromValue, "\"") { storageValue := strings.Split(spcNameFromValue, "\"") spcNameFromValue = storageValue[1] for _, spcNode := range rpt.StoragePoolClaim.Nodes { spcName, _ := spcNode.Latest.Lookup(kubernetes.Name) if spcName == spcNameFromValue { scNode.Adjacency = scNode.Adjacency.Add(spcNode.ID) scNode.Children = scNode.Children.Add(spcNode) } } } nodes[scID] = scNode } return Nodes{Nodes: nodes} } //PVToControllerRenderer is a Renderer which produces a renderable kubernetes PVC var PVToControllerRenderer = pvToControllerRenderer{} //pvTocontrollerRenderer is a Renderer to render PV & Controller. type pvToControllerRenderer struct{} //Render renders the PV & Controller nodes with adjacency. func (v pvToControllerRenderer) Render(rpt report.Report) Nodes { nodes := make(report.Nodes) for pvNodeID, p := range rpt.PersistentVolume.Nodes { volumeName, _ := p.Latest.Lookup(kubernetes.Name) for _, podNode := range rpt.Pod.Nodes { podVolumeName, _ := podNode.Latest.Lookup(kubernetes.VolumeName) if volumeName == podVolumeName { p.Adjacency = p.Adjacency.Add(podNode.ID) p.Children = p.Children.Add(podNode) } } for _, volumeSnapshotNode := range rpt.VolumeSnapshot.Nodes { snapshotPVName, _ := volumeSnapshotNode.Latest.Lookup(kubernetes.VolumeName) if volumeName == snapshotPVName { p.Adjacency = p.Adjacency.Add(volumeSnapshotNode.ID) p.Children = p.Children.Add(volumeSnapshotNode) } } nodes[pvNodeID] = p } return Nodes{Nodes: nodes} } // SPCToSPRenderer is a Renderer which produces a renderable kubernetes CRD SPC var SPCToSPRenderer = spcToSpRenderer{} // spcToSpRenderer is a Renderer to render SPC & SP nodes. type spcToSpRenderer struct{} // Render renders the SPC & SP nodes with adjacency. // Here we are obtaining the spc name from sp and adjacency is created by matching it with spc name. func (v spcToSpRenderer) Render(rpt report.Report) Nodes { nodes := make(report.Nodes) for spcID, spcNode := range rpt.StoragePoolClaim.Nodes { spcName, _ := spcNode.Latest.Lookup(kubernetes.Name) for _, spNode := range rpt.StoragePool.Nodes { spcNameFromLatest, _ := spNode.Latest.Lookup(kubernetes.StoragePoolClaimName) if spcName == spcNameFromLatest { spcNode.Adjacency = spcNode.Adjacency.Add(spNode.ID) spcNode.Children = spcNode.Children.Add(spNode) } } nodes[spcID] = spcNode } return Nodes{Nodes: nodes} } // SPToDiskRenderer is a Renderer which produces a renderable kubernetes CRD Disk var SPToDiskRenderer = spToDiskRenderer{} // spToDiskRenderer is a Renderer to render SP & Disk . type spToDiskRenderer struct{} // Render renders the SP & Disk nodes with adjacency. func (v spToDiskRenderer) Render(rpt report.Report) Nodes { var disks []string nodes := make(report.Nodes) for spID, spNode := range rpt.StoragePool.Nodes { disk, _ := spNode.Latest.Lookup(kubernetes.DiskList) if strings.Contains(disk, "/") { disks = strings.Split(disk, "/") } else { disks = []string{disk} } diskList := make(map[string]string) for _, disk := range disks { diskList[disk] = disk } for diskID, diskNode := range rpt.Disk.Nodes { diskName, _ := diskNode.Latest.Lookup(kubernetes.Name) if diskName == diskList[diskName] { spNode.Adjacency = spNode.Adjacency.Add(diskNode.ID) spNode.Children = spNode.Children.Add(diskNode) } nodes[diskID] = diskNode } nodes[spID] = spNode } return Nodes{Nodes: nodes} } // VolumeSnapshotRenderer is a renderer which produces a renderable Kubernetes Volume Snapshot and Volume Snapshot Data var VolumeSnapshotRenderer = volumeSnapshotRenderer{} // volumeSnapshotRenderer is a render to volume snapshot & volume snapshot data type volumeSnapshotRenderer struct{} // Render renders the volumeSnapshots & volumeSnapshotDatas with adjacency // It checks for the volumeSnapshotData name in volumeSnapshot, adjacency is created by matching the volumeSnapshotData name. func (v volumeSnapshotRenderer) Render(rpt report.Report) Nodes { nodes := make(report.Nodes) for volumeSnapshotID, volumeSnapshotNode := range rpt.VolumeSnapshot.Nodes { snapshotData, _ := volumeSnapshotNode.Latest.Lookup(kubernetes.SnapshotData) for volumeSnapshotDataID, volumeSnapshotDataNode := range rpt.VolumeSnapshotData.Nodes { snapshotDataName, _ := volumeSnapshotDataNode.Latest.Lookup(kubernetes.Name) if snapshotDataName == snapshotData { volumeSnapshotNode.Adjacency = volumeSnapshotNode.Adjacency.Add(volumeSnapshotDataNode.ID) volumeSnapshotNode.Children = volumeSnapshotNode.Children.Add(volumeSnapshotDataNode) } nodes[volumeSnapshotDataID] = volumeSnapshotDataNode } nodes[volumeSnapshotID] = volumeSnapshotNode } return Nodes{Nodes: nodes} }
render/persistentvolume.go
0.747155
0.475301
persistentvolume.go
starcoder
package block import ( "github.com/df-mc/dragonfly/dragonfly/entity/effect" "github.com/df-mc/dragonfly/dragonfly/entity/physics" "github.com/df-mc/dragonfly/dragonfly/internal/block_internal" "github.com/df-mc/dragonfly/dragonfly/internal/world_internal" "github.com/df-mc/dragonfly/dragonfly/item" "github.com/df-mc/dragonfly/dragonfly/world" "github.com/go-gl/mathgl/mgl64" "math" "time" _ "unsafe" // For compiler directives. ) // Beacon is a block that projects a light beam skyward, and can provide status effects such as Speed, Jump // Boost, Haste, Regeneration, Resistance, or Strength to nearby players. type Beacon struct { nbt solid transparent clicksAndSticks // Primary and Secondary are the primary and secondary effects broadcast to nearby entities by the // beacon. Primary, Secondary effect.Effect // level is the amount of the pyramid's levels, it is defined by the mineral blocks which build up the // pyramid, and can be 0-4. level int } // BreakInfo ... func (b Beacon) BreakInfo() BreakInfo { return BreakInfo{ Hardness: 3, Harvestable: alwaysHarvestable, Effective: nothingEffective, Drops: simpleDrops(item.NewStack(b, 1)), } } // UseOnBlock ... func (b Beacon) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) (used bool) { pos, _, used = firstReplaceable(w, pos, face, b) if !used { return } place(w, pos, b, user, ctx) return placed(ctx) } // Activate manages the opening of a beacon by activating it. func (b Beacon) Activate(pos world.BlockPos, _ world.Face, _ *world.World, u item.User) { if opener, ok := u.(ContainerOpener); ok { opener.OpenBlockContainer(pos) } } // DecodeNBT ... func (b Beacon) DecodeNBT(data map[string]interface{}) interface{} { b.level = int(readInt32(data, "Levels")) if primary, ok := effect_effectByID(int(readInt32(data, "Primary"))); ok { b.Primary = primary } if secondary, ok := effect_effectByID(int(readInt32(data, "Secondary"))); ok { b.Secondary = secondary } return b } // EncodeNBT ... func (b Beacon) EncodeNBT() map[string]interface{} { m := map[string]interface{}{ "Levels": int32(b.level), } if primary, ok := effect_idByEffect(b.Primary); ok { m["Primary"] = int32(primary) } if secondary, ok := effect_idByEffect(b.Secondary); ok { m["Secondary"] = int32(secondary) } return m } // CanDisplace ... func (b Beacon) CanDisplace(l world.Liquid) bool { _, water := l.(Water) return water } // SideClosed ... func (b Beacon) SideClosed(world.BlockPos, world.BlockPos, *world.World) bool { return false } // LightEmissionLevel ... func (Beacon) LightEmissionLevel() uint8 { return 15 } // Level returns an integer 0-4 which defines the current pyramid level of the beacon. func (b Beacon) Level() int { return b.level } // Tick recalculates level, recalculates the active state of the beacon, and powers players, // once every 80 ticks (4 seconds). func (b Beacon) Tick(currentTick int64, pos world.BlockPos, w *world.World) { if currentTick%80 == 0 { before := b.level // Recalculating pyramid level and powering up players in range once every 4 seconds. b.level = b.recalculateLevel(pos, w) if before != b.level { w.SetBlock(pos, b) } if b.level == 0 { return } if !b.obstructed(pos, w) { b.broadcastBeaconEffects(pos, w) } } } // recalculateLevel recalculates the level of the beacon's pyramid and returns it. The level can be 0-4. func (b Beacon) recalculateLevel(pos world.BlockPos, w *world.World) int { var lvl int iter := 1 // This loop goes over all 4 possible pyramid levels. for y := pos.Y() - 1; y >= pos.Y()-4; y-- { for x := pos.X() - iter; x <= pos.X()+iter; x++ { for z := pos.Z() - iter; z <= pos.Z()+iter; z++ { if src, ok := world_internal.BeaconSource[block_internal.World_runtimeID(w, world.BlockPos{x, y, z})]; !ok || !src { return lvl } } } iter++ lvl++ } return lvl } // obstructed determines whether the beacon is currently obstructed. func (b Beacon) obstructed(pos world.BlockPos, w *world.World) bool { // Fast obstructed light calculation. if w.SkyLight(pos.Add(world.BlockPos{0, 1})) == 15 { return false // Slow obstructed light calculation, if the fast way out failed. } else if world_highestLightBlocker(w, pos.X(), pos.Z()) <= uint8(pos.Y()) { return false } return true } // broadcastBeaconEffects determines the entities in range which could receive the beacon's powers, and // determines the powers (effects) that these entities could get. Afterwards, the entities in range that are // beaconAffected get their according effect(s). func (b Beacon) broadcastBeaconEffects(pos world.BlockPos, w *world.World) { seconds := 9 + b.level*2 if b.level == 4 { seconds-- } dur := time.Duration(seconds) * time.Second // Establishing what effects are active with the current amount of beacon levels. primary, secondary := b.Primary, effect.Effect(nil) switch b.level { case 0: primary = nil case 1: switch primary.(type) { case effect.Resistance, effect.JumpBoost, effect.Strength: primary = nil } case 2: if _, ok := primary.(effect.Strength); ok { primary = nil } case 3: default: secondary = b.Secondary } // Determining whether the primary power is set. if primary != nil { primary = primary.WithSettings(dur, 1, true) // Secondary power can only be set if the primary power is set. if secondary != nil { // It is possible to select 2 primary powers if the beacon's level is 4. pId, pOk := effect_idByEffect(primary) sId, sOk := effect_idByEffect(secondary) if pOk && sOk && pId == sId { primary = primary.WithSettings(dur, 2, true) secondary = nil } else { secondary = secondary.WithSettings(dur, 1, true) } } } // Finding entities in range. r := 10 + (b.level * 10) entitiesInRange := w.EntitiesWithin(physics.NewAABB( mgl64.Vec3{float64(pos.X() - r), -math.MaxFloat64, float64(pos.Z() - r)}, mgl64.Vec3{float64(pos.X() + r), math.MaxFloat64, float64(pos.Z() + r)}, )) for _, e := range entitiesInRange { if p, ok := e.(beaconAffected); ok { if primary != nil { p.AddEffect(primary) } if secondary != nil { p.AddEffect(secondary) } } } } // EncodeItem ... func (Beacon) EncodeItem() (id int32, meta int16) { return 138, 0 } // EncodeBlock ... func (Beacon) EncodeBlock() (name string, properties map[string]interface{}) { return "minecraft:beacon", nil } // Hash ... func (Beacon) Hash() uint64 { return hashBeacon } //go:linkname effect_effectByID github.com/df-mc/dragonfly/dragonfly/entity/effect.effectByID //noinspection ALL func effect_effectByID(id int) (effect.Effect, bool) //go:linkname effect_idByEffect github.com/df-mc/dragonfly/dragonfly/entity/effect.idByEffect //noinspection ALL func effect_idByEffect(e effect.Effect) (int, bool) //go:linkname world_highestLightBlocker github.com/df-mc/dragonfly/dragonfly/world.highestLightBlocker //noinspection ALL func world_highestLightBlocker(w *world.World, x, z int) uint8
dragonfly/block/beacon.go
0.699254
0.423041
beacon.go
starcoder
package v1alpha1 import ( internalinterfaces "kubeform.dev/provider-azurerm-api/client/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. type Interface interface { // Namespaces returns a NamespaceInformer. Namespaces() NamespaceInformer // NamespaceAuthorizationRules returns a NamespaceAuthorizationRuleInformer. NamespaceAuthorizationRules() NamespaceAuthorizationRuleInformer // NamespaceDisasterRecoveryConfigs returns a NamespaceDisasterRecoveryConfigInformer. NamespaceDisasterRecoveryConfigs() NamespaceDisasterRecoveryConfigInformer // NamespaceNetworkRuleSets returns a NamespaceNetworkRuleSetInformer. NamespaceNetworkRuleSets() NamespaceNetworkRuleSetInformer // Queues returns a QueueInformer. Queues() QueueInformer // QueueAuthorizationRules returns a QueueAuthorizationRuleInformer. QueueAuthorizationRules() QueueAuthorizationRuleInformer // Subscriptions returns a SubscriptionInformer. Subscriptions() SubscriptionInformer // SubscriptionRules returns a SubscriptionRuleInformer. SubscriptionRules() SubscriptionRuleInformer // Topics returns a TopicInformer. Topics() TopicInformer // TopicAuthorizationRules returns a TopicAuthorizationRuleInformer. TopicAuthorizationRules() TopicAuthorizationRuleInformer } type version struct { factory internalinterfaces.SharedInformerFactory namespace string tweakListOptions internalinterfaces.TweakListOptionsFunc } // New returns a new Interface. func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} } // Namespaces returns a NamespaceInformer. func (v *version) Namespaces() NamespaceInformer { return &namespaceInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // NamespaceAuthorizationRules returns a NamespaceAuthorizationRuleInformer. func (v *version) NamespaceAuthorizationRules() NamespaceAuthorizationRuleInformer { return &namespaceAuthorizationRuleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // NamespaceDisasterRecoveryConfigs returns a NamespaceDisasterRecoveryConfigInformer. func (v *version) NamespaceDisasterRecoveryConfigs() NamespaceDisasterRecoveryConfigInformer { return &namespaceDisasterRecoveryConfigInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // NamespaceNetworkRuleSets returns a NamespaceNetworkRuleSetInformer. func (v *version) NamespaceNetworkRuleSets() NamespaceNetworkRuleSetInformer { return &namespaceNetworkRuleSetInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Queues returns a QueueInformer. func (v *version) Queues() QueueInformer { return &queueInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // QueueAuthorizationRules returns a QueueAuthorizationRuleInformer. func (v *version) QueueAuthorizationRules() QueueAuthorizationRuleInformer { return &queueAuthorizationRuleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Subscriptions returns a SubscriptionInformer. func (v *version) Subscriptions() SubscriptionInformer { return &subscriptionInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // SubscriptionRules returns a SubscriptionRuleInformer. func (v *version) SubscriptionRules() SubscriptionRuleInformer { return &subscriptionRuleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // Topics returns a TopicInformer. func (v *version) Topics() TopicInformer { return &topicInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } // TopicAuthorizationRules returns a TopicAuthorizationRuleInformer. func (v *version) TopicAuthorizationRules() TopicAuthorizationRuleInformer { return &topicAuthorizationRuleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} }
client/informers/externalversions/servicebus/v1alpha1/interface.go
0.803019
0.408365
interface.go
starcoder
package gotvta var ( buy = "BUY" strongBuy = "STRONG_BUY" sell = "SELL" strongSell = "STRONG_SELL" neutral = "NEUTRAL" ) // ComputeMA returns technical analysis for moving averages. func ComputeMA(MA float64, close float64) string { if MA < close { return buy } else if MA > close { return sell } else { return neutral } } // ComputeRSI returns technical analysis for relative strength index. func ComputeRSI(RSI float64, RSI1 float64) string { if RSI < 30 && RSI1 > RSI { return buy } else if RSI > 70 && RSI1 < RSI { return sell } else { return neutral } } // ComputeStoch returns technical analysis for stochastic. func ComputeStoch(stochK float64, stochD float64, stochK1 float64, stochD1 float64) string { if stochK < 20 && stochD < 20 && stochK > stochD && stochK1 < stochD1 { return buy } else if stochK > 80 && stochD > 80 && stochK < stochD && stochK1 > stochD1 { return sell } else { return neutral } } // ComputeCCI20 returns technical analysis for commodity channel index 20. func ComputeCCI20(CCI20 float64, CCI201 float64) string { if CCI20 < -100 && CCI20 > CCI201 { return buy } else if CCI20 > 100 && CCI20 < CCI201 { return sell } else { return neutral } } // ComputeADX returns technical analysis for average directional index. func ComputeADX(ADX float64, ADXpDI float64, ADXnDI float64, ADXpDI1 float64, ADXnDI1 float64) string { if ADX > 20 && ADXpDI1 < ADXnDI1 && ADXpDI > ADXnDI { return buy } else if ADX > 20 && ADXpDI1 > ADXnDI1 && ADXpDI < ADXnDI { return sell } else { return neutral } } // ComputeAO returns technical analysis for awesome oscillator. func ComputeAO(AO float64, AO1 float64) string { if AO > 0 && AO1 < 0 || AO > 0 && AO1 > 0 && AO > AO1 { return buy } else if (AO < 0 && AO1 > 0 || AO < 0 && AO1 < 0 && AO < AO1) { return sell } else { return neutral } } // ComputeMom returns technical analysis for momentum. func ComputeMom(mom float64, mom1 float64) string { if mom < mom1 { return sell } else if mom > mom1 { return buy } else { return neutral } } // ComputeMACD returns technical analysis for moving average convergence/divergence. func ComputeMACD(MACD float64, signal float64) string { if MACD > signal { return buy } else if MACD < signal { return sell } else { return neutral } } // ComputeBBBuy returns technical analysis for bull bear buy. func ComputeBBBuy(close float64, BBLower float64) string { if close < BBLower { return buy } return neutral } // ComputeBBSell returns technical analysis for bull bear sell. func ComputeBBSell(close float64, BBUpper float64) string { if close > BBUpper { return sell } return neutral } // ComputePSAR returns technical analysis for parabolic stop-and-reverse. func ComputePSAR(PSAR float64, open float64) string { if PSAR < open { return buy } else if PSAR > open { return sell } else { return neutral } } // ComputeRecommend returns technical analysis for recommend. func ComputeRecommend(value float64) string { if value >= -1 && value < -.5 { return strongSell } else if value >= -.5 && value < 0 { return sell } else if value > 0 && value <= .5 { return buy } else if value > .5 && value <= 1 { return strongBuy } else { return neutral } } // ComputeSimple returns technical analysis for simple. func ComputeSimple(value float64) string { if value == -1 { return sell } else if value == 1 { return buy } else { return neutral } }
technicals.go
0.675229
0.415314
technicals.go
starcoder
package gassert func Go(condition bool) { if condition { panic("gAssertError") } } func Zeros(xs ...interface{}) { New().Zeros(xs...).Panic() } func Equals(x, y interface{}) { New().Equals(x, y).Panic() } func NotEquals(x, y interface{}) { New().NotEquals(x, y).Panic() } func NumLess(x, y interface{}) { New().NumLess(x, y).Panic() } func NumLessOrEquals(x, y interface{}) { New().NumLessOrEquals(x, y).Panic() } func NumGreater(x, y interface{}) { New().NumGreater(x, y).Panic() } func NumGreaterOrEquals(x, y interface{}) { New().NumGreaterOrEquals(x, y).Panic() } func StrLenEquals(s string, n int) { New().StrLenEquals(s, n).Panic() } func StrLenNotEquals(s string, n int) { New().StrLenNotEquals(s, n).Panic() } func StrLenLess(s string, n int) { New().StrLenLess(s, n).Panic() } func StrLenLessOrEquals(s string, n int) { New().StrLenLessOrEquals(s, n).Panic() } func StrLenGreater(s string, n int) { New().StrLenGreater(s, n).Panic() } func StrLenGreaterOrEquals(s string, n int) { New().StrLenGreaterOrEquals(s, n).Panic() } func ArrLenEquals(s interface{}, n int) { New().ArrLenEquals(s, n).Panic() } func ArrLenNotEquals(s interface{}, n int) { New().ArrLenNotEquals(s, n).Panic() } func ArrLenLess(s interface{}, n int) { New().ArrLenLess(s, n).Panic() } func ArrLenLessOrEquals(s interface{}, n int) { New().ArrLenLessOrEquals(s, n).Panic() } func ArrLenGreater(s interface{}, n int) { New().ArrLenGreater(s, n).Panic() } func ArrLenGreaterOrEquals(s interface{}, n int) { New().ArrLenGreaterOrEquals(s, n).Panic() } func SliceLenEquals(s interface{}, n int) { New().SliceLenEquals(s, n).Panic() } func SliceLenNotEquals(s interface{}, n int) { New().SliceLenNotEquals(s, n).Panic() } func SliceLenLess(s interface{}, n int) { New().SliceLenLess(s, n).Panic() } func SliceLenLessOrEquals(s interface{}, n int) { New().SliceLenLessOrEquals(s, n).Panic() } func SliceLenGreater(s interface{}, n int) { New().SliceLenGreater(s, n).Panic() } func SliceLenGreaterOrEquals(s interface{}, n int) { New().SliceLenGreaterOrEquals(s, n).Panic() } func SliceCapEquals(s interface{}, n int) { New().SliceCapEquals(s, n).Panic() } func SliceCapNotEquals(s interface{}, n int) { New().SliceCapNotEquals(s, n).Panic() } func SliceCapLess(s interface{}, n int) { New().SliceCapLess(s, n).Panic() } func SliceCapLessOrEquals(s interface{}, n int) { New().SliceCapLessOrEquals(s, n).Panic() } func SliceCapGreater(s interface{}, n int) { New().SliceCapGreater(s, n).Panic() } func SliceCapGreaterOrEquals(s interface{}, n int) { New().SliceCapGreaterOrEquals(s, n).Panic() } func MapLenEquals(s interface{}, n int) { New().MapLenEquals(s, n).Panic() } func MapLenNotEquals(s interface{}, n int) { New().MapLenNotEquals(s, n).Panic() } func MapLenLess(s interface{}, n int) { New().MapLenLess(s, n).Panic() } func MapLenLessOrEquals(s interface{}, n int) { New().MapLenLessOrEquals(s, n).Panic() } func MapLenGreater(s interface{}, n int) { New().MapLenGreater(s, n).Panic() } func MapLenGreaterOrEquals(s interface{}, n int) { New().MapLenGreaterOrEquals(s, n).Panic() } func New() *Event { return newEvent() }
gassert.go
0.660063
0.555676
gassert.go
starcoder
package yasup import ( crypto "crypto/rand" "math/big" "math/rand" ) var zeroValueInt64 int64 //Int64Insert will append elem at the position i. Might return ErrIndexOutOfBounds. func Int64Insert(sl *[]int64, elem int64, i int) error { if i < 0 || i > len(*sl) { return ErrIndexOutOfBounds } *sl = append(*sl, elem) copy((*sl)[i+1:], (*sl)[i:]) (*sl)[i] = elem return nil } //Int64Delete delete the element at the position i. Might return ErrIndexOutOfBounds. func Int64Delete(sl *[]int64, i int) error { if i < 0 || i >= len(*sl) { return ErrIndexOutOfBounds } *sl = append((*sl)[:i], (*sl)[i+1:]...) return nil } //Int64Contains will return true if elem is present in the slice and false otherwise. func Int64Contains(sl []int64, elem int64) bool { for i := range sl { if sl[i] == elem { return true } } return false } //Int64Index returns the index of the first instance of elem, or -1 if elem is not present. func Int64Index(sl []int64, elem int64) int { for i := range sl { if sl[i] == elem { return i } } return -1 } //Int64LastIndex returns the index of the last instance of elem in the slice, or -1 if elem is not present. func Int64LastIndex(sl []int64, elem int64) int { for i := len(sl) - 1; i >= 0; i-- { if sl[i] == elem { return i } } return -1 } //Int64Count will return an int representing the amount of times that elem is present in the slice. func Int64Count(sl []int64, elem int64) int { var n int for i := range sl { if sl[i] == elem { n++ } } return n } //Int64Push is equivalent to Int64Insert with index len(*sl). func Int64Push(sl *[]int64, elem int64) { Int64Insert(sl, elem, len(*sl)) } //Int64FrontPush is equivalent to Int64Insert with index 0. func Int64FrontPush(sl *[]int64, elem int64) { Int64Insert(sl, elem, 0) } //Int64Pop is equivalent to getting and removing the last element of the slice. Might return ErrEmptySlice. func Int64Pop(sl *[]int64) (int64, error) { if len(*sl) == 0 { return zeroValueInt64, ErrEmptySlice } last := len(*sl) - 1 ret := (*sl)[last] Int64Delete(sl, last) return ret, nil } //Int64Pop is equivalent to getting and removing the first element of the slice. Might return ErrEmptySlice. func Int64FrontPop(sl *[]int64) (int64, error) { if len(*sl) == 0 { return zeroValueInt64, ErrEmptySlice } ret := (*sl)[0] Int64Delete(sl, 0) return ret, nil } //Int64Replace modifies the slice with the first n non-overlapping instances of old replaced by new. If n equals -1, there is no limit on the number of replacements. func Int64Replace(sl []int64, old, new int64, n int) (replacements int) { left := n for i := range sl { if left == 0 { break // no replacements left } if sl[i] == old { sl[i] = new left-- } } return n - left } //Int64ReplaceAll is equivalent to Int64Replace with n = -1. func Int64ReplaceAll(sl []int64, old, new int64) (replacements int) { return Int64Replace(sl, old, new, -1) } //Int64Equals compares two int64 slices. Returns true if their elements are equal. func Int64Equals(a, b []int64) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } //Int64FastShuffle will randomly swap the int64 elements of a slice using math/rand (fast but not cryptographycally secure). func Int64FastShuffle(sp []int64) { rand.Shuffle(len(sp), func(i, j int) { sp[i], sp[j] = sp[j], sp[i] }) } //Int64SecureShuffle will randomly swap the int64 elements of a slice using crypto/rand (resource intensive but cryptographically secure). func Int64SecureShuffle(sp []int64) error { var i int64 size := int64(len(sp)) - 1 for i = 0; i < size+1; i++ { bigRandI, err := crypto.Int(crypto.Reader, big.NewInt(size)) if err != nil { return err } randI := bigRandI.Int64() sp[size-i], sp[randI] = sp[randI], sp[size-i] } return nil }
int64Slices.go
0.628863
0.422803
int64Slices.go
starcoder
package main import ( "log" "sort" ) type HeightMap struct { points [][]int } type Point32 struct { x int y int } func parseHeightMap(data []string) HeightMap { heightMap := HeightMap{[][]int{}} for _, line := range data { heights := []int{} for _, height := range line { heights = append(heights, int(height-'0')) } heightMap.points = append(heightMap.points, heights) } return heightMap } func (heightMap HeightMap) get(point Point32) int { return heightMap.points[point.y][point.x] } func (heightMap HeightMap) xsize() int { return len(heightMap.points[0]) } func (heightMap HeightMap) ysize() int { return len(heightMap.points) } func findLowPoints(heightMap HeightMap) []Point32 { points := []Point32{} for y := 0; y < heightMap.ysize(); y++ { for x := 0; x < heightMap.xsize(); x++ { point := Point32{x, y} value := heightMap.get(point) isLowest := true for _, adj := range heightMap.getAdjacentPoints(point) { if value >= heightMap.get(adj) { isLowest = false break } } if isLowest { points = append(points, Point32{x, y}) } } } return points } func calculateRisk(heightMap HeightMap, lowPoints []Point32) int { risk := 0 for _, point := range lowPoints { risk += heightMap.get(point) + 1 } return risk } func contains(list []Point32, p Point32) bool { for _, e := range list { if p == e { return true } } return false } func (heightMap HeightMap) getAdjacentPoints(point Point32) []Point32 { adjacent := []Point32{} if point.x > 0 { adjacent = append(adjacent, Point32{point.x - 1, point.y}) } if point.x < heightMap.xsize()-1 { adjacent = append(adjacent, Point32{point.x + 1, point.y}) } if point.y > 0 { adjacent = append(adjacent, Point32{point.x, point.y - 1}) } if point.y < heightMap.ysize()-1 { adjacent = append(adjacent, Point32{point.x, point.y + 1}) } return adjacent } func findBasinPoints(heightMap HeightMap, lowPoint Point32) []Point32 { toVisit := []Point32{lowPoint} basinPoints := []Point32{lowPoint} for len(toVisit) > 0 { point := toVisit[0] value := heightMap.get(point) toVisit = toVisit[1:] numLower := 0 for _, adj := range heightMap.getAdjacentPoints(point) { if contains(basinPoints, adj) { // ... } else if heightMap.get(adj) < value { numLower++ } else if heightMap.get(adj) < 9 { toVisit = append(toVisit, adj) } } if numLower <= 1 { if !contains(basinPoints, point) { basinPoints = append(basinPoints, point) } } } return basinPoints } func find3LargestBasins(heightMap HeightMap, lowPoints []Point32) [][]Point32 { basins := [][]Point32{} sizes := []int{} for _, lowPoint := range lowPoints { basin := findBasinPoints(heightMap, lowPoint) basins = append(basins, basin) sizes = append(sizes, len(basin)) } sort.SliceStable(basins, func(i, j int) bool { return len(basins[i]) > len(basins[j]) }) return basins[:3] } func basinSizeScore(basins [][]Point32) int { score := 1 for _, basin := range basins { score *= len(basin) } return score } func main9() { data, err := ReadInputFrom("9.inp") if err != nil { log.Fatal(err) return } heightMap := parseHeightMap(data) lowPoints := findLowPoints(heightMap) log.Println(calculateRisk(heightMap, lowPoints)) log.Println(basinSizeScore(find3LargestBasins(heightMap, lowPoints))) }
2021/9.go
0.623721
0.407864
9.go
starcoder
package rpg import ( "log" "time" astar "github.com/beefsack/go-astar" "github.com/faiface/pixel" ) func (e *Entity) pathcalc(target pixel.Vec) { var ( maxcost = 1000.00 ) if !e.calculated.IsZero() && time.Since(e.calculated) < time.Millisecond { return } e.calculated = time.Now() // get tiles, give world tile := e.w.Tile(e.Rect.Center()) tile.W = e.w targett := e.w.Tile(target) targett.W = e.w // check if tile.Type == O_NONE { // bad spawn, respawn e.P.Health = 0 return } if targett.Type == O_NONE { // player must be flying e.calculated = time.Now().Add(3 * time.Second) return } est := tile.PathEstimatedCost(targett) if est < 64 { //log.Println("direct to char", e, est) e.paths = []pixel.Vec{e.w.Char.Rect.Center(), e.w.Char.Rect.Center(), e.w.Char.Rect.Center()} return } if tile.PathEstimatedCost(targett) > 400 { // too far //log.Println("path too expensive, trying in 3 seconds") e.calculated = time.Now().Add(1 * time.Second) return } // calculate path path, distance, found := astar.Path(tile, targett) if found { if distance > maxcost { // cost path e.calculated = time.Now().Add(3 * time.Second) log.Println("too far") e.paths = nil return } //log.Println("distance:", distance) var paths []pixel.Vec for _, p := range path { //log.Println(p) center := p.(Object).Loc.Add(DefaultSpriteRectangle.Center()) paths = append(paths, center) } e.paths = paths return } //log.Println(e.Name, "no path found, distance:", distance) } func (o Object) PathNeighbors() []astar.Pather { neighbors := []astar.Pather{} of := 32.0 //of = 24.0 for _, offset := range [][]float64{ {-of, 0}, {of, 0}, {0, -of}, {0, of}, //{of, -of}, //{-of, -of}, //{of, of}, //{-of, of}, } { n := o.W.Tile(pixel.V(o.Rect.Center().X+offset[0], o.Rect.Center().Y+offset[1])) if n.Type == O_TILE { neighbors = append(neighbors, n) } } return neighbors } func (o Object) PathEstimatedCost(to astar.Pather) float64 { toT := to.(Object) absX := toT.Rect.Center().X - o.Rect.Center().X if absX < 0 { absX = -absX } absY := toT.Rect.Center().Y - o.Rect.Center().Y if absY < 0 { absY = -absY } return float64(absX + absY) } func (o Object) PathNeighborCost(to astar.Pather) float64 { toT := to.(Object) cost := tileCosts[toT.Type] return cost } // KindCosts map tile kinds to movement costs. var tileCosts = map[ObjectType]float64{ O_NONE: 30.00, O_BLOCK: 30.00, O_INVISIBLE: 3.00, O_SPECIAL: 0.00, O_TILE: 1.00, O_WIN: 0.00, O_DYNAMIC: 3.00, }
path.go
0.52683
0.403684
path.go
starcoder
package qr import ( "bytes" "fmt" "rsc.io/qr/gf256" ) type BitBlock struct { DataBytes int CheckBytes int B []byte M [][]byte Tmp []byte RS *gf256.RSEncoder bdata []byte cdata []byte } func newBlock(nd, nc int, rs *gf256.RSEncoder, dat, cdata []byte) *BitBlock { b := &BitBlock{ DataBytes: nd, CheckBytes: nc, B: make([]byte, nd+nc), Tmp: make([]byte, nc), RS: rs, bdata: dat, cdata: cdata, } copy(b.B, dat) rs.ECC(b.B[:nd], b.B[nd:]) b.check() if !bytes.Equal(b.Tmp, cdata) { panic("cdata") } b.M = make([][]byte, nd*8) for i := range b.M { row := make([]byte, nd+nc) b.M[i] = row for j := range row { row[j] = 0 } row[i/8] = 1 << (7 - uint(i%8)) rs.ECC(row[:nd], row[nd:]) } return b } func (b *BitBlock) check() { b.RS.ECC(b.B[:b.DataBytes], b.Tmp) if !bytes.Equal(b.B[b.DataBytes:], b.Tmp) { fmt.Printf("ecc mismatch\n%x\n%x\n", b.B[b.DataBytes:], b.Tmp) panic("mismatch") } } func (b *BitBlock) reset(bi uint, bval byte) { if (b.B[bi/8]>>(7-bi&7))&1 == bval { // already has desired bit return } // rows that have already been set m := b.M[len(b.M):cap(b.M)] for _, row := range m { if row[bi/8]&(1<<(7-bi&7)) != 0 { // Found it. for j, v := range row { b.B[j] ^= v } return } } panic("reset of unset bit") } func (b *BitBlock) canSet(bi uint, bval byte) bool { found := false m := b.M for j, row := range m { if row[bi/8]&(1<<(7-bi&7)) == 0 { continue } if !found { found = true if j != 0 { m[0], m[j] = m[j], m[0] } continue } for k := range row { row[k] ^= m[0][k] } } if !found { return false } targ := m[0] // Subtract from saved-away rows too. for _, row := range m[len(m):cap(m)] { if row[bi/8]&(1<<(7-bi&7)) == 0 { continue } for k := range row { row[k] ^= targ[k] } } // Found a row with bit #bi == 1 and cut that bit from all the others. // Apply to data and remove from m. if (b.B[bi/8]>>(7-bi&7))&1 != bval { for j, v := range targ { b.B[j] ^= v } } b.check() n := len(m) - 1 m[0], m[n] = m[n], m[0] b.M = m[:n] for _, row := range b.M { if row[bi/8]&(1<<(7-bi&7)) != 0 { panic("did not reduce") } } return true } func (b *BitBlock) copyOut() { b.check() copy(b.bdata, b.B[:b.DataBytes]) copy(b.cdata, b.B[b.DataBytes:]) }
models/qr/bitblock.go
0.52829
0.419232
bitblock.go
starcoder
package framework import ( "sigs.k8s.io/kustomize/kyaml/errors" "sigs.k8s.io/kustomize/kyaml/yaml" ) // Selector matches resources. A resource matches if and only if ALL of the Selector fields // match the resource. An empty Selector matches all resources. type Selector struct { // Names is a list of metadata.names to match. If empty match all names. // e.g. Names: ["foo", "bar"] matches if `metadata.name` is either "foo" or "bar". Names []string `json:"names" yaml:"names"` // Namespaces is a list of metadata.namespaces to match. If empty match all namespaces. // e.g. Namespaces: ["foo", "bar"] matches if `metadata.namespace` is either "foo" or "bar". Namespaces []string `json:"namespaces" yaml:"namespaces"` // Kinds is a list of kinds to match. If empty match all kinds. // e.g. Kinds: ["foo", "bar"] matches if `kind` is either "foo" or "bar". Kinds []string `json:"kinds" yaml:"kinds"` // APIVersions is a list of apiVersions to match. If empty apply match all apiVersions. // e.g. APIVersions: ["foo/v1", "bar/v1"] matches if `apiVersion` is either "foo/v1" or "bar/v1". APIVersions []string `json:"apiVersions" yaml:"apiVersions"` // Labels is a collection of labels to match. All labels must match exactly. // e.g. Labels: {"foo": "bar", "baz": "buz"] matches if BOTH "foo" and "baz" labels match. Labels map[string]string `json:"labels" yaml:"labels"` // Annotations is a collection of annotations to match. All annotations must match exactly. // e.g. Annotations: {"foo": "bar", "baz": "buz"] matches if BOTH "foo" and "baz" annotations match. Annotations map[string]string `json:"annotations" yaml:"annotations"` // ResourceMatcher is an arbitrary function used to match resources. // Selector matches if the function returns true. ResourceMatcher func(*yaml.RNode) bool // TemplateData if present will cause the selector values to be parsed as templates // and rendered using TemplateData before they are used. TemplateData interface{} // FailOnEmptyMatch makes the selector return an error when no items are selected. FailOnEmptyMatch bool } // Filter implements kio.Filter, returning only those items from the list that the selector // matches. func (s *Selector) Filter(items []*yaml.RNode) ([]*yaml.RNode, error) { andSel := AndSelector{TemplateData: s.TemplateData, FailOnEmptyMatch: s.FailOnEmptyMatch} if s.Names != nil { andSel.Matchers = append(andSel.Matchers, NameMatcher(s.Names...)) } if s.Namespaces != nil { andSel.Matchers = append(andSel.Matchers, NamespaceMatcher(s.Namespaces...)) } if s.Kinds != nil { andSel.Matchers = append(andSel.Matchers, KindMatcher(s.Kinds...)) } if s.APIVersions != nil { andSel.Matchers = append(andSel.Matchers, APIVersionMatcher(s.APIVersions...)) } if s.Labels != nil { andSel.Matchers = append(andSel.Matchers, LabelMatcher(s.Labels)) } if s.Annotations != nil { andSel.Matchers = append(andSel.Matchers, AnnotationMatcher(s.Annotations)) } if s.ResourceMatcher != nil { andSel.Matchers = append(andSel.Matchers, ResourceMatcherFunc(s.ResourceMatcher)) } return andSel.Filter(items) } // MatchAll is a shorthand for building an AndSelector from a list of ResourceMatchers. func MatchAll(matchers ...ResourceMatcher) *AndSelector { return &AndSelector{Matchers: matchers} } // MatchAny is a shorthand for building an OrSelector from a list of ResourceMatchers. func MatchAny(matchers ...ResourceMatcher) *OrSelector { return &OrSelector{Matchers: matchers} } // OrSelector is a kio.Filter that selects resources when that match at least one of its embedded // matchers. type OrSelector struct { // Matchers is the list of ResourceMatchers to try on the input resources. Matchers []ResourceMatcher // TemplateData, if present, is used to initialize any matchers that implement // ResourceTemplateMatcher. TemplateData interface{} // FailOnEmptyMatch makes the selector return an error when no items are selected. FailOnEmptyMatch bool } // Match implements ResourceMatcher so that OrSelectors can be composed func (s *OrSelector) Match(item *yaml.RNode) bool { for _, matcher := range s.Matchers { if matcher.Match(item) { return true } } return false } // Filter implements kio.Filter, returning only those items from the list that the selector // matches. func (s *OrSelector) Filter(items []*yaml.RNode) ([]*yaml.RNode, error) { if err := initMatcherTemplates(s.Matchers, s.TemplateData); err != nil { return nil, err } var selectedItems []*yaml.RNode for i := range items { for _, matcher := range s.Matchers { if matcher.Match(items[i]) { selectedItems = append(selectedItems, items[i]) break } } } if s.FailOnEmptyMatch && len(selectedItems) == 0 { return nil, errors.Errorf("selector did not select any items") } return selectedItems, nil } // DefaultTemplateData makes OrSelector a ResourceTemplateMatcher. // Although it does not contain templates itself, this allows it to support ResourceTemplateMatchers // when being used as a matcher itself. func (s *OrSelector) DefaultTemplateData(data interface{}) { if s.TemplateData == nil { s.TemplateData = data } } func (s *OrSelector) InitTemplates() error { return initMatcherTemplates(s.Matchers, s.TemplateData) } func initMatcherTemplates(matchers []ResourceMatcher, data interface{}) error { for _, matcher := range matchers { if tm, ok := matcher.(ResourceTemplateMatcher); ok { tm.DefaultTemplateData(data) if err := tm.InitTemplates(); err != nil { return err } } } return nil } var _ ResourceTemplateMatcher = &OrSelector{} // OrSelector is a kio.Filter that selects resources when that match all of its embedded // matchers. type AndSelector struct { // Matchers is the list of ResourceMatchers to try on the input resources. Matchers []ResourceMatcher // TemplateData, if present, is used to initialize any matchers that implement // ResourceTemplateMatcher. TemplateData interface{} // FailOnEmptyMatch makes the selector return an error when no items are selected. FailOnEmptyMatch bool } // Match implements ResourceMatcher so that AndSelectors can be composed func (s *AndSelector) Match(item *yaml.RNode) bool { for _, matcher := range s.Matchers { if !matcher.Match(item) { return false } } return true } // Filter implements kio.Filter, returning only those items from the list that the selector // matches. func (s *AndSelector) Filter(items []*yaml.RNode) ([]*yaml.RNode, error) { if err := initMatcherTemplates(s.Matchers, s.TemplateData); err != nil { return nil, err } var selectedItems []*yaml.RNode for i := range items { isSelected := true for _, matcher := range s.Matchers { if !matcher.Match(items[i]) { isSelected = false break } } if isSelected { selectedItems = append(selectedItems, items[i]) } } if s.FailOnEmptyMatch && len(selectedItems) == 0 { return nil, errors.Errorf("selector did not select any items") } return selectedItems, nil } // DefaultTemplateData makes AndSelector a ResourceTemplateMatcher. // Although it does not contain templates itself, this allows it to support ResourceTemplateMatchers // when being used as a matcher itself. func (s *AndSelector) DefaultTemplateData(data interface{}) { if s.TemplateData == nil { s.TemplateData = data } } func (s *AndSelector) InitTemplates() error { return initMatcherTemplates(s.Matchers, s.TemplateData) } var _ ResourceTemplateMatcher = &AndSelector{}
kyaml/fn/framework/selector.go
0.736116
0.461745
selector.go
starcoder
package ccsitef // ExtratoEletronico serviço/produto const ExtratoEletronico = ` servico: "extrato" versao: "1.6b–Agosto-2007" layout: "ccsitef" remessa: header_arquivo: codigo_registro: pos: [1, 2] picture: "X(2)" default: "A0" versao_layout: pos: [3, 8] picture: "X(6)" default: "001.6b" data_geracao: pos: [9, 16] picture: "9(8)" data_format: "yyyymmddd" hora_geracao: pos: [17, 22] picture: "9(6)" data_format: "hhmmss" id_movimento: pos: [23, 28] picture: "9(6)" nome_administradora: pos: [29, 58] picture: "X(30)" identificacao_remetente: pos: [59, 62] picture: "9(4)" identificacao_destinatario: pos: [63, 68] picture: "9(6)" nseq_registro: pos: [69, 74] picture: "9(6)" trailer_arquivo: codigo_registro: pos: [1, 2] picture: "X(2)" default: "A9" total_geral_registros: pos: [3, 8] picture: "9(6)" nseq_registro: pos: [9, 14] picture: "9(6)" header_lote: codigo_registro: pos: [1, 2] picture: "X(2)" default: "L0" data_movimento: pos: [3, 10] picture: "9(8)" data_format: "yyyymmdd" identificacao_moeda: pos: [11, 12] picture: "X(2)" data_format: "yyyymmdd" nseq: pos: [13, 18] picture: "9(6)" trailer_lote: codigo_registro: pos: [1, 2] picture: "X(2)" default: "L9" total_registros_transacao: pos: [3, 8] picture: "9(6)" total_valores_creditos: pos: [9, 22] picture: "9(14)" nseq: pos: [23, 28] picture: "9(6)" detalhes: segmento_cv: codigo_banco: pos: [1, 2] picture: "X(2)" default: "CV" identificacao_loja: pos: [3, 17] picture: "X(15)" nsu_host_transacao: pos: [18, 29] picture: "9(12)" data_transacao: pos: [30, 37] picture: "9(8)" data_format: "yyyymmdd" hora_transacao: pos: [38, 43] picture: "9(6)" data_format: "hhmmss" tipo_lancamento: pos: [44, 44] picture: "9(1)" data_lancamento: pos: [45, 52] picture: "9(8)" data_format: "yyyymmdd" tipo_produto: pos: [53, 53] picture: "X(1)" meio_captura: pos: [54, 54] picture: "9(1)" valor_bruno_venda: pos: [55, 65] picture: "9(11)" valor_desconto: pos: [66, 76] picture: "9(11)" valor_liquida_venda: pos: [77, 87] picture: "9(11)" numero_cartao: pos: [88, 106] picture: "X(19)" numero_parcela: pos: [107, 108] picture: "9(2)" numero_total_parcelas: pos: [109, 110] picture: "9(2)" nsu_host_parcela: pos: [111, 122] picture: "X(12)" valor_bruto_parcela: pos: [123, 133] picture: "9(11)" valor_desconto_parcela: pos: [134, 144] picture: "9(11)" valor_liquido_parcela: pos: [145, 155] picture: "9(11)" banco: pos: [156, 158] picture: "9(3)" agencia: pos: [159, 164] picture: "9(6)" conta: pos: [165, 175] picture: "X(11)" codigo_autorizacao: pos: [176, 187] picture: "9(12)" nseq: pos: [188, 193] picture: "9(6)" segmento_aj: codigo_banco: pos: [1, 2] picture: "X(2)" default: "AJ" identificacao_loja: pos: [3, 17] picture: "X(15)" nsu_host_transacao_original: pos: [18, 29] picture: "9(12)" data_transacao_original: pos: [30, 37] picture: "9(8)" data_format: "yyyymmdd" numero_parcela: pos: [38, 39] picture: "9(2)" nsu_host_transacao: pos: [40, 51] picture: "9(12)" data_transacao: pos: [52, 59] picture: "9(8)" data_format: "yyyymmdd" hora_transacao: pos: [60, 65] picture: "9(6)" data_format: "hhmmss" tipo_lancamento: pos: [66, 66] picture: "9(1)" data_lancamento: pos: [67, 74] picture: "9(8)" data_format: "yyyymmdd" meio_captura: pos: [75, 75] picture: "9(1)" tipo_ajuste: pos: [76, 76] picture: "9(1)" codigo_ajuste: pos: [77, 79] picture: "9(3)" descricao_motivo_ajuste: pos: [80, 109] picture: "X(30)" valor_bruto_parcela: pos: [110, 120] picture: "9(11)" valor_desconto_comissao: pos: [121, 131] picture: "9(11)" valor_liquido: pos: [132, 142] picture: "9(11)" banco: pos: [143, 145] picture: "9(3)" agencia: pos: [146, 151] picture: "9(6)" conta: pos: [152, 162] picture: "X(11)" nseq: pos: [163, 168] picture: "9(6)" segmento_cc: codigo_banco: pos: [1, 2] picture: "X(2)" default: "AJ" identificacao_loja: pos: [3, 17] picture: "X(15)" nsu_host_transacao_original: pos: [18, 29] picture: "9(12)" data_transacao_original: pos: [30, 37] picture: "9(8)" data_format: "yyyymmdd" numero_parcela: pos: [38, 39] picture: "9(2)" nsu_host_transacao: pos: [40, 51] picture: "9(12)" data_transacao: pos: [52, 59] picture: "9(8)" data_format: "yyyymmdd" hora_transacao: pos: [60, 65] picture: "9(6)" data_format: "hhmmss" meio_captura: pos: [66, 66] picture: "9(1)" nseq: pos: [67, 72] picture: "9(6)" retorno: header_arquivo: codigo_registro: pos: [1, 2] picture: "X(2)" default: "A0" versao_layout: pos: [3, 8] picture: "X(6)" default: "001.6b" data_geracao: pos: [9, 16] picture: "9(8)" data_format: "yyyymmddd" hora_geracao: pos: [17, 22] picture: "9(6)" data_format: "hhmmss" id_movimento: pos: [23, 28] picture: "9(6)" nome_administradora: pos: [29, 58] picture: "X(30)" identificacao_remetente: pos: [59, 62] picture: "9(4)" identificacao_destinatario: pos: [63, 68] picture: "9(6)" nseq_registro: pos: [69, 74] picture: "9(6)" trailer_arquivo: codigo_registro: pos: [1, 2] picture: "X(2)" default: "A9" total_geral_registros: pos: [3, 8] picture: "9(6)" nseq_registro: pos: [9, 14] picture: "9(6)" header_lote: codigo_registro: pos: [1, 2] picture: "X(2)" default: "L0" data_movimento: pos: [3, 10] picture: "9(8)" data_format: "yyyymmdd" identificacao_moeda: pos: [11, 12] picture: "X(2)" data_format: "yyyymmdd" nseq: pos: [13, 18] picture: "9(6)" trailer_lote: codigo_registro: pos: [1, 2] picture: "X(2)" default: "L9" total_registros_transacao: pos: [3, 8] picture: "9(6)" total_valores_creditos: pos: [9, 22] picture: "9(14)" nseq: pos: [23, 28] picture: "9(6)" detalhes: segmento_cv: codigo_banco: pos: [1, 2] picture: "X(2)" default: "CV" identificacao_loja: pos: [3, 17] picture: "X(15)" nsu_host_transacao: pos: [18, 29] picture: "9(12)" data_transacao: pos: [30, 37] picture: "9(8)" data_format: "yyyymmdd" hora_transacao: pos: [38, 43] picture: "9(6)" data_format: "hhmmss" tipo_lancamento: pos: [44, 44] picture: "9(1)" data_lancamento: pos: [45, 52] picture: "9(8)" data_format: "yyyymmdd" tipo_produto: pos: [53, 53] picture: "X(1)" meio_captura: pos: [54, 54] picture: "9(1)" valor_bruno_venda: pos: [55, 65] picture: "9(11)" valor_desconto: pos: [66, 76] picture: "9(11)" valor_liquida_venda: pos: [77, 87] picture: "9(11)" numero_cartao: pos: [88, 106] picture: "X(19)" numero_parcela: pos: [107, 108] picture: "9(2)" numero_total_parcelas: pos: [109, 110] picture: "9(2)" nsu_host_parcela: pos: [111, 122] picture: "X(12)" valor_bruto_parcela: pos: [123, 133] picture: "9(11)" valor_desconto_parcela: pos: [134, 144] picture: "9(11)" valor_liquido_parcela: pos: [145, 155] picture: "9(11)" banco: pos: [156, 158] picture: "9(3)" agencia: pos: [159, 164] picture: "9(6)" conta: pos: [165, 175] picture: "X(11)" codigo_autorizacao: pos: [176, 187] picture: "9(12)" nseq: pos: [188, 193] picture: "9(6)" segmento_aj: codigo_banco: pos: [1, 2] picture: "X(2)" default: "AJ" identificacao_loja: pos: [3, 17] picture: "X(15)" nsu_host_transacao_original: pos: [18, 29] picture: "9(12)" data_transacao_original: pos: [30, 37] picture: "9(8)" data_format: "yyyymmdd" numero_parcela: pos: [38, 39] picture: "9(2)" nsu_host_transacao: pos: [40, 51] picture: "9(12)" data_transacao: pos: [52, 59] picture: "9(8)" data_format: "yyyymmdd" hora_transacao: pos: [60, 65] picture: "9(6)" data_format: "hhmmss" tipo_lancamento: pos: [66, 66] picture: "9(1)" data_lancamento: pos: [67, 74] picture: "9(8)" data_format: "yyyymmdd" meio_captura: pos: [75, 75] picture: "9(1)" tipo_ajuste: pos: [76, 76] picture: "9(1)" codigo_ajuste: pos: [77, 79] picture: "9(3)" descricao_motivo_ajuste: pos: [80, 109] picture: "X(30)" valor_bruto_parcela: pos: [110, 120] picture: "9(11)" valor_desconto_comissao: pos: [121, 131] picture: "9(11)" valor_liquido: pos: [132, 142] picture: "9(11)" banco: pos: [143, 145] picture: "9(3)" agencia: pos: [146, 151] picture: "9(6)" conta: pos: [152, 162] picture: "X(11)" nseq: pos: [163, 168] picture: "9(6)" segmento_cc: codigo_banco: pos: [1, 2] picture: "X(2)" default: "AJ" identificacao_loja: pos: [3, 17] picture: "X(15)" nsu_host_transacao_original: pos: [18, 29] picture: "9(12)" data_transacao_original: pos: [30, 37] picture: "9(8)" data_format: "yyyymmdd" numero_parcela: pos: [38, 39] picture: "9(2)" nsu_host_transacao: pos: [40, 51] picture: "9(12)" data_transacao: pos: [52, 59] picture: "9(8)" data_format: "yyyymmdd" hora_transacao: pos: [60, 65] picture: "9(6)" data_format: "hhmmss" meio_captura: pos: [66, 66] picture: "9(1)" nseq: pos: [67, 72] picture: "9(6)" `
layout/ccsitef/extrato.go
0.540681
0.425009
extrato.go
starcoder
package main import ( "sort" "strconv" "strings" ) type Basin struct { points []Point } type Stack []Point func (s *Stack) IsEmpty() bool { return len(*s) == 0 } func (s *Stack) Push(point Point) { *s = append(*s, point) } func (s *Stack) Pop() Point { index := len(*s) - 1 element := (*s)[index] *s = (*s)[:index] return element } func AdjacentPoints(inputInt [][]int, point Point) []Point { adjacentPoints := make([]Point, 0) if point.x > 0 { adjacentPoints = append(adjacentPoints, Point{point.x - 1, point.y, inputInt[point.x-1][point.y]}) } if point.x < len(inputInt)-1 { adjacentPoints = append(adjacentPoints, Point{point.x + 1, point.y, inputInt[point.x+1][point.y]}) } if point.y > 0 { adjacentPoints = append(adjacentPoints, Point{point.x, point.y - 1, inputInt[point.x][point.y-1]}) } if point.y < len(inputInt[point.x])-1 { adjacentPoints = append(adjacentPoints, Point{point.x, point.y + 1, inputInt[point.x][point.y+1]}) } return adjacentPoints } // write a function that takes a point and flood fills it func FloodFill(inputInt [][]int, startingPoint Point) Basin { basin := Basin{} seen := make(map[Point]bool, 0) var stack Stack stack.Push(startingPoint) for !stack.IsEmpty() { point := stack.Pop() if seen[point] == false { seen[point] = true if point.value >= startingPoint.value { basin.points = append(basin.points, point) } } adjacentPoints := AdjacentPoints(inputInt, point) for _, adjacentPoint := range adjacentPoints { if seen[adjacentPoint] == false && adjacentPoint.value < 9 { stack.Push(adjacentPoint) } } } return basin } func DayNinePartTwo(input []string) int { inputInt := make([][]int, len(input)) for i, line := range input { parts := strings.Split(line, "") for _, part := range parts { pInt, _ := strconv.Atoi(part) inputInt[i] = append(inputInt[i], pInt) } } lowPoints := LowPoints(inputInt) basins := []Basin{} for _, point := range lowPoints { basins = append(basins, FloodFill(inputInt, point)) } // sort basins by size sort.Slice(basins, func(i, j int) bool { return len(basins[i].points) > len(basins[j].points) }) return len(basins[0].points) * len(basins[1].points) * len(basins[2].points) } func LowPoints(inputInt [][]int) []Point { lowPoints := make([]Point, 0) for i, l := range inputInt { for x, part := range l { var lowPoint bool = true if x+1 < len(inputInt[i]) && inputInt[i][x+1] <= part { lowPoint = false } if x-1 >= 0 && inputInt[i][x-1] <= part { lowPoint = false } if i > 0 && inputInt[i-1][x] <= part { lowPoint = false } if i < len(inputInt)-1 && inputInt[i+1][x] <= part { lowPoint = false } if lowPoint { point := Point{i, x, part + 1} lowPoints = append(lowPoints, point) } } } return lowPoints } func DayNinePartOne(input []string) int { inputInt := make([][]int, len(input)) for i, line := range input { parts := strings.Split(line, "") for _, part := range parts { pInt, _ := strconv.Atoi(part) inputInt[i] = append(inputInt[i], pInt) } } lowPoints := LowPoints(inputInt) sum := 0 for _, point := range lowPoints { sum += point.value } return sum }
lib/adventofcode/2021/9.go
0.594669
0.424293
9.go
starcoder
package d2 import "fmt" // Rectangler is the interface implemented by objects that can return a // rectangular representation of themselves. type Rectangler interface { Rectangle() Rectangle } // A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. // It is well-formed if Min.X <= Max.X and likewise for Y. Points are always // well-formed. A rectangle's methods always return well-formed outputs for // well-formed inputs. type Rectangle struct { Min, Max Vec } // Center returns the center of r. func (r Rectangle) Center() Vec { return r.Min.Add(r.Max.Div(2)) } // Dx returns r's width. func (r Rectangle) Dx() float64 { return r.Max.X - r.Min.X } // Dy returns r's height. func (r Rectangle) Dy() float64 { return r.Max.Y - r.Min.Y } // Size returns r's width and height. func (r Rectangle) Size() Vec { return Vec{ r.Max.X - r.Min.X, r.Max.Y - r.Min.Y, } } // Add returns the rectangle r translated by v. func (r Rectangle) Add(v Vec) Rectangle { return Rectangle{ Vec{r.Min.X + v.X, r.Min.Y + v.Y}, Vec{r.Max.X + v.X, r.Max.Y + v.Y}, } } // Sub returns the rectangle r translated by -v. func (r Rectangle) Sub(v Vec) Rectangle { return Rectangle{ Vec{r.Min.X - v.X, r.Min.Y - v.Y}, Vec{r.Max.X - v.X, r.Max.Y - v.Y}, } } // Inset returns the rectangle r inset by n, which may be negative. If either // of r's dimensions is less than 2*n then an empty rectangle near the center // of r will be returned. func (r Rectangle) Inset(n float64) Rectangle { if r.Dx() < 2*n { r.Min.X = (r.Min.X + r.Max.X) / 2 r.Max.X = r.Min.X } else { r.Min.X += n r.Max.X -= n } if r.Dy() < 2*n { r.Min.Y = (r.Min.Y + r.Max.Y) / 2 r.Max.Y = r.Min.Y } else { r.Min.Y += n r.Max.Y -= n } return r } // Intersect returns the largest rectangle contained by both r and s. If the // two rectangles do not overlap then the zero rectangle will be returned. func (r Rectangle) Intersect(s Rectangle) Rectangle { if r.Min.X < s.Min.X { r.Min.X = s.Min.X } if r.Min.Y < s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X > s.Max.X { r.Max.X = s.Max.X } if r.Max.Y > s.Max.Y { r.Max.Y = s.Max.Y } if r.Min.X > r.Max.X || r.Min.Y > r.Max.Y { return ZR } return r } // Union returns the smallest rectangle that contains both r and s. func (r Rectangle) Union(s Rectangle) Rectangle { if r.Empty() { return s } if s.Empty() { return r } if r.Min.X > s.Min.X { r.Min.X = s.Min.X } if r.Min.Y > s.Min.Y { r.Min.Y = s.Min.Y } if r.Max.X < s.Max.X { r.Max.X = s.Max.X } if r.Max.Y < s.Max.Y { r.Max.Y = s.Max.Y } return r } // Empty reports whether the rectangle contains no points. func (r Rectangle) Empty() bool { return r.Min.X >= r.Max.X || r.Min.Y >= r.Max.Y } // Eq reports whether r and s contain the same set of points. All empty // rectangles are considered equal. func (r Rectangle) Eq(s Rectangle) bool { return r == s || r.Empty() && s.Empty() } // Overlaps reports whether r and s have a non-empty intersection. func (r Rectangle) Overlaps(s Rectangle) bool { return !r.Empty() && !s.Empty() && r.Min.X < s.Max.X && s.Min.X < r.Max.X && r.Min.Y < s.Max.Y && s.Min.Y < r.Max.Y } // In reports whether every point in r is in s. func (r Rectangle) In(s Rectangle) bool { if r.Empty() { return true } // Note that r.Max is an exclusive bound for r, so that r.In(s) // does not require that r.Max.In(s). return s.Min.X <= r.Min.X && r.Max.X <= s.Max.X && s.Min.Y <= r.Min.Y && r.Max.Y <= s.Max.Y } // Canon returns the canonical version of r. The returned rectangle has minimum // and maximum coordinates swapped if necessary so that it is well-formed. func (r Rectangle) Canon() Rectangle { if r.Max.X < r.Min.X { r.Min.X, r.Max.X = r.Max.X, r.Min.X } if r.Max.Y < r.Min.Y { r.Min.Y, r.Max.Y = r.Max.Y, r.Min.Y } return r } // ZR is the zero Rectangle. var ZR Rectangle // Rect is shorthand for Rectangle{Vec(x0, y0), Vec(x1, y1)}. The returned // rectangle has minimum and maximum coordinates swapped if necessary so that // it is well-formed. func Rect(x0, y0, x1, y1 float64) Rectangle { if x0 > x1 { x0, x1 = x1, x0 } if y0 > y1 { y0, y1 = y1, y0 } return Rectangle{Vec{x0, y0}, Vec{x1, y1}} } // RectWH returns a rectangle whose origin is Vec{x,y}, w and h are its width // and height. func RectWH(x, y, w, h float64) Rectangle { return Rectangle{ Min: Vec{x, y}, Max: Vec{x + w, y + h}, } } // RectFromCircle returns the minimum rectangle that contains the circle of // center c and radius r func RectFromCircle(c Vec, r float64) Rectangle { return RectWH(c.X-r, c.Y-r, 2*r, 2*r) } // String returns a string representation of r. func (r Rectangle) String() string { return fmt.Sprintf("(Min:%v,Max:%v)", r.Min, r.Max) }
f64/d2/rect.go
0.912966
0.533154
rect.go
starcoder
package matrix import ( "errors" ) //type Matrix interface { //CountRows() int //CountCols() int //GetElm(i int, j int) float64 //trace() float64 //SetElm(i int, j int, v float64) //add(*Matrix) error //substract(*Matrix) error //scale(float64) //copy() []float64 //diagonalCopy() []float64 //} type Matrix struct { // Number of rows rows int // Number of columns cols int // Matrix stored as a flat array: Aij = Elements[i*step + j] Elements []float64 // Offset between rows step int } func MakeMatrix(Elements []float64, rows, cols int) *Matrix { A := new(Matrix) A.rows = rows A.cols = cols A.step = cols A.Elements = Elements return A } func (A *Matrix) CountRows() int { return A.rows } func (A *Matrix) CountCols() int { return A.cols } func (A *Matrix) GetElm(i int, j int) float64 { return A.Elements[i*A.step+j] } func (A *Matrix) SetElm(i int, j int, v float64) { A.Elements[i*A.step+j] = v } func (A *Matrix) diagonalCopy() []float64 { diag := make([]float64, A.cols) for i := 0; i < len(diag); i++ { diag[i] = A.GetElm(i, i) } return diag } func (A *Matrix) copy() *Matrix { B := new(Matrix) B.rows = A.rows B.cols = A.cols B.step = A.step B.Elements = make([]float64, A.cols*A.rows) for i := 0; i < A.rows; i++ { for j := 0; j < A.cols; j++ { B.Elements[i*A.step+j] = A.GetElm(i, j) } } return B } func (A *Matrix) trace() float64 { var tr float64 = 0 for i := 0; i < A.cols; i++ { tr += A.GetElm(i, i) } return tr } func (A *Matrix) add(B *Matrix) error { if A.cols != B.cols && A.rows != B.rows { return errors.New("Wrong input sizes") } for i := 0; i < A.rows; i++ { for j := 0; j < A.cols; j++ { A.SetElm(i, j, A.GetElm(i, j)+B.GetElm(i, j)) } } return nil } func (A *Matrix) substract(B *Matrix) error { if A.cols != B.cols && A.rows != B.rows { return errors.New("Wrong input sizes") } for i := 0; i < A.rows; i++ { for j := 0; j < A.cols; j++ { A.SetElm(i, j, A.GetElm(i, j)-B.GetElm(i, j)) } } return nil } func (A *Matrix) scale(a float64) { for i := 0; i < A.rows; i++ { for j := 0; j < A.cols; j++ { A.SetElm(i, j, a*A.GetElm(i, j)) } } } func Add(A *Matrix, B *Matrix) *Matrix { result := MakeMatrix(make([]float64, A.cols*A.rows), A.cols, A.rows) for i := 0; i < A.rows; i++ { for j := 0; j < A.cols; j++ { result.SetElm(i, j, A.GetElm(i, j)+B.GetElm(i, j)) } } return result } func Substract(A *Matrix, B *Matrix) *Matrix { result := MakeMatrix(make([]float64, A.cols*A.rows), A.cols, A.rows) for i := 0; i < A.rows; i++ { for j := 0; j < A.cols; j++ { result.SetElm(i, j, A.GetElm(i, j)-B.GetElm(i, j)) } } return result } func Multiply(A *Matrix, B *Matrix) *Matrix { result := MakeMatrix(make([]float64, A.cols*A.rows), A.cols, A.rows) for i := 0; i < A.rows; i++ { for j := 0; j < A.cols; j++ { sum := float64(0) for k := 0; k < A.cols; k++ { sum += A.GetElm(i, k) * B.GetElm(k, j) } result.SetElm(i, j, sum) } } return result }
data-structures/matrix/matrix.go
0.65202
0.415195
matrix.go
starcoder
package gol import ( "image" "math/rand" "time" ) var ( randSource = rand.NewSource(time.Now().UnixNano()) rnd = rand.New(randSource) ) // World represents the game state type World struct { area [][]bool width int height int } // NewWorld creates a new world func NewWorld(width, height int) *World { world := World{} world.area = makeArea(width, height) world.width = width world.height = height return &world } // RandomSeed inits world with a random state func (w *World) RandomSeed(limit int) { for i := 0; i < limit; i++ { x := rnd.Intn(w.width) y := rnd.Intn(w.height) w.area[y][x] = true } } // Progress game state by one tick func (w *World) Progress() { next := makeArea(w.width, w.height) for y := 0; y < w.height; y++ { for x := 0; x < w.width; x++ { pop := w.neighbourCount(x, y) switch { case pop < 2: // rule 1. Any live cell with fewer than two live neighbours // dies, as if caused by under-population. next[y][x] = false case (pop == 2 || pop == 3) && w.area[y][x]: // rule 2. Any live cell with two or three live neighbours // lives on to the next generation. next[y][x] = true case pop > 3: // rule 3. Any live cell with more than three live neighbours // dies, as if by over-population. next[y][x] = false case pop == 3: // rule 4. Any dead cell with exactly three live neighbours // becomes a live cell, as if by reproduction. next[y][x] = true } } } w.area = next } // DrawImage paints current game state func (w *World) DrawImage(img *image.RGBA) { for y := 0; y < w.height; y++ { for x := 0; x < w.width; x++ { w.drawPixel(img, x, y) } } } func (w *World) drawPixel(img *image.RGBA, x, y int) { pos := 4*y*w.width + 4*x if w.area[y][x] { img.Pix[pos] = 0xff img.Pix[pos+1] = 0xff img.Pix[pos+2] = 0xff img.Pix[pos+3] = 0xff } else { img.Pix[pos] = 0 img.Pix[pos+1] = 0 img.Pix[pos+2] = 0 img.Pix[pos+3] = 0 } } // calculates the Moore neighborhood of x, y func (w *World) neighbourCount(x, y int) int { norm := w.normalizeCoords(x, y) near := 0 for pY := norm.lowY; pY <= norm.highY; pY++ { for pX := norm.lowX; pX <= norm.highX; pX++ { if !(pX == x && pY == y) && w.area[pY][pX] { near++ } } } return near } type normalizedCoords struct { lowX int lowY int highX int highY int } func (w *World) normalizeCoords(x, y int) normalizedCoords { r := normalizedCoords{} r.highX = w.width - 1 r.highY = w.height - 1 if x > 0 { r.lowX = x - 1 } if y > 0 { r.lowY = y - 1 } if x < w.width-1 { r.highX = x + 1 } if y < w.height-1 { r.highY = y + 1 } return r } func makeArea(width, height int) [][]bool { area := make([][]bool, height) for i := 0; i < height; i++ { area[i] = make([]bool, width) } return area }
gol.go
0.583203
0.478041
gol.go
starcoder
package ihex32 import ( "encoding/binary" "errors" "sync" ) //record stores the data of one line/record of an ihex32 file. type record struct { //rwm is used to coordinate multithreaded reading/writing when applying offsets or calculating checksums. rwm sync.Mutex //byteCount contains the hex string value that defines the number of data bytes contained in the record. byteCount string //addressField contains the lower 2 Byte of the 32Bit address. The higher 2 Byte are in the offset value. addressField string //recordType defines which kind of data is contained within the record (data, address offset, eof-marker, etc.). recordType string //data contains byteCount number of hex Strings, each representing a single byte (e.g. FF -> 255). data []string //checksum contains a single byte hex string with the checksum computed from the individual fields of the record. checksum string //offset contains the upper 2 Byte of the final adress value of a entry. offset string } //parseRecord takes a line as string and fills the respective fields in the record struct. func parseRecord(line string) (*record, error) { r := record{} if line[0] == beginLineToken[0] && len(line) >= 11 { r.byteCount = line[1:3] r.addressField = line[3:7] r.recordType = line[7:9] for i := 9; i < len(line)-3; i += 2 { r.data = append(r.data, line[i:i+2]) } if r.recordType == extendedLinearAddressRecordToken { if len(line) >= 13 { r.offset = line[9:13] } else { err := errors.New("line is too short to parse extended address record") return &r, err } } else { r.offset = "0000" } r.checksum = line[len(line)-2:] return &r, nil } else { err := errors.New("entry has no begin line symbol or is too short") return &r, err } } //addOffsets walks through all records and updates the offset-value in the records of type data. //It stops when it finds a record that has already been updated by another goroutine. func addOffsets(wg *sync.WaitGroup, recs []*record, start int) { defer wg.Done() firstRecordAfterNewOffset := false offs := "0000" forLoop: for i := start; i < len(recs); i++ { recs[i].rwm.Lock() if recs[i].recordType == extendedLinearAddressRecordToken { offs = recs[i].offset firstRecordAfterNewOffset = true } else if recs[i].recordType == dataRecordToken { if firstRecordAfterNewOffset && recs[i].offset == offs { recs[i].rwm.Unlock() break forLoop } else if firstRecordAfterNewOffset && recs[i].offset != offs { recs[i].offset = offs firstRecordAfterNewOffset = false } else if recs[i].offset != offs && offs != "0000" /*only write if offset != 0000 as this is the init value anyway*/ { recs[i].offset = offs } } recs[i].rwm.Unlock() } } //validateChecksumsRoutine calls the validateChecksum Method for each record //it is given and sends false to a channel in case a checksum isn't valid. func validateChecksumsRoutine(wg *sync.WaitGroup, c chan bool, recs []*record) { defer wg.Done() var csValid bool var err error forLoop: for _, r := range recs { csValid, err = r.validateChecksum() if err != nil || !csValid { c <- false break forLoop } } } //validateChecksum computes a checksum for a single record func (r *record) validateChecksum() (bool, error) { //sum is intended to overflow if necessary. the checksum is valid if the least significant byte of the sum equals 0. //therefore we can ignore all higher bytes and just look at the least significant byte / this uint8. var sum uint8 var buf uint8 var err error //convert byteCount to uint8 buf, err = hexToByte(r.byteCount) if err != nil { return false, err } //and add to sum sum = sum + buf //convert first byte of line address to uint8 buf, err = hexToByte(r.addressField[0:2]) if err != nil { return false, err } sum = sum + buf //convert second byte of line address to uint8 buf, err = hexToByte(r.addressField[2:4]) if err != nil { return false, err } sum = sum + buf //convert record type to uint8 buf, err = hexToByte(string(r.recordType)) if err != nil { return false, err } sum = sum + buf //convert every data byte for _, d := range r.data { buf, err = hexToByte(d) if err != nil { return false, err } sum = sum + buf } //and also the checksum itself buf, err = hexToByte(r.checksum) if err != nil { return false, err } //checksum is valid if sum equals 0 (as explained in the declaration of sum) sum = sum + buf if sum == 0 { return true, nil } else { return false, nil } } func calcDataRoutine(c chan []dataByte, recs []*record) { var d []dataByte var ds []dataByte var err error for _, r := range recs { if r.recordType == dataRecordToken { d, err = r.calcDataEntries() if err != nil { c <- []dataByte{} } ds = append(ds, d...) } } c <- ds close(c) } //calcDataEntries calculates all data entries with their final addresses. func (r *record) calcDataEntries() ([]dataByte, error) { var d []dataByte var err error var bs []byte var b byte var lineAddress uint16 for i, s := range r.data { //add index position to the address of the line to get the individual byte position bs, err = hexToByteSlice(r.addressField) if err != nil { return d, err } //convert bytes to uint16, add index lineAddress = binary.BigEndian.Uint16(bs) lineAddress = lineAddress + uint16(i) //create 2 byte buffer lineAddressBytes := []byte{0, 0} //fill byte slice buffer with thenew value of line address binary.BigEndian.PutUint16(lineAddressBytes, lineAddress) //convert offset string to byte slice bs, err = hexToByteSlice(r.offset) if err != nil { return d, err } //add the offset to the existing address bs = append(bs, lineAddressBytes...) b, err = hexToByte(s) if err != nil { return d, err } //construct data with final uint32 address and a byte as value d = append(d, dataByte{address: binary.BigEndian.Uint32(bs), value: b}) } return d, nil }
ihex32/record.go
0.536313
0.514522
record.go
starcoder
package shimesaba import ( "errors" "log" "sort" "time" "github.com/mashiike/shimesaba/internal/timeutils" ) // Reliability represents a group of values related to reliability per tumbling window. type Reliability struct { cursorAt time.Time timeFrame time.Duration isNoViolation IsNoViolationCollection upTime time.Duration failureTime time.Duration } type IsNoViolationCollection map[time.Time]bool func (c IsNoViolationCollection) IsUp(t time.Time) bool { if isUp, ok := c[t]; ok && !isUp { return false } return true } func (c IsNoViolationCollection) NewReliabilities(timeFrame time.Duration, startAt, endAt time.Time) (Reliabilities, error) { startAt = startAt.Truncate(timeFrame) iter := timeutils.NewIterator(startAt, endAt, timeFrame) reliabilitySlice := make([]*Reliability, 0) for iter.HasNext() { cursorAt, _ := iter.Next() reliabilitySlice = append(reliabilitySlice, NewReliability(cursorAt, timeFrame, c)) } return NewReliabilities(reliabilitySlice) } func NewReliability(cursorAt time.Time, timeFrame time.Duration, isNoViolation IsNoViolationCollection) *Reliability { cursorAt = cursorAt.Truncate(timeFrame).Add(timeFrame).UTC() r := &Reliability{ cursorAt: cursorAt, timeFrame: timeFrame, isNoViolation: isNoViolation, } r = r.Clone() r.calc() return r } func (r *Reliability) Clone() *Reliability { cloned := &Reliability{ cursorAt: r.cursorAt, timeFrame: r.timeFrame, upTime: r.upTime, failureTime: r.failureTime, } iter := timeutils.NewIterator(r.TimeFrameStartAt(), r.TimeFrameEndAt(), time.Minute) clonedIsNoViolation := make(IsNoViolationCollection, r.timeFrame/time.Minute) for iter.HasNext() { t, _ := iter.Next() clonedIsNoViolation[t] = r.isNoViolation.IsUp(t) } cloned.isNoViolation = clonedIsNoViolation return cloned } func (r *Reliability) calc() { iter := timeutils.NewIterator(r.TimeFrameStartAt(), r.TimeFrameEndAt(), time.Minute) var upTime, failureTime time.Duration for iter.HasNext() { t, _ := iter.Next() if r.isNoViolation.IsUp(t) { upTime += time.Minute } else { failureTime += time.Minute } } r.upTime = upTime r.failureTime = failureTime } //CursorAt is a representative value of the time shown by the tumbling window func (r *Reliability) CursorAt() time.Time { return r.cursorAt } //TimeFrame is the size of the tumbling window func (r *Reliability) TimeFrame() time.Duration { return r.timeFrame } //TimeFrameStartAt is the start time of the tumbling window func (r *Reliability) TimeFrameStartAt() time.Time { return r.cursorAt.Add(-r.timeFrame) } //TimeFrameEndAt is the end time of the tumbling window func (r *Reliability) TimeFrameEndAt() time.Time { return r.cursorAt.Add(-time.Nanosecond) } //UpTime is the uptime that can guarantee reliability. func (r *Reliability) UpTime() time.Duration { return r.upTime } //FailureTime is the time when reliability could not be ensured, i.e. SLO was violated func (r *Reliability) FailureTime() time.Duration { return r.failureTime } //Merge must be the same tumbling window func (r *Reliability) Merge(other *Reliability) (*Reliability, error) { if r.cursorAt != other.cursorAt { return r, errors.New("mismatch cursorAt") } if r.timeFrame != other.timeFrame { return r, errors.New("mismatch timeFrame") } cloned := r.Clone() for t, isUp2 := range other.isNoViolation { cloned.isNoViolation[t] = r.isNoViolation.IsUp(t) && isUp2 } cloned.calc() return cloned, nil } // Reliabilities is sortable type Reliabilities []*Reliability func NewReliabilities(s []*Reliability) (Reliabilities, error) { c := Reliabilities(s) sort.Sort(c) if c.Len() == 0 { return c, nil } timeFrame := c[0].TimeFrame() cursorAt := time.Unix(0, 0) for _, r := range c { if r.CursorAt() == cursorAt { return nil, errors.New("duplicate cursorAt") } cursorAt = r.CursorAt() if r.TimeFrame() != timeFrame { return nil, errors.New("multiple timeFrame") } } return c, nil } func (c Reliabilities) Len() int { return len(c) } func (c Reliabilities) Less(i, j int) bool { return c[i].CursorAt().After(c[j].CursorAt()) } func (c Reliabilities) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c Reliabilities) Clone() Reliabilities { cloned := make(Reliabilities, 0, len(c)) for _, r := range c { cloned = append(cloned, r.Clone()) } sort.Sort(cloned) return cloned } func (c Reliabilities) CalcTime(cursor, n int) (upTime, failureTime, deltaFailureTime time.Duration) { deltaFailureTime = c[cursor].FailureTime() i := cursor for ; i < cursor+n && i < c.Len(); i++ { upTime += c[i].UpTime() failureTime += c[i].FailureTime() } log.Printf("[debug] CalcTime[%s~%s] = (%s, %s, %s)", c[cursor].TimeFrameStartAt(), c[i-1].TimeFrameEndAt(), upTime, failureTime, deltaFailureTime, ) return } //TimeFrame is the size of the tumbling window func (c Reliabilities) TimeFrame() time.Duration { if c.Len() == 0 { return 0 } return c[0].TimeFrame() } //CursorAt is a representative value of the time shown by the tumbling window func (c Reliabilities) CursorAt(i int) time.Time { if c.Len() == 0 { return time.Unix(0, 0) } return c[i].cursorAt } //Merge two collection func (c Reliabilities) Merge(other Reliabilities) (Reliabilities, error) { return c.MergeInRange(other, time.Unix(0, 0).UTC(), time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC)) } func (c Reliabilities) MergeInRange(other Reliabilities, startAt, endAt time.Time) (Reliabilities, error) { if len(other) == 0 { return c.Clone(), nil } if len(c) == 0 { return other.Clone(), nil } reliabilityByCursorAt := make(map[time.Time]*Reliability, len(c)) for _, r := range c { if r.TimeFrameStartAt().Before(startAt) { continue } if r.TimeFrameStartAt().After(endAt) { continue } reliabilityByCursorAt[r.CursorAt()] = r.Clone() } for _, r := range other { if r.TimeFrameStartAt().Before(startAt) { continue } if r.TimeFrameStartAt().After(endAt) { continue } cursorAt := r.CursorAt() if base, ok := reliabilityByCursorAt[cursorAt]; ok { var err error reliabilityByCursorAt[cursorAt], err = base.Merge(r) if err != nil { return nil, err } } else { reliabilityByCursorAt[cursorAt] = r } } merged := make([]*Reliability, 0, len(reliabilityByCursorAt)) for _, r := range reliabilityByCursorAt { merged = append(merged, r) } return NewReliabilities(merged) }
reliability.go
0.626581
0.482429
reliability.go
starcoder
package block import "fmt" // FlowerType represents a type of flower. type FlowerType struct { flower } type flower uint8 // Dandelion is a dandelion flower. func Dandelion() FlowerType { return FlowerType{0} } // Poppy is a poppy flower. func Poppy() FlowerType { return FlowerType{1} } // BlueOrchid is a blue orchid flower. func BlueOrchid() FlowerType { return FlowerType{2} } // Allium is an allium flower. func Allium() FlowerType { return FlowerType{3} } // AzureBluet is an azure bluet flower. func AzureBluet() FlowerType { return FlowerType{4} } // RedTulip is a red tulip flower. func RedTulip() FlowerType { return FlowerType{5} } // OrangeTulip is an orange tulip flower. func OrangeTulip() FlowerType { return FlowerType{6} } // WhiteTulip is a white tulip flower. func WhiteTulip() FlowerType { return FlowerType{7} } // PinkTulip is a pink tulip flower. func PinkTulip() FlowerType { return FlowerType{8} } // OxeyeDaisy is an oxeye daisy flower. func OxeyeDaisy() FlowerType { return FlowerType{9} } // Cornflower is a cornflower flower. func Cornflower() FlowerType { return FlowerType{10} } // LilyOfTheValley is a lily of the valley flower. func LilyOfTheValley() FlowerType { return FlowerType{11} } // WitherRose is a wither rose flower. func WitherRose() FlowerType { return FlowerType{12} } // Uint8 returns the flower as a uint8. func (f flower) Uint8() uint8 { return uint8(f) } // Name ... func (f flower) Name() string { switch f { case 0: return "Dandelion" case 1: return "Poppy" case 2: return "Blue Orchid" case 3: return "Allium" case 4: return "Azure Bluet" case 5: return "Red Tulip" case 6: return "Orange Tulip" case 7: return "White Tulip" case 8: return "Pink Tulip" case 9: return "Oxeye Daisy" case 10: return "Cornflower" case 11: return "Lily of the Valley" case 12: return "Wither Rose" } panic("unknown flower type") } // FromString ... func (f flower) FromString(s string) (interface{}, error) { switch s { case "dandelion": return FlowerType{flower(0)}, nil case "poppy": return FlowerType{flower(1)}, nil case "orchid": return FlowerType{flower(2)}, nil case "allium": return FlowerType{flower(3)}, nil case "houstonia": return FlowerType{flower(4)}, nil case "tulip_red": return FlowerType{flower(5)}, nil case "tulip_orange": return FlowerType{flower(6)}, nil case "tulip_white": return FlowerType{flower(7)}, nil case "tulip_pink": return FlowerType{flower(8)}, nil case "oxeye": return FlowerType{flower(9)}, nil case "cornflower": return FlowerType{flower(10)}, nil case "lily_of_the_valley": return FlowerType{flower(11)}, nil case "wither_rose": return FlowerType{flower(12)}, nil } return nil, fmt.Errorf("unexpected flower type '%v', expecting one of 'dandelion', 'poppy', 'orchid', 'allium', 'houstonia', 'tulip_red', 'tulip_orange', 'tulip_white', 'tulip_pink', 'oxeye', 'cornflower', 'lily_of_the_valley', or 'wither_rose'", s) } // String ... func (f flower) String() string { switch f { case 0: return "dandelion" case 1: return "poppy" case 2: return "orchid" case 3: return "allium" case 4: return "houstonia" case 5: return "tulip_red" case 6: return "tulip_orange" case 7: return "tulip_white" case 8: return "tulip_pink" case 9: return "oxeye" case 10: return "cornflower" case 11: return "lily_of_the_valley" case 12: return "wither_rose" } panic("unknown flower type") } // FlowerTypes ... func FlowerTypes() []FlowerType { return []FlowerType{Dandelion(), Poppy(), BlueOrchid(), Allium(), AzureBluet(), RedTulip(), OrangeTulip(), WhiteTulip(), PinkTulip(), OxeyeDaisy(), Cornflower(), LilyOfTheValley(), WitherRose()} }
server/block/flower_type.go
0.76882
0.522263
flower_type.go
starcoder
package assert import ( "testing" "time" "github.com/ppapapetrou76/go-testing/internal/pkg/values" ) // AssertableDuration is the assertable structure for time.Duration values. type AssertableDuration struct { t *testing.T actual values.DurationValue } // ThatDuration returns an AssertableDuration structure initialized with the test reference and the actual value to assert. func ThatDuration(t *testing.T, actual time.Duration) AssertableDuration { t.Helper() return AssertableDuration{ t: t, actual: values.NewDurationValue(actual), } } // IsEqualTo asserts if the expected time.Duration is equal to the assertable time.Duration value // It errors the tests if the compared values (actual VS expected) are not equal. func (a AssertableDuration) IsEqualTo(expected time.Duration) AssertableDuration { a.t.Helper() if a.actual.IsNotEqualTo(expected) { a.t.Error(shouldBeEqual(a.actual, expected)) } return a } // IsNotEqualTo asserts if the expected time.Duration is not equal to the assertable time.Duration value // It errors the tests if the compared values (actual VS expected) are equal. func (a AssertableDuration) IsNotEqualTo(expected time.Duration) AssertableDuration { a.t.Helper() if a.actual.IsEqualTo(expected) { a.t.Error(shouldNotBeEqual(a.actual, expected)) } return a } // IsShorterThan asserts if the assertable time.Duration value is shorter than the expected value // It errors the tests if is not shorter. func (a AssertableDuration) IsShorterThan(expected time.Duration) AssertableDuration { a.t.Helper() if !a.actual.IsShorterThan(expected) { a.t.Error(shouldBeShorter(a.actual, expected)) } return a } // IsLongerThan asserts if the assertable time.v value is longer than the expected value // It errors the tests if is not longer. func (a AssertableDuration) IsLongerThan(expected time.Duration) AssertableDuration { a.t.Helper() if !a.actual.IsLongerThan(expected) { a.t.Error(shouldBeLonger(a.actual, expected)) } return a }
assert/duration.go
0.824991
0.735618
duration.go
starcoder
package perseus // InFloat64 returns whether i is in list func InFloat64(i float64, list []float64) bool { for _, b := range list { if b == i { return true } } return false } // IndexFloat64 returns the position of s in list. If s is not found, return -1. func IndexFloat64(s float64, list []float64) int { for i, b := range list { if b == s { return i } } return -1 } // ShiftFloat64 returns the first element of slice and other element's slice. func ShiftFloat64(slice []float64) (float64, []float64) { return slice[0], slice[1:] } // UnshiftFloat64 add an element to the beginning of a slice. func UnshiftFloat64(sep float64, i []float64) []float64 { return append([]float64{sep}, i...) } // DeleteFloat64 Delete specified element from slice func DeleteFloat64(slice []float64, sep int) []float64 { return append(slice[:sep], slice[sep+1:]...) } // CutFloat64 Delete from i to j from the slice func CutFloat64(slice []float64, i, j int) []float64 { return append(slice[:i], slice[j:]...) } // InsertFloat64 Insert element to specified position func InsertFloat64(slice []float64, element float64, position int) []float64 { return append(slice[:position], append([]float64{element}, slice[position:]...)...) } // InsertVectorFloat64 Insert slice to specified position func InsertVectorFloat64(origin, insert []float64, position int) []float64 { return append(origin[:position], append(insert, origin[position:]...)...) } // PopFloat64 returns the last element of slice and other element's slice. func PopFloat64(slice []float64) (float64, []float64) { return slice[len(slice)-1], slice[:len(slice)-1] } // ReversedFloat64 returns reversed slice func ReversedFloat64(slice []float64) []float64 { for left, right := 0, len(slice)-1; left < right; left, right = left+1, right-1 { slice[left], slice[right] = slice[right], slice[left] } return slice } // ExtendFloat64 connect slices together func ExtendFloat64(A, B []float64) []float64 { return append(A, B...) } func sumFloat64(values ...float64) float64 { var sum float64 for _, v := range values { sum += v } return sum } // SumFloat64 calculate summaries of arguments func SumFloat64(values ...float64) float64 { return sumFloat64(values...) }
float64.go
0.852506
0.405302
float64.go
starcoder
package rtree // Delete removes a single record with a matching recordID from the RTree. The // box specifies where to search in the RTree for the record (the search box // must intersect with the box of the record for it to be found and deleted). // The returned bool indicates whether or not the record could be found and // thus removed from the RTree (true indicates success). func (t *RTree) Delete(box Box, recordID int) bool { if t.root == nil { return false } // D1 [Find node containing record] var foundNode *node var foundEntryIndex int var recurse func(*node) recurse = func(n *node) { for i := 0; i < n.numEntries; i++ { entry := n.entries[i] if !overlap(entry.box, box) { continue } if !n.isLeaf { recurse(entry.child) if foundNode != nil { break } } else { if entry.recordID == recordID { foundNode = n foundEntryIndex = i break } } } } recurse(t.root) if foundNode == nil { return false } // D2 [Delete record] originalCount := t.count deleteEntry(foundNode, foundEntryIndex) // D3 [Propagate changes] t.condenseTree(foundNode) // D4 [Shorten tree] if !t.root.isLeaf && t.root.numEntries == 1 { t.root = t.root.entries[0].child t.root.parent = nil } t.count = originalCount - 1 return true } func deleteEntry(n *node, entryIndex int) { n.entries[entryIndex] = n.entries[n.numEntries-1] n.numEntries-- n.entries[n.numEntries] = entry{} } func (t *RTree) condenseTree(leaf *node) { // CT1 [Initialise] var eliminated []*node current := leaf for current != t.root { // CT2 [Find Parent Entry] parent := current.parent entryIdx := -1 for i := 0; i < parent.numEntries; i++ { if parent.entries[i].child == current { entryIdx = i break } } // CT3 [Eliminate Under-Full Node] if current.numEntries < minChildren { eliminated = append(eliminated, current) deleteEntry(parent, entryIdx) } else { // CT4 [Adjust Covering Rectangle] newBox := current.entries[0].box for i := 1; i < current.numEntries; i++ { newBox = combine(newBox, current.entries[i].box) } parent.entries[entryIdx].box = newBox } // CT5 [Move Up One Level In Tree] current = parent } // CT6 [Reinsert orphaned entries] for _, node := range eliminated { if node.isLeaf { for i := 0; i < node.numEntries; i++ { e := node.entries[i] t.Insert(e.box, e.recordID) } } else { for i := 0; i < node.numEntries; i++ { t.reInsertNode(node.entries[i].child) } } } } // reInsertNode reinserts the subtree rooted at a node that was previously // deleted from the tree. func (t *RTree) reInsertNode(node *node) { box := calculateBound(node) treeDepth := t.root.depth() nodeDepth := node.depth() insNode := t.chooseBestNode(box, treeDepth-nodeDepth-1) insNode.appendChild(box, node) t.adjustBoxesUpwards(node, box) if insNode.numEntries <= maxChildren { return } newNode := t.splitNode(insNode) root1, root2 := t.adjustTree(insNode, newNode) if root2 != nil { t.joinRoots(root1, root2) } }
rtree/delete.go
0.666388
0.572185
delete.go
starcoder
package bitvector import ( "fmt" "go/build" ) // MAX_UINT const MAX_UINT = ^uint(0) // MAX_INT const MAX_INT = int(MAX_UINT >> 1) // MAX_SIZE is calculated at compile time var MAX_SIZE = maxSize() // PC64 is used to determine population count, e.g. PC64[i] is the population count of i var PC64 = pc64() // BitVector is the base type type BitVector []int // NewBitVector is the constructor // Given the maximum value to hold in the bit vector, return an int array sized to do so func NewBitVector(maxValue int) BitVector { sizeOfInt := 1 if maxValue > MAX_SIZE { sizeOfInt = (maxValue / MAX_SIZE) + 1 } return make([]int, sizeOfInt, sizeOfInt) } // Add is a method to add an integer to the bit vector func (BitVector BitVector) Add(k int) error { if k > (len(BitVector) * MAX_SIZE) { return fmt.Errorf("%d is too large for the current bit vector capacity (%d)", k, (len(BitVector) * MAX_SIZE)) } // check if it is already there before adding if ok := BitVector.Contains(k); !ok { BitVector[k/MAX_SIZE] |= (1 << uint(k%MAX_SIZE)) } return nil } // Contains is a method to check a bit vector for a value func (BitVector BitVector) Contains(k int) bool { return (BitVector[k/MAX_SIZE] & (1 << uint(k%MAX_SIZE))) != 0 } // Delete is a method to delete a value from a bit vector func (BitVector BitVector) Delete(k int) { BitVector[k/MAX_SIZE] &= ^(1 << uint(k%MAX_SIZE)) } // MaxOut is a method to flip all the bits in the bit vector to 1 func (BitVector BitVector) MaxOut() { for i := 0; i < len(BitVector); i++ { BitVector[i] = MAX_INT } } // WipeOut is a method to flip all the bits in the bit vector to 0 func (BitVector BitVector) WipeOut() { for i := 0; i < len(BitVector); i++ { BitVector[i] = 0 } } // BWAND is a method to return the bitwise AND of two BitVectors. func (BitVector BitVector) BWAND(bv2 BitVector) (BitVector, error) { if len(BitVector) != len(bv2) { return nil, fmt.Errorf("Can't perform bitwise AND when BitVectors are different sizes") } result := NewBitVector(len(BitVector) * MAX_SIZE) for i := 0; i < len(BitVector); i++ { result[i] = BitVector[i] & bv2[i] } return result, nil } // PopCount is a method to report the number of flipped bits in the bit vector (using the population count algorithm) func (BitVector BitVector) PopCount() int { count := 0 if MAX_SIZE == 64 { for i := 0; i < len(BitVector); i++ { count += int(PC64[byte(BitVector[i]>>(0*8))] + PC64[byte(BitVector[i]>>(1*8))] + PC64[byte(BitVector[i]>>(2*8))] + PC64[byte(BitVector[i]>>(3*8))] + PC64[byte(BitVector[i]>>(4*8))] + PC64[byte(BitVector[i]>>(5*8))] + PC64[byte(BitVector[i]>>(6*8))] + PC64[byte(BitVector[i]>>(7*8))]) } } else if MAX_SIZE == 32 { for i := 0; i < len(BitVector); i++ { count += int(PC64[byte(BitVector[i]>>(0*8))] + PC64[byte(BitVector[i]>>(1*8))] + PC64[byte(BitVector[i]>>(2*8))] + PC64[byte(BitVector[i]>>(3*8))]) } } else { panic("I need to extend popcount to work beyond int64") } return count } // maxSize returns the system architecture in bits func maxSize() int { var maxSize int switch arch := build.Default.GOARCH; arch { case "amd64": maxSize = 64 case "arm64": maxSize = 64 case "js": maxSize = 64 default: maxSize = 32 } return maxSize } // populates the reference bit vector func pc64() [256]byte { var pc64 [256]byte for i := range pc64 { pc64[i] = pc64[i/2] + byte(i&1) } return pc64 }
src/bitvector/bitvector.go
0.564579
0.521593
bitvector.go
starcoder
package matrix // Matrix represents a mathematical Matrix. type Matrix struct { Values []float64 // Values of the matrix Rows int // Number of rows Columns int // Number of columns } // ApplyFn represents a function that is applied to the matrix when Apply is called type ApplyFn func(value float64, idx int, self []float64) float64 // New creates a new Matrix with "r" rows and "c" columns, the "vals" must be arranged in row-major order. // If "vals == nil", a new slice will be allocated with "r * c" size. // If the length of the "vals" is "r * c" it will be used as the underlaying slice but the changes won't be reflected, otherwise it will return an error. // It will also return an error if "r <= 0" of "c <= 0". func New(r, c int, vals []float64) (*Matrix, error) { if r <= 0 { return nil, ErrZeroRow } if c <= 0 { return nil, ErrZeroCol } if vals == nil { vals = make([]float64, r*c) } else { tmp := make([]float64, len(vals)) copy(tmp, vals) vals = tmp } if len(vals) != r*c { return nil, ErrDataLength } m := &Matrix{vals, r, c} return m, nil } // Copy creates a new Matrix with the same properties as the given Matrix. // It will return an error if "m == nil". func Copy(m *Matrix) (*Matrix, error) { if m == nil { return nil, ErrNilMatrix } vals := make([]float64, m.Rows*m.Columns) nMat := &Matrix{vals, m.Rows, m.Columns} copy(nMat.Values, m.Values) return nMat, nil } // Add adds "aMat" and "bMat" element-wise, placing the result in the receiver. // It will return an error if the two matrices do not hase the same dimensions. // It will also return an error if "aMat == nil" or "bMat == nil". func (m *Matrix) Add(aMat, bMat *Matrix) error { if aMat == nil || bMat == nil { return ErrNilMatrix } aRows, aCols, bRows, bCols := aMat.Rows, aMat.Columns, bMat.Rows, bMat.Columns if aRows != bRows || aCols != bCols { return ErrDifferentDimensions } aVals, bVals := make([]float64, aRows*aCols), make([]float64, bRows*bCols) copy(aVals, aMat.Values) copy(bVals, bMat.Values) m.Rows = aRows m.Columns = aCols m.Values = make([]float64, m.Rows*m.Columns) for idx := range m.Values { m.Values[idx] = aVals[idx] + bVals[idx] } return nil } // Apply applies the function "fn" to each of the elements of "a", placing the resulting matrix in the receiver. // The function "fn" takes the value of the element, the index of the row and the column, and it returns a new value for that element. // It will return an error if "fn == nil" or "a == nil". func (m *Matrix) Apply(fn ApplyFn, aMat *Matrix) error { if fn == nil { return ErrNilFunction } if aMat == nil { return ErrNilMatrix } aRows, aCols := aMat.Rows, aMat.Columns aVals := make([]float64, aRows*aCols) copy(aVals, aMat.Values) m.Rows, m.Columns = aRows, aCols m.Values = make([]float64, m.Rows*m.Columns) for idx := range m.Values { s := append(m.Values[:idx], aVals[idx:]...) m.Values[idx] = fn(aVals[idx], idx, s) } return nil } // At returns the element at row "r", column "c". // Indexing is zero-based, so the first row will be at "0" and the last row will be at "numberOfRows - 1" same for the columns. // It will return an error if "r" bigger than the number of rows or "c" is bigger than the number columns. func (m *Matrix) At(r, c int) (float64, error) { if r > m.Rows-1 { return 0, ErrRowOutOfBounds } if c > m.Columns-1 { return 0, ErrColOutOfBounds } return m.Values[r*m.Columns+c], nil } // Multiply performs element-wise multiplication of "a" and "b", placing the result in the receiver. // It will return an error if the two matrices does not hase the same dimensions. // It will also return an error if "b == nil" or "a == nil". func (m *Matrix) Multiply(aMat, bMat *Matrix) error { if aMat == nil || bMat == nil { return ErrNilMatrix } aRows, aCols, bRows, bCols := aMat.Rows, aMat.Columns, bMat.Rows, bMat.Columns if aRows != bRows || aCols != bCols { return ErrDifferentDimensions } aVals, bVals := make([]float64, aRows*aCols), make([]float64, bRows*bCols) copy(aVals, aMat.Values) copy(bVals, bMat.Values) m.Rows = aRows m.Columns = aCols m.Values = make([]float64, m.Rows*m.Columns) for idx := range m.Values { m.Values[idx] = aVals[idx] * bVals[idx] } return nil } // Product performs matrix multiplication of "a" and "b", placing the result in the receiver. // It will return an error if the number of columns in "a" not equal with the number of rows in "b". // It will also return an error if "b == nil" or "a == nil". func (m *Matrix) Product(aMat, bMat *Matrix) error { if aMat == nil || bMat == nil { return ErrNilMatrix } aRows, aCols, bRows, bCols := aMat.Rows, aMat.Columns, bMat.Rows, bMat.Columns if aCols != bRows { return ErrBadProductDimension } aVals, bVals := make([]float64, aRows*aCols), make([]float64, bRows*bCols) copy(aVals, aMat.Values) copy(bVals, bMat.Values) m.Rows = aRows m.Columns = bCols m.Values = make([]float64, m.Rows*m.Columns) for mIdx := range m.Values { for bIdx := 0; bIdx < bRows; bIdx++ { m.Values[mIdx] += aVals[((mIdx/bCols)*aCols)+bIdx] * bVals[(bIdx*bCols)+(mIdx%bCols)] } } return nil } // Scale multiplies the elements of "a" by "s", placing the result in the receiver. // It will return an error if "a == nil". func (m *Matrix) Scale(s float64, aMat *Matrix) error { if aMat == nil { return ErrNilMatrix } aRows, aCols := aMat.Rows, aMat.Columns aVals := make([]float64, aRows*aCols) copy(aVals, aMat.Values) m.Rows, m.Columns = aRows, aCols m.Values = make([]float64, m.Rows*m.Columns) for idx := range m.Values { m.Values[idx] = s * aVals[idx] } return nil } // Subtract subtracts "a" and "b" element-wise, placing the result in the receiver, in the order of "a - b" // It will return an error if the two matrices do not hase the same dimensions. // It will also return an error if "b == nil" or "a == nil". func (m *Matrix) Subtract(aMat, bMat *Matrix) error { if aMat == nil || bMat == nil { return ErrNilMatrix } aRows, aCols, bRows, bCols := aMat.Rows, aMat.Columns, bMat.Rows, bMat.Columns if aRows != bRows || aCols != bCols { return ErrDifferentDimensions } aVals, bVals := make([]float64, aRows*aCols), make([]float64, bRows*bCols) copy(aVals, aMat.Values) copy(bVals, bMat.Values) m.Rows = aRows m.Columns = aCols m.Values = make([]float64, m.Rows*m.Columns) for idx := range m.Values { m.Values[idx] = aVals[idx] - bVals[idx] } return nil } // Transpose switches the row and column indices of the matrix, placing the result in the receiver. // It will return an error if "a == nil". func (m *Matrix) Transpose(aMat *Matrix) error { if aMat == nil { return ErrNilMatrix } aRows, aCols := aMat.Rows, aMat.Columns aVals := make([]float64, aRows*aCols) copy(aVals, aMat.Values) m.Rows, m.Columns = aCols, aRows m.Values = make([]float64, m.Rows*m.Columns) for idx := range m.Values { m.Values[idx] = aVals[(idx%aCols*aRows)+(idx/aCols)] } return nil }
matrix/matrix.go
0.870019
0.784608
matrix.go
starcoder
package modelselection import ( "runtime" "time" "github.com/pa-m/sklearn/base" "gonum.org/v1/gonum/mat" ) // CrossValidateResult is the struct result of CrossValidate. it includes TestScore,FitTime,ScoreTime,Estimator type CrossValidateResult struct { TestScore []float64 FitTime, ScoreTime []time.Duration Estimator []base.Transformer } // CrossValidate Evaluate a score by cross-validation // scorer is a func(Ytrue,Ypred) float64 // only mean_squared_error for now // NJobs is the number of goroutines. if <=0, runtime.NumCPU is used func CrossValidate(estimator base.Transformer, X, Y *mat.Dense, groups []int, scorer func(Ytrue, Ypred *mat.Dense) float64, cv Splitter, NJobs int) (res CrossValidateResult) { if NJobs <= 0 { NJobs = runtime.NumCPU() } NSplits := cv.GetNSplits(X, Y) if NJobs > NSplits { NJobs = NSplits } if cv == Splitter(nil) { cv = &KFold{NSplits: 3, Shuffle: true} } res.Estimator = make([]base.Transformer, NSplits) res.TestScore = make([]float64, NSplits) res.FitTime = make([]time.Duration, NSplits) res.ScoreTime = make([]time.Duration, NSplits) type structIn struct { iSplit int Split } type structOut struct { iSplit int score float64 } estimatorCloner := estimator.(base.TransformerCloner) NSamples, NFeatures := X.Dims() _, NOutputs := Y.Dims() processSplit := func(job int, Xjob, Yjob *mat.Dense, sin structIn) structOut { Xtrain, Xtest, Ytrain, Ytest := &mat.Dense{}, &mat.Dense{}, &mat.Dense{}, &mat.Dense{} trainLen, testLen := len(sin.Split.TrainIndex), len(sin.Split.TestIndex) Xtrain.SetRawMatrix(base.MatGeneralRowSlice(Xjob.RawMatrix(), 0, trainLen)) Ytrain.SetRawMatrix(base.MatGeneralRowSlice(Yjob.RawMatrix(), 0, trainLen)) Xtest.SetRawMatrix(base.MatGeneralRowSlice(Xjob.RawMatrix(), trainLen, trainLen+testLen)) Ytest.SetRawMatrix(base.MatGeneralRowSlice(Yjob.RawMatrix(), trainLen, trainLen+testLen)) for i0, i1 := range sin.Split.TrainIndex { Xtrain.SetRow(i0, X.RawRowView(i1)) Ytrain.SetRow(i0, Y.RawRowView(i1)) } for i0, i1 := range sin.Split.TestIndex { Xtest.SetRow(i0, X.RawRowView(i1)) Ytest.SetRow(i0, Y.RawRowView(i1)) } res.Estimator[sin.iSplit] = estimatorCloner.Clone() t0 := time.Now() res.Estimator[sin.iSplit].Fit(Xtrain, Ytrain) res.FitTime[sin.iSplit] = time.Since(t0) t0 = time.Now() _, Ypred := res.Estimator[sin.iSplit].Transform(Xtest, Ytest) score := scorer(Ytest, Ypred) res.ScoreTime[sin.iSplit] = time.Since(t0) //fmt.Printf("score for split %d is %g\n", sin.iSplit, score) return structOut{sin.iSplit, score} } if NJobs > 1 { /*var useChannels = false if useChannels { chin := make(chan structIn) chout := make(chan structOut) // launch workers for j := 0; j < NJobs; j++ { go func(job int) { var Xjob, Yjob = mat.NewDense(NSamples, NFeatures, nil), mat.NewDense(NSamples, NOutputs, nil) for sin := range chin { chout <- processSplit(job, Xjob, Yjob, sin) } }(j) } var isplit int for split := range cv.Split(X, Y) { chin <- structIn{isplit, split} isplit++ } close(chin) for range res.TestScore { sout := <-chout res.TestScore[sout.iSplit] = sout.score } close(chout) } else*/{ // use workGroup var sin = make([]structIn, 0, NSplits) for split := range cv.Split(X, Y) { sin = append(sin, structIn{iSplit: len(sin), Split: split}) } base.Parallelize(NJobs, NSplits, func(th, start, end int) { var Xjob, Yjob = mat.NewDense(NSamples, NFeatures, nil), mat.NewDense(NSamples, NOutputs, nil) for i := start; i < end; i++ { sout := processSplit(th, Xjob, Yjob, sin[i]) res.TestScore[sout.iSplit] = sout.score } }) } } else { // NJobs==1 var Xjob, Yjob = mat.NewDense(NSamples, NFeatures, nil), mat.NewDense(NSamples, NOutputs, nil) var isplit int for split := range cv.Split(X, Y) { sout := processSplit(0, Xjob, Yjob, structIn{iSplit: isplit, Split: split}) res.TestScore[sout.iSplit] = sout.score isplit++ } } return }
model_selection/validation.go
0.563618
0.407864
validation.go
starcoder
package containerkit import "math" // Interface Hashable is implemented by values providing a HashCode method. // The default generic hash function uses this interface for values that // don't have a specific predefined hash function (e.g. structs) type Hashable interface { HashCode() int } // Interface Comparable is implemented by values providing a Compare method. // The default generic comparison function uses this interface for values // that don't have a specific predefined comparison function (e.g. structs) type Comparable interface { Compare(other interface{}) int } // Interface Indentifiable is implemented by values providing an Equals // method which returns true if the given value is equivalent. type Identifiable interface { Equals(other interface{}) bool } // UniversalHash computes a hash sum for the given object 'x'. Supported are all // native types as well as objects implementing method HashCode. func UniversalHash(x interface{}) int { switch val := x.(type) { case nil: return 0 case bool: if val { return 1 } return 0 case byte: return int(val) case int: return val case uint: return int(val) case int32: return int(val) case int64: return int(val ^ (val >> 32)) case float32: return int(math.Float32bits(val)) case float64: return int(math.Float64bits(val)) case string: res := 0 for _, ch := range val { res = res * 31 + int(ch) } return res case Hashable: if res, valid := x.(Hashable); valid { return res.HashCode() } } panic("UniversalHash: Unknown type") } // UniversalEquality is a function for determining whether two objects 'x' and 'y' // are equals. For objects of a predefined atomic type (bool, byte, int, ...), the // operator '==' is used for checking equality. If objects of all other types // (e.g struct) are implementing interface Identifiable, method 'equals' is used. // Otherwise, for objects implementing interface Comparable, method 'Compare' is used. // Otherwise, UniversalEquality fails. func UniversalEquality(x, y interface{}) bool { switch this := x.(type) { case nil: return y == nil case bool: if that, valid := y.(bool); valid { return this == that } case byte: if that, valid := y.(byte); valid { return this == that } case int: if that, valid := y.(int); valid { return this == that } case uint: if that, valid := y.(uint); valid { return this == that } case int32: if that, valid := y.(int32); valid { return this == that } case int64: if that, valid := y.(int64); valid { return this == that } case float32: if that, valid := y.(float32); valid { return this == that } case float64: if that, valid := y.(float64); valid { return this == that } case string: if that, valid := y.(string); valid { return this == that } case Identifiable: return this.Equals(y) case Comparable: return this.Compare(y) == 0 } panic("UniversalEquality: Illegal parameters") } // UniversalComparison is a function for comparing two objects 'x' and 'y'. // For objects of a predefined atomic type (bool, byte, int, ...), the operators // '==' and '<' are used for comparisons. Objects of all other types (e.g struct) // need to implement interface Comparable. func UniversalComparison(x, y interface{}) int { switch this := x.(type) { case nil: return comparatorCode(y == nil, true) case bool: if that, valid := y.(bool); valid { return comparatorCode(this == that, !this) } case byte: if that, valid := y.(byte); valid { return comparatorCode(this == that, this < that) } case int: if that, valid := y.(int); valid { return comparatorCode(this == that, this < that) } case uint: if that, valid := y.(uint); valid { return comparatorCode(this == that, this < that) } case int32: if that, valid := y.(int32); valid { return comparatorCode(this == that, this < that) } case int64: if that, valid := y.(int64); valid { return comparatorCode(this == that, this < that) } case float32: if that, valid := y.(float32); valid { return comparatorCode(this == that, this < that) } case float64: if that, valid := y.(float64); valid { return comparatorCode(this == that, this < that) } case string: if that, valid := y.(string); valid { return comparatorCode(this == that, this < that) } case Comparable: return this.Compare(y) } panic("UniversalComparison: Illegal parameters") } func comparatorCode(eq bool, less bool) int { if eq { return 0 } else if less { return -1 } return 1 }
comparisons.go
0.826607
0.492005
comparisons.go
starcoder
package parse import ( "bytes" "fmt" ) // Tree is the representation of a single parsed SQL statement. type Tree struct { Root BoolExpr lex *lexer depth int } // Parse parses the SQL statement and returns a Tree. func Parse(buf []byte) (*Tree, error) { t := new(Tree) t.lex = new(lexer) return t.Parse(buf) } // Parse parses the SQL statement buffer to construct an ast // representation for execution. func (t *Tree) Parse(buf []byte) (tree *Tree, err error) { defer t.recover(&err) t.lex.init(buf) t.Root = t.parseExpr() return t, nil } // recover is the handler that turns panics into returns. func (t *Tree) recover(err *error) { if e := recover(); e != nil { *err = e.(error) } } // errorf formats the error and terminates processing. func (t *Tree) errorf(format string, args ...interface{}) { t.Root = nil format = fmt.Sprintf("selector: parse error:%d: %s", t.lex.start, format) panic(fmt.Errorf(format, args...)) } func (t *Tree) parseExpr() BoolExpr { switch t.lex.peek() { case tokenLparen: t.lex.scan() return t.parseGroup() case tokenNot: t.lex.scan() return t.parseNot() } left := t.parseVal() node := t.parseComparison(left) switch t.lex.scan() { case tokenOr: return t.parseOr(node) case tokenAnd: return t.parseAnd(node) case tokenRparen: if t.depth == 0 { t.errorf("unexpected token") return nil } return node default: return node } } func (t *Tree) parseGroup() BoolExpr { t.depth++ node := t.parseExpr() t.depth-- switch t.lex.scan() { case tokenOr: return t.parseOr(node) case tokenAnd: return t.parseAnd(node) case tokenEOF: return node default: t.errorf("unexpected token") return nil } } func (t *Tree) parseAnd(left BoolExpr) BoolExpr { node := new(AndExpr) node.Left = left node.Right = t.parseExpr() return node } func (t *Tree) parseOr(left BoolExpr) BoolExpr { node := new(OrExpr) node.Left = left node.Right = t.parseExpr() return node } func (t *Tree) parseNot() BoolExpr { node := new(NotExpr) node.Expr = t.parseExpr() return node } func (t *Tree) parseComparison(left ValExpr) BoolExpr { var negate bool if t.lex.peek() == tokenNot { t.lex.scan() negate = true } op := t.parseOperator() if negate { switch op { case OperatorIn: op = OperatorNotIn case OperatorGlob: op = OperatorNotGlob case OperatorRe: op = OperatorNotRe case OperatorBetween: op = OperatorNotBetween } } switch op { case OperatorBetween: return t.parseBetween(left) case OperatorNotBetween: return t.parseNotBetween(left) } node := new(ComparisonExpr) node.Left = left node.Operator = op switch node.Operator { case OperatorIn, OperatorNotIn: node.Right = t.parseList() case OperatorRe, OperatorNotRe: // TODO we should use a custom regexp node here that parses and // compiles the regexp, insteam of recompiling on every evaluation. node.Right = t.parseVal() default: node.Right = t.parseVal() } return node } func (t *Tree) parseNotBetween(value ValExpr) BoolExpr { node := new(NotExpr) node.Expr = t.parseBetween(value) return node } func (t *Tree) parseBetween(value ValExpr) BoolExpr { left := new(ComparisonExpr) left.Left = value left.Operator = OperatorGte left.Right = t.parseVal() if t.lex.scan() != tokenAnd { t.errorf("unexpected token, expecting AND") return nil } right := new(ComparisonExpr) right.Left = value right.Operator = OperatorLte right.Right = t.parseVal() node := new(AndExpr) node.Left = left node.Right = right return node } func (t *Tree) parseOperator() (op Operator) { switch t.lex.scan() { case tokenEq: return OperatorEq case tokenGt: return OperatorGt case tokenGte: return OperatorGte case tokenLt: return OperatorLt case tokenLte: return OperatorLte case tokenNeq: return OperatorNeq case tokenIn: return OperatorIn case tokenRegexp: return OperatorRe case tokenGlob: return OperatorGlob case tokenBetween: return OperatorBetween default: t.errorf("illegal operator") return } } func (t *Tree) parseVal() ValExpr { switch t.lex.scan() { case tokenIdent: node := new(Field) node.Name = t.lex.bytes() return node case tokenText: return t.parseText() case tokenReal, tokenInteger, tokenTrue, tokenFalse: node := new(BasicLit) node.Value = t.lex.bytes() return node default: t.errorf("illegal value expression") return nil } } func (t *Tree) parseList() ValExpr { if t.lex.scan() != tokenLparen { t.errorf("unexpected token, expecting (") return nil } node := new(ArrayLit) for { next := t.lex.peek() switch next { case tokenEOF: t.errorf("unexpected eof, expecting )") case tokenComma: t.lex.scan() case tokenRparen: t.lex.scan() return node default: child := t.parseVal() node.Values = append(node.Values, child) } } } func (t *Tree) parseText() ValExpr { node := new(BasicLit) node.Value = t.lex.bytes() // this is where we strip the starting and ending quote // and unescape the string. On the surface this might look // like it is subject to index out of bounds errors but // it is safe because it is already verified by the lexer. node.Value = node.Value[1 : len(node.Value)-1] node.Value = bytes.Replace(node.Value, quoteEscaped, quoteUnescaped, -1) return node } var ( quoteEscaped = []byte("\\'") quoteUnescaped = []byte("'") )
vendor/github.com/woodpecker-ci/expr/parse/parse.go
0.677581
0.488222
parse.go
starcoder
package literally //StringPtr takes a string literal and provides a pointer to it func StringPtr(literal string) *string { return &literal } //BoolPtr takes a bool literal and provides a pointer to it func BoolPtr(literal bool) *bool { return &literal } //BytePtr takes byte literal and provides a pointer to it func BytePtr(literal byte) *byte { return &literal } //RunePtr takes a float64 literal and provides a pointer to it func RunePtr(literal rune) *rune { return &literal } //IntPtr takes a int literal and provides a pointer to it func IntPtr(literal int) *int { return &literal } //Int8Ptr takes a int8 literal and provides a pointer to it func Int8Ptr(literal int8) *int8 { return &literal } //Int16Ptr takes a int16 literal and provides a pointer to it func Int16Ptr(literal int16) *int16 { return &literal } //Int32Ptr takes a int32 literal and provides a pointer to it func Int32Ptr(literal int32) *int32 { return &literal } //Int64Ptr takes a int64 literal and provides a pointer to it func Int64Ptr(literal int64) *int64 { return &literal } //UintPtr takes a uint literal and provides a pointer to it func UintPtr(literal uint) *uint { return &literal } //Uint8Ptr takes a uint8 literal and provides a pointer to it func Uint8Ptr(literal uint8) *uint8 { return &literal } //Uint16Ptr takes a uint16 literal and provides a pointer to it func Uint16Ptr(literal uint16) *uint16 { return &literal } //Uint32Ptr takes a uint32 literal and provides a pointer to it func Uint32Ptr(literal uint32) *uint32 { return &literal } //Uint64Ptr takes a uint64 literal and provides a pointer to it func Uint64Ptr(literal uint64) *uint64 { return &literal } //Float32Ptr takes a float32 literal and provides a pointer to it func Float32Ptr(literal float32) *float32 { return &literal } //Float64Ptr takes a float64 literal and provides a pointer to it func Float64Ptr(literal float64) *float64 { return &literal } //Complex64Ptr takes a complex64 literal and provides a pointer to it func Complex64Ptr(literal complex64) *complex64 { return &literal } //Complex128Ptr takes a complex128 literal and provides a pointer to it func Complex128Ptr(literal complex128) *complex128 { return &literal }
literally.go
0.654011
0.589805
literally.go
starcoder
package internal import ( "fmt" ) //TicTacToe contains the games state. type TicTacToe struct { currentState turns currentWorld world inputAndOutput bool } //NewTicTacToe creates a new instance of the tictactoe game. func NewTicTacToe() *TicTacToe { newTicTacToe := TicTacToe{} newTicTacToe.currentState = &splash{context: &newTicTacToe} newTicTacToe.currentWorld = world{board: make(map[int]Owner)} return &newTicTacToe } //LaunchTicTacToeGame creates a new instance of the tictactoe game. //This instance allows human input and shows output. The game starts //immediately after calling this method. func LaunchTicTacToeGame() { newTicTacToe := TicTacToe{} newTicTacToe.inputAndOutput = true newTicTacToe.currentState = &splash{context: &newTicTacToe} newTicTacToe.currentWorld = world{board: make(map[int]Owner)} fmt.Println("Welcome to TicTacToe CLI, please input anything to start the game.") var trash string _, inputError := fmt.Scan(&trash) if inputError != nil { fmt.Println("Error parsing input, please try again.") LaunchTicTacToeGame() } else { newTicTacToe.NumEntered(1) } } func getInput() int { var input int _, inputError := fmt.Scan(&input) if inputError != nil || input < 1 || input > 9 { fmt.Println("Your input was invalid, please enter an integral number between 1 and 9.") return getInput() } return input } //NumEntered is used for making a turn. func (t *TicTacToe) NumEntered(field int) { t.currentState.numEntered(field) if t.inputAndOutput { t.currentWorld.print() t.NumEntered(getInput()) } } //GetWinner primarily exists for calling it from a unit test func (t *TicTacToe) GetWinner() *Owner { return t.currentWorld.getWinner() } func printEndResult(player Owner) { if player == None { fmt.Println("Noone has won, it is a tie!") } else if player == X { fmt.Println("Player X has won!") } else if player == O { fmt.Println("Player O has won!") } else { fmt.Println("The game is still going, keep fighting fiercly!") } }
internal/ttt.go
0.52975
0.426381
ttt.go
starcoder
// B illuminant conversion functions // Standard Illuminant B is generally similar to D50 and a 5000 K blackbody radiator (actually closer to 4871 K). package white // B illuminant conversion functions // Standard Illuminant B is generally similar to D50 and a 5000 K blackbody radiator (actually closer to 4871 K). // B_A functions func B_A_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.1389718, 0.0771960, -0.1256680}, {0.1046012, 0.9341802, -0.0443668}, {-0.0208883, 0.0324959, 0.4037039}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_A_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0475866, 0.1690489, -0.1272120}, {0.0185688, 0.9847959, -0.0037460}, {0.0000000, 0.0000000, 0.4175516}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_A_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.1087896, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 0.4175516}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_C functions func B_C_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9505386, -0.0254257, 0.0756230}, {-0.0305443, 1.0089768, 0.0249746}, {0.0149704, -0.0250917, 1.3993642}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_C_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9824697, -0.0622785, 0.0817457}, {-0.0068409, 1.0056021, 0.0013790}, {0.0000000, 0.0000000, 1.3873250}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_C_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9899265, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.3873250}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_D50 functions func B_D50_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9850292, -0.0093910, -0.0026720}, {-0.0147751, 1.0146711, -0.0000389}, {-0.0017035, 0.0035957, 0.9660561}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D50_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9951852, -0.0171026, -0.0054296}, {-0.0018786, 1.0015377, 0.0003795}, {0.0000000, 0.0000000, 0.9682949}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D50_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9732518, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 0.9682949}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_D55 functions func B_D55_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9674769, -0.0186924, 0.0199637}, {-0.0265230, 1.0198211, 0.0075752}, {0.0025844, -0.0034696, 1.0823359}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D55_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9890450, -0.0389162, 0.0186211}, {-0.0042747, 1.0034998, 0.0008627}, {0.0000000, 0.0000000, 1.0812691}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D55_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9657825, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.0812691}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_D65 functions func B_D65_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9415037, -0.0321240, 0.0584672}, {-0.0428238, 1.0250998, 0.0203309}, {0.0101511, -0.0161170, 1.2847354}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D65_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9798627, -0.0715373, 0.0601219}, {-0.0078579, 1.0064341, 0.0015850}, {0.0000000, 0.0000000, 1.2776246}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D65_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9593730, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.2776246}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_D75 functions func B_D75_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9232662, -0.0412875, 0.0895406}, {-0.0533960, 1.0269180, 0.0304876}, {0.0164490, -0.0267652, 1.4513087}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D75_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9733376, -0.0947188, 0.0940283}, {-0.0104042, 1.0085195, 0.0020982}, {0.0000000, 0.0000000, 1.4390247}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_D75_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9586160, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.4390247}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_E functions func B_E_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9874297, -0.0056086, 0.0320832}, {-0.0049796, 0.9962653, 0.0101710}, {0.0069424, -0.0120086, 1.1794125}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_E_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9952976, -0.0167072, 0.0359597}, {-0.0018352, 1.0015032, 0.0003695}, {0.0000000, 0.0000000, 1.1733922}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_E_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0093669, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.1733922}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_F2 functions func B_F2_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0237573, 0.0119487, -0.0403007}, {0.0138105, 0.9975484, -0.0131781}, {-0.0081608, 0.0137933, 0.7840861}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_F2_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0084966, 0.0301855, -0.0439590}, {0.0033157, 0.9972846, -0.0006683}, {0.0000000, 0.0000000, 0.7907842}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_F2_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0011507, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 0.7907842}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_F7 functions func B_F7_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9416371, -0.0320617, 0.0581686}, {-0.0427619, 1.0251198, 0.0202354}, {0.0100877, -0.0160079, 1.2830854}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_F7_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9799118, -0.0713629, 0.0597898}, {-0.0078387, 1.0064184, 0.0015812}, {0.0000000, 0.0000000, 1.2760288}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_F7_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {0.9593124, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.2760288}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } // B_F11 functions func B_F11_Bradford(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0400419, 0.0213649, -0.0494410}, {0.0272759, 0.9872237, -0.0167167}, {-0.0092461, 0.0151560, 0.7480426}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_F11_vonKries(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0139654, 0.0496126, -0.0522728}, {0.0054496, 0.9955375, -0.0010989}, {0.0000000, 0.0000000, 0.7550779}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return } func B_F11_Xyz(xs, ys, zs float64) (xd, yd, zd float64) { m := [3][3]float64{ {1.0190770, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 0.7550779}} xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return }
f64/white/b.go
0.625667
0.651189
b.go
starcoder
package gorules import ( "errors" "fmt" "strconv" ) // Value refers to anytype that can be evaluated to a concrete string value type Value interface { Evaluate(interface{}) (string, error) String() string } // Constant is used to hold the string value type Constant struct { value string } // EmptyConstant is the string form of empty Constant value var EmptyConstant = "''" // Evaluate returns the string from the Constant func (c Constant) Evaluate(_ interface{}) (string, error) { if startsWithSingleQuotes(c.value) { return stringBetweenSingleQuotes(c.value), nil } return "", errors.New("Not a Constant") } // String makes Constant implement Stringer func (c Constant) String() string { return c.value } // NewConstant creates new Constant which is within single quotes.Creates an empty string if value has no quotes func NewConstant(value string) Constant { return Constant{value: value} } // Path has the JSON Path. Needs data to be evaluated to the final string value type Path struct { jsonPath string } // Evaluate returns the string from the Constant func (p Path) Evaluate(data interface{}) (string, error) { // fmt.Println(p, data) return selectValue(data.(map[string]interface{}), p.jsonPath).(string), nil } // String makes Path implement Stringer func (p Path) String() string { return p.jsonPath } // NewPath creates new JSON path which can be evaluated with supplied data func NewPath(value string) Path { return Path{jsonPath: value} } // NewValue used to create any of the value type func NewValue(value string) Value { if startsWithSingleQuotes(value) { return NewConstant(value) } else if startsWithPipe(value) { x := spiltWithSpace(stringBetweenPipe(value))[0] if isMathOperator(x) { return NewMathExpression(decodeSpace(stringBetweenPipe(value))) } return NewStringExpression(decodeSpace(stringBetweenPipe(value))) } return NewPath(value) } // MathExpression is used to evaluate mathematical expressions on json values type MathExpression struct { operand1 Value operand2 Value operator MathOperator } //NewMathExpression is a wrapper around MathExpression func NewMathExpression(expression string) MathExpression { parsedOperandsAndOperatorValue := StringSlice(spiltWithSpace(expression)) mathOperator, _ := toMathOperator(parsedOperandsAndOperatorValue.getOrEmpty(0)) return MathExpression{operand1: NewValue(trim(parsedOperandsAndOperatorValue.getOrDefault(1, EmptyConstant))), operand2: NewValue(trim(parsedOperandsAndOperatorValue.getOrDefault(2, EmptyConstant))), operator: mathOperator} } // Evaluate works out the expression and returns the result as a string func (m MathExpression) Evaluate(data interface{}) (string, error) { operand1, _ := m.operand1.Evaluate(data) operand2, _ := m.operand2.Evaluate(data) firstOperand, _ := strconv.Atoi(operand1) secondOperand, _ := strconv.Atoi(operand2) mathOperatorFunc := mathOperatorFuncList[m.operator] result, err := mathOperatorFunc(firstOperand, secondOperand) return strconv.Itoa(result), err } func (m MathExpression) String() string { dummyValue, _ := m.operand1.Evaluate(make([]interface{}, 0)) return dummyValue } // StringExpression is used to evaluate strings expressions on json values type StringExpression struct { operand1 Value operand2 Value operator StringOperator } //NewStringExpression is a wrapper around StringExpression func NewStringExpression(expression string) StringExpression { parsedOperandsAndOperatorValue := StringSlice(spiltWithSpace(expression)) fmt.Println(expression, parsedOperandsAndOperatorValue) stringOperator, _ := toStringOperator(parsedOperandsAndOperatorValue.getOrEmpty(0)) return StringExpression{operand1: NewValue(trim(parsedOperandsAndOperatorValue.getOrDefault(1, EmptyConstant))), operand2: NewValue(trim(parsedOperandsAndOperatorValue.getOrDefault(2, EmptyConstant))), operator: stringOperator} } func (m StringExpression) String() string { dummyValue, _ := m.operand1.Evaluate(make([]interface{}, 0)) return dummyValue } // Evaluate works out the expression and returns the result as a string func (m StringExpression) Evaluate(data interface{}) (string, error) { operand1, _ := m.operand1.Evaluate(data) operand2, _ := m.operand2.Evaluate(data) fmt.Println(operand1, "re", operand2) stringOperatorFunc := stringOperatorFuncList[m.operator] result, err := stringOperatorFunc(operand1, operand2) return result, err }
value.go
0.750644
0.57344
value.go
starcoder
package baseclient import ( "math" "github.com/SOMAS2020/SOMAS2020/internal/common/shared" ) // DisasterInfo defines the disaster location and magnitude. // These disasters will be stored in PastDisastersDict (maps round number to disaster that occurred) // TODO: Agree with environment team on disaster struct representation type DisasterInfo struct { CoordinateX shared.Coordinate CoordinateY shared.Coordinate Magnitude shared.Magnitude Turn uint } // PastDisastersList is a List of previous disasters. type PastDisastersList = []DisasterInfo // MakeDisasterPrediction is called on each client for them to make a prediction about a disaster // Prediction includes location, magnitude, confidence etc // COMPULSORY, you need to implement this method func (c *BaseClient) MakeDisasterPrediction() shared.DisasterPredictionInfo { // Set up dummy disasters for testing purposes pastDisastersList := make(PastDisastersList, 5) for i := 0; i < 4; i++ { pastDisastersList[i] = (DisasterInfo{ CoordinateX: float64(i), CoordinateY: float64(i), Magnitude: float64(i), Turn: uint(i), }) } // Use the sample mean of each field as our prediction meanDisaster := getMeanDisaster(pastDisastersList) prediction := shared.DisasterPrediction{ CoordinateX: meanDisaster.CoordinateX, CoordinateY: meanDisaster.CoordinateY, Magnitude: meanDisaster.Magnitude, TimeLeft: meanDisaster.Turn, } // Use (variance limit - mean(sample variance)), where the mean is taken over each field, as confidence // Use a variance limit of 100 for now varianceLimit := 100.0 prediction.Confidence = determineConfidence(pastDisastersList, meanDisaster, varianceLimit) // For MVP, share this prediction with all islands since trust has not yet been implemented trustedIslands := make([]shared.ClientID, len(shared.TeamIDs)) for index, id := range shared.TeamIDs { trustedIslands[index] = id } // Return all prediction info and store our own island's prediction in global variable predictionInfo := shared.DisasterPredictionInfo{ PredictionMade: prediction, TeamsOfferedTo: trustedIslands, } c.predictionInfo = predictionInfo return predictionInfo } func getMeanDisaster(pastDisastersList PastDisastersList) DisasterInfo { totalCoordinateX, totalCoordinateY, totalMagnitude, totalTurn := 0.0, 0.0, 0.0, 0.0 numberDisastersPassed := float64(len(pastDisastersList)) if numberDisastersPassed == 0 { return DisasterInfo{0, 0, 0, 1000} } for _, disaster := range pastDisastersList { totalCoordinateX += disaster.CoordinateX totalCoordinateY += disaster.CoordinateY totalMagnitude += float64(disaster.Magnitude) totalTurn += float64(disaster.Turn) } meanDisaster := DisasterInfo{ CoordinateX: totalCoordinateX / numberDisastersPassed, CoordinateY: totalCoordinateY / numberDisastersPassed, Magnitude: totalMagnitude / numberDisastersPassed, Turn: uint(math.Round(totalTurn / numberDisastersPassed)), } return meanDisaster } func determineConfidence(pastDisastersList PastDisastersList, meanDisaster DisasterInfo, varianceLimit float64) float64 { totalDisaster := DisasterInfo{} numberDisastersPassed := float64(len(pastDisastersList)) // Find the sum of the square of the difference between the actual and mean, for each field for _, disaster := range pastDisastersList { totalDisaster.CoordinateX += math.Pow(disaster.CoordinateX-meanDisaster.CoordinateX, 2) totalDisaster.CoordinateY += math.Pow(disaster.CoordinateY-meanDisaster.CoordinateY, 2) totalDisaster.Magnitude += math.Pow(disaster.Magnitude-meanDisaster.Magnitude, 2) totalDisaster.Turn += uint(math.Round(math.Pow(float64(disaster.Turn-meanDisaster.Turn), 2))) } // Find the sum of the variances and the average variance varianceSum := (totalDisaster.CoordinateX + totalDisaster.CoordinateY + totalDisaster.Magnitude + float64(totalDisaster.Turn)) / numberDisastersPassed averageVariance := varianceSum / 4 // Implement the variance cap chosen if averageVariance > varianceLimit { averageVariance = varianceLimit } // Return the confidence of the prediction return math.Round(varianceLimit - averageVariance) } // ReceiveDisasterPredictions provides each client with the prediction info, in addition to the source island, // that they have been granted access to see // COMPULSORY, you need to implement this method func (c *BaseClient) ReceiveDisasterPredictions(receivedPredictions shared.ReceivedDisasterPredictionsDict) { // If we assume that we trust each island equally (including ourselves), then take the final prediction // of disaster as being the weighted mean of predictions according to confidence numberOfPredictions := float64(len(receivedPredictions) + 1) selfConfidence := c.predictionInfo.PredictionMade.Confidence // Initialise running totals using our own island's predictions totalCoordinateX := selfConfidence * c.predictionInfo.PredictionMade.CoordinateX totalCoordinateY := selfConfidence * c.predictionInfo.PredictionMade.CoordinateY totalMagnitude := selfConfidence * c.predictionInfo.PredictionMade.Magnitude totalTimeLeft := uint(math.Round(selfConfidence)) * c.predictionInfo.PredictionMade.TimeLeft totalConfidence := selfConfidence // Add other island's predictions using their confidence values for _, prediction := range receivedPredictions { totalCoordinateX += prediction.PredictionMade.Confidence * prediction.PredictionMade.CoordinateX totalCoordinateY += prediction.PredictionMade.Confidence * prediction.PredictionMade.CoordinateY totalMagnitude += prediction.PredictionMade.Confidence * prediction.PredictionMade.Magnitude totalTimeLeft += uint(math.Round(prediction.PredictionMade.Confidence)) * prediction.PredictionMade.TimeLeft totalConfidence += prediction.PredictionMade.Confidence } // Finally get the final prediction generated by considering predictions from all islands that we have available // This result is currently unused but would be used in decision making in full implementation finalPrediction := shared.DisasterPrediction{ CoordinateX: totalCoordinateX / totalConfidence, CoordinateY: totalCoordinateY / totalConfidence, Magnitude: totalMagnitude / totalConfidence, TimeLeft: uint((float64(totalTimeLeft) / totalConfidence) + 0.5), Confidence: totalConfidence / numberOfPredictions, } c.Logf("Final Prediction: [%v]", finalPrediction) } // MakeForageInfo allows clients to share their most recent foraging DecisionMade, ResourceObtained from it to // other clients. // OPTIONAL. If this is not implemented then all values are nil. func (c *BaseClient) MakeForageInfo() shared.ForageShareInfo { contribution := shared.ForageDecision{Type: shared.DeerForageType, Contribution: 0} return shared.ForageShareInfo{DecisionMade: contribution, ResourceObtained: 0, ShareTo: []shared.ClientID{}} } // ReceiveForageInfo lets clients know what other clients has obtained from their most recent foraging attempt. // Most recent foraging attempt includes information about: foraging DecisionMade and ResourceObtained as well // as where this information came from. // OPTIONAL. func (c *BaseClient) ReceiveForageInfo(neighbourForaging []shared.ForageShareInfo) { // Return on Investment roi := map[shared.ClientID]shared.Resources{} for _, val := range neighbourForaging { if val.DecisionMade.Type == shared.DeerForageType { roi[val.SharedFrom] = val.ResourceObtained / shared.Resources(val.DecisionMade.Contribution) * 100 } } }
internal/common/baseclient/iifo.go
0.641647
0.427636
iifo.go
starcoder
package core import ( "github.com/pingcap/errors" "github.com/pingcap/tidb/planner/property" ) // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *basePhysicalPlan) GetPlanCost(taskType property.TaskType) (float64, error) { if p.planCostInit { // just calculate the cost once and always reuse it return p.planCost, nil } p.planCost = 0 // the default implementation, the operator have no cost for _, child := range p.children { childCost, err := child.GetPlanCost(taskType) if err != nil { return 0, err } p.planCost += childCost } p.planCostInit = true return p.planCost, nil } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalSelection) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalProjection) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalIndexLookUpReader) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalIndexReader) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalTableReader) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalIndexMergeReader) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalTableScan) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalIndexScan) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalIndexJoin) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalIndexHashJoin) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalIndexMergeJoin) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalApply) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalMergeJoin) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalHashJoin) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalStreamAgg) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalHashAgg) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalSort) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalTopN) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *BatchPointGetPlan) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PointGetPlan) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalUnionAll) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") } // GetPlanCost calculates the cost of the plan if it has not been calculated yet and returns the cost. func (p *PhysicalExchangeReceiver) GetPlanCost(taskType property.TaskType) (float64, error) { return 0, errors.New("not implemented") }
planner/core/plan_cost.go
0.765067
0.474875
plan_cost.go
starcoder
package linkedlist // demonstration of singly linked list in golang import ( "errors" "fmt" ) // Singly structure with length of the list and its head type Singly struct { length int // Note that Node here holds both Next and Prev Node // however only the Next node is used in Singly methods. Head *Node } // NewSingly returns a new instance of a linked list func NewSingly() *Singly { return &Singly{} } // AddAtBeg adds a new snode with given value at the beginning of the list. func (ll *Singly) AddAtBeg(val interface{}) { n := NewNode(val) n.Next = ll.Head ll.Head = n ll.length++ } // AddAtEnd adds a new snode with given value at the end of the list. func (ll *Singly) AddAtEnd(val interface{}) { n := NewNode(val) if ll.Head == nil { ll.Head = n ll.length++ return } cur := ll.Head for ; cur.Next != nil; cur = cur.Next { } cur.Next = n ll.length++ } // DelAtBeg deletes the snode at the head(beginning) of the list and returns its value. Returns -1 if the list is empty. func (ll *Singly) DelAtBeg() interface{} { if ll.Head == nil { return -1 } cur := ll.Head ll.Head = cur.Next ll.length-- return cur.Val } // DelAtEnd deletes the snode at the tail(end) of the list and returns its value. Returns -1 if the list is empty. func (ll *Singly) DelAtEnd() interface{} { if ll.Head == nil { return -1 } if ll.Head.Next == nil { return ll.DelAtBeg() } cur := ll.Head for ; cur.Next.Next != nil; cur = cur.Next { } retval := cur.Next.Val cur.Next = nil ll.length-- return retval } // Count returns the current size of the list. func (ll *Singly) Count() int { return ll.length } // Reverse reverses the list. func (ll *Singly) Reverse() { var prev, Next *Node cur := ll.Head for cur != nil { Next = cur.Next cur.Next = prev prev = cur cur = Next } ll.Head = prev } // ReversePartition Reverse the linked list from the ath to the bth node func (ll *Singly) ReversePartition(left, right int) error { err := ll.CheckRangeFromIndex(left, right) if err != nil { return err } tmpNode := NewNode(-1) tmpNode.Next = ll.Head pre := tmpNode for i := 0; i < left-1; i++ { pre = pre.Next } cur := pre.Next for i := 0; i < right-left; i++ { next := cur.Next cur.Next = next.Next next.Next = pre.Next pre.Next = next } ll.Head = tmpNode.Next return nil } func (ll *Singly) CheckRangeFromIndex(left, right int) error { if left > right { return errors.New("left boundary must smaller than right") } else if left < 1 { return errors.New("left boundary starts from the first node") } else if right > ll.length { return errors.New("right boundary cannot be greater than the length of the linked list") } return nil } // Display prints out the elements of the list. func (ll *Singly) Display() { for cur := ll.Head; cur != nil; cur = cur.Next { fmt.Print(cur.Val, " ") } fmt.Print("\n") }
structure/linkedlist/singlylinkedlist.go
0.649467
0.450541
singlylinkedlist.go
starcoder
package common import ( "math" "math/rand" ) const ( perlinYwrapb = 4 perlinYwrap = 1 << perlinYwrapb perlinZwrapb = 8 perlinZwrap = 1 << perlinZwrapb perlinSize = 4095 perlinOctaves = 4 perlinAmpFalloff = 0.5 ) // PerlinNoise is a perline noise struct to generate perlin noise. type PerlinNoise struct { perlin []float64 } // NewPerlinNoise returns a PerlinNoise object. func NewPerlinNoise() *PerlinNoise { perlin := &PerlinNoise{perlin: nil} perlin.perlin = make([]float64, perlinSize+1) for i, _ := range perlin.perlin { perlin.perlin[i] = rand.Float64() } return perlin } // Noise1D returns a float noise number on one dimension. func (p *PerlinNoise) Noise1D(x float64) float64 { return p.noise(x, 0, 0) } // Noise1D returns a float noise number on two dimensions. func (p *PerlinNoise) Noise2D(x, y float64) float64 { return p.noise(x, y, 0) } // Noise1D returns a float noise number on three dimensions. func (p *PerlinNoise) Noise3D(x, y, z float64) float64 { return p.noise(x, y, z) } func (p *PerlinNoise) noise(x, y, z float64) float64 { if x < 0 { x = -x } if y < 0 { y = -y } if z < 0 { z = -z } xi, yi, zi := int(math.Floor(x)), int(math.Floor(y)), int(math.Floor(z)) xf, yf, zf := x-float64(xi), y-float64(yi), z-float64(zi) var rxf, ryf, n1, n2, n3 float64 var r float64 var ampl float64 = 0.5 for o := 0; o < perlinOctaves; o++ { of := xi + (yi << perlinYwrapb) + (zi << perlinZwrapb) rxf = scaledCosin(xf) ryf = scaledCosin(yf) n1 = p.perlin[of&perlinSize] n1 += rxf * (p.perlin[(of+1)&perlinSize] - n1) n2 = p.perlin[(of+perlinYwrap)&perlinSize] n2 += rxf * (p.perlin[(of+perlinYwrap+1)&perlinSize] - n2) n1 += ryf * (n2 - n1) of += perlinZwrap n2 = p.perlin[of&perlinSize] n2 += rxf * (p.perlin[(of+1)&perlinSize] - n2) n3 = p.perlin[(of+perlinYwrap)&perlinSize] n3 += rxf * (p.perlin[(of+perlinYwrap+1)&perlinSize] - n3) n2 += ryf * (n3 - n2) n1 += scaledCosin(zf) * (n2 - n1) r += n1 * ampl ampl *= perlinAmpFalloff xi <<= 1 xf *= 2 yi <<= 1 yf *= 2 zi <<= 1 zf *= 2 if xf >= 1.0 { xi += 1 xf -= 1 } if yf >= 1.0 { yi += 1 yf -= 1 } if zf >= 1.0 { zi += 1 zf -= 1 } } return r } func scaledCosin(x float64) float64 { return 0.5 * (1.0 - math.Cos(x*math.Pi)) }
common/perlinnoise.go
0.776708
0.407039
perlinnoise.go
starcoder
package game import ( "log" "math/rand" "time" ) //Level represents one level of the dungeon type Level struct { cells Cells rooms []*Room monsters []*Monster prevFloorX int prevFloorY int nextFloorX int nextFloorY int } //Cells is a type for a double array of cells type Cells [][]Cell func (c Cells) get(x, y int) *Cell { return &c[y][x] } func (c Cells) set(x, y int, cell Cell) { c[y][x] = cell } //Cell represents a single cell or tile in the level type Cell struct { content rune visible bool } //Recommended max size is 80x24. 0-based indexing. Allow bottom row for text and one spacer. const maxX int = 79 const maxY int = 19 const minRoomSize = 4 const maxRoomSize = 10 const numAttemptRooms = 20 var levelRand *rand.Rand // NewLevel generates the level func NewLevel(levelNum int) *Level { levelRand = rand.New(rand.NewSource(time.Now().UnixNano())) cells := make(Cells, maxY+1) //+1 needed because maxX, maxY are 0-based for i := range cells { cells[i] = make([]Cell, maxX+1) for j := range cells[i] { cells[i][j] = Cell{ content: WALL, visible: false, } } } rooms := generateRooms() for i, r := range rooms { log.Printf("Generated room #%d: %+v\n", i, r) } convertRoomsToCells(rooms, &cells) for i := 0; i < len(rooms)-1; i++ { r1x, r1y := rooms[i].getCenter() r2x, r2y := rooms[i+1].getCenter() generateTunnel(r1x, r1y, r2x, r2y, &cells) } prevFloorX, prevFloorY := rooms[0].getCenter() var nextFloorX, nextFloorY int for { roomPos := random(0, len(rooms), levelRand) nextFloorX, nextFloorY = rooms[roomPos].getPointInRoom() if nextFloorX != prevFloorX || nextFloorY != prevFloorY { break } } prevFloorCell := cells.get(prevFloorX, prevFloorY) prevFloorCell.content = FLOOR_PREV if levelNum < numLevels-1 { nextFloorCell := cells.get(nextFloorX, nextFloorY) nextFloorCell.content = FLOOR_NEXT } monsters := generateMonsters(rooms, prevFloorX, prevFloorY, levelNum) handleFinalRoom(rooms, monsters, &cells, prevFloorX, prevFloorY, levelNum) return &Level{ cells: cells, rooms: rooms, monsters: monsters, prevFloorX: prevFloorX, prevFloorY: prevFloorY, nextFloorX: nextFloorX, nextFloorY: nextFloorY, } } func (l *Level) roomContainsPoint(x, y int) *Room { for _, r := range l.rooms { if r.pointIntersects(x, y) { return r } } return nil } //Room represents a single room within a level type Room struct { x1 int y1 int x2 int y2 int } func (r *Room) getCenter() (int, int) { return (r.x1 + r.x2) / 2, (r.y1 + r.y2) / 2 } func (r *Room) intersects(r2 *Room) bool { return (r.x1 <= r2.x2 && r.x2 >= r2.x1 && r.y1 <= r2.y2 && r.y2 >= r2.y1) } func (r *Room) pointIntersects(x, y int) bool { //Do not check equals because we don't want to intersect when we are along a wall return x > r.x1 && x < r.x2 && y > r.y1 && y < r.y2 } func (r *Room) getPointInRoom() (x, y int) { width := r.x2 - r.x1 - 2 //The -2 is because our width and height includes walls, which we don't want height := r.y2 - r.y1 - 2 pos := levelRand.Intn(width * height) x = r.x1 + 1 + (pos % width) y = r.y1 + 1 + (pos / width) return } func convertRoomsToCells(rooms []*Room, cells *Cells) { for _, room := range rooms { for x := room.x1 + 1; x < room.x2; x++ { for y := room.y1 + 1; y < room.y2; y++ { c := Cell{ content: FLOOR, visible: false, } cells.set(x, y, c) } } } } func generateRooms() []*Room { rooms := make([]*Room, 0) for i := 0; i < numAttemptRooms; i++ { x1 := random(0, maxX-minRoomSize, levelRand) y1 := random(0, maxY-minRoomSize, levelRand) x2 := min(maxX, x1+random(minRoomSize, maxRoomSize, levelRand)) y2 := min(maxY, y1+random(minRoomSize, maxRoomSize, levelRand)) r := &Room{ x1: x1, y1: y1, x2: x2, y2: y2, } //Check if intersects any already added room intersects := false for _, existingRoom := range rooms { if r.intersects(existingRoom) { intersects = true continue } } if intersects { continue } rooms = append(rooms, r) } return rooms } func generateTunnel(x1, y1, x2, y2 int, cells *Cells) { if x1 == x2 { log.Printf("Generating only vertical tunnel from (%d, %d) to (%d, %d)\n", x1, y1, x2, y2) generateVertTunnel(x1, y1, y2, cells) return } if y1 == y2 { log.Printf("Generating only horizontal tunnel from (%d, %d) to (%d, %d)\n", x1, y1, x2, y2) generateHorizTunnel(x1, x2, y1, cells) return } dir := levelRand.Intn(2) if dir == 0 { log.Printf("Generating first horizontal tunnel from (%d, %d) to (%d, %d); then vertical from (%d, %d) to (%d, %d)\n", x1, y1, x2, y1, x2, y1, x2, y2) generateHorizTunnel(x1, x2, y1, cells) generateVertTunnel(x2, y1, y2, cells) } else { log.Printf("Generating first vertical tunnel from (%d, %d) to (%d, %d); then horizontal from (%d, %d) to (%d, %d)\n", x1, y1, x1, y2, x1, y2, x2, y2) generateVertTunnel(x1, y1, y2, cells) generateHorizTunnel(x1, x2, y2, cells) } } func generateHorizTunnel(x1, x2, y int, cells *Cells) { if x1 > x2 { x1, x2 = x2, x1 } for i := x1; i <= x2; i++ { cells.set(i, y, Cell{ content: FLOOR, visible: false, }) } } func generateVertTunnel(x, y1, y2 int, cells *Cells) { if y1 > y2 { y1, y2 = y2, y1 } for i := y1; i <= y2; i++ { cells.set(x, i, Cell{ content: FLOOR, visible: false, }) } } func generateMonsters(rooms []*Room, startX, startY, levelNum int) []*Monster { allMonsters := make([]*Monster, 0) for rIndex, r := range rooms { roomMonsters := getMonstersForRoom(levelNum) for i := 0; i < len(roomMonsters); i++ { roomMonsters[i].room = r roomMonsters[i].x, roomMonsters[i].y = r.getPointInRoom() monsterPosHasConflict := false for j := 0; j < i; j++ { if roomMonsters[j].x == roomMonsters[i].x && roomMonsters[j].y == roomMonsters[i].y { monsterPosHasConflict = true break } } if roomMonsters[i].x == startX && roomMonsters[i].y == startY { monsterPosHasConflict = true } if monsterPosHasConflict { i-- //Try again to generate this position } else { log.Printf("Added monster %s in room %d at position (%d, %d) \n", roomMonsters[i].name, rIndex, roomMonsters[i].x, roomMonsters[i].y) } } allMonsters = append(allMonsters, roomMonsters...) } return allMonsters } func getMonstersForRoom(levelNum int) []*Monster { num := levelRand.Intn(100) if levelNum == 0 { switch { case num < 30: return []*Monster{} case num < 50: return []*Monster{NewMonster(Page)} case num < 70: return []*Monster{NewMonster(Page), NewMonster(Page)} case num < 90: return []*Monster{NewMonster(Page), NewMonster(Page), NewMonster(Page)} default: return []*Monster{NewMonster(Page), NewMonster(Squire)} } } else if levelNum == 1 { switch { case num < 10: return []*Monster{} case num < 20: return []*Monster{NewMonster(Page), NewMonster(Page)} case num < 50: return []*Monster{NewMonster(Squire)} case num < 70: return []*Monster{NewMonster(Squire), NewMonster(Squire)} case num < 90: return []*Monster{NewMonster(Squire), NewMonster(Squire), NewMonster(Squire)} default: return []*Monster{NewMonster(Squire), NewMonster(Knight)} } } else if levelNum == 2 { switch { case num < 10: return []*Monster{} case num < 50: return []*Monster{NewMonster(Knight)} case num < 70: return []*Monster{NewMonster(Knight), NewMonster(Knight)} default: return []*Monster{NewMonster(Knight), NewMonster(Knight), NewMonster(Knight)} } } return []*Monster{} } func handleFinalRoom(rooms []*Room, monsters []*Monster, cells *Cells, startX, startY, levelNum int) { if levelNum != numLevels-1 { return } finalRoom := getFurthestRoomFromPoint(rooms, startX, startY) for i := 0; i < len(monsters); i++ { if monsters[i].room == finalRoom { monsters = append(monsters[:i], monsters[i+1:]...) } } x, y := finalRoom.getCenter() cells.set(x, y, Cell{ content: CHALICE, visible: false, }) commander := NewMonster(Commander) commander.x, commander.y = finalRoom.getPointInRoom() commander.room = finalRoom monsters = append(monsters, commander) } func getFurthestRoomFromPoint(rooms []*Room, x, y int) *Room { if rooms == nil || len(rooms) == 0 { return nil } maxDistance := -1.0 var furthestRoom *Room for _, r := range rooms { roomX, roomY := r.getCenter() distance := distance(x, y, roomX, roomY) if distance > maxDistance { maxDistance = distance furthestRoom = r } } return furthestRoom }
game/level.go
0.590189
0.433802
level.go
starcoder
package match import ( "fmt" "net/http" pandascore "github.com/vahill-corp/pandascore-go" ) // Match resources is the interface on the library to interact with the match section of the pandascore API. // More info here : https://developers.pandascore.co/doc/#tag/Matches type Match struct { Backend *pandascore.Backend } // List is returning matches as described here : https://developers.pandascore.co/doc/#tag/Matches func (m *Match) List(params *pandascore.MatchListParams) ([]pandascore.Match, error) { if params == nil { params = &pandascore.MatchListParams{ // In case no parameters are given, we want to find results for all games. VideoGame: pandascore.VideoGameAll, } } path := fmt.Sprintf("%s/", params.VideoGame.GetURLPath()) matchesResponse := make([]pandascore.Match, 0) err := m.Backend.Call(http.MethodGet, path, params, &matchesResponse) return matchesResponse, err } // ListPast is returning matches as described here : https://developers.pandascore.co/doc/#tag/Matches func (m *Match) ListPast(params *pandascore.MatchListParams) ([]pandascore.Match, error) { if params == nil { params = &pandascore.MatchListParams{ // In case no parameters are given, we want to find results for all games. VideoGame: pandascore.VideoGameAll, } } path := fmt.Sprintf("%s/matches/past", params.VideoGame.GetURLPath()) matchesResponse := make([]pandascore.Match, 0) err := m.Backend.Call(http.MethodGet, path, params, &matchesResponse) return matchesResponse, err } // ListRunning is returning matches as described here : https://developers.pandascore.co/doc/#tag/Matches func (m *Match) ListRunning(params *pandascore.MatchListParams) ([]pandascore.Match, error) { if params == nil { params = &pandascore.MatchListParams{ // In case no parameters are given, we want to find results for all games. VideoGame: pandascore.VideoGameAll, } } path := fmt.Sprintf("%s/matches/running", params.VideoGame.GetURLPath()) matchesResponse := make([]pandascore.Match, 0) err := m.Backend.Call(http.MethodGet, path, params, &matchesResponse) return matchesResponse, err } // ListUpcoming is returning matches as described here : https://developers.pandascore.co/doc/#tag/Matches func (m *Match) ListUpcoming(params *pandascore.MatchListParams) ([]pandascore.Match, error) { if params == nil { params = &pandascore.MatchListParams{ // In case no parameters are given, we want to find results for all games. VideoGame: pandascore.VideoGameAll, } } path := fmt.Sprintf("%s/matches/upcoming", params.VideoGame.GetURLPath()) matchesResponse := make([]pandascore.Match, 0) err := m.Backend.Call(http.MethodGet, path, params, &matchesResponse) return matchesResponse, err } // GetByID returns a match using the ID given as parameter. func (m *Match) GetByID(ID int) (*pandascore.Match, error) { matchResponse := &pandascore.Match{} err := m.Backend.Call(http.MethodGet, fmt.Sprintf("/matches/%d", ID), &pandascore.EmptyParams{}, matchResponse) return matchResponse, err } // GetMatchOpponents returns a match's opponents using the ID given as parameter. func (m *Match) GetMatchOpponents(MatchID int) (*pandascore.MatchOpponents, error) { opponentsResponse := &pandascore.MatchOpponents{} err := m.Backend.Call(http.MethodGet, fmt.Sprintf("/matches/%d/opponents", MatchID), &pandascore.EmptyParams{}, opponentsResponse) return opponentsResponse, err }
match/client.go
0.647464
0.417331
client.go
starcoder
package flows import ( "analysis/flows" "time" ) type MetricFlowRate struct { // Sampling rate in milliseconds. If equal to zero the // average over the entirety of the flow will be calculated. samplingRate int64 } func newMetricFlowRate() *MetricFlowRate { return &MetricFlowRate{} } func (mfr *MetricFlowRate) calc(flow *flows.Flow) ValueFlowRate { var flowRates []uint var flowRatesClient []uint var flowRatesServer []uint size := 0 sizeClient := 0 sizeServer := 0 packets := flow.Packets sampleTimespan := time.Millisecond.Nanoseconds() * mfr.samplingRate sampleSeconds := float64(sampleTimespan) / float64(time.Second.Nanoseconds()) start := packets[0].Timestamp nextSampleStart := start + sampleTimespan for i := 0; i < len(packets); i++ { p := packets[i] payloadLength := int(p.LengthPayload) if p.Timestamp >= nextSampleStart { nextSampleStart += sampleTimespan flowRates = append(flowRates, uint(float64(size)/sampleSeconds)) flowRatesClient = append(flowRatesClient, uint(float64(sizeClient)/sampleSeconds)) flowRatesServer = append(flowRatesServer, uint(float64(sizeServer)/sampleSeconds)) size = payloadLength sizeClient = 0 sizeServer = 0 if p.FromClient { sizeClient = payloadLength } else { sizeServer = payloadLength } } else { size += payloadLength if p.FromClient { sizeClient += payloadLength } else { sizeServer += payloadLength } } } flowRates = append(flowRates, uint(float64(size)/sampleSeconds)) flowRatesClient = append(flowRatesClient, uint(float64(sizeClient)/sampleSeconds)) flowRatesServer = append(flowRatesServer, uint(float64(sizeServer)/sampleSeconds)) return ValueFlowRate{ flowRates: flowRates, flowRatesClient: flowRatesClient, flowRatesServer: flowRatesServer, } } func (mfr *MetricFlowRate) calcAverage(flow *flows.Flow) ValueFlowRate { var flowRates []uint var flowRatesClient []uint var flowRatesServer []uint size := 0 sizeClient := 0 sizeServer := 0 packets := flow.Packets for i := 0; i < len(packets); i++ { p := packets[i] payloadLength := int(p.LengthPayload) size += payloadLength if p.FromClient { sizeClient += payloadLength } else { sizeServer += payloadLength } } start := packets[0].Timestamp end := packets[len(packets)-1].Timestamp seconds := float64(end-start) / float64(time.Second.Nanoseconds()) if seconds == 0 { seconds = 1 } flowRates = append(flowRates, uint(float64(size)/seconds)) flowRatesClient = append(flowRatesClient, uint(float64(sizeClient)/seconds)) flowRatesServer = append(flowRatesServer, uint(float64(sizeServer)/seconds)) return ValueFlowRate{ flowRates: flowRates, flowRatesClient: flowRatesClient, flowRatesServer: flowRatesServer, } } func (mfr *MetricFlowRate) onFlush(flow *flows.Flow) ExportableValue { var value ValueFlowRate if mfr.samplingRate == 0 { value = mfr.calcAverage(flow) } else { value = mfr.calc(flow) } return value } type ValueFlowRate struct { // All rates observed in a flow. flowRates []uint // All upstream rates observed in a flow. flowRatesClient []uint // All downstream rates observed in a flow. flowRatesServer []uint } func (vfr ValueFlowRate) export() map[string]interface{} { return map[string]interface{}{ "flowRates": vfr.flowRates, "flowRatesClient": vfr.flowRatesClient, "flowRatesServer": vfr.flowRatesServer, } }
src/analysis/metrics/flows/FlowRate.go
0.750918
0.514705
FlowRate.go
starcoder
package graph import ( "container/list" "fmt" "github.com/DmitryBogomolov/algorithms/graph/internal/utils" ) // Paths is a collection of paths from the source vertex to other vertices. // A path is a sequence of vertices connected by edges. type Paths struct { sourceVertex int vertexCount int edgeTo []int } func initPaths(gr Graph, vertexID int) Paths { count := gr.NumVertices() edgeTo := make([]int, count) utils.ResetList(edgeTo) return Paths{ sourceVertex: vertexID, vertexCount: 0, edgeTo: edgeTo, } } // SourceVertex gets source vertex. func (paths Paths) SourceVertex() int { return paths.sourceVertex } // VertexCount gets number of vertices connected with source vertex. func (paths Paths) VertexCount() int { return paths.vertexCount } // HasPathTo tells if a vertex is connected with source vertex. func (paths Paths) HasPathTo(vertexID int) bool { if vertexID < 0 || vertexID > len(paths.edgeTo)-1 { panic(fmt.Sprintf("vertex '%d' is out of range", vertexID)) } return paths.edgeTo[vertexID] >= 0 || vertexID == paths.sourceVertex } // PathTo returns path from source vertex to a vertex. func (paths Paths) PathTo(vertexID int) []int { if !paths.HasPathTo(vertexID) { return nil } var stack []int for currentVertexID := vertexID; currentVertexID >= 0; currentVertexID = paths.edgeTo[currentVertexID] { stack = append(stack, currentVertexID) } utils.ReverseList(stack) return stack } type _SearchPathsVisitor interface { searchPathsVisit(vertexID int, parentVertexID int) } func searchPathsDepthFirstCore(gr Graph, marked []bool, visitor _SearchPathsVisitor, vertexID int) { marked[vertexID] = true for _, adjacentVertexID := range gr.AdjacentVertices(vertexID) { if !marked[adjacentVertexID] { visitor.searchPathsVisit(adjacentVertexID, vertexID) searchPathsDepthFirstCore(gr, marked, visitor, adjacentVertexID) } } } func searchPathsDepthFirst(gr Graph, visitor _SearchPathsVisitor, vertexID int) { marked := make([]bool, gr.NumVertices()) searchPathsDepthFirstCore(gr, marked, visitor, vertexID) } func (paths *Paths) searchPathsVisit(vertexID int, parentVertexID int) { paths.vertexCount++ paths.edgeTo[vertexID] = parentVertexID } // FindPathsDepthFirst returns paths from a vertex using depth-first search. // https://algs4.cs.princeton.edu/41graph/DepthFirstSearch.java.html func FindPathsDepthFirst(gr Graph, vertexID int) Paths { paths := initPaths(gr, vertexID) searchPathsDepthFirst(gr, &paths, vertexID) return paths } func searchPathsBreadthFirstCore(gr Graph, marked []bool, queue *list.List, visitor _SearchPathsVisitor) { for queue.Len() > 0 { vertexID := queue.Front().Value.(int) queue.Remove(queue.Front()) for _, adjacentVertexID := range gr.AdjacentVertices(vertexID) { if !marked[adjacentVertexID] { marked[adjacentVertexID] = true queue.PushBack(adjacentVertexID) visitor.searchPathsVisit(adjacentVertexID, vertexID) } } } } func searchPathsBreadthFirst(gr Graph, visitor _SearchPathsVisitor, vertexID int) { marked := make([]bool, gr.NumVertices()) queue := list.New() queue.PushBack(vertexID) marked[vertexID] = true searchPathsBreadthFirstCore(gr, marked, queue, visitor) } // FindPathsBreadthFirst returns paths from a vertex using breadth-first search. // https://algs4.cs.princeton.edu/41graph/BreadthFirstPaths.java.html func FindPathsBreadthFirst(gr Graph, vertexID int) Paths { paths := initPaths(gr, vertexID) searchPathsBreadthFirst(gr, &paths, vertexID) return paths }
graph/graph/paths.go
0.812496
0.50952
paths.go
starcoder
package psbt // The Creator has only one function: // takes a list of inputs and outputs and converts them to // the simplest Psbt, i.e. one with no data appended to inputs or outputs, // but only the raw unsigned transaction in the global section. import ( "github.com/btcsuite/btcd/wire" ) // Creator holds a reference to a created Psbt struct. type Creator struct { Cpsbt *Psbt } // CreatePsbt , on provision of an input and output 'skeleton' for // the transaction, returns a Creator struct. // Note that we require OutPoints and not TxIn structs, as we will // only populate the txid:n information, *not* any scriptSig/witness // information. The values of nLockTime, nSequence (per input) and // transaction version (must be 1 of 2) must be specified here. Note // that the default nSequence value is wire.MaxTxInSequenceNum. func (c *Creator) CreatePsbt(inputs []*wire.OutPoint, outputs []*wire.TxOut, Version int32, nLockTime uint32, nSequences []uint32) error { // Create the new struct; the input and output lists will be empty, // the unsignedTx object must be constructed and serialized, // and that serialization should be entered as the only entry for // the globalKVPairs list. // Check the version is a valid Bitcoin tx version; the nLockTime // can be any valid uint32. There must be one sequence number per // input. if !(Version == 1 || Version == 2) || len(nSequences) != len(inputs) { return ErrInvalidPsbtFormat } unsignedTx := wire.NewMsgTx(Version) unsignedTx.LockTime = nLockTime for i, in := range inputs { unsignedTx.AddTxIn(&wire.TxIn{ PreviousOutPoint: *in, Sequence: nSequences[i], }) } for _, out := range outputs { unsignedTx.AddTxOut(out) } // The input and output lists are empty, but there is a list of those // two lists, and each one must be of length matching the unsigned // transaction; the unknown list can be nil. pInputs := make([]PInput, len(unsignedTx.TxIn)) pOutputs := make([]POutput, len(unsignedTx.TxOut)) c.Cpsbt = &Psbt{ UnsignedTx: unsignedTx, Inputs: pInputs, Outputs: pOutputs, Unknowns: nil, } // This new Psbt is "raw" and contains no key-value fields, // so sanity checking with c.Cpsbt.SanityCheck() is not required. return nil }
psbt/creator.go
0.570212
0.445047
creator.go
starcoder
package main import ( "bufio" "errors" "fmt" "os" "strconv" "time" ) type Puzzle [][]Tile // NewPuzzle returns a blank puzzle with the specified length and width func NewPuzzle(length, width int) Puzzle { p := make(Puzzle, width) for y := 0; y < width; y++ { p[y] = make([]Tile, length) for x := range p[y] { p[y][x] = NewTile(0) } } return p } // LoadPuzzle reads a QQWing formatted Sudoku board from a text file into a // Puzzle value in memory func LoadPuzzle(path string) (Puzzle, error) { puzz := NewPuzzle(boardDiameter, boardDiameter) file, err := os.Open(path) defer file.Close() if err != nil { return puzz, fmt.Errorf("Fatal error opening QQWing puzzle text file: %w", err) } lines := bufio.NewScanner(file) tileY := 0 for lines.Scan() { line := lines.Bytes() if tileY >= len(puzz) { return puzz, errors.New("Inputted puzzle has too many rows") } tileX := 0 for _, char := range line { if tileX >= len(puzz[0]) { return puzz, errors.New("Inputted puzzle has too many columns") } var value int if char == '.' { value = blank } else if char < '0' || char > '9' { continue } else { value, err = strconv.Atoi(string(char)) if err != nil { return puzz, fmt.Errorf( "Error converting ASCII character to a valid Sudoku value: %w", err, ) } } tile := NewTile(value) puzz.SetTile(tileX, tileY, &tile) tileX++ } if tileX > 0 { tileY++ } } if lines.Err() != nil { return puzz, fmt.Errorf("Fatal error reading QQWing puzzle text file: %w", lines.Err()) } return puzz, nil } // Tile returns the Tile at the specified x and y func (p Puzzle) Tile(x, y int) *Tile { return &p[y][x] } func (p Puzzle) SetTile(x, y int, t *Tile) { p[y][x] = *t } func (p Puzzle) value(x, y int) int { return p[y][x].Value } func (p Puzzle) setValue(x, y, val int) { p[y][x].Value = val } // IsValid returns true if the specified tile in the puzzle does not violate any // sudoku rules. func (p Puzzle) IsValid(x, y int) bool { return p.isValidSquare(x, y) && p.isValidRow(y) && p.isValidCol(x) } func (p Puzzle) isValidRow(y int) bool { return p.isValidRange(0, y, boardDiameter-1, y) } func (p Puzzle) isValidCol(x int) bool { return p.isValidRange(x, 0, x, boardDiameter-1) } func (p Puzzle) isValidSquare(x, y int) bool { topLeftX := (x / squareDiameter) * squareDiameter topLeftY := (y / squareDiameter) * squareDiameter botRightX := topLeftX + squareDiameter - 1 botRightY := topLeftY + squareDiameter - 1 return p.isValidRange(topLeftX, topLeftY, botRightX, botRightY) } func (p Puzzle) isValidRange(minX, minY, maxX, maxY int) bool { existingDigits := make(map[int]struct{}) for x := minX; x <= maxX; x++ { for y := minY; y <= maxY; y++ { value := p.Tile(x, y).Value if value == blank { continue } _, present := existingDigits[value] if present { return false } existingDigits[value] = struct{}{} } } return true } // blockingSolve waits for the specified amount of time after going down a new path. func (p Puzzle) blockingSolve(wait time.Duration) bool { for x := 0; x < boardDiameter; x++ { for y := 0; y < boardDiameter; y++ { // Skip tiles with assigned values if p.value(x, y) != blank { continue } // Try 1-9 in an open tile for i := 1; i <= boardDiameter; i++ { p.setValue(x, y, i) if p.IsValid(x, y) { time.Sleep(wait) // If we've reached the max x and y, we have found a // solution (this assumes a rectangular puzzle) if x == len(p[0])-1 && y == len(p)-1 { return true } // For valid guesses, attempt to search further if p.blockingSolve(wait) { return true } } p.setValue(x, y, blank) } // If the values 1 to 9 are tried with no success, the puzzle is invalid return false } } return false } // solve attempts to solve the sudoku puzzle. If the puzzle is not valid, it // should return false func (p Puzzle) solve() bool { for x := 0; x < boardDiameter; x++ { for y := 0; y < boardDiameter; y++ { // Skip tiles with assigned values if p.value(x, y) != blank { continue } // Try 1-9 in an open tile for i := 1; i <= boardDiameter; i++ { p.setValue(x, y, i) if p.IsValid(x, y) { // If we've reached the max x and y, we have found a // solution (this assumes a rectangular puzzle) if x == len(p[0])-1 && y == len(p)-1 { return true } // For valid guesses, attempt to search further if p.solve() { return true } } p.setValue(x, y, blank) } // If the values 1 to 9 are tried with no success, the puzzle is invalid return false } } return false } func (p Puzzle) String() string { var result string for _, row := range p { for _, tile := range row { result += fmt.Sprintf("%d ", tile.Value) } result += "\n" } return result }
sudoku.go
0.633864
0.40389
sudoku.go
starcoder
package wfc import ( // "fmt" "image" "image/color" ) /** * SimpleTiledModel Type */ type SimpleTiledModel struct { *BaseModel // Underlying model of generic Wave Function Collapse algorithm TileSize int // The size in pixels of the length and height of each tile Tiles []TilePattern // List of all possible tiles as images, including inversions Propagator [][][]bool // All possible connections between tiles } // Parsed data supplied by user type SimpleTiledData struct { Unique bool // False if each tile can have variants. (Default to false?) TileSize int // Default to 16 Tiles []Tile // List of all possible tiles, not including inversions Neighbors []Neighbor // List of possible connections between tiles } // Raw information on a tile type Tile struct { Name string // Name used to identify the tile Symmetry string // Default to "" Weight float64 // Default to 1 Variants []image.Image // Preloaded image for the tile } // Information on which tiles can be neighbors type Neighbor struct { Left string // Mathces Tile.Name LeftNum int // Default to 0 Right string // Mathces Tile.Name RightNum int // Default to 0 } // Flat array of colors in a tile type TilePattern []color.Color // Tile inversion function type type Inversion func(int) int /** * NewSimpleTiledModel * @param {object} data Tiles and constraints definitions * @param {int} width The width of the generation, in terms of tiles (not pixels) * @param {int} height The height of the generation, in terms of tiles (not pixels) * @param {bool} periodic Whether the source image is to be considered as periodic / as a repeatable texture * @return *SimpleTiledModel A pointer to a new copy of the model */ func NewSimpleTiledModel(data SimpleTiledData, width, height int, periodic bool) *SimpleTiledModel { // Initialize model model := &SimpleTiledModel{BaseModel: &BaseModel{}} model.Fmx = width model.Fmy = height model.Periodic = periodic model.TileSize = data.TileSize model.Tiles = make([]TilePattern, 0) model.Stationary = make([]float64, 0) firstOccurrence := make(map[string]int) action := make([][]int, 0) tile := func(transformer func(x, y int) color.Color) TilePattern { result := make(TilePattern, model.TileSize*model.TileSize) for y := 0; y < model.TileSize; y++ { for x := 0; x < model.TileSize; x++ { result[x+y*model.TileSize] = transformer(x, y) } } return result } rotate := func(p TilePattern) TilePattern { return tile(func(x, y int) color.Color { return p[model.TileSize-1-y+x*model.TileSize] }) } for i := 0; i < len(data.Tiles); i++ { currentTile := data.Tiles[i] var cardinality int var inversion1, inversion2 Inversion switch currentTile.Symmetry { case "L": cardinality = 4 inversion1 = func(i int) int { return (i + 1) % 4 } inversion2 = func(i int) int { if i%2 == 0 { return i + 1 } return i - 1 } case "T": cardinality = 4 inversion1 = func(i int) int { return (i + 1) % 4 } inversion2 = func(i int) int { if i%2 == 0 { return i } return 4 - i } case "I": cardinality = 2 inversion1 = func(i int) int { return 1 - i } inversion2 = func(i int) int { return i } case "\\": cardinality = 2 inversion1 = func(i int) int { return 1 - i } inversion2 = func(i int) int { return 1 - i } case "X": cardinality = 1 inversion1 = func(i int) int { return i } inversion2 = func(i int) int { return i } default: cardinality = 1 inversion1 = func(i int) int { return i } inversion2 = func(i int) int { return i } } model.T = len(action) firstOccurrence[currentTile.Name] = model.T for t := 0; t < cardinality; t++ { action = append(action, []int{ model.T + t, model.T + inversion1(t), model.T + inversion1(inversion1(t)), model.T + inversion1(inversion1(inversion1(t))), model.T + inversion2(t), model.T + inversion2(inversion1(t)), model.T + inversion2(inversion1(inversion1(t))), model.T + inversion2(inversion1(inversion1(inversion1(t)))), }) } if data.Unique { for t := 0; t < cardinality; t++ { img := currentTile.Variants[t] model.Tiles = append(model.Tiles, tile(func(x, y int) color.Color { return img.At(x, y) })) } } else { img := currentTile.Variants[0] model.Tiles = append(model.Tiles, tile(func(x, y int) color.Color { return img.At(x, y) })) for t := 1; t < cardinality; t++ { model.Tiles = append(model.Tiles, rotate(model.Tiles[model.T+t-1])) } } for t := 0; t < cardinality; t++ { model.Stationary = append(model.Stationary, currentTile.Weight) } } model.T = len(action) model.Propagator = make([][][]bool, 4) for i := 0; i < 4; i++ { model.Propagator[i] = make([][]bool, model.T) for t := 0; t < model.T; t++ { model.Propagator[i][t] = make([]bool, model.T) for t2 := 0; t2 < model.T; t2++ { model.Propagator[i][t][t2] = false } } } model.Wave = make([][][]bool, model.Fmx) model.Changes = make([][]bool, model.Fmx) for x := 0; x < model.Fmx; x++ { model.Wave[x] = make([][]bool, model.Fmy) model.Changes[x] = make([]bool, model.Fmy) for y := 0; y < model.Fmy; y++ { model.Wave[x][y] = make([]bool, model.T) } } for i := 0; i < len(data.Neighbors); i++ { neighbor := data.Neighbors[i] l := action[firstOccurrence[neighbor.Left]][neighbor.LeftNum] d := action[l][1] r := action[firstOccurrence[neighbor.Right]][neighbor.RightNum] u := action[r][1] model.Propagator[0][r][l] = true model.Propagator[0][action[r][6]][action[l][6]] = true model.Propagator[0][action[l][4]][action[r][4]] = true model.Propagator[0][action[l][2]][action[r][2]] = true model.Propagator[1][u][d] = true model.Propagator[1][action[d][6]][action[u][6]] = true model.Propagator[1][action[u][4]][action[d][4]] = true model.Propagator[1][action[d][2]][action[u][2]] = true } for t := 0; t < model.T; t++ { for t2 := 0; t2 < model.T; t2++ { model.Propagator[2][t][t2] = model.Propagator[0][t2][t] model.Propagator[3][t][t2] = model.Propagator[1][t2][t] } } return model } /** * OnBoundary */ func (model *SimpleTiledModel) OnBoundary(x, y int) bool { return false } /** * Propagate * return: bool, change occured in this iteration */ func (model *SimpleTiledModel) Propagate() bool { change := false for x2 := 0; x2 < model.Fmx; x2++ { for y2 := 0; y2 < model.Fmy; y2++ { for d := 0; d < 4; d++ { x1 := x2 y1 := y2 if d == 0 { if x2 == 0 { if !model.Periodic { continue } else { x1 = model.Fmx - 1 } } else { x1 = x2 - 1 } } else if d == 1 { if y2 == model.Fmy-1 { if !model.Periodic { continue } else { y1 = 0 } } else { y1 = y2 + 1 } } else if d == 2 { if x2 == model.Fmx-1 { if !model.Periodic { continue } else { x1 = 0 } } else { x1 = x2 + 1 } } else { if y2 == 0 { if !model.Periodic { continue } else { y1 = model.Fmy - 1 } } else { y1 = y2 - 1 } } if !model.Changes[x1][y1] { continue } for t2 := 0; t2 < model.T; t2++ { if model.Wave[x2][y2][t2] { b := false for t1 := 0; t1 < model.T && !b; t1++ { if model.Wave[x1][y1][t1] { b = model.Propagator[d][t2][t1] } } if !b { model.Wave[x2][y2][t2] = false model.Changes[x2][y2] = true change = true } } } } } } return change } /** * Clear the internal state, then set ground pattern */ func (model *SimpleTiledModel) Clear() { model.ClearBase(model) } /** * Create a image.Image holding the data for a complete image */ func (model *SimpleTiledModel) RenderCompleteImage() image.Image { output := make([][]color.Color, model.Fmx*model.TileSize) for i := range output { output[i] = make([]color.Color, model.Fmy*model.TileSize) } for y := 0; y < model.Fmy; y++ { for x := 0; x < model.Fmx; x++ { for yt := 0; yt < model.TileSize; yt++ { for xt := 0; xt < model.TileSize; xt++ { for t := 0; t < model.T; t++ { if model.Wave[x][y][t] { output[x*model.TileSize+xt][y*model.TileSize+yt] = model.Tiles[t][yt*model.TileSize+xt] break } } } } } } return GeneratedImage{output} } /** * Create a image.Image holding the data for an incomplete image */ func (model *SimpleTiledModel) RenderIncompleteImage() image.Image { output := make([][]color.Color, model.Fmx*model.TileSize) for i := range output { output[i] = make([]color.Color, model.Fmy*model.TileSize) } for y := 0; y < model.Fmy; y++ { for x := 0; x < model.Fmx; x++ { amount := 0 sum := 0.0 for t := 0; t < len(model.Wave[x][y]); t++ { if model.Wave[x][y][t] { amount += 1 sum += model.Stationary[t] } } for yt := 0; yt < model.TileSize; yt++ { for xt := 0; xt < model.TileSize; xt++ { if amount == model.T { output[x*model.TileSize+xt][y*model.TileSize+yt] = color.RGBA{127, 127, 127, 255} } else { sR, sG, sB, sA := 0.0, 0.0, 0.0, 0.0 for t := 0; t < model.T; t++ { if model.Wave[x][y][t] { r, g, b, a := model.Tiles[t][yt*model.TileSize+xt].RGBA() sR += float64(r) * model.Stationary[t] sG += float64(g) * model.Stationary[t] sB += float64(b) * model.Stationary[t] sA += float64(a) * model.Stationary[t] } } uR := uint8(int(sR/sum) >> 8) uG := uint8(int(sG/sum) >> 8) uB := uint8(int(sB/sum) >> 8) uA := uint8(int(sA/sum) >> 8) output[x*model.TileSize+xt][y*model.TileSize+yt] = color.RGBA{uR, uG, uB, uA} } } } } } return GeneratedImage{output} } /** * Retrieve the RGBA data * returns: Image */ func (model *SimpleTiledModel) Render() image.Image { if model.IsGenerationSuccessful() { return model.RenderCompleteImage() } else { return model.RenderIncompleteImage() } } /** * Retrieve the RGBA data * returns: Image, finished, successful */ func (model *SimpleTiledModel) Iterate(iterations int) (image.Image, bool, bool) { finished := model.BaseModel.Iterate(model, iterations) return model.Render(), finished, model.IsGenerationSuccessful() } /** * Retrieve the RGBA data * returns: Image, successful */ func (model *SimpleTiledModel) Generate() (image.Image, bool) { model.BaseModel.Generate(model) return model.Render(), model.IsGenerationSuccessful() }
simple-tiled-model.go
0.63273
0.489931
simple-tiled-model.go
starcoder
package physics import ( "fmt" "math" ) type Vector2D struct { X float64 Y float64 } // NewVector2D creates a new Vector2D with supplied x and y components func NewVector2D(x float64, y float64) *Vector2D { return &Vector2D{X: x, Y: y} } // Add returns a new Vector2D of the addition of two vectors. func (v1 *Vector2D) Add(v2 *Vector2D) *Vector2D { return NewVector2D(v1.X+v2.X, v1.Y+v2.Y) } // Subtract returns a new Vector2D of the subtraction of two vectors. func (v1 *Vector2D) Subtract(v2 *Vector2D) *Vector2D { return NewVector2D(v1.X-v2.X, v1.Y-v2.Y) } // Scalarmul returns a new Vector2D of the vector components multiplied // each by the scalar value. func (v *Vector2D) Scalarmul(scalar float64) *Vector2D { return NewVector2D(v.X*scalar, v.Y*scalar) } // Dotproduct returns the dot product of two vectors. func (v1 *Vector2D) Dotproduct(v2 *Vector2D) float64 { return v1.X*v2.X + v1.Y*v2.Y } // Length returns the scalar length of the vector. func (v *Vector2D) Length() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } // Normalize returns a new Vector2D that is a normalized version // of the original vector. func (v *Vector2D) Normalize() *Vector2D { normlen := 1.0 / v.Length() return NewVector2D(v.X*normlen, v.Y*normlen) } // Rotate returns a new Vector2D that is a counterclockwise // rotation of given radians of the original vector. func (v *Vector2D) Rotate(radians float64) *Vector2D { cr := math.Cos(radians) cs := math.Sin(radians) return NewVector2D(v.X*cr-v.Y*cs, v.X*cs+v.Y*cr) } // InvertX returns a new Vector2D that has an inverted x component func (v *Vector2D) InvertX() *Vector2D { // Do not use the IEEE754 negative zero if v.X == 0 { return NewVector2D(0, v.Y) } return NewVector2D(-v.X, v.Y) } // InvertY returns a new Vector2D that has an inverted y component func (v *Vector2D) InvertY() *Vector2D { // Do not use the IEEE754 negative zero if v.Y == 0 { return NewVector2D(v.X, 0) } return NewVector2D(v.X, -v.Y) } // Invert returns a new Vector2D that has both x and y component inverted func (v *Vector2D) Invert() *Vector2D { // Do not use the IEEE754 negative zero if v.X == 0 && v.Y == 0 { return NewVector2D(0, 0) } else if v.X == 0 { return NewVector2D(0, -v.Y) } else if v.Y == 0 { return NewVector2D(-v.X, 0) } else { return NewVector2D(-v.X, -v.Y) } } // String returns the formatted string "Vector{X: ..., ...}". func (v *Vector2D) String() string { return fmt.Sprintf("Vector{X: %v, %v}", v.X, v.Y) }
physics/vectors.go
0.927577
0.878575
vectors.go
starcoder
package bexpr import ( "fmt" ) func validateRecurse(ast Expression, fields FieldConfigurations, maxRawValueLength int) (int, error) { switch node := ast.(type) { case *UnaryExpression: switch node.Operator { case UnaryOpNot: // this is fine default: return 0, fmt.Errorf("Invalid unary expression operator: %d", node.Operator) } if node.Operand == nil { return 0, fmt.Errorf("Invalid unary expression operand: nil") } return validateRecurse(node.Operand, fields, maxRawValueLength) case *BinaryExpression: switch node.Operator { case BinaryOpAnd, BinaryOpOr: // this is fine default: return 0, fmt.Errorf("Invalid binary expression operator: %d", node.Operator) } if node.Left == nil { return 0, fmt.Errorf("Invalid left hand side of binary expression: nil") } else if node.Right == nil { return 0, fmt.Errorf("Invalid right hand side of binary expression: nil") } leftMatches, err := validateRecurse(node.Left, fields, maxRawValueLength) if err != nil { return leftMatches, err } rightMatches, err := validateRecurse(node.Right, fields, maxRawValueLength) return leftMatches + rightMatches, err case *MatchExpression: if len(node.Selector) < 1 { return 1, fmt.Errorf("Invalid selector: %q", node.Selector) } if node.Value != nil && maxRawValueLength != 0 && len(node.Value.Raw) > maxRawValueLength { return 1, fmt.Errorf("Value in expression with length %d for selector %q exceeds maximum length of", len(node.Value.Raw), maxRawValueLength) } // exit early if we have no fields to check against if len(fields) < 1 { return 1, nil } configs := fields var lastConfig *FieldConfiguration // validate the selector for idx, field := range node.Selector { if fcfg, ok := configs[FieldName(field)]; ok { lastConfig = fcfg configs = fcfg.SubFields } else if fcfg, ok := configs[FieldNameAny]; ok { lastConfig = fcfg configs = fcfg.SubFields } else { return 1, fmt.Errorf("Selector %q is not valid", node.Selector[:idx+1]) } // this just verifies that the FieldConfigurations we are using was created properly if lastConfig == nil { return 1, fmt.Errorf("FieldConfiguration for selector %q is nil", node.Selector[:idx]) } } // check the operator found := false for _, op := range lastConfig.SupportedOperations { if op == node.Operator { found = true break } } if !found { return 1, fmt.Errorf("Invalid match operator %q for selector %q", node.Operator, node.Selector) } // coerce/validate the value if node.Value != nil { if lastConfig.CoerceFn != nil { coerced, err := lastConfig.CoerceFn(node.Value.Raw) if err != nil { return 1, fmt.Errorf("Failed to coerce value %q for selector %q: %v", node.Value.Raw, node.Selector, err) } node.Value.Converted = coerced } } else { switch node.Operator { case MatchIsEmpty, MatchIsNotEmpty: // these don't require values default: return 1, fmt.Errorf("Match operator %q requires a non-nil value", node.Operator) } } return 1, nil } return 0, fmt.Errorf("Cannot validate: Invalid AST") } func validate(ast Expression, fields FieldConfigurations, maxMatches, maxRawValueLength int) error { matches, err := validateRecurse(ast, fields, maxRawValueLength) if err != nil { return err } if maxMatches != 0 && matches > maxMatches { return fmt.Errorf("Number of match expressions (%d) exceeds the limit (%d)", matches, maxMatches) } return nil }
vendor/github.com/hashicorp/go-bexpr/validate.go
0.651022
0.416381
validate.go
starcoder
package metrics import ( //"fmt" ) // Point represents a single data point for a given timestamp. type Sample struct { T int64 V float64 } // Series is a stream of data points belonging to a metric. type PointSeries struct { Metric Labels Points []float64 evalInterval int64 } func (ps *PointSeries) EvalInterval() int64 { return ps.evalInterval } func NewPointSeries(labels Labels, evalInterval int64) *PointSeries { return &PointSeries{ Metric: labels, evalInterval: evalInterval, } } type Matrix []PointSeries func Rate(ps PointSeries) PointSeries { result := NewPointSeries(ps.Metric, ps.evalInterval) result.Metric = ps.Metric result.Points = append(result.Points, 0.2) if len(ps.Points) == 0 { result.Points = append(result.Points, 0) } for i, _ := range ps.Points { if i == 0 { continue } r := (ps.Points[i] - ps.Points[i-1]) / float64(ps.evalInterval) result.Points = append(result.Points, r) } return *result } func Avg(ps PointSeries) float64 { var sumRate float64 for _, p := range ps.Points { sumRate += p } samples := len(ps.Points) return sumRate / float64(samples) } func dim(m Matrix) int { var max int for _, s := range m { l := len(s.Points) if l > max { max = l } } return max } func extrapolate(m Matrix) Matrix { d := dim(m) for i, _ := range m { l := len(m[i].Points) if l < d { for j := 1; j <= d-l; j++ { m[i].Points = append([]float64{0.0}, m[i].Points...) } } } return m } func Sum(m Matrix) PointSeries { d := dim(m) m = extrapolate(m) evalInterval := m[0].EvalInterval() result := NewPointSeries(Labels{}, evalInterval) for i := 0; i < d; i++ { sum := 0.0 for _, s := range m { sum += s.Points[i] } result.Points = append(result.Points, sum) } return *result } func existInList(l []string, val string) bool { for _, item := range l { if item == val { return true } } return false } func SumBy(m Matrix, by []string) Matrix { var result Matrix matrixMap := make(map[uint64]Matrix) for _, s := range m { var mergeLables Labels for _, l := range s.Metric { if existInList(by, l.Name) { mergeLables = append(mergeLables, Label{Name: l.Name, Value: l.Value}) } } hash := mergeLables.Hash() s.Metric = mergeLables if _, ok := matrixMap[hash]; ok { matrixMap[hash] = append(matrixMap[hash], s) } else { matrixMap[hash] = []PointSeries{s} } } for _, m := range matrixMap { sum := Sum(m) sum.Metric = m[0].Metric result = append(result, sum) } return result }
pkg/metrics/functions.go
0.794982
0.563558
functions.go
starcoder
package imports import ( . "reflect" "image" "image/color" ) // reflection: allow interpreted code to import "image" func init() { Packages["image"] = Package{ Binds: map[string]Value{ "Black": ValueOf(&image.Black).Elem(), "Decode": ValueOf(image.Decode), "DecodeConfig": ValueOf(image.DecodeConfig), "ErrFormat": ValueOf(&image.ErrFormat).Elem(), "NewAlpha": ValueOf(image.NewAlpha), "NewAlpha16": ValueOf(image.NewAlpha16), "NewCMYK": ValueOf(image.NewCMYK), "NewGray": ValueOf(image.NewGray), "NewGray16": ValueOf(image.NewGray16), "NewNRGBA": ValueOf(image.NewNRGBA), "NewNRGBA64": ValueOf(image.NewNRGBA64), "NewNYCbCrA": ValueOf(image.NewNYCbCrA), "NewPaletted": ValueOf(image.NewPaletted), "NewRGBA": ValueOf(image.NewRGBA), "NewRGBA64": ValueOf(image.NewRGBA64), "NewUniform": ValueOf(image.NewUniform), "NewYCbCr": ValueOf(image.NewYCbCr), "Opaque": ValueOf(&image.Opaque).Elem(), "Pt": ValueOf(image.Pt), "Rect": ValueOf(image.Rect), "RegisterFormat": ValueOf(image.RegisterFormat), "Transparent": ValueOf(&image.Transparent).Elem(), "White": ValueOf(&image.White).Elem(), "YCbCrSubsampleRatio410": ValueOf(image.YCbCrSubsampleRatio410), "YCbCrSubsampleRatio411": ValueOf(image.YCbCrSubsampleRatio411), "YCbCrSubsampleRatio420": ValueOf(image.YCbCrSubsampleRatio420), "YCbCrSubsampleRatio422": ValueOf(image.YCbCrSubsampleRatio422), "YCbCrSubsampleRatio440": ValueOf(image.YCbCrSubsampleRatio440), "YCbCrSubsampleRatio444": ValueOf(image.YCbCrSubsampleRatio444), "ZP": ValueOf(&image.ZP).Elem(), "ZR": ValueOf(&image.ZR).Elem(), }, Types: map[string]Type{ "Alpha": TypeOf((*image.Alpha)(nil)).Elem(), "Alpha16": TypeOf((*image.Alpha16)(nil)).Elem(), "CMYK": TypeOf((*image.CMYK)(nil)).Elem(), "Config": TypeOf((*image.Config)(nil)).Elem(), "Gray": TypeOf((*image.Gray)(nil)).Elem(), "Gray16": TypeOf((*image.Gray16)(nil)).Elem(), "Image": TypeOf((*image.Image)(nil)).Elem(), "NRGBA": TypeOf((*image.NRGBA)(nil)).Elem(), "NRGBA64": TypeOf((*image.NRGBA64)(nil)).Elem(), "NYCbCrA": TypeOf((*image.NYCbCrA)(nil)).Elem(), "Paletted": TypeOf((*image.Paletted)(nil)).Elem(), "PalettedImage": TypeOf((*image.PalettedImage)(nil)).Elem(), "Point": TypeOf((*image.Point)(nil)).Elem(), "RGBA": TypeOf((*image.RGBA)(nil)).Elem(), "RGBA64": TypeOf((*image.RGBA64)(nil)).Elem(), "Rectangle": TypeOf((*image.Rectangle)(nil)).Elem(), "Uniform": TypeOf((*image.Uniform)(nil)).Elem(), "YCbCr": TypeOf((*image.YCbCr)(nil)).Elem(), "YCbCrSubsampleRatio": TypeOf((*image.YCbCrSubsampleRatio)(nil)).Elem(), }, Proxies: map[string]Type{ "Image": TypeOf((*P_image_Image)(nil)).Elem(), "PalettedImage": TypeOf((*P_image_PalettedImage)(nil)).Elem(), }, Wrappers: map[string][]string{ "NYCbCrA": []string{"Bounds","COffset","YCbCrAt","YOffset",}, }, } } // --------------- proxy for image.Image --------------- type P_image_Image struct { Object interface{} At_ func(_proxy_obj_ interface{}, x int, y int) color.Color Bounds_ func(interface{}) image.Rectangle ColorModel_ func(interface{}) color.Model } func (P *P_image_Image) At(x int, y int) color.Color { return P.At_(P.Object, x, y) } func (P *P_image_Image) Bounds() image.Rectangle { return P.Bounds_(P.Object) } func (P *P_image_Image) ColorModel() color.Model { return P.ColorModel_(P.Object) } // --------------- proxy for image.PalettedImage --------------- type P_image_PalettedImage struct { Object interface{} At_ func(_proxy_obj_ interface{}, x int, y int) color.Color Bounds_ func(interface{}) image.Rectangle ColorIndexAt_ func(_proxy_obj_ interface{}, x int, y int) uint8 ColorModel_ func(interface{}) color.Model } func (P *P_image_PalettedImage) At(x int, y int) color.Color { return P.At_(P.Object, x, y) } func (P *P_image_PalettedImage) Bounds() image.Rectangle { return P.Bounds_(P.Object) } func (P *P_image_PalettedImage) ColorIndexAt(x int, y int) uint8 { return P.ColorIndexAt_(P.Object, x, y) } func (P *P_image_PalettedImage) ColorModel() color.Model { return P.ColorModel_(P.Object) }
vendor/github.com/cosmos72/gomacro/imports/image.go
0.612194
0.443962
image.go
starcoder
package physics import ( "math" "github.com/dayaftereh/discover/server/mathf" ) type RigidBody struct { Mass float64 // World space position of the body. Position *mathf.Vec3 // World space rotational force on the body, around center of mass. Rotation *mathf.Quaternion // World space velocity of the body. Velocity *mathf.Vec3 // Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates. AngularVelocity *mathf.Vec3 // Linear force on the body in world space. Force *mathf.Vec3 // World space rotational force on the body, around center of mass. Torque *mathf.Vec3 // LinearFactor use to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none. LinearFactor *mathf.Vec3 // AngularFactor use to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none. AngularFactor *mathf.Vec3 // moment of inertia components Inertia *mathf.Vec3 InverseInertiaWorld *mathf.Mat3 LinearDamping float64 AngularDamping float64 } func NewRigidBody() *RigidBody { return &RigidBody{ Mass: 1.0, Position: mathf.NewZeroVec3(), Rotation: mathf.NewZeroQuaternion(), Velocity: mathf.NewZeroVec3(), AngularVelocity: mathf.NewZeroVec3(), Force: mathf.NewZeroVec3(), Torque: mathf.NewZeroVec3(), LinearFactor: mathf.NewVec3(1.0, 1.0, 1.0), AngularFactor: mathf.NewVec3(1.0, 1.0, 1.0), Inertia: mathf.NewZeroVec3(), InverseInertiaWorld: mathf.NewIdentityMat3(), LinearDamping: 0.01, AngularDamping: 0.01, } } func (rigidbody *RigidBody) InverseMass() float64 { if rigidbody.Mass > 0 { return 1.0 / rigidbody.Mass } return 0.0 } func (rigidbody *RigidBody) InverseInertia() *mathf.Vec3 { return mathf.NewVec3( 1.0/rigidbody.Inertia.X, 1.0/rigidbody.Inertia.Y, 1.0/rigidbody.Inertia.Z, ) } func (rigidbody *RigidBody) PointToLocalFrame(worldPoint *mathf.Vec3) *mathf.Vec3 { p := worldPoint.SubtractVec(rigidbody.Position) r := rigidbody.Rotation.Conjugate().MultiplyVec(p) return r } func (rigidbody *RigidBody) VectorToLocalFrame(worldVector *mathf.Vec3) *mathf.Vec3 { r := rigidbody.Rotation.Conjugate().MultiplyVec(worldVector) return r } func (rigidbody *RigidBody) PointToWorldFrame(localPoint *mathf.Vec3) *mathf.Vec3 { p := rigidbody.Rotation.MultiplyVec(localPoint) r := p.AddVec(rigidbody.Position) return r } func (rigidbody *RigidBody) VectorToWorldFrame(localVector *mathf.Vec3) *mathf.Vec3 { r := rigidbody.Rotation.MultiplyVec(localVector) return r } func (rigidbody *RigidBody) AddTorque(torque *mathf.Vec3) { // Add rotational force rigidbody.Torque = rigidbody.Torque.AddVec(torque) } func (rigidbody *RigidBody) AddLocalTorque(localTorque *mathf.Vec3) { worldTorque := rigidbody.VectorToWorldFrame(localTorque) rigidbody.AddTorque(worldTorque) } func (rigidbody *RigidBody) ApplyForce(force *mathf.Vec3, relativePoint *mathf.Vec3) { // Add linear force rigidbody.Force = rigidbody.Force.AddVec(force) // Compute produced rotational force rotForce := relativePoint.Cross(force) // Add rotational force rigidbody.AddTorque(rotForce) } func (rigidbody *RigidBody) ApplyLocalForce(localForce *mathf.Vec3, localPoint *mathf.Vec3) { // Transform the force vector to world space worldForce := rigidbody.VectorToWorldFrame(localForce) relativePointWorld := rigidbody.VectorToWorldFrame(localPoint) rigidbody.ApplyForce(worldForce, relativePointWorld) } func (rigidbody *RigidBody) ApplyImpulse(impulse *mathf.Vec3, relativePoint *mathf.Vec3) { // Compute produced central impulse velocity velo := impulse.Multiply(rigidbody.InverseMass()) // Add linear impulse rigidbody.Velocity = rigidbody.Velocity.AddVec(velo) // Compute produced rotational impulse velocity rotVelo := relativePoint.Cross(impulse) /* rotVelo.x *= this.invInertia.x; rotVelo.y *= this.invInertia.y; rotVelo.z *= this.invInertia.z; */ rotVeloInertia := rigidbody.InverseInertiaWorld.MultiplyVec(rotVelo) // Add rotational Impulse rigidbody.AngularVelocity = rigidbody.AngularVelocity.AddVec(rotVeloInertia) } func (rigidbody *RigidBody) ApplyLocalImpulse(localImpulse *mathf.Vec3, localPoint *mathf.Vec3) { // Transform the force vector to world space worldImpulse := rigidbody.VectorToWorldFrame(localImpulse) relativePointWorld := rigidbody.VectorToWorldFrame(localPoint) rigidbody.ApplyImpulse(worldImpulse, relativePointWorld) } func (rigidbody *RigidBody) Update(delta float64) { // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details linearDamping := math.Pow(1.0-rigidbody.LinearDamping, delta) rigidbody.Velocity = rigidbody.Velocity.Multiply(linearDamping) angularDamping := math.Pow(1.0-rigidbody.AngularDamping, delta) rigidbody.AngularVelocity = rigidbody.AngularVelocity.Multiply(angularDamping) // calculate linera Velocity invMassDelta := rigidbody.InverseMass() * delta velo := mathf.NewVec3( rigidbody.Velocity.X+(rigidbody.Force.X*invMassDelta*rigidbody.LinearFactor.X), rigidbody.Velocity.Y+(rigidbody.Force.Y*invMassDelta*rigidbody.LinearFactor.Y), rigidbody.Velocity.Z+(rigidbody.Force.Z*invMassDelta*rigidbody.LinearFactor.Z), ) // caluclate AngularVelocity tx := rigidbody.Torque.X * rigidbody.AngularFactor.X ty := rigidbody.Torque.Y * rigidbody.AngularFactor.Y tz := rigidbody.Torque.Z * rigidbody.AngularFactor.Z e := rigidbody.InverseInertiaWorld.Elements() rigidbody.AngularVelocity = mathf.NewVec3( rigidbody.AngularVelocity.X+(delta*(e[0]*tx+e[1]*ty+e[2]*tz)), rigidbody.AngularVelocity.Y+(delta*(e[3]*tx+e[4]*ty+e[5]*tz)), rigidbody.AngularVelocity.Z+(delta*(e[6]*tx+e[7]*ty+e[8]*tz)), ) // Use new linera velocity - leap frog // update position rigidbody.Velocity = velo.Multiply(delta) rigidbody.Position = rigidbody.Position.AddVec(rigidbody.Velocity) // update rotation rotation := rigidbody.Rotation.Integrate(rigidbody.AngularVelocity, delta, rigidbody.AngularFactor) rigidbody.Rotation = rigidbody.Rotation.Add(rotation).Normalize() // update the inertia world rigidbody.UpdateInertiaWorld(false) // clear all forces on the object rigidbody.Force = mathf.NewZeroVec3() rigidbody.Torque = mathf.NewZeroVec3() } func (rigidbody *RigidBody) UpdateInertiaWorld(force bool) { I := rigidbody.InverseInertia() if I.X == I.Y && I.Y == I.Z && !force { // If inertia M = s*I, where I is identity and s a scalar, then // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M // where R is the rotation matrix. // In other words, we don't have to transform the inertia if all // inertia diagonal entries are equal. return } m1 := mathf.Mat3FromQuaternion(rigidbody.Rotation) m2 := m1.Transpose() m1 = m1.Scale(I) rigidbody.InverseInertiaWorld = m1.Multiply(m2) }
server/game/engine/physics/rigidbody.go
0.892744
0.635972
rigidbody.go
starcoder
package qson type ComparisonQuery interface { Query comparisonQueryProof() } type comparisonQuery func(M) M func (q comparisonQuery) Ensure(m M) M { return q(initializer().Ensure(m)) } func (q comparisonQuery) operatorProof() {} func (q comparisonQuery) queryProof() {} func (q comparisonQuery) comparisonQueryProof() {} // Same matches values that are equal to a specified value. func Same(field, value string) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = value return m }) } // Eq matches values that are equal to a specified value. func Eq(field string, value interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$eq": value} return m }) } // Gt matches values that are greater than a specified value. func Gt(field string, value interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$gt": value} return m }) } // Gte matches values that are greater than or equal to a specified value. func Gte(field string, value interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$gte": value} return m }) } // In matches any of the values specified in an array. func In(field string, values interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$in": values} return m }) } // Lt matches values that are less than a specified value. func Lt(field string, value interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$lt": value} return m }) } // Lte matches values that are less than or equal to a specified value. func Lte(field string, value interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$lte": value} return m }) } // Ne matches all values that are not equal to a specified value. func Ne(field string, value interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$ne": value} return m }) } // Nin matches none of the values specified in an array. func Nin(field string, values interface{}) comparisonQuery { return comparisonQuery(func(m M) M { m[field] = M{"$nin": values} return m }) }
query_operators_comparison.go
0.853791
0.645246
query_operators_comparison.go
starcoder
package integrationtest /* Goal of this test: Verify that the user specified client name parameter when we create an Election gets set as expected inside the ephemeral node that is created for the client Steps in this test: 1. Create a election resource 2. Create a election client and provide the hostname as the client name 3. Let this client win the election 4. Get the value stored in the ephemeral node for this client and make sure the payload stored in the ephemeral node is the hostname 5. Repeat step 2 with the client name being "foobar" 6. This client would be the follower for this election 7. Verify that the value stored in the ephemeral node for this follower client has the payload matching "foobar" */ import ( "fmt" "os" "time" "github.com/Comcast/go-leaderelection" "github.com/go-zookeeper/zk" "log" ) const ( defaultClientName = "myclientname" ) // zkClientNameTest is the struct that controls the test. type zkClientNameTest struct { testSetup ZKTestSetup leaderElector *leaderelection.Election followerElector *leaderelection.Election zkConn *zk.Conn done chan struct{} expectedName1 string expectedName2 string info *log.Logger error *log.Logger } // CreateTestData: Implement the zkTestCallbacks interface func (test *zkClientNameTest) CreateTestData() (err error) { return nil } // CreateTestData: Implement the zkTestCallbacks interface // Initialize the steps func (test *zkClientNameTest) InitFunc() ([]time.Duration, error) { zkConn, _, err := zk.Connect([]string{test.testSetup.zkURL}, test.testSetup.heartBeat) test.zkConn = zkConn test.done = make(chan struct{}, 2) if err != nil { return nil, err } // Create the election node in ZooKeeper _, err = test.zkConn.Create(test.testSetup.electionNode, []byte("data"), 0, zk.WorldACL(zk.PermAll)) if err != nil { return nil, err } return []time.Duration{ time.Second * 1, time.Second * 1, time.Second * 1, time.Second * 1, }, nil } // CreateTestData: Implement the zkTestCallbacks interface func (test *zkClientNameTest) StepFunc(idx int) error { switch idx { case 0: // Create the Election test.info.Printf("Step %d: Create Election.", idx) test.expectedName1, _ = os.Hostname() if test.expectedName1 == "" { test.expectedName1 = defaultClientName } elector, err := leaderelection.NewElection(test.zkConn, test.testSetup.electionNode, test.expectedName1) test.leaderElector = elector if err != nil { test.error.Printf("zkClientNameTest: Error in NewElection (%s): %v", test.testSetup.electionNode, err) return err } case 1: // Elect the leader test.info.Printf("Step %d: Elect Leader", idx) go func() { test.leaderElector.ElectLeader() test.done <- struct{}{} }() // Expect this to succeed; there is only one candidate status := <-test.leaderElector.Status() if status.Role != leaderelection.Leader { return fmt.Errorf("zkClientNameTest: Expected to be a leader but am not") } // Check payload to make sure it has the expected string data, _, err := test.zkConn.Get(status.CandidateID) if err != nil { test.info.Printf("zkClientNameTest: Error %v when calling Get on %s", err, status.CandidateID) return err } if string(data) != test.expectedName1 { test.info.Printf("zkClientNameTest: Expected Client Name: %s, Got: %s", test.expectedName1, data) return fmt.Errorf("zkClientNameTest: Expected Client Name: %s, Got: %s", test.expectedName1, data) } case 2: // Perform similar test for the follower case test.info.Printf("Step %d: Elect Follower", idx) test.expectedName2 = "foobar" elector, err := leaderelection.NewElection(test.zkConn, test.testSetup.electionNode, test.expectedName2) test.followerElector = elector if err != nil { return err } go func() { test.followerElector.ElectLeader() test.done <- struct{}{} }() // Expect to become a follower status := <-test.followerElector.Status() if status.Role != leaderelection.Follower { return fmt.Errorf("zkClientNameTest: Expected to be a follower but am not") } // Check payload to make sure it has the expected string data, _, err := test.zkConn.Get(status.CandidateID) if err != nil { return err } if string(data) != test.expectedName2 { return fmt.Errorf("zkClientNameTest: Expected Client Name: %s, Got: %s", test.expectedName2, data) } case 3: // Resign test.info.Printf("Step %d: Resign", idx) test.followerElector.Resign() <-test.done test.leaderElector.Resign() <-test.done test.info.Printf("zkClientNameTest: Test Success") } return nil } // Verify the results func (test *zkClientNameTest) EndFunc() error { test.info.Printf("zkClientNameTest: EndFunc(): Verification") err := test.zkConn.Delete(test.testSetup.electionNode, 0) if err != nil { children, _, _ := test.zkConn.Children(test.testSetup.electionNode) return fmt.Errorf("zkClientNameTest: Error deleting election node! %v, children: %v", err, children) } // SUCCESS return nil } // NewZKClientNameTest creates a new happy path test case func NewZKClientNameTest(setup ZKTestSetup) *ZKTest { clientNameTest := zkClientNameTest{ testSetup: setup, info: log.New(os.Stderr, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile), error: log.New(os.Stderr, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile), } zkClientNameTest := ZKTest{ Desc: "Client Name Test", Callbacks: &clientNameTest, Err: nil, } return &zkClientNameTest }
integrationtest/zk_clientname.go
0.595493
0.515437
zk_clientname.go
starcoder
package rfc2866 import ( "strconv" "fbc/lib/go/radius" ) const ( AcctStatusType_Type radius.Type = 40 AcctDelayTime_Type radius.Type = 41 AcctInputOctets_Type radius.Type = 42 AcctOutputOctets_Type radius.Type = 43 AcctSessionID_Type radius.Type = 44 AcctAuthentic_Type radius.Type = 45 AcctSessionTime_Type radius.Type = 46 AcctInputPackets_Type radius.Type = 47 AcctOutputPackets_Type radius.Type = 48 AcctTerminateCause_Type radius.Type = 49 AcctMultiSessionID_Type radius.Type = 50 AcctLinkCount_Type radius.Type = 51 ) type AcctStatusType uint32 const ( AcctStatusType_Value_Start AcctStatusType = 1 AcctStatusType_Value_Stop AcctStatusType = 2 AcctStatusType_Value_InterimUpdate AcctStatusType = 3 AcctStatusType_Value_AccountingOn AcctStatusType = 7 AcctStatusType_Value_AccountingOff AcctStatusType = 8 AcctStatusType_Value_Failed AcctStatusType = 15 ) var AcctStatusType_Strings = map[AcctStatusType]string{ AcctStatusType_Value_Start: "Start", AcctStatusType_Value_Stop: "Stop", AcctStatusType_Value_InterimUpdate: "Interim-Update", AcctStatusType_Value_AccountingOn: "Accounting-On", AcctStatusType_Value_AccountingOff: "Accounting-Off", AcctStatusType_Value_Failed: "Failed", } func (a AcctStatusType) String() string { if str, ok := AcctStatusType_Strings[a]; ok { return str } return "AcctStatusType(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctStatusType_Add(p *radius.Packet, value AcctStatusType) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctStatusType_Type, a) return nil } func AcctStatusType_Get(p *radius.Packet) (value AcctStatusType) { value, _ = AcctStatusType_Lookup(p) return } func AcctStatusType_Gets(p *radius.Packet) (values []AcctStatusType, err error) { var i uint32 for _, attr := range p.Attributes[AcctStatusType_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctStatusType(i)) } return } func AcctStatusType_Lookup(p *radius.Packet) (value AcctStatusType, err error) { a, ok := p.Lookup(AcctStatusType_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctStatusType(i) return } func AcctStatusType_Set(p *radius.Packet, value AcctStatusType) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctStatusType_Type, a) return nil } type AcctDelayTime uint32 var AcctDelayTime_Strings = map[AcctDelayTime]string{} func (a AcctDelayTime) String() string { if str, ok := AcctDelayTime_Strings[a]; ok { return str } return "AcctDelayTime(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctDelayTime_Add(p *radius.Packet, value AcctDelayTime) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctDelayTime_Type, a) return nil } func AcctDelayTime_Get(p *radius.Packet) (value AcctDelayTime) { value, _ = AcctDelayTime_Lookup(p) return } func AcctDelayTime_Gets(p *radius.Packet) (values []AcctDelayTime, err error) { var i uint32 for _, attr := range p.Attributes[AcctDelayTime_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctDelayTime(i)) } return } func AcctDelayTime_Lookup(p *radius.Packet) (value AcctDelayTime, err error) { a, ok := p.Lookup(AcctDelayTime_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctDelayTime(i) return } func AcctDelayTime_Set(p *radius.Packet, value AcctDelayTime) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctDelayTime_Type, a) return nil } type AcctInputOctets uint32 var AcctInputOctets_Strings = map[AcctInputOctets]string{} func (a AcctInputOctets) String() string { if str, ok := AcctInputOctets_Strings[a]; ok { return str } return "AcctInputOctets(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctInputOctets_Add(p *radius.Packet, value AcctInputOctets) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctInputOctets_Type, a) return nil } func AcctInputOctets_Get(p *radius.Packet) (value AcctInputOctets) { value, _ = AcctInputOctets_Lookup(p) return } func AcctInputOctets_Gets(p *radius.Packet) (values []AcctInputOctets, err error) { var i uint32 for _, attr := range p.Attributes[AcctInputOctets_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctInputOctets(i)) } return } func AcctInputOctets_Lookup(p *radius.Packet) (value AcctInputOctets, err error) { a, ok := p.Lookup(AcctInputOctets_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctInputOctets(i) return } func AcctInputOctets_Set(p *radius.Packet, value AcctInputOctets) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctInputOctets_Type, a) return nil } type AcctOutputOctets uint32 var AcctOutputOctets_Strings = map[AcctOutputOctets]string{} func (a AcctOutputOctets) String() string { if str, ok := AcctOutputOctets_Strings[a]; ok { return str } return "AcctOutputOctets(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctOutputOctets_Add(p *radius.Packet, value AcctOutputOctets) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctOutputOctets_Type, a) return nil } func AcctOutputOctets_Get(p *radius.Packet) (value AcctOutputOctets) { value, _ = AcctOutputOctets_Lookup(p) return } func AcctOutputOctets_Gets(p *radius.Packet) (values []AcctOutputOctets, err error) { var i uint32 for _, attr := range p.Attributes[AcctOutputOctets_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctOutputOctets(i)) } return } func AcctOutputOctets_Lookup(p *radius.Packet) (value AcctOutputOctets, err error) { a, ok := p.Lookup(AcctOutputOctets_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctOutputOctets(i) return } func AcctOutputOctets_Set(p *radius.Packet, value AcctOutputOctets) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctOutputOctets_Type, a) return nil } func AcctSessionID_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(AcctSessionID_Type, a) return nil } func AcctSessionID_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(AcctSessionID_Type, a) return nil } func AcctSessionID_Get(p *radius.Packet) (value []byte) { value, _ = AcctSessionID_Lookup(p) return } func AcctSessionID_GetString(p *radius.Packet) (value string) { return string(AcctSessionID_Get(p)) } func AcctSessionID_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[AcctSessionID_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func AcctSessionID_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[AcctSessionID_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func AcctSessionID_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(AcctSessionID_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func AcctSessionID_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(AcctSessionID_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func AcctSessionID_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(AcctSessionID_Type, a) return } func AcctSessionID_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(AcctSessionID_Type, a) return } type AcctAuthentic uint32 const ( AcctAuthentic_Value_RADIUS AcctAuthentic = 1 AcctAuthentic_Value_Local AcctAuthentic = 2 AcctAuthentic_Value_Remote AcctAuthentic = 3 AcctAuthentic_Value_Diameter AcctAuthentic = 4 ) var AcctAuthentic_Strings = map[AcctAuthentic]string{ AcctAuthentic_Value_RADIUS: "RADIUS", AcctAuthentic_Value_Local: "Local", AcctAuthentic_Value_Remote: "Remote", AcctAuthentic_Value_Diameter: "Diameter", } func (a AcctAuthentic) String() string { if str, ok := AcctAuthentic_Strings[a]; ok { return str } return "AcctAuthentic(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctAuthentic_Add(p *radius.Packet, value AcctAuthentic) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctAuthentic_Type, a) return nil } func AcctAuthentic_Get(p *radius.Packet) (value AcctAuthentic) { value, _ = AcctAuthentic_Lookup(p) return } func AcctAuthentic_Gets(p *radius.Packet) (values []AcctAuthentic, err error) { var i uint32 for _, attr := range p.Attributes[AcctAuthentic_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctAuthentic(i)) } return } func AcctAuthentic_Lookup(p *radius.Packet) (value AcctAuthentic, err error) { a, ok := p.Lookup(AcctAuthentic_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctAuthentic(i) return } func AcctAuthentic_Set(p *radius.Packet, value AcctAuthentic) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctAuthentic_Type, a) return nil } type AcctSessionTime uint32 var AcctSessionTime_Strings = map[AcctSessionTime]string{} func (a AcctSessionTime) String() string { if str, ok := AcctSessionTime_Strings[a]; ok { return str } return "AcctSessionTime(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctSessionTime_Add(p *radius.Packet, value AcctSessionTime) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctSessionTime_Type, a) return nil } func AcctSessionTime_Get(p *radius.Packet) (value AcctSessionTime) { value, _ = AcctSessionTime_Lookup(p) return } func AcctSessionTime_Gets(p *radius.Packet) (values []AcctSessionTime, err error) { var i uint32 for _, attr := range p.Attributes[AcctSessionTime_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctSessionTime(i)) } return } func AcctSessionTime_Lookup(p *radius.Packet) (value AcctSessionTime, err error) { a, ok := p.Lookup(AcctSessionTime_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctSessionTime(i) return } func AcctSessionTime_Set(p *radius.Packet, value AcctSessionTime) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctSessionTime_Type, a) return nil } type AcctInputPackets uint32 var AcctInputPackets_Strings = map[AcctInputPackets]string{} func (a AcctInputPackets) String() string { if str, ok := AcctInputPackets_Strings[a]; ok { return str } return "AcctInputPackets(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctInputPackets_Add(p *radius.Packet, value AcctInputPackets) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctInputPackets_Type, a) return nil } func AcctInputPackets_Get(p *radius.Packet) (value AcctInputPackets) { value, _ = AcctInputPackets_Lookup(p) return } func AcctInputPackets_Gets(p *radius.Packet) (values []AcctInputPackets, err error) { var i uint32 for _, attr := range p.Attributes[AcctInputPackets_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctInputPackets(i)) } return } func AcctInputPackets_Lookup(p *radius.Packet) (value AcctInputPackets, err error) { a, ok := p.Lookup(AcctInputPackets_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctInputPackets(i) return } func AcctInputPackets_Set(p *radius.Packet, value AcctInputPackets) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctInputPackets_Type, a) return nil } type AcctOutputPackets uint32 var AcctOutputPackets_Strings = map[AcctOutputPackets]string{} func (a AcctOutputPackets) String() string { if str, ok := AcctOutputPackets_Strings[a]; ok { return str } return "AcctOutputPackets(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctOutputPackets_Add(p *radius.Packet, value AcctOutputPackets) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctOutputPackets_Type, a) return nil } func AcctOutputPackets_Get(p *radius.Packet) (value AcctOutputPackets) { value, _ = AcctOutputPackets_Lookup(p) return } func AcctOutputPackets_Gets(p *radius.Packet) (values []AcctOutputPackets, err error) { var i uint32 for _, attr := range p.Attributes[AcctOutputPackets_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctOutputPackets(i)) } return } func AcctOutputPackets_Lookup(p *radius.Packet) (value AcctOutputPackets, err error) { a, ok := p.Lookup(AcctOutputPackets_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctOutputPackets(i) return } func AcctOutputPackets_Set(p *radius.Packet, value AcctOutputPackets) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctOutputPackets_Type, a) return nil } type AcctTerminateCause uint32 const ( AcctTerminateCause_Value_UserRequest AcctTerminateCause = 1 AcctTerminateCause_Value_LostCarrier AcctTerminateCause = 2 AcctTerminateCause_Value_LostService AcctTerminateCause = 3 AcctTerminateCause_Value_IdleTimeout AcctTerminateCause = 4 AcctTerminateCause_Value_SessionTimeout AcctTerminateCause = 5 AcctTerminateCause_Value_AdminReset AcctTerminateCause = 6 AcctTerminateCause_Value_AdminReboot AcctTerminateCause = 7 AcctTerminateCause_Value_PortError AcctTerminateCause = 8 AcctTerminateCause_Value_NASError AcctTerminateCause = 9 AcctTerminateCause_Value_NASRequest AcctTerminateCause = 10 AcctTerminateCause_Value_NASReboot AcctTerminateCause = 11 AcctTerminateCause_Value_PortUnneeded AcctTerminateCause = 12 AcctTerminateCause_Value_PortPreempted AcctTerminateCause = 13 AcctTerminateCause_Value_PortSuspended AcctTerminateCause = 14 AcctTerminateCause_Value_ServiceUnavailable AcctTerminateCause = 15 AcctTerminateCause_Value_Callback AcctTerminateCause = 16 AcctTerminateCause_Value_UserError AcctTerminateCause = 17 AcctTerminateCause_Value_HostRequest AcctTerminateCause = 18 ) var AcctTerminateCause_Strings = map[AcctTerminateCause]string{ AcctTerminateCause_Value_UserRequest: "User-Request", AcctTerminateCause_Value_LostCarrier: "Lost-Carrier", AcctTerminateCause_Value_LostService: "Lost-Service", AcctTerminateCause_Value_IdleTimeout: "Idle-Timeout", AcctTerminateCause_Value_SessionTimeout: "Session-Timeout", AcctTerminateCause_Value_AdminReset: "Admin-Reset", AcctTerminateCause_Value_AdminReboot: "Admin-Reboot", AcctTerminateCause_Value_PortError: "Port-Error", AcctTerminateCause_Value_NASError: "NAS-Error", AcctTerminateCause_Value_NASRequest: "NAS-Request", AcctTerminateCause_Value_NASReboot: "NAS-Reboot", AcctTerminateCause_Value_PortUnneeded: "Port-Unneeded", AcctTerminateCause_Value_PortPreempted: "Port-Preempted", AcctTerminateCause_Value_PortSuspended: "Port-Suspended", AcctTerminateCause_Value_ServiceUnavailable: "Service-Unavailable", AcctTerminateCause_Value_Callback: "Callback", AcctTerminateCause_Value_UserError: "User-Error", AcctTerminateCause_Value_HostRequest: "Host-Request", } func (a AcctTerminateCause) String() string { if str, ok := AcctTerminateCause_Strings[a]; ok { return str } return "AcctTerminateCause(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctTerminateCause_Add(p *radius.Packet, value AcctTerminateCause) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctTerminateCause_Type, a) return nil } func AcctTerminateCause_Get(p *radius.Packet) (value AcctTerminateCause) { value, _ = AcctTerminateCause_Lookup(p) return } func AcctTerminateCause_Gets(p *radius.Packet) (values []AcctTerminateCause, err error) { var i uint32 for _, attr := range p.Attributes[AcctTerminateCause_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctTerminateCause(i)) } return } func AcctTerminateCause_Lookup(p *radius.Packet) (value AcctTerminateCause, err error) { a, ok := p.Lookup(AcctTerminateCause_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctTerminateCause(i) return } func AcctTerminateCause_Set(p *radius.Packet, value AcctTerminateCause) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctTerminateCause_Type, a) return nil } func AcctMultiSessionID_Add(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Add(AcctMultiSessionID_Type, a) return nil } func AcctMultiSessionID_AddString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Add(AcctMultiSessionID_Type, a) return nil } func AcctMultiSessionID_Get(p *radius.Packet) (value []byte) { value, _ = AcctMultiSessionID_Lookup(p) return } func AcctMultiSessionID_GetString(p *radius.Packet) (value string) { return string(AcctMultiSessionID_Get(p)) } func AcctMultiSessionID_Gets(p *radius.Packet) (values [][]byte, err error) { var i []byte for _, attr := range p.Attributes[AcctMultiSessionID_Type] { i = radius.Bytes(attr) if err != nil { return } values = append(values, i) } return } func AcctMultiSessionID_GetStrings(p *radius.Packet) (values []string, err error) { var i string for _, attr := range p.Attributes[AcctMultiSessionID_Type] { i = radius.String(attr) if err != nil { return } values = append(values, i) } return } func AcctMultiSessionID_Lookup(p *radius.Packet) (value []byte, err error) { a, ok := p.Lookup(AcctMultiSessionID_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.Bytes(a) return } func AcctMultiSessionID_LookupString(p *radius.Packet) (value string, err error) { a, ok := p.Lookup(AcctMultiSessionID_Type) if !ok { err = radius.ErrNoAttribute return } value = radius.String(a) return } func AcctMultiSessionID_Set(p *radius.Packet, value []byte) (err error) { var a radius.Attribute a, err = radius.NewBytes(value) if err != nil { return } p.Set(AcctMultiSessionID_Type, a) return } func AcctMultiSessionID_SetString(p *radius.Packet, value string) (err error) { var a radius.Attribute a, err = radius.NewString(value) if err != nil { return } p.Set(AcctMultiSessionID_Type, a) return } type AcctLinkCount uint32 var AcctLinkCount_Strings = map[AcctLinkCount]string{} func (a AcctLinkCount) String() string { if str, ok := AcctLinkCount_Strings[a]; ok { return str } return "AcctLinkCount(" + strconv.FormatUint(uint64(a), 10) + ")" } func AcctLinkCount_Add(p *radius.Packet, value AcctLinkCount) (err error) { a := radius.NewInteger(uint32(value)) p.Add(AcctLinkCount_Type, a) return nil } func AcctLinkCount_Get(p *radius.Packet) (value AcctLinkCount) { value, _ = AcctLinkCount_Lookup(p) return } func AcctLinkCount_Gets(p *radius.Packet) (values []AcctLinkCount, err error) { var i uint32 for _, attr := range p.Attributes[AcctLinkCount_Type] { i, err = radius.Integer(attr) if err != nil { return } values = append(values, AcctLinkCount(i)) } return } func AcctLinkCount_Lookup(p *radius.Packet) (value AcctLinkCount, err error) { a, ok := p.Lookup(AcctLinkCount_Type) if !ok { err = radius.ErrNoAttribute return } var i uint32 i, err = radius.Integer(a) if err != nil { return } value = AcctLinkCount(i) return } func AcctLinkCount_Set(p *radius.Packet, value AcctLinkCount) (err error) { a := radius.NewInteger(uint32(value)) p.Set(AcctLinkCount_Type, a) return nil }
feg/radius/lib/go/radius/rfc2866/generated.go
0.523664
0.434821
generated.go
starcoder
package graph import ( "fmt" "sync" ) var Lock = sync.RWMutex{} //GQueue is a queue which holds GNode type GQueue []*GNode //GStack stores pointers to GNode type GStack []*GNode //GNode represent a node in a graph type GNode struct { id int neighbors []*GNode edges []*Edge } //Edge stores edge information in a node type Edge struct { source *GNode target *GNode weight int } //Graph is a map of nodes type Graph map[int]*GNode //NewGraph creates a new graph func NewGraph() *Graph { graph := make(Graph) return &graph } //NewNode creates a new node in a given graph func newNode(id int) *GNode { node := &GNode{ id: id, neighbors: make([]*GNode, 0), edges: make([]*Edge, 0), } return node } //NewNode creates a new node in a given graph func newEdge(source, target *GNode, weight int) *Edge { edge := &Edge{ source: source, target: target, weight: weight, } return edge } func (g *Graph) getNodeFromId(id int) (node *GNode, ok bool) { Lock.RLock() node, ok = (*g)[id] Lock.RUnlock() return } //Contains checks if a node with given `id` exists in the graph func (g *Graph) Contains(id int) bool { _, ok := g.getNodeFromId(id) return ok } //AddVertex adds a new node to a graph func (g *Graph) AddVertex(id int) error { ok := g.Contains(id) if ok { return fmt.Errorf("Node already exists") } Lock.Lock() defer Lock.Unlock() (*g)[id] = newNode(id) return nil } //EdgeExists returns true if an edge exists from src, target node func (g *Graph) EdgeExists(src, target int) (bool, error) { if !g.Contains(src) || !g.Contains(target) { return false, fmt.Errorf("Either of nodes %d or %d does not exist, please add it first", src, target) } node, ok := g.getNodeFromId(src) if ok { for _, nodes := range node.neighbors { if target == nodes.id { return true, nil } } } return false, nil } //AddEdge creates an edge between two nodes represented by id1, id2. //`directed`=true creates a directed graph from id1->id2 func (g *Graph) AddEdge(id1, id2 int, directed bool, weight int) error { if !g.Contains(id1) || !g.Contains(id2) { return fmt.Errorf("Either of nodes %d or %d does not exist, please add it first", id1, id2) } node1, _ := g.getNodeFromId(id1) node2, _ := g.getNodeFromId(id2) node1.neighbors = append(node1.neighbors, node2) node1.edges = append(node1.edges, newEdge(node1, node2, weight)) //undirected graph case if !directed { node2.neighbors = append(node2.neighbors, node1) node2.edges = append(node2.edges, newEdge(node2, node1, weight)) } return nil } //GetVertices gives a list of all the vertices in this graph func (g *Graph) GetVertices() []*GNode { nodes := make([]*GNode, 0) for k := range *g { vertex, ok := g.getNodeFromId(k) if ok { nodes = append(nodes, vertex) } } return nodes } //TODO: Get ride of this function later //GetVerticesID gives a list of all the verticx-id (unique identifier of a node) in this graph func (g *Graph) GetVerticesID() []int { nodes := make([]int, 0) for k := range *g { vertex, ok := g.getNodeFromId(k) if ok { nodes = append(nodes, vertex.id) } } return nodes } //GetNeighbors returns neighbors of a given node with identifier=id func (g *Graph) GetNeighbors(id int) ([]*GNode, error) { node, ok := g.getNodeFromId(id) if !ok { return nil, fmt.Errorf("Node %d does not exist", id) } return node.neighbors, nil } //GetEdges returns the edges of a given node with identifier=id func (g *Graph) GetEdges(id int) ([]*Edge, error) { node, ok := g.getNodeFromId(id) if !ok { return nil, fmt.Errorf("Node %d does not exist", id) } return node.edges, nil } //RemoveEdge removes an edge between two nodes, id1, id2. //If `directed=false` both the edges will be removed. func (g *Graph) RemoveEdge(id1, id2 int, directed bool) error { if !g.Contains(id1) || !g.Contains(id2) { return fmt.Errorf("Either of nodes %d or %d does not exist, please add it first", id1, id2) } node1, _ := g.getNodeFromId(id1) node2, _ := g.getNodeFromId(id2) //Removed the edge from node1. for idx, ed := range node1.edges { if ed.target.id == id2 { (node1.edges) = append(node1.edges[0:idx], node1.edges[idx+1:]...) break } } if !directed { for idx, ed := range node2.edges { if ed.target.id == id1 { (node2.edges) = append(node2.edges[0:idx], node2.edges[idx+1:]...) break } } } return nil }
graph/graph.go
0.619701
0.400192
graph.go
starcoder
package file // List provides a listing of files that can be reasoned about with memorybox // semantics. It also satisfies the sort.Sortable interface. type List []*File // Len returns the length of the underlying array. func (l List) Len() int { return len(l) } // Less returns which of two indexes in the array is "smaller" alphanumerically. func (l List) Less(i, j int) bool { return l[i].Name < l[j].Name } // Swap re-orders the underlying array (used by sort.Sort). func (l List) Swap(i, j int) { l[i], l[j] = l[j], l[i] } // Filter returns a new index where each file has been kept or discarded on // based on the result of processing it with the supplied predicate function. func (l List) Filter(fn func(*File) bool) List { var result List for _, file := range l { if fn(file) { result = append(result, file) continue } } return result } // Meta produces a new file list that only contains metafiles. func (l List) Meta() List { return l.Filter(func(file *File) bool { return IsMetaFileName(file.Name) }) } // Data produces a new file list that only contains datafiles. func (l List) Data() List { return l.Filter(func(file *File) bool { return !IsMetaFileName(file.Name) }) } // ByName produces a map keyed by filename of all files in the list. func (l List) ByName() map[string]*File { result := make(map[string]*File, len(l)) for _, file := range l { name := file.Name result[name] = file } return result } // Names produces an array of filenames in the same order as the file list. func (l List) Names() []string { result := make([]string, len(l)) for index, file := range l { result[index] = file.Name } return result } // Invalid returns a list of files that lack a metafile or datafile pair. func (l List) Invalid() List { return l.paired(false) } // Valid returns a list of files have a metafile or datafile pair. func (l List) Valid() List { return l.paired(true) } func (l List) paired(hasPair bool) List { index := l.ByName() return l.Filter(func(file *File) bool { pair := MetaNameFrom(file.Name) if IsMetaFileName(file.Name) { pair = DataNameFrom(file.Name) } _, ok := index[pair] return ok == hasPair }) }
pkg/file/list.go
0.772402
0.547222
list.go
starcoder
// statemachine package contains the helper code for generating a state machine representing the statement // and expression level of the ES5 generator. package statemachine import ( "fmt" "github.com/serulian/compiler/graphs/typegraph" "github.com/serulian/compiler/compilergraph" "github.com/serulian/compiler/generator/es5/codedom" "github.com/serulian/compiler/generator/es5/dombuilder" "github.com/serulian/compiler/generator/es5/expressiongenerator" "github.com/serulian/compiler/generator/es5/shared" "github.com/serulian/compiler/generator/escommon/esbuilder" "github.com/serulian/compiler/graphs/scopegraph" ) var _ = fmt.Printf // FunctionDef defines the struct for a function accepted by GenerateFunctionSource. type FunctionDef struct { Generics []string // Returns the names of the generics on the function, if any. Parameters []string // Returns the names of the parameters on the function, if any. RequiresThis bool // Returns if this function is requires the "this" var to be added. WorkerExecutes bool // Returns true if this function should be executed by a web worker. GeneratorYieldType *typegraph.TypeReference // Returns a non-nil value if the function being generated is a generator. BodyNode compilergraph.GraphNode // The parser root node for the function body. } // GenerateFunctionSource generates the source code for a function, including its internal state machine. func GenerateFunctionSource(functionDef FunctionDef, scopegraph *scopegraph.ScopeGraph) esbuilder.SourceBuilder { // Build the body via CodeDOM. funcBody := dombuilder.BuildStatement(scopegraph, functionDef.BodyNode) // Instantiate a new state machine generator and use it to generate the function. functionTraits := shared.FunctionTraits(codedom.IsAsynchronous(funcBody, scopegraph), functionDef.GeneratorYieldType != nil, codedom.IsManagingResources(funcBody)) sg := buildGenerator(scopegraph, shared.NewTemplater(), functionTraits) specialization := codedom.NormalFunction if functionDef.WorkerExecutes { specialization = codedom.AsynchronousWorkerFunction } domDefinition := codedom.FunctionDefinition( functionDef.Generics, functionDef.Parameters, funcBody, functionDef.RequiresThis, specialization, functionDef.BodyNode) if functionDef.GeneratorYieldType != nil { domDefinition = codedom.GeneratorDefinition( functionDef.Generics, functionDef.Parameters, funcBody, functionDef.RequiresThis, *functionDef.GeneratorYieldType, functionDef.BodyNode) } // Generate the function expression. result := expressiongenerator.GenerateExpression(domDefinition, expressiongenerator.AllowedSync, scopegraph, sg.generateMachine) return result.Build() } // GenerateExpressionResult generates the expression result for an expression. func GenerateExpressionResult(expressionNode compilergraph.GraphNode, scopegraph *scopegraph.ScopeGraph) expressiongenerator.ExpressionResult { // Build the CodeDOM for the expression. domDefinition := dombuilder.BuildExpression(scopegraph, expressionNode) // Generate the state machine. functionTraits := shared.FunctionTraits(domDefinition.IsAsynchronous(scopegraph), false, false) sg := buildGenerator(scopegraph, shared.NewTemplater(), functionTraits) return expressiongenerator.GenerateExpression(domDefinition, expressiongenerator.AllowedSync, scopegraph, sg.generateMachine) }
generator/es5/statemachine/statemachine.go
0.621885
0.468547
statemachine.go
starcoder
package ast import ( "fmt" "github.com/tabby-lang/tc/token" ) // interface methods func (p Program) TokenLiteral() string { return "Program" } // Statements func (ls AssignStatement) statementNode() {} func (ls AssignStatement) TokenLiteral() string { return "AssignStatement" } func (rs ReturnStatement) statementNode() {} func (rs ReturnStatement) TokenLiteral() string { return "ReturnStatement" } func (es ExpressionStatement) statementNode() {} func (es ExpressionStatement) TokenLiteral() string { return "ExpressionStatement" } func (is IfStatement) statementNode() {} func (is IfStatement) TokenLiteral() string { return "IfStatement" } func (bs BlockStatement) statementNode() {} func (bs BlockStatement) TokenLiteral() string { return "BlockStatement" } func (is InitStatement) statementNode() {} func (is InitStatement) TokenLiteral() string { return "InitStatement" } func (fs FunctionStatement) statementNode() {} func (fs FunctionStatement) TokenLiteral() string { return "FunctionStatement" } // Expressions func (i Identifier) expressionNode() {} func (i Identifier) TokenLiteral() string { return string(i.Token.Lit) } func (sl StringLiteral) expressionNode() {} func (sl StringLiteral) TokenLiteral() string { return string(sl.Token.Lit) } func (b Boolean) expressionNode() {} func (b Boolean) TokenLiteral() string { return string(b.Token.Lit) } func (il IntegerLiteral) expressionNode() {} func (il IntegerLiteral) TokenLiteral() string { return string(il.Token.Lit) } func (oe InfixExpression) expressionNode() {} func (oe InfixExpression) TokenLiteral() string { return string(oe.Token.Lit) } func (fc FunctionCall) expressionNode() {} func (fc FunctionCall) TokenLiteral() string { return string(fc.Token.Lit) } func Error(fun, expected, v string, got interface{}) error { return fmt.Errorf("AST construction error: In function: %s, expected %s for %s. got=%T", fun, expected, v, got) } // AST Constructors func NewProgram(funcs, stmts Attrib) (*Program, error) { s, ok := stmts.([]Statement) if !ok { return nil, Error("NewProgram", "[]Statement", "stmts", stmts) } f, ok := funcs.([]Statement) if !ok { return nil, Error("NewProgram", "[]Statement", "funcs", funcs) } return &Program{Functions: f, Statements: s}, nil } func NewStatementList() ([]Statement, error) { return []Statement{}, nil } func AppendStatement(stmtList, stmt Attrib) ([]Statement, error) { s, ok := stmt.(Statement) if !ok { return nil, Error("AppendStatement", "Statement", "stmt", stmt) } return append(stmtList.([]Statement), s), nil } func NewAssignStatement(left, right Attrib) (Statement, error) { l, ok := left.(*token.Token) if !ok { return nil, Error("NewAssignStatement", "Identifier", "left", left) } r, ok := right.(Expression) if !ok { return nil, Error("NewAssignStatement", "Expression", "right", right) } return &AssignStatement{Left: Identifier{Value: string(l.Lit)}, Right: r}, nil } func NewExpressionStatement(expr Attrib) (Statement, error) { e, ok := expr.(Expression) if !ok { return nil, Error("NewExpressionStatement", "Expression", "expr", expr) } return &ExpressionStatement{Expression: e}, nil } func NewBlockStatement(stmts Attrib) (*BlockStatement, error) { s, ok := stmts.([]Statement) if !ok { return nil, Error("NewBlockStatement", "[]Statement", "stmts", stmts) } return &BlockStatement{Statements: s}, nil } func NewFunctionStatement(name, args, ret, block Attrib) (Statement, error) { n, ok := name.(*token.Token) if !ok { return nil, Error("NewFunctionStatement", "*token.Token", "name", name) } b, ok := block.(*BlockStatement) if !ok { return nil, Error("NewFunctionStatement", "BlockStatement", "block", block) } a := []FormalArg{} if args != nil { a, ok = args.([]FormalArg) if !ok { return nil, Error("NewFunctionStatement", "[]FormalArg", "args", args) } } r, ok := ret.(*token.Token) if !ok { // bad } return &FunctionStatement{Name: string(n.Lit), Body: b, Parameters: a, Return: string(r.Lit)}, nil } func NewIfStatement(cond, cons, alt Attrib) (Statement, error) { c, ok := cond.(Expression) if !ok { return nil, fmt.Errorf("invalid type of cond. got=%T", cond) } cs, ok := cons.(*BlockStatement) if !ok { return nil, fmt.Errorf("invalid type of cons. got=%T", cons) } a, ok := alt.(*BlockStatement) if !ok { return nil, fmt.Errorf("invalid type of alt. got=%T", alt) } return &IfStatement{Condition: c, Block: cs, Alternative: a}, nil } func NewInfixExpression(left, right, oper Attrib) (Expression, error) { l, ok := left.(Expression) if !ok { fmt.Println(left) return nil, Error("NewInfixExpression", "Expression", "left", left) } o, ok := oper.(*token.Token) if !ok { return nil, Error("NewInfixExpression", "*token.Token", "oper", oper) } r, ok := right.(Expression) if !ok { return nil, Error("NewInfixExpression", "Expression", "right", right) } return &InfixExpression{Left: l, Operator: string(o.Lit), Right: r, Token: o}, nil } func NewIntegerLiteral(integer Attrib) (Expression, error) { intLit, ok := integer.(*token.Token) if !ok { return nil, Error("NewIntegerLiteral", "*token.Token", "integer", integer) } return &IntegerLiteral{Token: intLit, Value: string(intLit.Lit)}, nil } func NewStringLiteral(str Attrib) (Expression, error) { return &StringLiteral{Value: string(str.(*token.Token).Lit), Token: str.(*token.Token)}, nil } func NewIdentInit(ident, expr Attrib) (Statement, error) { e, ok := expr.(Expression) if !ok { return nil, Error("NewIdentInit", "Expression", "expr", expr) } return &InitStatement{Location: string(ident.(*token.Token).Lit), Token: ident.(*token.Token), Expr: e}, nil } func NewIdentExpression(ident Attrib) (*Identifier, error) { return &Identifier{Value: string(ident.(*token.Token).Lit), Token: ident.(*token.Token)}, nil } func NewBoolExpression(val Attrib) (Expression, error) { return &Boolean{Value: val.(bool)}, nil } func NewReturnStatement(exp Attrib) (Statement, error) { e, ok := exp.(Expression) if !ok { return nil, Error("NewReturnExpression", "Expression", "exp", exp) } return &ReturnStatement{ReturnValue: e}, nil } func NewFunctionCall(name, args Attrib) (Expression, error) { n, ok := name.(*token.Token) if !ok { return nil, fmt.Errorf("invalid type of name. got=%T", name) } a := []Expression{} if args != nil { var ok bool a, ok = args.([]Expression) if !ok { return nil, Error("NewFunctionCall", "[]Expression", "args", args) } } return &FunctionCall{Name: string(n.Lit), Args: a, Token: n}, nil } func NewFormalArg() ([]FormalArg, error) { return []FormalArg{}, nil } func AppendFormalArgs(args, arg, kind Attrib) ([]FormalArg, error) { as, ok := args.([]FormalArg) if !ok { return nil, Error("AppendFormalArgs", "[]FormalArg", "args", args) } a, ok := arg.(*token.Token) if !ok { return nil, Error("AppendFormalArgs", "*token.Token", "arg", arg) } k, ok := kind.(*token.Token) if !ok { return nil, fmt.Errorf("invalid type of kind. got=%T", kind) } return append(as, FormalArg{string(a.Lit), string(k.Lit)}), nil } func NewArg() ([]Expression, error) { return []Expression{}, nil } func AppendArgs(expr, args Attrib) ([]Expression, error) { as, ok := args.([]Expression) if !ok { return nil, Error("AppendFormalArgs", "[]FormalArgs", "args", args) } e, ok := expr.(Expression) if !ok { return nil, Error("AppendFormalArgs", "Expression", "expr", expr) } return append(as, e), nil }
ast/ast.go
0.588889
0.470128
ast.go
starcoder
package types import ( "sync" ) type TSafeUint64s interface { // Reset the slice. Reset() // Contains say if "s" contains "values". Contains(...uint64) bool // ContainsOneOf says if "s" contains one of the "values". ContainsOneOf(...uint64) bool // Copy create a new copy of the slice. Copy() TSafeUint64s // Diff returns the difference between "s" and "s2". Diff(Uint64s) Uint64s // Empty says if the slice is empty. Empty() bool // Equal says if "s" and "s2" are equal. Equal(Uint64s) bool // Find the first element matching the pattern. Find(func(v uint64) bool) (uint64, bool) // FindAll elements matching the pattern. FindAll(func(v uint64) bool) Uint64s // First return the value of the first element. First() (uint64, bool) // Get the element "i" and say if it has been found. Get(int) (uint64, bool) // Intersect return the intersection between "s" and "s2". Intersect(Uint64s) Uint64s // Last return the value of the last element. Last() (uint64, bool) // Len returns the size of the slice. Len() int // Take n element and return a new slice. Take(int) Uint64s // S convert s into []interface{} S() []interface{} // S convert s into Uint64s Uint64s() Uint64s } func SyncUint64s() TSafeUint64s { return &tsafeUint64s{&sync.RWMutex{}, Uint64s{}} } type tsafeUint64s struct { mu *sync.RWMutex values Uint64s } func (s *tsafeUint64s) Reset() { s.mu.Lock() s.values.Reset() s.mu.Unlock() } func (s *tsafeUint64s) Contains(values ...uint64) (ok bool) { s.mu.RLock() ok = s.values.Contains(values...) s.mu.RUnlock() return } func (s *tsafeUint64s) ContainsOneOf(values ...uint64) (ok bool) { s.mu.RLock() ok = s.values.ContainsOneOf(values...) s.mu.RUnlock() return } func (s *tsafeUint64s) Copy() TSafeUint64s { s2 := &tsafeUint64s{mu: &sync.RWMutex{}} s.mu.RLock() s2.values = s.values.Copy() s.mu.RUnlock() return s2 } func (s *tsafeUint64s) Diff(s2 Uint64s) (out Uint64s) { s.mu.RLock() out = s.values.Diff(s2) s.mu.RUnlock() return } func (s *tsafeUint64s) Empty() (ok bool) { s.mu.RLock() ok = s.values.Empty() s.mu.RUnlock() return } func (s *tsafeUint64s) Equal(s2 Uint64s) (ok bool) { s.mu.RLock() ok = s.values.Equal(s2) s.mu.RUnlock() return } func (s *tsafeUint64s) Find(matcher func(v uint64) bool) (v uint64, ok bool) { s.mu.RLock() v, ok = s.values.Find(matcher) s.mu.RUnlock() return } func (s *tsafeUint64s) FindAll(matcher func(v uint64) bool) (v Uint64s) { s.mu.RLock() v = s.values.FindAll(matcher) s.mu.RUnlock() return } func (s *tsafeUint64s) First() (v uint64, ok bool) { s.mu.RLock() v, ok = s.values.First() s.mu.RUnlock() return } func (s *tsafeUint64s) Get(i int) (v uint64, ok bool) { s.mu.RLock() v, ok = s.values.Get(i) s.mu.RUnlock() return } func (s *tsafeUint64s) Intersect(s2 Uint64s) (v Uint64s) { s.mu.RLock() v = s.values.Intersect(s2) s.mu.RUnlock() return } func (s *tsafeUint64s) Last() (v uint64, ok bool) { s.mu.RLock() v, ok = s.values.Last() s.mu.RUnlock() return } func (s *tsafeUint64s) Len() (v int) { s.mu.RLock() v = s.values.Len() s.mu.RUnlock() return } func (s *tsafeUint64s) Take(n int) (v Uint64s) { s.mu.RLock() v = s.values.Take(n) s.mu.RUnlock() return } func (s *tsafeUint64s) S() (out []interface{}) { s.mu.RLock() out = s.values.S() s.mu.RUnlock() return } func (s *tsafeUint64s) Uint64s() (v Uint64s) { s.mu.RLock() v = s.values.Copy() s.mu.RUnlock() return }
syncuint64s.go
0.68763
0.427994
syncuint64s.go
starcoder
package tokenizer import ( "fmt" "strings" "github.com/ikawaha/kagome-dict/dict" "github.com/ikawaha/kagome/v2/tokenizer/lattice" ) // TokenClass represents the token class. type TokenClass lattice.NodeClass const ( // DUMMY represents the dummy token. DUMMY = TokenClass(lattice.DUMMY) // KNOWN represents the token in the dictionary. KNOWN = TokenClass(lattice.KNOWN) // UNKNOWN represents the token which is not in the dictionary. UNKNOWN = TokenClass(lattice.UNKNOWN) // USER represents the token in the user dictionary. USER = TokenClass(lattice.USER) ) // String returns string representation of a token class. func (c TokenClass) String() string { ret := "" switch c { case DUMMY: ret = "DUMMY" case KNOWN: ret = "KNOWN" case UNKNOWN: ret = "UNKNOWN" case USER: ret = "USER" } return ret } // Token represents a morph of a sentence. type Token struct { Index int ID int Class TokenClass Position int // byte position Start int End int Surface string dict *dict.Dict udict *dict.UserDict } // Features returns contents of a token. func (t Token) Features() []string { switch t.Class { case KNOWN: var c int if t.dict.Contents != nil { c = len(t.dict.Contents[t.ID]) } features := make([]string, 0, len(t.dict.POSTable.POSs[t.ID])+c) for _, id := range t.dict.POSTable.POSs[t.ID] { features = append(features, t.dict.POSTable.NameList[id]) } if t.dict.Contents != nil { features = append(features, t.dict.Contents[t.ID]...) } return features case UNKNOWN: features := make([]string, len(t.dict.UnkDict.Contents[t.ID])) for i := range t.dict.UnkDict.Contents[t.ID] { features[i] = t.dict.UnkDict.Contents[t.ID][i] } return features case USER: pos := t.udict.Contents[t.ID].Pos tokens := strings.Join(t.udict.Contents[t.ID].Tokens, "/") yomi := strings.Join(t.udict.Contents[t.ID].Yomi, "/") return []string{pos, tokens, yomi} } return nil } // FeatureAt returns the i th feature if exists. func (t Token) FeatureAt(i int) (string, bool) { if i < 0 { return "", false } switch t.Class { case KNOWN: pos := t.dict.POSTable.POSs[t.ID] if i < len(pos) { id := pos[i] if int(id) > len(t.dict.POSTable.NameList) { return "", false } return t.dict.POSTable.NameList[id], true } i -= len(pos) if len(t.dict.Contents) <= t.ID { return "", false } c := t.dict.Contents[t.ID] if i >= len(c) { return "", false } return c[i], true case UNKNOWN: if len(t.dict.UnkDict.Contents) <= t.ID { return "", false } c := t.dict.UnkDict.Contents[t.ID] if i >= len(c) { return "", false } return c[i], true case USER: if len(t.udict.Contents) <= t.ID { return "", false } switch i { case 0: return t.udict.Contents[t.ID].Pos, true case 1: return strings.Join(t.udict.Contents[t.ID].Tokens, "/"), true case 2: return strings.Join(t.udict.Contents[t.ID].Yomi, "/"), true } } return "", false } // POS returns POS elements of features. func (t Token) POS() []string { switch t.Class { case KNOWN: ret := make([]string, 0, len(t.dict.POSTable.POSs[t.ID])) for _, id := range t.dict.POSTable.POSs[t.ID] { ret = append(ret, t.dict.POSTable.NameList[id]) } return ret case UNKNOWN: start := 0 if v, ok := t.dict.UnkDict.ContentsMeta[dict.POSStartIndex]; ok { start = int(v) } end := 1 if v, ok := t.dict.UnkDict.ContentsMeta[dict.POSHierarchy]; ok { end = start + int(v) } feature := t.dict.UnkDict.Contents[t.ID] if start >= end || end > len(feature) { return nil } ret := make([]string, 0, end-start) for i := start; i < end; i++ { ret = append(ret, feature[i]) } return ret case USER: pos := t.udict.Contents[t.ID].Pos return []string{pos} } return nil } // InflectionalType returns the inflectional type feature if exists. func (t Token) InflectionalType() (string, bool) { return t.pickupFromFeatures(dict.InflectionalType) } // InflectionalForm returns the inflectional form feature if exists. func (t Token) InflectionalForm() (string, bool) { return t.pickupFromFeatures(dict.InflectionalForm) } // BaseForm returns the base form features if exists. func (t Token) BaseForm() (string, bool) { return t.pickupFromFeatures(dict.BaseFormIndex) } // Reading returns the reading feature if exists. func (t Token) Reading() (string, bool) { return t.pickupFromFeatures(dict.ReadingIndex) } // Pronunciation returns the pronunciation feature if exists. func (t Token) Pronunciation() (string, bool) { return t.pickupFromFeatures(dict.PronunciationIndex) } func (t Token) pickupFromFeatures(key string) (string, bool) { var meta dict.ContentsMeta switch t.Class { case KNOWN: meta = t.dict.ContentsMeta case UNKNOWN: meta = t.dict.UnkDict.ContentsMeta } i, ok := meta[key] if !ok { return "", false } return t.FeatureAt(int(i)) } // String returns a string representation of a token. func (t Token) String() string { return fmt.Sprintf("%d:%q (%d: %d, %d) %v [%d]", t.Index, t.Surface, t.Position, t.Start, t.End, t.Class, t.ID) } // Equal returns true if tokens are equal. func (t Token) Equal(v Token) bool { return t.ID == v.ID && t.Class == v.Class && t.Surface == v.Surface } // TokenData is a data format with all the contents of the token. type TokenData struct { ID int `json:"id"` Start int `json:"start"` End int `json:"end"` Surface string `json:"surface"` Class string `json:"class"` POS []string `json:"pos"` BaseForm string `json:"base_form"` Reading string `json:"reading"` Pronunciation string `json:"pronunciation"` Features []string `json:"features"` } // NewTokenData returns a data which has with all the contents of the token. func NewTokenData(t Token) TokenData { ret := TokenData{ ID: t.ID, Start: t.Start, End: t.End, Surface: t.Surface, Class: t.Class.String(), POS: t.POS(), Features: t.Features(), } if ret.POS == nil { ret.POS = []string{} } if ret.Features == nil { ret.Features = []string{} } ret.BaseForm, _ = t.BaseForm() ret.Reading, _ = t.Reading() ret.Pronunciation, _ = t.Pronunciation() return ret }
tokenizer/token.go
0.660282
0.486149
token.go
starcoder
package toy import ( "github.com/OpenWhiteBox/primitives/encoding" "github.com/OpenWhiteBox/primitives/gfmatrix" ) // permutation is a byte-wise permutation of a block. type permutation encoding.Shuffle // newPermutation returns an identity permutation. func newPermutation() *permutation { p := &permutation{} for i := byte(0); i < 16; i++ { p.EncKey[i], p.DecKey[i] = i, i } return p } func (p *permutation) Encode(in [16]byte) (out [16]byte) { for i := byte(0); i < 16; i++ { out[(*encoding.Shuffle)(p).Encode(i)] = in[i] } return out } func (p *permutation) Decode(in [16]byte) (out [16]byte) { for i := byte(0); i < 16; i++ { out[(*encoding.Shuffle)(p).Decode(i)] = in[i] } return out } func (p *permutation) swap(i, j int) { p.DecKey[p.EncKey[i]], p.DecKey[p.EncKey[j]] = p.DecKey[p.EncKey[j]], p.DecKey[p.EncKey[i]] p.EncKey[i], p.EncKey[j] = p.EncKey[j], p.EncKey[i] } // smallMatrix is a round matrix compressed to only its MixColumns coefficient. type smallMatrix gfmatrix.Matrix func (sm smallMatrix) swapRows(x, y int) { sm[x], sm[y] = sm[y], sm[x] } func (sm smallMatrix) swapCols(x, y int) { for row := 0; row < 16; row++ { sm[row][x], sm[row][y] = sm[row][y], sm[row][x] } } // unpermute transforms sm until it is equal to a compressed round matrix. sm is mutated to the compressed round matrix, // and permIn and permOut are the permutations that moved it there. func (sm smallMatrix) unpermute() (permIn, permOut *permutation) { permIn, permOut = newPermutation(), newPermutation() ok := sm.unpermuteStep(0, permIn, permOut) if !ok { panic("unable to unpermute matrix") } return } // unpermuteStep is one step of the dynamic programming algorithm. It works by moving different twos to the diagonal and // checking if this leads to a partially correct matrix. func (sm smallMatrix) unpermuteStep(step int, permIn, permOut *permutation) bool { if step == 16 { return true } // Build a list of all twos below. twos := [][2]int{} for row := step; row < 16; row++ { for col := step; col < 16; col++ { if sm[row][col] == 2 { twos = append(twos, [2]int{row, col}) } } } // Foreach two, try to put it in the diagonal. Check neighboring entries for correctness. Recurse. for _, two := range twos { // Put this two in the diagonal. sm.swapRows(step, two[0]) sm.swapCols(step, two[1]) permIn.swap(step, two[1]) permOut.swap(step, two[0]) // Check for correctness. ok := true for row := 0; row < step; row++ { ok = ok && sm[row][step] == smallRound[row][step] } for col := 0; col < step; col++ { ok = ok && sm[step][col] == smallRound[step][col] } if !ok { continue } // Recurse down. if sm.unpermuteStep(step+1, permIn, permOut) { return true } // Couldn't find lower solution. Undo swaps. sm.swapRows(step, two[0]) sm.swapCols(step, two[1]) permIn.swap(step, two[1]) permOut.swap(step, two[0]) } return false }
cryptanalysis/toy/small_matrix.go
0.809276
0.484868
small_matrix.go
starcoder
package fake var EasypostFakeCreateOrder string var EasypostFakeBuyOrder string func init() { EasypostFakeCreateOrder = ` { "id": "order_b39d44e7059a46c8a787174e8320bf1c", "mode": "test", "reference": null, "is_return": false, "options": {"currency": "USD","label_date": null}, "messages": [], "created_at": "2016-02-17T02:51:04Z", "updated_at": "2016-02-17T02:51:04Z", "customs_info": null, "to_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "from_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "items": [], "containers": [], "shipments": [ { "id": "shp_7a387659db374a8ea197d7bba3009d5d", "created_at": "2016-02-17T02:51:04Z", "updated_at": "2016-02-17T02:51:10Z", "is_return": false, "messages": [], "mode": "test", "options": {"currency": "USD", "label_date": null}, "reference": null, "status": "unknown", "tracking_code": "1ZE6A4850190733810", "batch_id": null, "batch_status": null, "batch_message": null, "parcel": { "id": "prcl_071994637e1046ab98a79f96d8b26488", "object": "Parcel", "length": 20.2, "width": 10.9, "height": 5.0, "predefined_package": null, "weight": 17.5, "created_at": "2013-04-22T05:39:57Z", "updated_at": "2013-04-22T05:39:57Z" }, "customs_info": null, "to_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "from_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "postage_label": null, "rates": [ { "id": "rate_1f168714581b40af965dd740ddf35f69", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "PRIORITY_OVERNIGHT", "carrier": "FedEx", "rate": "47.36", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T10:30:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_b701a9da21424a5f85a09530c9f924aa", "carrier_account_id": "<KEY>" }, { "id": "rate_1567998062c445ab909daf872461d15e", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "STANDARD_OVERNIGHT", "carrier": "FedEx", "rate": "118.00", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T15:00:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_b701a9da21424a5f85a09530c9f924aa", "carrier_account_id": "<KEY>" }, { "id": "rate_f9a9706f99754609a60b2ec512e82cbf", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "FEDEX_GROUND", "carrier": "FedEx", "rate": "17.96", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 4, "delivery_date": null, "delivery_date_guaranteed": false, "est_delivery_days": null, "shipment_id": "shp_b701a9da21424a5f85a09530c9f924aa", "carrier_account_id": "ca_f02596dcabbb46a8ba823280efc277bb" } ], "refund_status": null, "scan_form": null, "selected_rate": null, "tracker": null, "forms": [], "fees": [], "object": "Shipment" }, { "id": "shp_b25c22b64a7f45bd859e826d3701471c", "created_at": "2016-02-17T02:51:04Z", "updated_at": "2016-02-17T02:51:10Z", "is_return": false, "messages": [], "mode": "test", "options": {"currency": "USD", "label_date": null}, "reference": null, "status": "unknown", "tracking_code": "1ZE6A4850190733810", "batch_id": null, "batch_status": null, "batch_message": null, "parcel": { "id": "prcl_307ea2f3486544e58d5496fc840f6376", "object": "Parcel", "length": 7.2, "width": 1.9, "height": 1.0, "predefined_package": null, "weight": 10.8, "created_at": "2013-04-22T05:39:57Z", "updated_at": "2013-04-22T05:39:57Z" }, "customs_info": null, "to_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "from_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "postage_label": null, "rates": [], "refund_status": null, "scan_form": null, "selected_rate": null, "tracker": null, "forms": [], "fees": [], "object": "Shipment" } ], "rates": [ { "id": "rate_1f168714581b40af965dd740ddf35f69", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "PRIORITY_OVERNIGHT", "carrier": "FedEx", "rate": "47.36", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T10:30:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_7a387659db374a8ea197d7bba3009d5d", "carrier_account_id": "<KEY>" }, { "id": "rate_1567998062c445ab909daf872461d15e", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "STANDARD_OVERNIGHT", "carrier": "FedEx", "rate": "118.00", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T15:00:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_7a387659db374a8ea197d7bba3009d5d", "carrier_account_id": "<KEY>" }, { "id": "rate_f9a9706f99754609a60b2ec512e82cbf", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "FEDEX_GROUND", "carrier": "FedEx", "rate": "17.96", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 4, "delivery_date": null, "delivery_date_guaranteed": false, "est_delivery_days": null, "shipment_id": "shp_7a387659db374a8ea197d7bba3009d5d", "carrier_account_id": "<KEY>" } ], "object": "Order" } ` EasypostFakeBuyOrder = ` { "id": "order_b39d44e7059a46c8a787174e8320bf1c", "mode": "test", "reference": null, "is_return": false, "options": {"currency": "USD","label_date": null}, "messages": [], "created_at": "2016-02-17T02:51:04Z", "updated_at": "2016-02-17T02:51:04Z", "customs_info": null, "to_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "from_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "items": [], "containers": [], "shipments": [ { "id": "shp_7a387659db374a8ea197d7bba3009d5d", "created_at": "2016-02-17T02:51:04Z", "updated_at": "2016-02-17T02:51:10Z", "is_return": false, "messages": [], "mode": "test", "options": {"currency": "USD", "label_date": null}, "reference": null, "status": "unknown", "tracking_code": "1ZE6A4850190733810", "batch_id": null, "batch_status": null, "batch_message": null, "parcel": { "id": "prcl_071994637e1046ab98a79f96d8b26488", "object": "Parcel", "length": 20.2, "width": 10.9, "height": 5.0, "predefined_package": null, "weight": 17.5, "created_at": "2013-04-22T05:39:57Z", "updated_at": "2013-04-22T05:39:57Z" }, "customs_info": null, "to_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "from_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "postage_label": { "id": "pl_317098e591fc4d0bbc94bf5e7e47668f", "object": "PostageLabel", "created_at": "2016-02-17T03:10:30Z", "updated_at": "2016-02-17T03:10:30Z", "date_advance": 0, "integrated_form": "none", "label_date": "2016-02-17T03:00:16Z", "label_resolution": 200, "label_size": "PAPER_4X6", "label_type": "default", "label_url": "http://assets.geteasypost.com/postage_labels/labels/20160217/5205d36225364da686e2ba8476b565a9.png", "label_file_type": "image/png", "label_pdf_url": null, "label_epl2_url": null, "label_zpl_url": null }, "rates": [ { "id": "rate_1f168714581b40af965dd740ddf35f69", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "PRIORITY_OVERNIGHT", "carrier": "FedEx", "rate": "47.36", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T10:30:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_b701a9da21424a5f85a09530c9f924aa", "carrier_account_id": "<KEY>" }, { "id": "rate_1567998062c445ab909daf872461d15e", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "STANDARD_OVERNIGHT", "carrier": "FedEx", "rate": "118.00", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T15:00:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_b701a9da21424a5f85a09530c9f924aa", "carrier_account_id": "<KEY>" }, { "id": "rate_f9a9706f99754609a60b2ec512e82cbf", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "FEDEX_GROUND", "carrier": "FedEx", "rate": "17.96", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 4, "delivery_date": null, "delivery_date_guaranteed": false, "est_delivery_days": null, "shipment_id": "shp_b701a9da21424a5f85a09530c9f924aa", "carrier_account_id": "<KEY>" } ], "refund_status": null, "scan_form": null, "selected_rate": null, "tracker": null, "forms": [], "fees": [], "object": "Shipment" }, { "id": "shp_b25c22b64a7f45bd859e826d3701471c", "created_at": "2016-02-17T02:51:04Z", "updated_at": "2016-02-17T02:51:10Z", "is_return": false, "messages": [], "mode": "test", "options": {"currency": "USD", "label_date": null}, "reference": null, "status": "unknown", "tracking_code": "1ZE6A4850190733810", "batch_id": null, "batch_status": null, "batch_message": null, "parcel": { "id": "prcl_307ea2f3486544e58d5496fc840f6376", "object": "Parcel", "length": 7.2, "width": 1.9, "height": 1.0, "predefined_package": null, "weight": 10.8, "created_at": "2013-04-22T05:39:57Z", "updated_at": "2013-04-22T05:39:57Z" }, "customs_info": null, "to_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "from_address": { "id": "adr_7a387659db374a8ea197d7bba3009d5d" }, "postage_label": { "id": "pl_1a118b22c63f4bf9825437c01f6f9f38", "object": "PostageLabel", "created_at": "2016-02-17T03:10:32Z", "updated_at": "2016-02-17T03:10:32Z", "date_advance": 0, "integrated_form": "none", "label_date": "2016-02-17T03:00:16Z", "label_resolution": 200, "label_size": "PAPER_4X6", "label_type": "default", "label_url": "http://assets.geteasypost.com/postage_labels/labels/20160217/788f130b67f34a92b65b8b6f5c17e792.png", "label_file_type": "image/png", "label_pdf_url": null, "label_epl2_url": null, "label_zpl_url": null }, "rates": [], "refund_status": null, "scan_form": null, "selected_rate": null, "tracker": null, "forms": [], "fees": [], "object": "Shipment" } ], "rates": [ { "id": "rate_1f168714581b40af965dd740ddf35f69", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "PRIORITY_OVERNIGHT", "carrier": "FedEx", "rate": "47.36", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T10:30:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_7a387659db374a8ea197d7bba3009d5d", "carrier_account_id": "<KEY>" }, { "id": "rate_1567998062c445ab909daf872461d15e", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "STANDARD_OVERNIGHT", "carrier": "FedEx", "rate": "118.00", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 1, "delivery_date": "2016-02-18T15:00:00Z", "delivery_date_guaranteed": true, "est_delivery_days": null, "shipment_id": "shp_7a387659db374a8ea197d7bba3009d5d", "carrier_account_id": "<KEY>" }, { "id": "rate_f9a9706f99754609a60b2ec512e82cbf", "object": "Rate", "created_at": null, "updated_at": null, "mode": "test", "service": "FEDEX_GROUND", "carrier": "FedEx", "rate": "17.96", "currency": "USD", "retail_rate": null, "retail_currency": null, "list_rate": null, "list_currency": null, "delivery_days": 4, "delivery_date": null, "delivery_date_guaranteed": false, "est_delivery_days": null, "shipment_id": "shp_7a387659db374a8ea197d7bba3009d5d", "carrier_account_id": "<KEY>" } ], "object": "Order" } ` }
fake/orderFake.go
0.562777
0.4231
orderFake.go
starcoder
// Package elliptic implements several standard elliptic curves over prime // fields. package elliptic // This package operates, internally, on Jacobian coordinates. For a given // (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1) // where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole // calculation can be performed within the transform (as in ScalarMult and // ScalarBaseMult). But even for Add and Double, it's faster to apply and // reverse the transform than to operate in affine coordinates. import ( "io" "math/big" "sync" ) // A Curve represents a short-form Weierstrass curve with a=-3. // See https://www.hyperelliptic.org/EFD/g1p/auto-shortw.html type Curve interface { // Params returns the parameters for the curve. Params() *CurveParams // IsOnCurve reports whether the given (x,y) lies on the curve. IsOnCurve(x, y *big.Int) bool // Add returns the sum of (x1,y1) and (x2,y2) Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int) // Double returns 2*(x,y) Double(x1, y1 *big.Int) (x, y *big.Int) // ScalarMult returns k*(Bx,By) where k is a number in big-endian form. ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int) // ScalarBaseMult returns k*G, where G is the base point of the group // and k is an integer in big-endian form. ScalarBaseMult(k []byte) (x, y *big.Int) } // CurveParams contains the parameters of an elliptic curve and also provides // a generic, non-constant time implementation of Curve. type CurveParams struct { P *big.Int // the order of the underlying field N *big.Int // the order of the base point B *big.Int // the constant of the curve equation Gx, Gy *big.Int // (x,y) of the base point BitSize int // the size of the underlying field Name string // the canonical name of the curve } func (curve *CurveParams) Params() *CurveParams { return curve } func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool { // y^2 y2 := new(big.Int).Mul(y, y) y2.Mod(y2, curve.P) // x^3 + b x3 := new(big.Int).Mul(x, x) x3.Mul(x3, x) x3.Add(x3, curve.B) x3.Mod(x3, curve.P) return y2.Cmp(x3) == 0 } func zForAffine(xA, yA *big.Int) (z *big.Int) { z = new(big.Int) if xA.Sign() != 0 || yA.Sign() != 0 { return z.SetInt64(1) } return // point at infinity } func (curve *CurveParams) affineFromJacobian(x, y, z *big.Int) (xA, yA *big.Int) { // point at infinity if z.Sign() == 0 { return new(big.Int), new(big.Int) } // 1/Z^1 zInv := new(big.Int).ModInverse(z, curve.P) // 1/Z^2 zzInv := new(big.Int).Mul(zInv, zInv) // 1/Z^3 zzzInv := new(big.Int).Mul(zzInv, zInv) // x = X/Z^2 xA = new(big.Int).Mul(x, zzInv) xA.Mod(xA, curve.P) // y = Y/Z^3 yA = new(big.Int).Mul(y, zzzInv) yA.Mod(yA, curve.P) return } func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int) { z1 := zForAffine(x1, y1) z2 := zForAffine(x2, y2) return curve.affineFromJacobian(curve.addJacobian(x1, y1, z1, x2, y2, z2)) } // ref. https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl func (curve *CurveParams) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (x3, y3, z3 *big.Int) { x3, y3, z3 = new(big.Int), new(big.Int), new(big.Int) // (x1, y1) is point at infinity in affine coordinates if z1.Sign() == 0 { // (x3, y3) = (x2, y2) in affine coordinates x3.Set(x2) y3.Set(y2) z3.Set(z2) return } // (x2, y2) is point at infinity in affine coordinates if z2.Sign() == 0 { // (x3, y3) = (x1, y1) in affine coordinates x3.Set(x1) y3.Set(y1) z3.Set(z1) return } // Z1Z1 = Z1^2 z1z1 := new(big.Int).Mul(z1, z1) // 1S // Z2Z2 = Z2^2 z2z2 := new(big.Int).Mul(z2, z2) // 2S // U1 = X1*Z2Z2 u1 := new(big.Int).Mul(x1, z2z2) // 1M u1.Mod(u1, curve.P) // U2 = X2*Z1Z1 u2 := new(big.Int).Mul(x2, z1z1) // 2M u2.Mod(u2, curve.P) // S1 = Y1*Z2*Z2Z2 s1 := new(big.Int).Mul(y1, z2) // 3M s1.Mul(s1, z2z2) // 4M s1.Mod(s1, curve.P) // S2 = Y2*Z1*Z1Z1 s2 := new(big.Int).Mul(y2, z1) // 5M s2.Mul(s2, z1z1) // 6M s2.Mod(s2, curve.P) // x1 == x2 and y1 == y2 in affine coordinates if u1.Cmp(u2) == 0 && s1.Cmp(s2) == 0 { return curve.doubleJacobian(x1, y1, z1) } // H = U2 - U1 h := new(big.Int).Sub(u2, u1) // 1add // I = (2*H)^2 i := new(big.Int).Lsh(h, 1) // 1*2 i.Mul(i, i) // 3S // J = H*I j := new(big.Int).Mul(h, i) // 7M // r = 2*(S2 - S1) r := new(big.Int).Sub(s2, s1) // 2add r.Lsh(r, 1) // 2*2 // V = U1*I v := new(big.Int).Mul(u1, i) // 8M // tmp1 = 2*V tmp1 := new(big.Int).Lsh(v, 1) // 3*2 // tmp2 = 2*S1*J tmp2 := new(big.Int).Mul(s1, j) // 9M tmp2.Lsh(tmp2, 1) // 4*2 // X3 = r^2 - J - 2*V x3.Mul(r, r) // 4S x3.Sub(x3, j) // 3add x3.Sub(x3, tmp1) // 4add x3.Mod(x3, curve.P) // Y3 = r*(V - X3) - 2*S1*J y3.Sub(v, x3) // 5add y3.Mul(r, y3) // 10M y3.Sub(y3, tmp2) // 6add y3.Mod(y3, curve.P) // Z3 = ((Z1 + Z2)^2 - Z1Z1 - Z2Z2)*H z3.Add(z1, z2) // 7add z3.Mul(z3, z3) // 5S z3.Sub(z3, z1z1) // 8add z3.Sub(z3, z2z2) // 9add z3.Mul(z3, h) // 11M z3.Mod(z3, curve.P) // cost: 11M + 5S + 9add + 4*2 return } func (curve *CurveParams) Double(x1, y1 *big.Int) (x, y *big.Int) { z1 := zForAffine(x1, y1) return curve.affineFromJacobian(curve.doubleJacobian(x1, y1, z1)) } // ref. https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l func (curve *CurveParams) doubleJacobian(x1, y1, z1 *big.Int) (x3, y3, z3 *big.Int) { x3, y3, z3 = new(big.Int), new(big.Int), new(big.Int) // (x1, y1) is point at infinity in affine coordinates if y1.Sign() == 0 || z1.Sign() == 0 { return } // A = X1^2 a := new(big.Int).Mul(x1, x1) // 1S // B = Y1^2 b := new(big.Int).Mul(y1, y1) // 2S // C = B^2 c := new(big.Int).Mul(b, b) // 3S // D = 2*((X1 + B)^2 - A - C) d := new(big.Int).Add(x1, b) // 1add d.Mul(d, d) // 4S d.Sub(d, a) // 2add d.Sub(d, c) // 3add d.Lsh(d, 1) // 1*2 // E = 3*A e := new(big.Int).Lsh(a, 1) // 2*2 e.Add(e, a) // 4add // F = E^2 f := new(big.Int).Mul(e, e) // 5S // tmp1 = 2*D tmp1 := new(big.Int).Lsh(d, 1) // 3*2 // tmp2 = 8*C tmp2 := new(big.Int).Lsh(c, 3) // 1*8 // X3 = F - 2*D x3.Sub(f, tmp1) // 5add x3.Mod(x3, curve.P) // Y3 = E * (D - X3) - 8*C y3.Sub(d, x3) // 6add y3.Mul(e, y3) // 1M y3.Sub(y3, tmp2) // 7add y3.Mod(y3, curve.P) // Z3 = 2 * Y1 * Z1 z3.Mul(y1, z1) // 2M z3.Lsh(z3, 1) // 4*2 z3.Mod(z3, curve.P) // cost: 2M + 5S + 7add + 4*2 + 1*8 return } func (curve *CurveParams) ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int) { z1 := new(big.Int).SetInt64(1) x, y, z := new(big.Int), new(big.Int), new(big.Int) for _, byte := range k { for bitNum := 0; bitNum < 8; bitNum++ { x, y, z = curve.doubleJacobian(x, y, z) if byte&0x80 == 0x80 { x, y, z = curve.addJacobian(x1, y1, z1, x, y, z) } byte <<= 1 } } return curve.affineFromJacobian(x, y, z) } func (curve *CurveParams) ScalarBaseMult(k []byte) (x, y *big.Int) { return curve.ScalarMult(curve.Gx, curve.Gy, k) } const ( p = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f" n = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141" b = "0000000000000000000000000000000000000000000000000000000000000007" gx = "<KEY>" gy = "<KEY>" bitSize = 256 ) var ( initonce sync.Once secp256k1 *CurveParams ) func initS256() { secp256k1 = &CurveParams{Name: "secp256k1"} secp256k1.P = hexToBigInt(p) secp256k1.N = hexToBigInt(n) secp256k1.B = hexToBigInt(b) secp256k1.Gx = hexToBigInt(gx) secp256k1.Gy = hexToBigInt(gy) secp256k1.BitSize = bitSize } func hexToBigInt(s string) *big.Int { i, ok := new(big.Int).SetString(s, 16) if !ok { panic("invalid hex : " + s) } return i } var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f} // GenerateKey returns a public/private key pair. The private key is // generated using the given reader, which must return random data. func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error) { N := curve.Params().N bitSize := N.BitLen() byteLen := (bitSize + 7) >> 3 priv = make([]byte, byteLen) for x == nil { _, err = io.ReadFull(rand, priv) if err != nil { return } // We have to mask off any excess bits in the case that the size of the // underlying field is not a whole number of bytes. priv[0] &= mask[bitSize%8] // This is because, in tests, rand will return all zeros and we don't // want to get the point at infinity and loop forever. priv[1] ^= 0x42 // If the scalar is out of range, sample another random number. if new(big.Int).SetBytes(priv).Cmp(N) >= 0 { continue } x, y = curve.ScalarBaseMult(priv) } return } // Marshal converts a point into the uncompressed form specified in section 4.3.6 of ANSI X9.62. func Marshal(curve Curve, x, y *big.Int) []byte { byteLen := (curve.Params().BitSize + 7) >> 3 ret := make([]byte, 1+2*byteLen) ret[0] = 4 // uncompressed point xBytes := x.Bytes() copy(ret[1+byteLen-len(xBytes):], xBytes) yBytes := y.Bytes() copy(ret[1+2*byteLen-len(yBytes):], yBytes) return ret } // Unmarshal converts a point, serialized by Marshal, into an x, y pair. // It is an error if the point is not in uncompressed form or is not on the curve. // On error, x = nil. func Unmarshal(curve Curve, data []byte) (x, y *big.Int) { byteLen := (curve.Params().BitSize + 7) >> 3 if len(data) != 1+2*byteLen { return } if data[0] != 4 { // uncompressed form return } p := curve.Params().P x = new(big.Int).SetBytes(data[1 : 1+byteLen]) y = new(big.Int).SetBytes(data[1+byteLen:]) if x.Cmp(p) >= 0 || y.Cmp(p) >= 0 { return nil, nil } if !curve.IsOnCurve(x, y) { return nil, nil } return } func S256() Curve { initonce.Do(initS256) return secp256k1 }
src/crypto/elliptic/elliptic.go
0.865523
0.721375
elliptic.go
starcoder
package mlpack /* #cgo CFLAGS: -I./capi -Wall #cgo LDFLAGS: -L. -lmlpack_go_nca #include <capi/nca.h> #include <stdlib.h> */ import "C" import "gonum.org/v1/gonum/mat" type NcaOptionalParam struct { ArmijoConstant float64 BatchSize int Labels *mat.Dense LinearScan bool MaxIterations int MaxLineSearchTrials int MaxStep float64 MinStep float64 Normalize bool NumBasis int Optimizer string Seed int StepSize float64 Tolerance float64 Verbose bool Wolfe float64 } func NcaOptions() *NcaOptionalParam { return &NcaOptionalParam{ ArmijoConstant: 0.0001, BatchSize: 50, Labels: nil, LinearScan: false, MaxIterations: 500000, MaxLineSearchTrials: 50, MaxStep: 1e+20, MinStep: 1e-20, Normalize: false, NumBasis: 5, Optimizer: "sgd", Seed: 0, StepSize: 0.01, Tolerance: 1e-07, Verbose: false, Wolfe: 0.9, } } /* This program implements Neighborhood Components Analysis, both a linear dimensionality reduction technique and a distance learning technique. The method seeks to improve k-nearest-neighbor classification on a dataset by scaling the dimensions. The method is nonparametric, and does not require a value of k. It works by using stochastic ("soft") neighbor assignments and using optimization techniques over the gradient of the accuracy of the neighbor assignments. To work, this algorithm needs labeled data. It can be given as the last row of the input dataset (specified with "Input"), or alternatively as a separate matrix (specified with "Labels"). This implementation of NCA uses stochastic gradient descent, mini-batch stochastic gradient descent, or the L_BFGS optimizer. These optimizers do not guarantee global convergence for a nonconvex objective function (NCA's objective function is nonconvex), so the final results could depend on the random seed or other optimizer parameters. Stochastic gradient descent, specified by the value 'sgd' for the parameter "Optimizer", depends primarily on three parameters: the step size (specified with "StepSize"), the batch size (specified with "BatchSize"), and the maximum number of iterations (specified with "MaxIterations"). In addition, a normalized starting point can be used by specifying the "Normalize" parameter, which is necessary if many warnings of the form 'Denominator of p_i is 0!' are given. Tuning the step size can be a tedious affair. In general, the step size is too large if the objective is not mostly uniformly decreasing, or if zero-valued denominator warnings are being issued. The step size is too small if the objective is changing very slowly. Setting the termination condition can be done easily once a good step size parameter is found; either increase the maximum iterations to a large number and allow SGD to find a minimum, or set the maximum iterations to 0 (allowing infinite iterations) and set the tolerance (specified by "Tolerance") to define the maximum allowed difference between objectives for SGD to terminate. Be careful---setting the tolerance instead of the maximum iterations can take a very long time and may actually never converge due to the properties of the SGD optimizer. Note that a single iteration of SGD refers to a single point, so to take a single pass over the dataset, set the value of the "MaxIterations" parameter equal to the number of points in the dataset. The L-BFGS optimizer, specified by the value 'lbfgs' for the parameter "Optimizer", uses a back-tracking line search algorithm to minimize a function. The following parameters are used by L-BFGS: "NumBasis" (specifies the number of memory points used by L-BFGS), "MaxIterations", "ArmijoConstant", "Wolfe", "Tolerance" (the optimization is terminated when the gradient norm is below this value), "MaxLineSearchTrials", "MinStep", and "MaxStep" (which both refer to the line search routine). For more details on the L-BFGS optimizer, consult either the mlpack L-BFGS documentation (in lbfgs.hpp) or the vast set of published literature on L-BFGS. By default, the SGD optimizer is used. Input parameters: - input (mat.Dense): Input dataset to run NCA on. - ArmijoConstant (float64): Armijo constant for L-BFGS. Default value 0.0001. - BatchSize (int): Batch size for mini-batch SGD. Default value 50. - Labels (mat.Dense): Labels for input dataset. - LinearScan (bool): Don't shuffle the order in which data points are visited for SGD or mini-batch SGD. - MaxIterations (int): Maximum number of iterations for SGD or L-BFGS (0 indicates no limit). Default value 500000. - MaxLineSearchTrials (int): Maximum number of line search trials for L-BFGS. Default value 50. - MaxStep (float64): Maximum step of line search for L-BFGS. Default value 1e+20. - MinStep (float64): Minimum step of line search for L-BFGS. Default value 1e-20. - Normalize (bool): Use a normalized starting point for optimization. This is useful for when points are far apart, or when SGD is returning NaN. - NumBasis (int): Number of memory points to be stored for L-BFGS. Default value 5. - Optimizer (string): Optimizer to use; 'sgd' or 'lbfgs'. Default value 'sgd'. - Seed (int): Random seed. If 0, 'std::time(NULL)' is used. Default value 0. - StepSize (float64): Step size for stochastic gradient descent (alpha). Default value 0.01. - Tolerance (float64): Maximum tolerance for termination of SGD or L-BFGS. Default value 1e-07. - Verbose (bool): Display informational messages and the full list of parameters and timers at the end of execution. - Wolfe (float64): Wolfe condition parameter for L-BFGS. Default value 0.9. Output parameters: - output (mat.Dense): Output matrix for learned distance matrix. */ func Nca(input *mat.Dense, param *NcaOptionalParam) (*mat.Dense) { resetTimers() enableTimers() disableBacktrace() disableVerbose() restoreSettings("Neighborhood Components Analysis (NCA)") // Detect if the parameter was passed; set if so. gonumToArmaMat("input", input) setPassed("input") // Detect if the parameter was passed; set if so. if param.ArmijoConstant != 0.0001 { setParamDouble("armijo_constant", param.ArmijoConstant) setPassed("armijo_constant") } // Detect if the parameter was passed; set if so. if param.BatchSize != 50 { setParamInt("batch_size", param.BatchSize) setPassed("batch_size") } // Detect if the parameter was passed; set if so. if param.Labels != nil { gonumToArmaUrow("labels", param.Labels) setPassed("labels") } // Detect if the parameter was passed; set if so. if param.LinearScan != false { setParamBool("linear_scan", param.LinearScan) setPassed("linear_scan") } // Detect if the parameter was passed; set if so. if param.MaxIterations != 500000 { setParamInt("max_iterations", param.MaxIterations) setPassed("max_iterations") } // Detect if the parameter was passed; set if so. if param.MaxLineSearchTrials != 50 { setParamInt("max_line_search_trials", param.MaxLineSearchTrials) setPassed("max_line_search_trials") } // Detect if the parameter was passed; set if so. if param.MaxStep != 1e+20 { setParamDouble("max_step", param.MaxStep) setPassed("max_step") } // Detect if the parameter was passed; set if so. if param.MinStep != 1e-20 { setParamDouble("min_step", param.MinStep) setPassed("min_step") } // Detect if the parameter was passed; set if so. if param.Normalize != false { setParamBool("normalize", param.Normalize) setPassed("normalize") } // Detect if the parameter was passed; set if so. if param.NumBasis != 5 { setParamInt("num_basis", param.NumBasis) setPassed("num_basis") } // Detect if the parameter was passed; set if so. if param.Optimizer != "sgd" { setParamString("optimizer", param.Optimizer) setPassed("optimizer") } // Detect if the parameter was passed; set if so. if param.Seed != 0 { setParamInt("seed", param.Seed) setPassed("seed") } // Detect if the parameter was passed; set if so. if param.StepSize != 0.01 { setParamDouble("step_size", param.StepSize) setPassed("step_size") } // Detect if the parameter was passed; set if so. if param.Tolerance != 1e-07 { setParamDouble("tolerance", param.Tolerance) setPassed("tolerance") } // Detect if the parameter was passed; set if so. if param.Verbose != false { setParamBool("verbose", param.Verbose) setPassed("verbose") enableVerbose() } // Detect if the parameter was passed; set if so. if param.Wolfe != 0.9 { setParamDouble("wolfe", param.Wolfe) setPassed("wolfe") } // Mark all output options as passed. setPassed("output") // Call the mlpack program. C.mlpackNca() // Initialize result variable and get output. var outputPtr mlpackArma output := outputPtr.armaToGonumMat("output") // Clear settings. clearSettings() // Return output(s). return output }
nca.go
0.669421
0.530358
nca.go
starcoder
package wltree import ( "fmt" "github.com/mozu0/bitvector" "github.com/mozu0/huffman" ) // Interface is a interface for arraylike elements that can be indexed by Wavelet Tree. // Equal elements must have the same key, and different elements must have different keys. type Interface interface { // Len returns the length of the arraylike. Len() int // Key returns the integer key of the i-th element. Key(i int) int64 } // Int64Keys represents a Wavelet Tree on int64 keys. type Int64Keys struct { nodes map[int64][]*bitvector.BitVector codes map[int64]string } // NewInt64Keys makes a Wavlet Tree from arraylike s whose elements can yield integer keys. func NewInt64Keys(s Interface) *Int64Keys { w := &Int64Keys{ nodes: make(map[int64][]*bitvector.BitVector), codes: make(map[int64]string), } // Generate huffman tree based on character occurrences in s. keyset, counts := freq(s) codes := huffman.FromInts(counts) for i, code := range codes { w.codes[keyset[i]] = code } // Count number of bits in each node of the wavelet tree. sizes := make(map[string]int) for i := range keyset { code := codes[i] count := counts[i] for j := range code { sizes[code[:j]] += count } } // Assign BitVector Builders to each wavelet tree node. builders := make(map[string]*bitvector.Builder) var keys []string for key, size := range sizes { keys = append(keys, key) builders[key] = bitvector.NewBuilder(size) } // Set bits in each BitVector Builder. index := make(map[string]int) for i, size := 0, s.Len(); i < size; i++ { k := s.Key(i) code := w.codes[k] for j := range code { if code[j] == '1' { builders[code[:j]].Set(index[code[:j]]) } index[code[:j]]++ } } // Build all BitVectors. bvs := make(map[string]*bitvector.BitVector) for key, builder := range builders { bvs[key] = builder.Build() } // For each charactor, register the path from wavelet tree root, through wavelet tree nodes, and // to the leaf. for i, k := range keyset { code := codes[i] for j := range code { w.nodes[k] = append(w.nodes[k], bvs[code[:j]]) } } return w } // Rank returns the count of elements with the key in s[0:i]. func (w *Int64Keys) Rank(key int64, i int) int { code := w.codes[key] if code == "" { return 0 } nodes := w.nodes[key] for j := range nodes { if code[j] == '1' { i = nodes[j].Rank1(i) } else { i = nodes[j].Rank0(i) } } return i } // Select returns i such that Rank(c, i) = r. // i.e. it returns the index of r-th occurrence of the element with the key. // Note that r is 0-origined, so wt.Select('a', 2) returns the index of the third 'a'. func (w *Int64Keys) Select(key int64, r int) int { code := w.codes[key] if code == "" { panic(fmt.Sprintf("wltree: no such element with key %v in s.", key)) } nodes := w.nodes[key] for j := len(nodes) - 1; j >= 0; j-- { if code[j] == '1' { r = nodes[j].Select1(r) } else { r = nodes[j].Select0(r) } } return r } // Bytes represents a Wavelet Tree on bytestring. type Bytes struct { nodes [256][]*bitvector.BitVector codes [256]string } // NewBytes constructs a Wavelet Tree from bytestring. func NewBytes(s []byte) *Bytes { intKeys := NewInt64Keys(byteSlice(s)) b := &Bytes{} for i, nodes := range intKeys.nodes { b.nodes[i] = nodes } for i, code := range intKeys.codes { b.codes[i] = code } return b } // Rank returns the count of the character c in s[0:i]. func (w *Bytes) Rank(c byte, i int) int { code := w.codes[c] if code == "" { return 0 } nodes := w.nodes[c] for j := range nodes { if code[j] == '1' { i = nodes[j].Rank1(i) } else { i = nodes[j].Rank0(i) } } return i } // Select returns i such that Rank(c, i) = r. // i.e. it returns the index of r-th occurrence of the character c. // Note that r is 0-origined, so wt.Select('a', 2) returns the index of the third 'a'. func (w *Bytes) Select(c byte, r int) int { code := w.codes[c] if code == "" { panic(fmt.Sprintf("wltree: no such character %q in s.", string(c))) } nodes := w.nodes[c] for j := len(nodes) - 1; j >= 0; j-- { if code[j] == '1' { r = nodes[j].Select1(r) } else { r = nodes[j].Select0(r) } } return r } func freq(s Interface) (keyset []int64, counts []int) { freqs := make(map[int64]int) for i, size := 0, s.Len(); i < size; i++ { freqs[s.Key(i)]++ } for k, w := range freqs { keyset = append(keyset, k) counts = append(counts, w) } return } type byteSlice []byte func (b byteSlice) Len() int { return len(b) } func (b byteSlice) Key(i int) int64 { return int64(b[i]) }
pkg/internal/wltree/wltree.go
0.670824
0.514583
wltree.go
starcoder