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 sparse
import (
"math"
"github.com/kzahedi/goent/discrete"
"github.com/kzahedi/goent/sm"
)
// ConditionalMutualInformation calculates the conditional
// mutual information with the given lnFunc function for each (x_t,y_t,z_t)
// I(X_t,Y_t|Z_t) = (lnFunc(p(x,y|z)) - lnFunc(p(x|z)p(y|z)))
func ConditionalMutualInformation(xyz [][]int, ln lnFunc) []float64 {
pxyz := discrete.Empirical3DSparse(xyz)
r := make([]float64, len(xyz), len(xyz))
pxyCz := sm.CreateSparseMatrix()
pxCz := sm.CreateSparseMatrix()
pyCz := sm.CreateSparseMatrix()
pz := sm.CreateSparseMatrix()
for _, index := range pxyz.Indices {
x := index[0]
y := index[1]
z := index[2]
zi := sm.SparseMatrixIndex{z}
xzi := sm.SparseMatrixIndex{x, z}
yzi := sm.SparseMatrixIndex{y, z}
v, _ := pxyz.Get(index)
pz.Add(zi, v)
pxCz.Add(xzi, v)
pyCz.Add(yzi, v)
pxyCz.Add(index, v)
}
for _, index := range pxCz.Indices {
zi := sm.SparseMatrixIndex{index[1]}
v, _ := pz.Get(zi)
pxCz.Mul(index, 1.0/v)
}
for _, index := range pyCz.Indices {
zi := sm.SparseMatrixIndex{index[1]}
v, _ := pz.Get(zi)
pyCz.Mul(index, 1.0/v)
}
for _, index := range pxyCz.Indices {
zi := sm.SparseMatrixIndex{index[1]}
v, _ := pz.Get(zi)
pxyCz.Mul(index, 1.0/v)
}
for i, d := range xyz {
x := d[0]
y := d[1]
z := d[2]
xyzi := sm.SparseMatrixIndex{x, y, z}
xzi := sm.SparseMatrixIndex{x, z}
yzi := sm.SparseMatrixIndex{y, z}
xyCz, _ := pxyCz.Get(xyzi)
xCz, _ := pxCz.Get(xzi)
yCz, _ := pxCz.Get(yzi)
if xyCz > 0.0 && xCz > 0.0 && yCz > 0.0 {
r[i] = ln(xyCz - ln(xCz*yCz))
}
}
return r
}
// ConditionalMutualInformationBaseE calculates the conditional
// mutual information with base e
// I(X,Y|Z) = \sum_x,y, p(x,y,z) (ln(p(x,y|z)) - ln(p(x|z)p(y|z)))
func ConditionalMutualInformationBaseE(xyz [][]int) []float64 {
return ConditionalMutualInformation(xyz, math.Log)
}
// ConditionalMutualInformationBase2 calculates the conditional
// mutual information with base 2
// I(X,Y|Z) = \sum_x,y, p(x,y,z) (log2(p(x,y|z)) - log2(p(x|z)p(y|z)))
func ConditionalMutualInformationBase2(xyz [][]int) []float64 {
return ConditionalMutualInformation(xyz, math.Log2)
} | discrete/state/sparse/ConditionalMutualInformation.go | 0.687105 | 0.419232 | ConditionalMutualInformation.go | starcoder |
package text
import (
"unicode"
)
// Calculates string width to be displayed.
func Width(s string, eastAsianEncoding bool, countDiacriticalSign bool, countFormatCode bool) int {
l := 0
inEscSeq := false // Ignore ANSI Escape Sequence
for _, r := range s {
if inEscSeq {
if unicode.IsLetter(r) {
inEscSeq = false
}
} else if r == 27 {
inEscSeq = true
} else {
l = l + RuneWidth(r, eastAsianEncoding, countDiacriticalSign, countFormatCode)
}
}
return l
}
// Calculates character width to be displayed.
func RuneWidth(r rune, eastAsianEncoding bool, countDiacriticalSign bool, countFormatCode bool) int {
switch {
case unicode.IsControl(r):
return 0
case !countFormatCode && (unicode.In(r, FormatCharTable) || unicode.In(r, ZeroWidthSpaceTable)):
return 0
case !countDiacriticalSign && unicode.In(r, DiacriticalSignTable):
return 0
case unicode.In(r, FullWidthTable):
return 2
case eastAsianEncoding && unicode.In(r, AmbiguousTable):
return 2
}
return 1
}
// Calculates byte size of a character.
func RuneByteSize(r rune, encoding Encoding) int {
if encoding == SJIS {
return sjisRuneByteSize(r)
} else if isUTF16Encoding(encoding) {
return utf16RuneByteSize(r)
}
return len(string(r))
}
func isUTF16Encoding(enc Encoding) bool {
return enc == UTF16 || enc == UTF16BE || enc == UTF16LE || enc == UTF16BEM || enc == UTF16LEM
}
func sjisRuneByteSize(r rune) int {
if unicode.In(r, SJISSingleByteTable) || unicode.IsControl(r) {
return 1
}
return 2
}
func utf16RuneByteSize(r rune) int {
if 65536 <= r {
return 4
}
return 2
}
// Calculates byte size of a string.
func ByteSize(s string, encoding Encoding) int {
size := 0
for _, c := range s {
size = size + RuneByteSize(c, encoding)
}
return size
}
// Returns if a string is Right-to-Left horizontal writing characters.
func IsRightToLeftLetters(s string) bool {
inEscSeq := false // Ignore ANSI Escape Sequence
for _, r := range s {
if inEscSeq {
if unicode.IsLetter(r) {
inEscSeq = false
}
} else if r == 27 {
inEscSeq = true
} else {
if !unicode.IsLetter(r) {
continue
}
return unicode.In(r, RightToLeftTable)
}
}
return false
} | vendor/github.com/mithrandie/go-text/string.go | 0.573678 | 0.406862 | string.go | starcoder |
package dcl
// Bool converts a bool to a *bool
func Bool(b bool) *bool {
return &b
}
// Float64 converts a float64 to *float64
func Float64(f float64) *float64 {
return &f
}
// Float64OrNil converts a float64 to *float64, returning nil if it's empty (0.0).
func Float64OrNil(f float64) *float64 {
if f == 0.0 {
return nil
}
return &f
}
// Int64 converts an int64 to *int64
func Int64(i int64) *int64 {
return &i
}
// Int64OrNil converts an int64 to *int64, returning nil if it's empty (0).
func Int64OrNil(i int64) *int64 {
if i == 0 {
return nil
}
return &i
}
// String converts a string to a *string
func String(s string) *string {
return &s
}
// StringWithError converts a string to a *string, returning a nil error to
// satisfy type signatures that expect one.
func StringWithError(s string) (*string, error) {
return &s, nil
}
// StringOrNil converts a string to a *string, returning nil if it's empty ("").
func StringOrNil(s string) *string {
if s == "" {
return nil
}
return &s
}
// Optional refers to all primitives that handle the proto3 optional keyword.
type Optional interface {
IsUnset() bool
GetValue() interface{}
}
// OptionalBool refers to a boolean value that is optional.
type OptionalBool struct {
Unset bool
Value *bool
}
// IsUnset returns if it is unset.
func (b *OptionalBool) IsUnset() bool {
return b.Unset
}
// GetValue returns the value of this type.
func (b *OptionalBool) GetValue() interface{} {
return b.Value
}
// OptionalInt64 refers to an int64 value that is optional.
type OptionalInt64 struct {
Unset bool
Value *int64
}
// IsUnset returns if it is unset.
func (b *OptionalInt64) IsUnset() bool {
return b.Unset
}
// GetValue returns the value of this type.
func (b *OptionalInt64) GetValue() interface{} {
return b.Value
}
// OptionalFloat64 refers to a float64 value that is optional.
type OptionalFloat64 struct {
Unset bool
Value *float64
}
// IsUnset returns if it is unset.
func (b *OptionalFloat64) IsUnset() bool {
return b.Unset
}
// GetValue returns the value of this type.
func (b *OptionalFloat64) GetValue() interface{} {
return b.Value
}
// OptionalString refers to a string value that is optional.
type OptionalString struct {
Unset bool
Value *string
}
// IsUnset returns if it is unset.
func (b *OptionalString) IsUnset() bool {
return b.Unset
}
// GetValue returns the value of this type.
func (b *OptionalString) GetValue() interface{} {
return b.Value
}
// SetOptionalString returns a optional string that is not unset.
func SetOptionalString(value string) *OptionalString {
return &OptionalString{
Unset: false,
Value: String(value),
}
}
// UnsetOptionalString returns a optional string that is unset.
func UnsetOptionalString() *OptionalString {
return &OptionalString{
Unset: true,
}
}
// SetOptionalBool returns a optional bool that is not unset.
func SetOptionalBool(value bool) *OptionalBool {
return &OptionalBool{
Unset: false,
Value: Bool(value),
}
}
// UnsetOptionalBool returns a optional bool that is unset.
func UnsetOptionalBool() *OptionalBool {
return &OptionalBool{
Unset: true,
}
}
// SetOptionalInt64 returns a optional int64 that is not unset.
func SetOptionalInt64(value int64) *OptionalInt64 {
return &OptionalInt64{
Unset: false,
Value: Int64(value),
}
}
// UnsetOptionalInt64 returns a optional int64 that is unset.
func UnsetOptionalInt64() *OptionalInt64 {
return &OptionalInt64{
Unset: true,
}
}
// SetOptionalFloat64 returns a optional float64 that is not unset.
func SetOptionalFloat64(value float64) *OptionalFloat64 {
return &OptionalFloat64{
Unset: false,
Value: Float64(value),
}
}
// UnsetOptionalFloat64 returns a optional float64 that is unset.
func UnsetOptionalFloat64() *OptionalFloat64 {
return &OptionalFloat64{
Unset: true,
}
} | terraform/google/vendor/github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl/type.go | 0.897586 | 0.53127 | type.go | starcoder |
package axis
import (
"math"
"time"
"github.com/mayowa/chart/format"
"github.com/mayowa/chart/image"
)
// Axis defines an axis (doh)
type Axis struct {
position Position
format Formatter
duration time.Duration
grid int
ticks int
center bool
}
// Formatter is the callback interface function used to format a label.
type Formatter func(value float64) string
// Liner is the callback interface function to draw a line.
// Any padding/margin offsets should be applied by the caller.
type Liner func(x1, y1, x2, y2 int)
// Position defines the position for the axis. Bottom, Top, Left or Right
type Position int
const (
// Bottom defines an axis aligned to the bottom of the image.
Bottom Position = iota
// Left defines an axis aligned to the let of the image.
// Only Bottom and Left are defined at the moment.
Left
)
// New creates a new Axis on the specified position using the formatter.
func New(p Position, f Formatter) *Axis {
return &Axis{
position: p,
format: f,
}
}
// NewSI creates a new Axis on the specified position using the default SI formatter.
func NewSI(p Position, base int) *Axis {
return New(p, func(in float64) string {
return format.SI(in, 1, float64(base), "", "", "")
})
}
// NewTime creates a new Axis on the specified position using the default Time formatter.
// A timefmt is specified using the default Go Time format, e.g. 2006-01-02 15:04
func NewTime(p Position, timefmt string) *Axis {
return New(p, func(in float64) string {
return time.Unix(int64(in), 0).Format(timefmt)
})
}
// Ticks sets the number of gridlines/labels or ticks for this axis.
// This configures an equally centered grid pattern for an axis.
// Use either one of Ticks() or Duration()
func (a *Axis) Ticks(n int) *Axis {
a.ticks = n
return a
}
// Duration sets the time period for the gridlines/labels or ticks for the axis.
// This configures a grid aligned to the nearest time unit.
// Use either one of Ticks() or Duration()
func (a *Axis) Duration(d time.Duration) *Axis {
a.duration = d
return a
}
// Grid displays a grid for this axis. By default it doesn't show a grid.
// n is the amount of gridlines to draw between axis ticks. If your axis
// spans 4 hours and n = 2 then a gridline will be drawn every 2 hours.
func (a *Axis) Grid(n int) *Axis {
a.grid = n
return a
}
// Center aligns the label in tne center of the grid instead of the start/end of grid.
func (a *Axis) Center() *Axis {
a.center = true
return a
}
// Draw renders the grid and labels.
// mx/my is the top-left start position, the margin (or offset).
// FIXME there are text-margin constants in this function which are probably dependent on the font and size used.
// It also depends a bit too much on the actual font/line/color drawing stuff.
func (a *Axis) Draw(img image.Image, w, h, mx, my int, min, max float64) {
const col = "title2"
switch a.position {
case Bottom:
off := 0 // grid line offset, TODO calculate from rounded time.Duration
if a.duration > 0 {
t := int(a.duration / time.Second)
a.ticks = 1
if t > 0 {
a.ticks = int(math.Round((max - min) / float64(t)))
}
}
if a.grid > 0 {
t := a.ticks * a.grid
o := float64(w) / float64(t)
for dx := o; dx < float64(w); dx += o {
col := "grid"
if int(dx/o)%a.grid != 0 {
col = "grid2"
}
img.Line(col, int(dx)+mx+off, my, int(dx)+mx+off, my+h)
}
}
toff := 0. // text offset
if a.center {
toff = float64(w) / float64(a.ticks) / 2.
}
for dx := (float64(w) / float64(a.ticks)) - float64(off); dx < float64(w)+toff; dx += float64(w) / float64(a.ticks) {
str := a.format(min + ((max-min)/float64(w))*(float64(dx)-float64(toff)))
img.TextID("grid", col, "middle", image.GridRole, int(dx)+mx+off-int(toff), my+h+14, str) // FIXME "14" (padding/offset)
}
case Left:
if a.grid > 0 {
t := a.ticks * a.grid
o := h / t
for dy := o; dy < h; dy += o {
col := "grid"
if dy/o%a.grid != 0 {
col = "grid2"
}
img.Line(col, mx, dy+my, mx+w, dy+my)
}
}
sc := a.Scales(h, min, max)
i := 0
// TODO if show or hide zero value option
for dy := 0; dy <= h; dy += h / a.ticks {
str := sc[i]
i++
img.TextID("ygrid", col, "end", image.GridRole, mx-4, dy+my+4, str) // FIXME "4" (padding/spacing)
}
}
}
// Scales creates and formats the Y-axis scale.
func (a *Axis) Scales(h int, min, max float64) []string {
s := []string{}
switch a.position {
case Left:
for dy := 0; dy <= h; dy += h / a.ticks {
str := a.format(max - ((max-min)/float64(h))*float64(dy))
s = append(s, str)
}
}
return s
} | axis/axis.go | 0.736685 | 0.476397 | axis.go | starcoder |
package lttb
import (
"math"
)
// Point represents a Cartesian coordinate pair.
type Point struct {
X float64
Y float64
}
// Downsample selects the most visually significant points from a series.
func Downsample(data []Point, threshold int) (sampled []Point) {
dataLength := len(data)
if threshold >= dataLength || threshold == 0 {
return data // Nothing to do
}
sampled = make([]Point, threshold)
// Bucket size. Leave room for start and end data points
every := float64(dataLength-2) / float64(threshold-2)
var a, nextA int // Initially a is the first point in the triangle
var maxArea, area float64
sampled[0] = data[a] // Always add the first point
sampledIndex := 1
for i := 0; i < threshold-2; i++ {
// Calculate point average for next bucket (containing c)
var avgX, avgY float64
avgRangeStart := int(float64(i+1)*every) + 1
avgRangeEnd := int(float64(i+2)*every) + 1
if avgRangeEnd >= dataLength {
avgRangeEnd = dataLength
}
avgRangeLength := avgRangeEnd - avgRangeStart
for ; avgRangeStart < avgRangeEnd; avgRangeStart++ {
avgX += data[avgRangeStart].X
avgY += data[avgRangeStart].Y
}
avgX /= float64(avgRangeLength)
avgY /= float64(avgRangeLength)
// Get the range for this bucket
rangeOffs := int(float64(i+0)*every) + 1
rangeTo := int(float64(i+1)*every) + 1
// Point a
pointAX := data[a].X
pointAY := data[a].Y
maxArea = -1.0
var maxAreaPoint Point
for ; rangeOffs < rangeTo; rangeOffs++ {
// Calculate triangle area over three buckets
area = math.Abs(
(pointAX-avgX)*(data[rangeOffs].Y-pointAY)-
(pointAX-data[rangeOffs].X)*(avgY-pointAY)) * 0.5
if area > maxArea {
maxArea = area
maxAreaPoint = data[rangeOffs]
nextA = rangeOffs // Next a is this b
}
}
sampled[sampledIndex] = maxAreaPoint // Pick this point from the bucket
sampledIndex++
a = nextA // This a is the next a (chosen b)
}
sampled[sampledIndex] = data[dataLength-1] // Always add last
return sampled
} | master/internal/lttb/lttb.go | 0.770896 | 0.602091 | lttb.go | starcoder |
package datatypes
import (
"bytes"
"encoding/json"
)
// EntityName is the storage structure for a UTF-8 entity name
type EntityName [32]byte
// StringToEntityName converts a string to an entity name data
func StringToEntityName(s string) EntityName {
var e EntityName
b := []byte(s)
copy(e[:], b)
return e
}
// String returns the string represenation of the entity name data
func (e EntityName) String() string {
end := bytes.IndexByte(e[:], 0)
return string(e[:end])
}
// MarshalJSON writes the string representation of the entity name to JSON
func (e EntityName) MarshalJSON() ([]byte, error) {
return json.Marshal(e.String())
}
// UnmarshalJSON converts the string representation of the entity name to
// the data structure
func (e *EntityName) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
copy(e[:], []byte(s))
return nil
}
// FCTag is the storage structure for a UTF-8 FC tag
type FCTag [6]byte
// StringToFCTag converts a string to FC tag data
func StringToFCTag(s string) FCTag {
var e FCTag
b := []byte(s)
copy(e[:], b)
return e
}
// String returns the string represenation of the FC tag data
func (e FCTag) String() string {
end := bytes.IndexByte(e[:], 0)
return string(e[:end])
}
// MarshalJSON writes the string representation of the FC tag to JSON
func (e FCTag) MarshalJSON() ([]byte, error) {
return json.Marshal(e.String())
}
// UnmarshalJSON converts the string representation of the FC tag to
// the data structure
func (e *FCTag) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
copy(e[:], []byte(s))
return nil
}
// FCName is the storage structure for a UTF-8 FC name
type FCName [46]byte
// StringToFCName converts a string to FC name data
func StringToFCName(s string) FCName {
var e FCName
b := []byte(s)
copy(e[:], b)
return e
}
// String returns the string represenation of the FC name data
func (e FCName) String() string {
end := bytes.IndexByte(e[:], 0)
return string(e[:end])
}
// MarshalJSON writes the string representation of the FC name to JSON
func (e FCName) MarshalJSON() ([]byte, error) {
return json.Marshal(e.String())
}
// UnmarshalJSON converts the string representation of the FC name to
// the data structure
func (e *FCName) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
copy(e[:], []byte(s))
return nil
}
type ChatMessage [1024]byte
// StringToChatMessage converts a string to an chat message data
func StringToChatMessage(s string) ChatMessage {
var e ChatMessage
b := []byte(s)
copy(e[:], b)
return e
}
// String returns the string represenation of the entity name data
func (e ChatMessage) String() string {
end := bytes.IndexByte(e[:], 0)
return string(e[:end])
}
// MarshalJSON writes the string representation of the chat message to JSON
func (e ChatMessage) MarshalJSON() ([]byte, error) {
return json.Marshal(e.String())
}
// UnmarshalJSON converts the string representation of the chat message to
// the data structure
func (e *ChatMessage) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
copy(e[:], []byte(s))
return nil
} | datatypes/string.go | 0.693058 | 0.464355 | string.go | starcoder |
package graphs
// Graph holds vertices and edges of a graph
type Graph struct {
isDirected bool
vertices []node
}
type node struct {
name interface{}
edges []interface{}
}
const infinity = int(^uint(0) >> 1)
// NewDirectedGraph is for creating a directed graph
func NewDirectedGraph() *Graph {
g := Graph{}
g.vertices = make([]node, 0)
g.isDirected = true
return &g
}
// NewUndirectedGraph is for creating an undirected graph
func NewUndirectedGraph() *Graph {
g := Graph{}
g.vertices = make([]node, 0)
g.isDirected = false
return &g
}
// AddVertice is for adding a new vertice. id vertice exists do nothing
func (g *Graph) AddVertice(name interface{}) {
g.addVertice(name)
}
// AddEdge if for adding a new edge.
func (g *Graph) AddEdge(from, to interface{}) {
g.addEdge(from, to)
}
// GetEdge is for getting all the edges of vertice n
func (g *Graph) GetEdge(n interface{}) []interface{} {
return g.getEdge(n)
}
// GetVertices is for getting all vertices info
func (g *Graph) GetVertices() []interface{} {
return g.getVertices()
}
// ShortestPath is for finding shortest path from edge s to t by using belman-ford algorithm
func (g *Graph) ShortestPath(s, t interface{}) map[interface{}]int {
return g.shortestPath(s, t)
}
func (g *Graph) addVertice(name interface{}) int {
for i, v := range g.vertices {
if v.name == name {
return i
}
}
n := node{}
n.name = name
n.edges = make([]interface{}, 0)
g.vertices = append(g.vertices, n)
return len(g.vertices) - 1
}
func (g *Graph) addEdge(from, to interface{}) {
f := g.addVertice(from)
t := g.addVertice(to)
g.vertices[f].edges = append(g.vertices[f].edges, to)
if !g.isDirected {
g.vertices[t].edges = append(g.vertices[t].edges, from)
}
}
func (g *Graph) getEdge(n interface{}) []interface{} {
for _, v := range g.vertices {
if v.name == n {
return v.edges
}
}
// todo throw exception
return nil
}
func (g *Graph) getVertices() []interface{} {
vertices := make([]interface{}, 0)
for i := 0; i < len(g.vertices); i++ {
vertices = append(vertices, g.vertices[i].name)
}
return vertices
}
func (g *Graph) shortestPath(sName, tName interface{}) map[interface{}]int {
n := len(g.vertices)
s := g.addVertice(sName)
dist := make([]int, n)
for i := 0; i < n; i++ {
dist[i] = infinity
}
dist[s] = 0
for u := 0; u < n-1; u++ {
for _, vName := range g.vertices[u].edges {
v := g.addVertice(vName)
if dist[u] != infinity && dist[u]+1 < dist[v] {
dist[v] = dist[u] + 1
}
}
}
result := make(map[interface{}]int)
for i, d := range dist {
result[g.vertices[i].name] = d
}
return result
} | graphs/graph.go | 0.621196 | 0.474449 | graph.go | starcoder |
package schema
// ActionSchemaJSON is the content of the file "actions.schema.json".
const ActionSchemaJSON = `{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "actions.schema.json#",
"title": "Action Definition",
"description": "Describes an action with its scope and steps to perform.",
"allowComments": true,
"type": "object",
"additionalProperties": false,
"required": [
"scopeQuery",
"steps"
],
"properties": {
"$schema": {
"description": "URL of the JSON Schema for an Action Definition.",
"type": "string",
"minLength": 1
},
"scopeQuery": {
"description": "A Sourcegraph search query to generate a list of repositories over which to run the action. Use 'src actions scope-query' to see which repositories are matched by the query.",
"type": "string",
"minLength": 1
},
"steps": {
"description": "A list of action steps to execute in each repository.",
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["type"],
"additionalProperties": false,
"properties": {
"type": {
"description": "Can be either \"command\", which executes the step in the native environment (OS) of the machine where 'src actions exec' is executed, or \"docker\" which runs a container with the repository contents mounted in at ` + "`" + `/work` + "`" + `. Note that local images (not from a Docker registry) must be built manually prior to executing.",
"type": "string",
"enum": ["command", "docker"]
},
"args": {
"description": "The command and its argument to execute if \"type\" is \"command\", or a list of arguments to be passed to the Docker container if \"type\" is \"docker\".",
"type": "array",
"minItems": 1,
"items": {
"type": "string"
}
},
"image": {
"description": "The Docker image handle for running the container executing this step. Just like when running ` + "`" + `docker run` + "`" + `, ` + "`" + `args` + "`" + ` here override the default ` + "`" + `CMD` + "`" + ` to be executed.",
"type": "string",
"minLength": 1
},
"cacheDirs": {
"description": "Names of directories to create in a temporary location and mount into each \"docker\" step container under the specified name.",
"type": "array",
"items": {
"type": "string"
}
}
},
"oneOf": [
{
"required": ["args"],
"properties": {
"type": { "const": "command" },
"image": { "type": "null" }
}
},
{
"required": ["image"],
"properties": {
"type": { "const": "docker" }
}
}
]
}
}
}
}
` | schema/action_stringdata.go | 0.816699 | 0.47384 | action_stringdata.go | starcoder |
package main
import (
"github.com/ByteArena/box2d"
"github.com/wdevore/RangerGo/api"
"github.com/wdevore/RangerGo/engine/nodes/custom"
"github.com/wdevore/RangerGo/engine/rendering"
)
// BoxComponent is a box
type BoxComponent struct {
visual api.INode
b2Body *box2d.B2Body
scale float64
categoryBits uint16 // I am a...
maskBits uint16 // I can collide with a...
}
// NewBoxComponent constructs a component
func NewBoxComponent(name string, parent api.INode) *BoxComponent {
o := new(BoxComponent)
o.visual = NewRectangleNode(name, parent.World(), parent)
o.visual.SetID(1000)
return o
}
// Configure component
func (b *BoxComponent) Configure(scale float64, categoryBits, maskBits uint16, b2World *box2d.B2World) {
b.scale = scale
b.categoryBits = categoryBits
b.maskBits = maskBits
buildBox(b, b2World)
}
// SetColor sets the visual's color
func (b *BoxComponent) SetColor(color api.IPalette) {
gr := b.visual.(*custom.RectangleNode)
gr.SetColor(color)
}
// SetPosition sets component's location.
func (b *BoxComponent) SetPosition(x, y float64) {
b.visual.SetPosition(x, y)
b.b2Body.SetTransform(box2d.MakeB2Vec2(x, y), b.b2Body.GetAngle())
}
// Update component
func (b *BoxComponent) Update() {
if b.b2Body.IsActive() {
pos := b.b2Body.GetPosition()
b.visual.SetPosition(pos.X, pos.Y)
rot := b.b2Body.GetAngle()
b.visual.SetRotation(rot)
}
}
// ------------------------------------------------------
// Physics control
// ------------------------------------------------------
// EnableGravity enables/disables gravity for this component
func (b *BoxComponent) EnableGravity(enable bool) {
if enable {
b.b2Body.SetGravityScale(-9.8)
} else {
b.b2Body.SetGravityScale(0.0)
}
}
// Reset configures the component back to defaults
func (b *BoxComponent) Reset(x, y float64) {
b.visual.SetPosition(x, y)
b.b2Body.SetTransform(box2d.MakeB2Vec2(x, y), 0.0)
b.b2Body.SetLinearVelocity(box2d.MakeB2Vec2(0.0, 0.0))
b.b2Body.SetAngularVelocity(0.0)
b.b2Body.SetAwake(true)
}
// ApplyForce applies linear force to box center
func (b *BoxComponent) ApplyForce(dirX, dirY float64) {
b.b2Body.ApplyForce(box2d.B2Vec2{X: dirX, Y: dirY}, b.b2Body.GetWorldCenter(), true)
}
// ApplyImpulse applies linear impulse to box center
func (b *BoxComponent) ApplyImpulse(dirX, dirY float64) {
b.b2Body.ApplyLinearImpulse(box2d.B2Vec2{X: dirX, Y: dirY}, b.b2Body.GetWorldCenter(), true)
}
// ApplyImpulseToCorner applies linear impulse to 1,1 box corner
// As the box rotates the 1,1 corner rotates which means impulses
// could change the rotation to either CW or CCW.
func (b *BoxComponent) ApplyImpulseToCorner(dirX, dirY float64) {
b.b2Body.ApplyLinearImpulse(box2d.B2Vec2{X: dirX, Y: dirY}, b.b2Body.GetWorldPoint(box2d.B2Vec2{X: 1.0, Y: 1.0}), true)
}
// ApplyTorque applies torgue to box center
func (b *BoxComponent) ApplyTorque(torgue float64) {
b.b2Body.ApplyTorque(torgue, true)
}
// ApplyAngularImpulse applies angular impulse to box center
func (b *BoxComponent) ApplyAngularImpulse(impulse float64) {
b.b2Body.ApplyAngularImpulse(impulse, true)
}
// ------------------------------------------------------
// Physics feedback
// ------------------------------------------------------
// HandleBeginContact processes BeginContact events
func (b *BoxComponent) HandleBeginContact(nodeA, nodeB api.INode) bool {
n, ok := nodeA.(*RectangleNode)
if !ok {
n, ok = nodeB.(*RectangleNode)
}
if ok {
n.SetColor(rendering.NewPaletteInt64(rendering.LightPurple))
}
return false
}
// HandleEndContact processes EndContact events
func (b *BoxComponent) HandleEndContact(nodeA, nodeB api.INode) bool {
n, ok := nodeA.(*RectangleNode)
if !ok {
n, ok = nodeB.(*RectangleNode)
}
if ok {
n.SetColor(rendering.NewPaletteInt64(rendering.Orange))
}
return false
}
func buildBox(b *BoxComponent, b2World *box2d.B2World) {
// A body def used to create bodies
bDef := box2d.MakeB2BodyDef()
bDef.Type = box2d.B2BodyType.B2_dynamicBody
// An instance of a body to contain Fixture
b.b2Body = b2World.CreateBody(&bDef)
b.visual.SetScale(2.0 * b.scale)
gb := b.visual.(*RectangleNode)
gb.SetColor(rendering.NewPaletteInt64(rendering.Orange))
// Every Fixture has a shape
b2Shape := box2d.MakeB2PolygonShape()
b2Shape.SetAsBoxFromCenterAndAngle(1.0*b.scale, 1.0*b.scale, box2d.B2Vec2{X: b.visual.Position().X(), Y: b.visual.Position().Y()}, 0.0)
fd := box2d.MakeB2FixtureDef()
fd.Shape = &b2Shape
fd.Density = 1.0
fd.UserData = b.visual
fd.Filter.CategoryBits = b.categoryBits
fd.Filter.MaskBits = b.maskBits
b.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body
} | examples/physics/intermediate/callback_listening/box_component.go | 0.730963 | 0.527864 | box_component.go | starcoder |
package esearch6
import (
"encoding/json"
"fmt"
"time"
"github.com/olivere/elastic"
"git.coinninja.net/backend/blocc/blocc"
"git.coinninja.net/backend/blocc/store"
)
// InsertBlock replaces a block
func (e *esearch) InsertBlock(symbol string, b *blocc.Block) error {
request := elastic.NewBulkIndexRequest().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Id(b.BlockId).
Doc(b)
request.Source() // Convert to json so we can modify b
e.bulk.Add(request)
return nil
}
// UpdateBlock updates status and data based on blockId
func (e *esearch) UpdateBlock(symbol string, blockId string, status string, nextBlockId string, data map[string]string, metric map[string]float64) error {
// Build block update
var block = make(map[string]interface{})
if status != "" {
block["status"] = status
}
if nextBlockId != "" {
block["next_block_id"] = nextBlockId
}
if data != nil {
block["data"] = data
}
if metric != nil {
block["metric"] = metric
}
request := elastic.NewBulkUpdateRequest().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Id(blockId).
Doc(&block).
DocAsUpsert(true)
// Force create the source so we can manipulate block
request.Source()
// Add it to the bulk handler
e.bulk.Add(request)
return nil
}
// UpdateBlockStatusByHeight updates status between heights
func (e *esearch) UpdateBlockStatusByStatusesAndHeight(symbol string, statuses []string, startHeight int64, endHeight int64, status string) error {
query := elastic.NewBoolQuery()
// If we specify statuses
if statuses != nil {
// Convert it to an interface
statusesInterface := make([]interface{}, len(statuses), len(statuses))
for i, status := range statuses {
statusesInterface[i] = status
}
if len(statusesInterface) > 0 {
query.Filter(elastic.NewTermsQuery("status", statusesInterface...))
}
}
// If we specify the height
if startHeight != blocc.HeightUnknown && endHeight != blocc.HeightUnknown {
query.Filter(elastic.NewRangeQuery("height").From(startHeight).To(endHeight).IncludeLower(true).IncludeUpper(true))
} else if startHeight != blocc.HeightUnknown {
query.Filter(elastic.NewRangeQuery("height").Gte(startHeight))
} else if endHeight != blocc.HeightUnknown {
query.Filter(elastic.NewRangeQuery("height").Lte(endHeight))
}
// If it's already the same status, don't bother
query.MustNot(elastic.NewTermQuery("status", status))
// Update the status where the status is not already and it's between height
_, err := e.client.UpdateByQuery().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Query(query).
Script(elastic.NewScript(`ctx._source['status'] = '` + status + `'`).Lang("painless")).
ScrollSize(2500).
Do(e.ctx)
return err
}
// DeleteBlockByBlockId removes a block by BlockId
func (e *esearch) DeleteBlockByBlockId(symbol string, blockId string) error {
_, err := e.client.Delete().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Id(blockId).
Refresh("true").
Do(e.ctx)
return err
}
// DeleteAboveBlockHeight removes a block by BlockId
func (e *esearch) DeleteAboveBlockHeight(symbol string, above int64) error {
_, err := e.client.DeleteByQuery().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Query(elastic.NewRangeQuery("height").Gt(above)).
Refresh("true").
Do(e.ctx)
if err != nil {
return fmt.Errorf("Could not DeleteByQuery blocks: %f", err)
}
_, err = e.client.DeleteByQuery().
Index(e.indexName(IndexTypeTx, symbol)).
Type(DocType).
Query(elastic.NewRangeQuery("block_height").Gt(above)).
Refresh("true").
Do(e.ctx)
if err != nil {
return fmt.Errorf("Could not DeleteByQuery tx: %f", err)
}
return nil
}
// FlushBlocks flushes transactions and refreshes the index
func (e *esearch) FlushBlocks(symbol string) error {
err := e.bulk.Flush()
if err != nil {
return err
}
_, err = e.client.Refresh(e.indexName(IndexTypeBlock, symbol)).Do(e.ctx)
if err != nil {
return err
}
// Return the bulk error (if there was one)
e.Lock()
err = e.lastBulkError
e.Unlock()
return err
}
// GetBlockHeaderTopByStatuses will return the top block header as it stands
func (e *esearch) GetBlockHeaderTopByStatuses(symbol string, statuses []string) (*blocc.BlockHeader, error) {
e.throttleSearches <- struct{}{}
defer func() {
<-e.throttleSearches
}()
query := elastic.NewBoolQuery()
if statuses != nil {
// Convert it to an interface
statusesInterface := make([]interface{}, len(statuses), len(statuses))
for i, status := range statuses {
statusesInterface[i] = status
}
if len(statusesInterface) > 0 {
query.Filter(elastic.NewTermsQuery("status", statusesInterface...))
}
}
res, err := e.client.Search().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Sort("height", false).
Query(query).
FetchSourceContext(elastic.NewFetchSourceContext(true).Include("height").Include("block_id").Include("prev_block_id").Include("time")).
From(0).Size(1).Do(e.ctx)
if err != nil {
return nil, err
}
if res.Hits.TotalHits == 0 {
return nil, blocc.ErrNotFound
}
var bh = new(blocc.BlockHeader)
err = json.Unmarshal(*res.Hits.Hits[0].Source, &bh)
if err != nil {
return nil, fmt.Errorf("Could not parse BlockHeader: %s", err)
}
// Return the height but also an error indicating the height and the number of blocks do not match up (ie missing data)
if bh.Height > res.Hits.TotalHits+1 {
return bh, fmt.Errorf("Validation Error: Missing Blocks Detected height:%d blocks:%d", bh.Height, res.Hits.TotalHits)
} else if bh.Height+1 < res.Hits.TotalHits {
return bh, fmt.Errorf("Validation Error: Missing Blocks Detected height:%d blocks:%d", bh.Height, res.Hits.TotalHits)
}
return bh, nil
}
// GetBlockByBlockId gets a block by blockId
func (e *esearch) GetBlockByBlockId(symbol string, blockId string, include blocc.BlockInclude) (*blocc.Block, error) {
e.throttleSearches <- struct{}{}
defer func() {
<-e.throttleSearches
}()
res, err := e.client.Get().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Id(blockId).
FetchSourceContext(blockFetchSourceContext(include)).
Do(e.ctx)
if elastic.IsNotFound(err) {
return nil, blocc.ErrNotFound
} else if err != nil {
return nil, fmt.Errorf("Could not get block: %v", err)
}
// Unmarshal the block
b := new(blocc.Block)
err = json.Unmarshal(*res.Source, b)
return b, err
}
// GetBlockByTip gets the top block
func (e *esearch) GetBlockTopByStatuses(symbol string, statuses []string, include blocc.BlockInclude) (*blocc.Block, error) {
// Determine the tip
bh, err := e.GetBlockHeaderTopByStatuses(symbol, statuses)
// If it's not a validation error, there's still data
if err != nil && !blocc.IsValidationError(err) {
return nil, err
}
blk, newErr := e.GetBlockByBlockId(symbol, bh.BlockId, include)
if newErr != nil && !blocc.IsValidationError(newErr) {
return nil, newErr
}
// Return the block and original error if any
return blk, err
}
// FindBlocksByHeight fetches blocks by height
func (e *esearch) FindBlocksByHeight(symbol string, height int64, include blocc.BlockInclude) ([]*blocc.Block, error) {
e.throttleSearches <- struct{}{}
defer func() {
<-e.throttleSearches
}()
query := elastic.NewBoolQuery().Filter(elastic.NewTermQuery("height", height))
// If height is zero, we also need to search for blocks with missing height field since it will omitempty
if height == 0 {
query = elastic.NewBoolQuery().
Should(elastic.NewTermQuery("height", height)).
Should(elastic.NewBoolQuery().MustNot(elastic.NewExistsQuery("height")))
}
res, err := e.client.Search().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Query(query).
FetchSourceContext(blockFetchSourceContext(include)).
From(0).Size(e.countMax).Do(e.ctx)
if err != nil {
return nil, fmt.Errorf("Could not get block: %v", err)
}
if res.Hits.TotalHits == 0 {
return nil, blocc.ErrNotFound
}
ret := make([]*blocc.Block, len(res.Hits.Hits), len(res.Hits.Hits))
for i, hit := range res.Hits.Hits {
tx := new(blocc.Block)
err := json.Unmarshal(*hit.Source, &tx)
if err != nil {
return nil, fmt.Errorf("Could not parse Block: %s", err)
}
ret[i] = tx
}
return ret, nil
}
// FindBlocksByPrevBlockId returns blocks by previous blockId
func (e *esearch) FindBlocksByPrevBlockId(symbol string, prevBlockId string, include blocc.BlockInclude) ([]*blocc.Block, error) {
e.throttleSearches <- struct{}{}
defer func() {
<-e.throttleSearches
}()
res, err := e.client.Search().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Query(elastic.NewBoolQuery().Filter(elastic.NewTermQuery("prev_block_id", prevBlockId))).
FetchSourceContext(blockFetchSourceContext(include)).
From(0).Size(e.countMax).Do(e.ctx)
if err != nil {
return nil, fmt.Errorf("Could not get block: %v", err)
}
if res.Hits.TotalHits == 0 {
return nil, blocc.ErrNotFound
}
ret := make([]*blocc.Block, len(res.Hits.Hits), len(res.Hits.Hits))
for i, hit := range res.Hits.Hits {
tx := new(blocc.Block)
err := json.Unmarshal(*hit.Source, &tx)
if err != nil {
return nil, fmt.Errorf("Could not parse Block: %s", err)
}
ret[i] = tx
}
return ret, nil
}
// FindBlocksByTxId returns blocks with TxId
func (e *esearch) FindBlocksByTxId(symbol string, txId string, include blocc.BlockInclude) ([]*blocc.Block, error) {
e.throttleSearches <- struct{}{}
defer func() {
<-e.throttleSearches
}()
res, err := e.client.Search().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Query(elastic.NewBoolQuery().Filter(elastic.NewTermQuery("tx_id", txId))).
FetchSourceContext(blockFetchSourceContext(include)).
From(0).Size(e.countMax).
Do(e.ctx)
if err != nil {
return nil, fmt.Errorf("Could not get block: %v", err)
}
if res.Hits.TotalHits == 0 {
return nil, blocc.ErrNotFound
}
ret := make([]*blocc.Block, len(res.Hits.Hits), len(res.Hits.Hits))
for i, hit := range res.Hits.Hits {
tx := new(blocc.Block)
err := json.Unmarshal(*hit.Source, &tx)
if err != nil {
return nil, fmt.Errorf("Could not parse Block: %s", err)
}
ret[i] = tx
}
return ret, nil
}
// FindBlocksByBlockIdsAndTime returns blocks optionally by blockId, time and pagination by descending time
func (e *esearch) FindBlocksByBlockIdsAndTime(symbol string, blockIds []string, start *time.Time, end *time.Time, include blocc.BlockInclude, offset int, count int) ([]*blocc.Block, error) {
e.throttleSearches <- struct{}{}
defer func() {
<-e.throttleSearches
}()
// Convert it to an interface
blockIdsInterface := make([]interface{}, len(blockIds), len(blockIds))
for i, blockId := range blockIds {
blockIdsInterface[i] = blockId
}
query := elastic.NewBoolQuery()
if len(blockIdsInterface) > 0 {
query.Filter(elastic.NewTermsQuery("block_id", blockIdsInterface...))
}
if start != nil && end != nil {
query.Filter(elastic.NewRangeQuery("time").From(start.Unix()).To(end.Unix()).IncludeLower(true).IncludeUpper(true))
} else if start != nil {
query.Filter(elastic.NewRangeQuery("time").Gte(start.Unix()))
} else if end != nil {
query.Filter(elastic.NewRangeQuery("time").Lte(end.Unix()))
}
// Max results
if count == store.CountMax {
count = e.countMax
}
res, err := e.client.Search().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Sort("time", false).
Query(query).
FetchSourceContext(blockFetchSourceContext(include)).
From(offset).Size(count).
Do(e.ctx)
if err != nil {
return nil, err
}
if res.Hits.TotalHits == 0 {
return nil, blocc.ErrNotFound
}
ret := make([]*blocc.Block, len(res.Hits.Hits), len(res.Hits.Hits))
for i, hit := range res.Hits.Hits {
tx := new(blocc.Block)
err := json.Unmarshal(*hit.Source, &tx)
if err != nil {
return nil, fmt.Errorf("Could not parse Block: %s", err)
}
ret[i] = tx
}
return ret, nil
}
// FindBlocksByStatusAndHeight returns blocks by status and height ascending height
func (e *esearch) FindBlocksByStatusAndHeight(symbol string, statuses []string, startHeight int64, endHeight int64, include blocc.BlockInclude, offset int, count int) ([]*blocc.Block, error) {
e.throttleSearches <- struct{}{}
defer func() {
<-e.throttleSearches
}()
query := elastic.NewBoolQuery()
if statuses != nil {
// Convert it to an interface
statusesInterface := make([]interface{}, len(statuses), len(statuses))
for i, status := range statuses {
statusesInterface[i] = status
}
if len(statusesInterface) > 0 {
query.Filter(elastic.NewTermsQuery("status", statusesInterface...))
}
}
if startHeight != blocc.HeightUnknown && endHeight != blocc.HeightUnknown {
query.Filter(elastic.NewRangeQuery("height").From(startHeight).To(endHeight).IncludeLower(true).IncludeUpper(true))
} else if startHeight != blocc.HeightUnknown {
query.Filter(elastic.NewRangeQuery("height").Gte(startHeight))
} else if endHeight != blocc.HeightUnknown {
query.Filter(elastic.NewRangeQuery("height").Lte(endHeight))
}
// Max results
if count == store.CountMax {
count = e.countMax
}
res, err := e.client.Search().
Index(e.indexName(IndexTypeBlock, symbol)).
Type(DocType).
Sort("height", true).
Query(query).
FetchSourceContext(blockFetchSourceContext(include)).
From(offset).Size(count).
Do(e.ctx)
if err != nil {
return nil, err
}
if res.Hits.TotalHits == 0 {
return nil, blocc.ErrNotFound
}
ret := make([]*blocc.Block, len(res.Hits.Hits), len(res.Hits.Hits))
for i, hit := range res.Hits.Hits {
tx := new(blocc.Block)
err := json.Unmarshal(*hit.Source, &tx)
if err != nil {
return nil, fmt.Errorf("Could not parse Block: %s", err)
}
ret[i] = tx
}
return ret, nil
}
// This adds a fetch filter to the document so we only fetch what we need
func blockFetchSourceContext(include blocc.BlockInclude) *elastic.FetchSourceContext {
// Don't filter anything
if include == blocc.BlockIncludeAll {
return elastic.NewFetchSourceContext(true)
}
// It's easier to exclude things
excludes := make([]string, 0)
if include&blocc.BlockIncludeData == 0 {
excludes = append(excludes, "data.*")
}
if include&blocc.BlockIncludeRaw == 0 {
excludes = append(excludes, "raw")
}
if include&blocc.BlockIncludeTxIds == 0 {
excludes = append(excludes, "tx_id")
}
return elastic.NewFetchSourceContext(true).Exclude(excludes...)
} | store/esearch6/block.go | 0.703448 | 0.417984 | block.go | starcoder |
package geometry
import (
"github.com/g3n/engine/gls"
"github.com/g3n/engine/math32"
"math"
)
// Torus represents a torus geometry
type Torus struct {
Geometry // embedded geometry
Radius float64 // Torus radius
Tube float64 // Diameter of the torus tube
RadialSegments int // Number of radial segments
TubularSegments int // Number of tubular segments
Arc float64 // Central angle
}
// NewTorus returns a pointer to a new torus geometry
func NewTorus(radius, tube float64, radialSegments, tubularSegments int, arc float64) *Torus {
t := new(Torus)
t.Geometry.Init()
t.Radius = radius
t.Tube = tube
t.RadialSegments = radialSegments
t.TubularSegments = tubularSegments
t.Arc = arc
// Create buffers
positions := math32.NewArrayF32(0, 0)
normals := math32.NewArrayF32(0, 0)
uvs := math32.NewArrayF32(0, 0)
indices := math32.NewArrayU32(0, 0)
var center math32.Vector3
for j := 0; j <= radialSegments; j++ {
for i := 0; i <= tubularSegments; i++ {
u := float64(i) / float64(tubularSegments) * arc
v := float64(j) / float64(radialSegments) * math.Pi * 2
center.X = float32(radius * math.Cos(u))
center.Y = float32(radius * math.Sin(u))
var vertex math32.Vector3
vertex.X = float32((radius + tube*math.Cos(v)) * math.Cos(u))
vertex.Y = float32((radius + tube*math.Cos(v)) * math.Sin(u))
vertex.Z = float32(tube * math.Sin(v))
positions.AppendVector3(&vertex)
uvs.Append(float32(float64(i)/float64(tubularSegments)), float32(float64(j)/float64(radialSegments)))
normals.AppendVector3(vertex.Sub(¢er).Normalize())
}
}
for j := 1; j <= radialSegments; j++ {
for i := 1; i <= tubularSegments; i++ {
a := (tubularSegments+1)*j + i - 1
b := (tubularSegments+1)*(j-1) + i - 1
c := (tubularSegments+1)*(j-1) + i
d := (tubularSegments+1)*j + i
indices.Append(uint32(a), uint32(b), uint32(d), uint32(b), uint32(c), uint32(d))
}
}
t.SetIndices(indices)
t.AddVBO(gls.NewVBO(positions).AddAttrib(gls.VertexPosition))
t.AddVBO(gls.NewVBO(normals).AddAttrib(gls.VertexNormal))
t.AddVBO(gls.NewVBO(uvs).AddAttrib(gls.VertexTexcoord))
return t
} | geometry/torus.go | 0.788054 | 0.493775 | torus.go | starcoder |
package topo
import (
"context"
"crypto/tls"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"io"
"testing"
"github.com/onosproject/onos-topo/api/device"
"github.com/stretchr/testify/assert"
)
// TestDeviceService : test
func (s *TestSuite) TestDeviceService(t *testing.T) {
client, err := getDeviceServiceClient()
assert.NoError(t, err)
list, err := client.List(context.Background(), &device.ListRequest{})
assert.NoError(t, err)
count := 0
for {
_, err := list.Recv()
if err == io.EOF {
break
}
assert.NoError(t, err)
count++
}
assert.Equal(t, 0, count)
events := make(chan *device.ListResponse)
eventList, eventErr := client.List(context.Background(), &device.ListRequest{
Subscribe: true,
})
assert.NoError(t, eventErr)
go func() {
for {
response, err := eventList.Recv()
if err != nil {
break
}
events <- response
}
}()
addResponse, err := client.Add(context.Background(), &device.AddRequest{
Device: &device.Device{
ID: "test1",
Type: "Stratum",
Address: "device-test1:5000",
Target: "device-test1",
Version: "1.0.0",
},
})
assert.NoError(t, err)
assert.Equal(t, device.ID("test1"), addResponse.Device.ID)
assert.NotEqual(t, device.Revision(0), addResponse.Device.Revision)
getResponse, err := client.Get(context.Background(), &device.GetRequest{
ID: "test1",
})
assert.NoError(t, err)
assert.Equal(t, device.ID("test1"), getResponse.Device.ID)
assert.Equal(t, addResponse.Device.Revision, getResponse.Device.Revision)
eventResponse := <-events
deviceEventTypes := []device.ListResponse_Type{device.ListResponse_NONE, device.ListResponse_ADDED}
assert.Contains(t, deviceEventTypes, eventResponse.Type)
assert.Equal(t, device.ID("test1"), eventResponse.Device.ID)
assert.Equal(t, addResponse.Device.Revision, eventResponse.Device.Revision)
list, err = client.List(context.Background(), &device.ListRequest{})
assert.NoError(t, err)
for {
response, err := list.Recv()
if err == io.EOF {
break
}
assert.NoError(t, err)
assert.Equal(t, device.ListResponse_NONE, response.Type)
assert.Equal(t, device.ID("test1"), response.Device.ID)
assert.Equal(t, addResponse.Device.Revision, response.Device.Revision)
count++
}
assert.Equal(t, 1, count)
removeResponse, err := client.Remove(context.Background(), &device.RemoveRequest{
Device: getResponse.Device,
})
assert.NoError(t, err)
assert.NotNil(t, removeResponse)
eventResponse = <-events
assert.Equal(t, device.ListResponse_REMOVED, eventResponse.Type)
assert.Equal(t, device.ID("test1"), eventResponse.Device.ID)
assert.True(t, eventResponse.Device.Revision > addResponse.Device.Revision)
}
func getDeviceServiceClient() (device.DeviceServiceClient, error) {
creds, err := getClientCredentials()
if err != nil {
return nil, err
}
conn, err := grpc.Dial("onos-topo:5150", grpc.WithTransportCredentials(credentials.NewTLS(creds)))
if err != nil {
return nil, err
}
return device.NewDeviceServiceClient(conn), nil
}
func getClientCredentials() (*tls.Config, error) {
cert, err := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))
if err != nil {
return nil, err
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
}, nil
}
const clientCert = `
-----BEGIN CERTIFICATE-----
<KEY>
-----END CERTIFICATE-----
`
const clientKey = `
-----<KEY>
` | test/topo/deviceservicetest.go | 0.511961 | 0.442335 | deviceservicetest.go | starcoder |
package ps
// List is a persistent list of possibly heterogenous values.
type List interface {
// IsNil returns true if the list is empty
IsNil() bool
// Cons returns a new list with val as the head
Cons(val interface{}) List
// Head returns the first element of the list;
// panics if the list is empty
Head() interface{}
// Tail returns a list with all elements except the head;
// panics if the list is empty
Tail() List
// Size returns the list's length. This takes O(1) time.
Size() int
// ForEach executes a callback for each value in the list.
ForEach(f func(interface{}))
// Reverse returns a list whose elements are in the opposite order as
// the original list.
Reverse() List
}
// Immutable (i.e. persistent) list
type list struct {
depth int // the number of nodes after, and including, this one
value interface{}
tail *list
}
// An empty list shared by all lists
var nilList = &list{}
// NewList returns a new, empty list. The result is a singly linked
// list implementation. All lists share an empty tail, so allocating
// empty lists is efficient in time and memory.
func NewList() List {
return nilList
}
func (self *list) IsNil() bool {
return self == nilList
}
func (self *list) Size() int {
return self.depth
}
func (tail *list) Cons(val interface{}) List {
var xs list
xs.depth = tail.depth + 1
xs.value = val
xs.tail = tail
return &xs
}
func (self *list) Head() interface{} {
if self.IsNil() {
panic("Called Head() on an empty list")
}
return self.value
}
func (self *list) Tail() List {
if self.IsNil() {
panic("Called Tail() on an empty list")
}
return self.tail
}
// ForEach executes a callback for each value in the list
func (self *list) ForEach(f func(interface{})) {
if self.IsNil() {
return
}
f(self.Head())
self.Tail().ForEach(f)
}
// Reverse returns a list with elements in opposite order as this list
func (self *list) Reverse() List {
reversed := NewList()
self.ForEach(func(v interface{}) { reversed = reversed.Cons(v) })
return reversed
} | deepfence_agent/tools/apache/scope/vendor/github.com/weaveworks/ps/list.go | 0.798344 | 0.483587 | list.go | starcoder |
package webfan
import "github.com/vjeantet/bitfan/processors/doc"
func (p *processor) Doc() *doc.Processor {
return &doc.Processor{
Name: "webfan",
ImportPath: "github.com/vjeantet/bitfan/processors/webfan",
Doc: "Example\n```\ninput{\n webhook{\n uri => \"toto/titi\"\n pipeline=> \"test.conf\"\n codec => plain{\n role => \"decoder\"\n }\n codec => plain{\n role => \"encoder\"\n format=> \"<h1>Hello {{.request.querystring.name}}</h1>\"\n }\n headers => {\n \"Content-Type\" => \"text/html\"\n }\n }\n}\n```",
DocShort: "Reads events from standard input",
Options: &doc.ProcessorOptions{
Doc: "",
Options: []*doc.ProcessorOption{
&doc.ProcessorOption{
Name: "processors.CommonOptions",
Alias: ",squash",
Doc: "",
Required: false,
Type: "processors.CommonOptions",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "",
},
&doc.ProcessorOption{
Name: "Codec",
Alias: "",
Doc: "The codec used for posted data. Input codecs are a convenient method for decoding\nyour data before it enters the pipeline, without needing a separate filter in your bitfan pipeline\n\nDefault decode http request as plain text, response is json encoded.\nSet multiple codec with role to customize",
Required: false,
Type: "codec",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "codec => plain { role=>\"encoder\"} codec => json { role=>\"decoder\"}",
},
&doc.ProcessorOption{
Name: "Uri",
Alias: "uri",
Doc: "URI path /_/path",
Required: true,
Type: "string",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "",
},
&doc.ProcessorOption{
Name: "Pipeline",
Alias: "pipeline",
Doc: "Path to pipeline's configuration to execute on request\nThis configuration should contains only a filter section an a output like ```output{pass{}}```",
Required: true,
Type: "string",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "",
},
&doc.ProcessorOption{
Name: "Headers",
Alias: "headers",
Doc: "Headers to send back into outgoing response",
Required: false,
Type: "hash",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "{\"X-Processor\" => \"bitfan\"}",
},
},
},
Ports: []*doc.ProcessorPort{},
}
} | processors/webfan/docdoc.go | 0.666605 | 0.498047 | docdoc.go | starcoder |
package model
type TypeInfo struct {
TypeID1 int
TypeID2 int
TypeID3 int
TypeID4 int
}
func (ti TypeInfo) IsEquipment() bool {
return ti.TypeID1 == 3 && ti.TypeID2 == 1
}
func (ti TypeInfo) IsItem() bool {
return ti.TypeID1 == 3
}
func (ti TypeInfo) IsContainer() bool {
return ti.TypeID1 == 3 && ti.TypeID2 == 2
}
func (ti TypeInfo) IsExpendable() bool {
return ti.TypeID1 == 3 && ti.TypeID2 == 3
}
func (ti TypeInfo) IsWeapon() bool {
return ti.IsEquipment() && ti.TypeID3 == 6
}
func (ti TypeInfo) IsChineseWeapon() bool {
return ti.IsWeapon() && ti.TypeID4 > 1 && ti.TypeID4 < 7
}
func (ti TypeInfo) IsEuropeanWeapon() bool {
return ti.IsWeapon() && ti.TypeID4 >= 7 && ti.TypeID4 < 16
}
func (ti TypeInfo) IsShield() bool {
return ti.IsEquipment() && ti.TypeID3 == 4
}
func (ti TypeInfo) IsCHShield() bool {
return ti.IsShield() && ti.TypeID4 == 1
}
func (ti TypeInfo) IsEUShield() bool {
return ti.IsShield() && ti.TypeID4 == 2
}
func (ti TypeInfo) IsSword() bool {
return ti.IsWeapon() && ti.TypeID4 == 2
}
func (ti TypeInfo) IsBow() bool {
return ti.IsWeapon() && ti.TypeID4 == 6
}
func (ti TypeInfo) IsCrossbow() bool {
return ti.IsWeapon() && ti.TypeID4 == 12
}
func (ti TypeInfo) IsBlade() bool {
return ti.IsWeapon() && ti.TypeID4 == 2
}
func (ti TypeInfo) Is1HSword() bool {
return ti.IsWeapon() && ti.TypeID4 == 2
}
func (ti TypeInfo) IsWarlockRod() bool {
return ti.IsWeapon() && ti.TypeID4 == 10
}
func (ti TypeInfo) IsClericRod() bool {
return ti.IsWeapon() && ti.TypeID4 == 15
}
func (ti TypeInfo) IsOneHandedWeapon() bool {
return ti.IsSword() || ti.IsBlade() || ti.Is1HSword() || ti.IsWarlockRod() || ti.IsClericRod()
}
func (ti TypeInfo) IsCHArmorPart() bool {
return ti.IsEquipment() && ti.TypeID3 == 3
}
func (ti TypeInfo) IsCHProtectorPart() bool {
return ti.IsEquipment() && ti.TypeID3 == 2
}
func (ti TypeInfo) IsCHGarmentPart() bool {
return ti.IsEquipment() && ti.TypeID3 == 1
}
func (ti TypeInfo) IsCHAccessory() bool {
return ti.IsEquipment() && ti.TypeID3 == 5
}
func (ti TypeInfo) IsEUAccessory() bool {
return ti.IsEquipment() && ti.TypeID3 == 12
}
func (ti TypeInfo) IsEUArmorPart() bool {
return ti.IsEquipment() && ti.TypeID3 == 11
}
func (ti TypeInfo) IsEUProtectorPart() bool {
return ti.IsEquipment() && ti.TypeID3 == 10
}
func (ti TypeInfo) IsEUGarmentPart() bool {
return ti.IsEquipment() && ti.TypeID3 == 9
}
func (ti TypeInfo) IsCHHelmet() bool {
return (ti.IsCHArmorPart() || ti.IsCHProtectorPart() || ti.IsCHGarmentPart()) && ti.TypeID4 == 1
}
func (ti TypeInfo) IsCHShoulder() bool {
return (ti.IsCHArmorPart() || ti.IsCHProtectorPart() || ti.IsCHGarmentPart()) && ti.TypeID4 == 2
}
func (ti TypeInfo) IsCHChest() bool {
return (ti.IsCHArmorPart() || ti.IsCHProtectorPart() || ti.IsCHGarmentPart()) && ti.TypeID4 == 3
}
func (ti TypeInfo) IsCHPant() bool {
return (ti.IsCHArmorPart() || ti.IsCHProtectorPart() || ti.IsCHGarmentPart()) && ti.TypeID4 == 4
}
func (ti TypeInfo) IsCHGlove() bool {
return (ti.IsCHArmorPart() || ti.IsCHProtectorPart() || ti.IsCHGarmentPart()) && ti.TypeID4 == 5
}
func (ti TypeInfo) IsCHBoots() bool {
return (ti.IsCHArmorPart() || ti.IsCHProtectorPart() || ti.IsCHGarmentPart()) && ti.TypeID4 == 6
}
func (ti TypeInfo) IsEUHelmet() bool {
return (ti.IsEUArmorPart() || ti.IsEUProtectorPart() || ti.IsEUGarmentPart()) && ti.TypeID4 == 1
}
func (ti TypeInfo) IsEUShoulder() bool {
return (ti.IsEUArmorPart() || ti.IsEUProtectorPart() || ti.IsEUGarmentPart()) && ti.TypeID4 == 2
}
func (ti TypeInfo) IsEUChest() bool {
return (ti.IsEUArmorPart() || ti.IsEUProtectorPart() || ti.IsEUGarmentPart()) && ti.TypeID4 == 3
}
func (ti TypeInfo) IsEUPant() bool {
return (ti.IsEUArmorPart() || ti.IsEUProtectorPart() || ti.IsEUGarmentPart()) && ti.TypeID4 == 4
}
func (ti TypeInfo) IsEUGlove() bool {
return (ti.IsEUArmorPart() || ti.IsEUProtectorPart() || ti.IsEUGarmentPart()) && ti.TypeID4 == 5
}
func (ti TypeInfo) IsEUBoots() bool {
return (ti.IsEUArmorPart() || ti.IsEUProtectorPart() || ti.IsEUGarmentPart()) && ti.TypeID4 == 6
}
func (ti TypeInfo) IsCHRing() bool {
return ti.IsCHAccessory() && ti.TypeID4 == 3
}
func (ti TypeInfo) IsEURing() bool {
return ti.IsEUAccessory() && ti.TypeID4 == 3
}
func (ti TypeInfo) IsCHEarring() bool {
return ti.IsCHAccessory() && ti.TypeID4 == 1
}
func (ti TypeInfo) IsEUEarring() bool {
return ti.IsEUAccessory() && ti.TypeID4 == 1
}
func (ti TypeInfo) IsCHNecklace() bool {
return ti.IsCHAccessory() && ti.TypeID4 == 2
}
func (ti TypeInfo) IsEUNecklace() bool {
return ti.IsEUAccessory() && ti.TypeID4 == 2
}
func (ti TypeInfo) IsArrow() bool {
return ti.IsExpendable() && ti.TypeID3 == 4 && ti.TypeID4 == 1
}
func (ti TypeInfo) IsBolt() bool {
return ti.IsExpendable() && ti.TypeID3 == 4 && ti.TypeID4 == 2
}
func (ti TypeInfo) IsCharacter() bool {
return ti.TypeID1 == 1
}
func (ti TypeInfo) IsPlayerCharacter() bool {
return ti.IsCharacter() && ti.TypeID2 == 1
}
func (ti TypeInfo) IsNPC() bool {
return ti.IsCharacter() && ti.TypeID2 == 2
}
func (ti TypeInfo) IsNPCMob() bool {
return ti.IsNPC() && ti.TypeID3 == 1
}
func (ti TypeInfo) IsNPCNpc() bool {
return ti.IsNPC() && ti.TypeID3 == 2
}
func (ti TypeInfo) IsCOS() bool {
return ti.IsNPC() && ti.TypeID3 == 3
}
func (ti TypeInfo) IsSiegeObject() bool {
return ti.IsNPC() && ti.TypeID3 == 4
}
func (ti TypeInfo) IsSiegeStruct() bool {
return ti.IsNPC() && ti.TypeID3 == 5
}
func (ti TypeInfo) IsGold() bool {
return ti.IsExpendable() && ti.TypeID3 == 5 && ti.TypeID4 == 0
}
func (ti TypeInfo) IsTradeItem() bool {
return ti.IsExpendable() && ti.TypeID3 == 8
}
func (ti TypeInfo) IsQuestItem() bool {
return ti.IsExpendable() && ti.TypeID3 == 9
}
func (ti TypeInfo) IsStructure() bool {
return ti.TypeID1 == 4
} | model/type_info.go | 0.590897 | 0.636847 | type_info.go | starcoder |
package asyncpi
import (
"bufio"
"bytes"
"io"
)
// scanner is a lexical scanner.
type scanner struct {
r *bufio.Reader
pos TokenPos
}
// newScanner returns a new instance of Scanner.
func newScanner(r io.Reader) *scanner {
return &scanner{r: bufio.NewReader(r), pos: TokenPos{Char: 0, Lines: []int{}}}
}
// read reads the next rune from the buffered reader.
// Returns the rune(0) if reached the end or error occurs.
func (s *scanner) read() rune {
ch, _, err := s.r.ReadRune()
if err != nil {
return eof
}
if ch == '\n' {
s.pos.Lines = append(s.pos.Lines, s.pos.Char)
s.pos.Char = 0
} else {
s.pos.Char++
}
return ch
}
// unread places the previously read rune back on the reader.
func (s *scanner) unread() {
_ = s.r.UnreadRune()
if s.pos.Char == 0 {
s.pos.Char = s.pos.Lines[len(s.pos.Lines)-1]
s.pos.Lines = s.pos.Lines[:len(s.pos.Lines)-1]
} else {
s.pos.Char--
}
}
// Scan returns the next token and parsed value.
func (s *scanner) Scan() (token tok, value string, startPos, endPos TokenPos) {
ch := s.read()
if isWhitespace(ch) {
s.skipWhitespace()
ch = s.read()
}
if isAlphaNum(ch) {
s.unread()
return s.scanName()
}
// Track token positions.
startPos = s.pos
defer func() { endPos = s.pos }()
switch ch {
case eof:
return 0, "", startPos, endPos
case '<':
return kLANGLE, string(ch), startPos, endPos
case '>':
return kRANGLE, string(ch), startPos, endPos
case '(':
return kLPAREN, string(ch), startPos, endPos
case ')':
return kRPAREN, string(ch), startPos, endPos
case '.':
return kPREFIX, string(ch), startPos, endPos
case ';':
return kSEMICOLON, string(ch), startPos, endPos
case ':':
return kCOLON, string(ch), startPos, endPos
case '|':
return kPAR, string(ch), startPos, endPos
case '!':
return kREPEAT, string(ch), startPos, endPos
case ',':
return kCOMMA, string(ch), startPos, endPos
case '#':
s.skipToEOL()
return s.Scan()
}
return kILLEGAL, string(ch), startPos, endPos
}
func (s *scanner) scanName() (token tok, value string, startPos, endPos TokenPos) {
var buf bytes.Buffer
startPos = s.pos
defer func() { endPos = s.pos }()
buf.WriteRune(s.read())
for {
if ch := s.read(); ch == eof {
break
} else if !isAlphaNum(ch) && !isNameSymbols(ch) {
s.unread()
break
} else {
_, _ = buf.WriteRune(ch)
}
}
switch buf.String() {
case "0":
return kNIL, buf.String(), startPos, endPos
case "new":
return kNEW, buf.String(), startPos, endPos
}
return kNAME, buf.String(), startPos, endPos
}
func (s *scanner) skipWhitespace() {
for {
if ch := s.read(); ch == eof {
break
} else if !isWhitespace(ch) {
s.unread()
break
}
}
}
func (s *scanner) skipToEOL() {
for {
if ch := s.read(); ch == '\n' || ch == eof {
break
}
}
} | scanner.go | 0.582372 | 0.490236 | scanner.go | starcoder |
package main
var (
// Datacenter list is adopted from https://cloud.google.com/compute/docs/regions-zones/
// and Cloud Run regions are at https://cloud.google.com/run/docs/locations
datacenters = map[string]struct {
location string
flagURL string // flag images must be public domain, as SVG, ideally from Wikipedia
}{
"northamerica-northeast1": {
location: "MontrΓ©al, Canada",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/d/d9/Flag_of_Canada_%28Pantone%29.svg",
},
"us-central1": {
location: "Council Bluffs, Iowa, USA",
flagURL: "https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg",
},
"us-west1": {
location: "The Dalles, Oregon, USA",
flagURL: "https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg",
},
"us-east4": {
location: "Ashburn, Virginia, USA",
flagURL: "https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg",
},
"us-east1": {
location: "Moncks Corner, South Carolina, USA",
flagURL: "https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg",
},
"southamerica-east1": {
location: "SΓ£o Paulo, Brazil",
flagURL: "https://upload.wikimedia.org/wikipedia/en/0/05/Flag_of_Brazil.svg",
},
"europe-north1": {
location: "Hamina, Finland",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/b/bc/Flag_of_Finland.svg",
},
"europe-west1": {
location: "St. Ghislain, Belgium",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/6/65/Flag_of_Belgium.svg",
},
"europe-west2": {
location: "London, U.K.",
flagURL: "https://upload.wikimedia.org/wikipedia/en/a/ae/Flag_of_the_United_Kingdom.svg",
},
"europe-west3": {
location: "Frankfurt, Germany",
flagURL: "https://upload.wikimedia.org/wikipedia/en/b/ba/Flag_of_Germany.svg",
},
"europe-west4": {
location: "Eemshaven, Netherlands",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/2/20/Flag_of_the_Netherlands.svg",
},
"europe-west6": {
location: "Zurich, Switzerland",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/f/f3/Flag_of_Switzerland.svg",
},
"asia-south1": {
location: "Mumbai, India",
flagURL: "https://upload.wikimedia.org/wikipedia/en/4/41/Flag_of_India.svg",
},
"asia-southeast1": {
location: "Jurong West, Singapore",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/4/48/Flag_of_Singapore.svg",
},
"asia-southeast2": {
location: "Jakarta, Indonesia",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/9/9f/Flag_of_Indonesia.svg",
},
"asia-east1": {
location: "Changhua County, Taiwan",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/7/72/Flag_of_the_Republic_of_China.svg",
},
"asia-east2": {
location: "Hong Kong",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/5/5b/Flag_of_Hong_Kong.svg",
},
"asia-northeast1": {
location: "Tokyo, Japan",
flagURL: "https://upload.wikimedia.org/wikipedia/en/9/9e/Flag_of_Japan.svg",
},
"asia-northeast2": {
location: "Osaka, Japan",
flagURL: "https://upload.wikimedia.org/wikipedia/en/9/9e/Flag_of_Japan.svg",
},
"asia-northeast3": {
location: "Seoul, South Korea",
flagURL: "https://upload.wikimedia.org/wikipedia/commons/0/09/Flag_of_South_Korea.svg",
},
"australia-southeast1": {
location: "Sydney, Australia",
flagURL: "https://upload.wikimedia.org/wikipedia/en/b/b9/Flag_of_Australia.svg",
},
}
) | datacenters.go | 0.544559 | 0.472197 | datacenters.go | starcoder |
package main
import "sync"
// LargestFreeAI is an AI which navigates the player in the direction of the largest free area (calculated as a line from the current position).
type LargestFreeAI struct {
l sync.Mutex
i chan string
}
// GetChannel receives the answer channel.
func (lf *LargestFreeAI) GetChannel(c chan string) {
lf.l.Lock()
defer lf.l.Unlock()
lf.i = c
}
// GetState gets the game state and computes an answer.
func (lf *LargestFreeAI) GetState(g *Game) {
lf.l.Lock()
defer lf.l.Unlock()
if lf.i == nil {
return
}
if g.Running && g.Players[g.You].Active {
action := ActionNOOP
free := 0
// Fill potential dead zones
for k := range g.Players {
if k == g.You {
continue
}
if !g.Players[k].Active {
continue
}
for i := 1; i <= g.Players[k].Speed+1; i++ {
x, y := g.Players[k].X+i, g.Players[k].Y
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
x, y = g.Players[k].X-i, g.Players[k].Y
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
x, y = g.Players[k].X, g.Players[k].Y+i
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
x, y = g.Players[k].X, g.Players[k].Y-i
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
// invalid - do nothing
} else {
g.Cells[y][x] = -100
}
}
}
// Test direction
switch g.Players[g.You].Direction {
case DirectionUp:
// Straight
found := lf.GetFree(func(x, y int) (int, int) { return x, y - 1 }, g)
if found > free {
free = found
action = ActionNOOP
}
// Left
found = lf.GetFree(func(x, y int) (int, int) { return x - 1, y }, g)
if found > free {
free = found
action = ActionTurnLeft
}
// Right
found = lf.GetFree(func(x, y int) (int, int) { return x + 1, y }, g)
if found > free {
free = found
action = ActionTurnRight
}
case DirectionRight:
// Straight - right
found := lf.GetFree(func(x, y int) (int, int) { return x + 1, y }, g)
if found > free {
free = found
action = ActionNOOP
}
// Left - up
found = lf.GetFree(func(x, y int) (int, int) { return x, y - 1 }, g)
if found > free {
free = found
action = ActionTurnLeft
}
// Right - down
found = lf.GetFree(func(x, y int) (int, int) { return x, y + 1 }, g)
if found > free {
free = found
action = ActionTurnRight
}
case DirectionLeft:
// Straight - left
found := lf.GetFree(func(x, y int) (int, int) { return x - 1, y }, g)
if found > free {
free = found
action = ActionNOOP
}
// Left - down
found = lf.GetFree(func(x, y int) (int, int) { return x, y + 1 }, g)
if found > free {
free = found
action = ActionTurnLeft
}
// Right - up
found = lf.GetFree(func(x, y int) (int, int) { return x, y - 1 }, g)
if found > free {
free = found
action = ActionTurnRight
}
case DirectionDown:
// Straight
found := lf.GetFree(func(x, y int) (int, int) { return x, y + 1 }, g)
if found > free {
free = found
action = ActionNOOP
}
// Left
found = lf.GetFree(func(x, y int) (int, int) { return x + 1, y }, g)
if found > free {
free = found
action = ActionTurnLeft
}
// Right
found = lf.GetFree(func(x, y int) (int, int) { return x - 1, y }, g)
if found > free {
free = found
action = ActionTurnRight
}
}
// Send action
lf.i <- action
}
}
// Name returns the name of the AI.
func (lf *LargestFreeAI) Name() string {
return "LargestFreeAI"
}
// GetFree returns the number of free cells in the direction given by dostep.
// It is not safe for concurrent usage on the same game.
func (lf *LargestFreeAI) GetFree(dostep func(x, y int) (int, int), g *Game) int {
x, y := g.Players[g.You].X, g.Players[g.You].Y
free := 0
for {
x, y = dostep(x, y)
if x < 0 || x >= g.Width || y < 0 || y >= g.Height {
break
}
if g.Cells[y][x] != 0 {
break
}
free++
}
return free
} | ai_largestfree.go | 0.502197 | 0.458712 | ai_largestfree.go | starcoder |
package it
import (
"gonum.org/v1/gonum/mat"
)
// Emperical1D is an empirical estimator for a one-dimensional
// probability distribution
func Emperical1D(d []int) mat.Vector {
max := 0
for _, v := range d {
if v > max {
max = v
}
}
max++
c := make([]float64, max, max)
l := float64(len(d))
for _, v := range d {
c[v] += 1.0
}
for i := range c {
c[i] /= l
}
p := mat.NewVecDense(max, c)
return p
}
// Emperical2D is an empirical estimator for a two-dimensional
// probability distribution
func Emperical2D(d [][]int) [][]float64 {
max := make([]int, 2, 2)
rows := len(d)
for r := 0; r < rows; r++ {
for c := 0; c < 2; c++ {
if d[r][c] > max[c] {
max[c] = d[r][c]
}
}
}
max[0]++
max[1]++
p := make([][]float64, max[0], max[0])
for m := 0; m < max[0]; m++ {
p[m] = make([]float64, max[1], max[1])
}
for r := 0; r < rows; r++ {
p[d[r][0]][d[r][1]] += 1.0
}
l := float64(len(d))
for r := 0; r < max[0]; r++ {
for c := 0; c < max[1]; c++ {
p[r][c] /= l
}
}
return p
}
// Emperical3D is an empirical estimator for a three-dimensional
// probability distribution
func Emperical3D(d [][]int) [][][]float64 {
max := make([]int, 3, 3)
rows := len(d)
for r := 0; r < rows; r++ {
for c := 0; c < 3; c++ {
if d[r][c] > max[c] {
max[c] = d[r][c]
}
}
}
max[0]++
max[1]++
max[2]++
p := make([][][]float64, max[0], max[0])
for m := 0; m < max[0]; m++ {
p[m] = make([][]float64, max[1], max[1])
for n := 0; n < max[1]; n++ {
p[m][n] = make([]float64, max[2], max[2])
}
}
for r := 0; r < rows; r++ {
p[d[r][0]][d[r][1]][d[r][2]] += 1.0
}
l := float64(len(d))
for a := 0; a < max[0]; a++ {
for b := 0; b < max[1]; b++ {
for c := 0; c < max[2]; c++ {
p[a][b][c] /= l
}
}
}
return p
}
// Emperical4D is an empirical estimator for a three-dimensional
// probability distribution
func Emperical4D(d [][]int) [][][][]float64 {
max := make([]int, 4, 4)
rows := len(d)
for r := 0; r < rows; r++ {
for c := 0; c < 4; c++ {
if d[r][c] > max[c] {
max[c] = d[r][c]
}
}
}
max[0]++
max[1]++
max[2]++
max[3]++
p := make([][][][]float64, max[0], max[0])
for m := 0; m < max[0]; m++ {
p[m] = make([][][]float64, max[1], max[1])
for n := 0; n < max[1]; n++ {
p[m][n] = make([][]float64, max[2], max[2])
for k := 0; k < max[2]; k++ {
p[m][n][k] = make([]float64, max[3], max[3])
}
}
}
for r := 0; r < rows; r++ {
p[d[r][0]][d[r][1]][d[r][2]][d[r][3]] += 1.0
}
l := float64(len(d))
for a := 0; a < max[0]; a++ {
for b := 0; b < max[1]; b++ {
for c := 0; c < max[2]; c++ {
for d := 0; d < max[3]; d++ {
p[a][b][c][d] /= l
}
}
}
}
return p
} | stat/it/probabilityestimators.go | 0.60778 | 0.482978 | probabilityestimators.go | starcoder |
package types
import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"math/big"
"time"
)
// BxBlockTransaction represents a tx in the BxBlock.
type BxBlockTransaction struct {
hash SHA256Hash
content []byte
}
// NewBxBlockTransaction creates a new tx in the BxBlock. This transaction is usable for compression.
func NewBxBlockTransaction(hash SHA256Hash, content []byte) *BxBlockTransaction {
return &BxBlockTransaction{
hash: hash,
content: content,
}
}
// NewRawBxBlockTransaction creates a new transaction that's not ready for compression. This should only be used when parsing the result of an existing BxBlock.
func NewRawBxBlockTransaction(content []byte) *BxBlockTransaction {
return &BxBlockTransaction{
content: content,
}
}
// Hash returns the transaction hash
func (b BxBlockTransaction) Hash() SHA256Hash {
return b.hash
}
// Content returns the transaction bytes
func (b BxBlockTransaction) Content() []byte {
return b.content
}
// BxBlock represents an encoded block ready for compression or decompression
type BxBlock struct {
hash SHA256Hash
Header []byte
Txs []*BxBlockTransaction
Trailer []byte
TotalDifficulty *big.Int
Number *big.Int
timestamp time.Time
size int
}
// NewBxBlock creates a new BxBlock that's ready for compression. This means that all transaction hashes must be included.
func NewBxBlock(hash SHA256Hash, header []byte, txs []*BxBlockTransaction, trailer []byte, totalDifficulty *big.Int, number *big.Int, size int) (*BxBlock, error) {
for _, tx := range txs {
if tx.Hash() == (SHA256Hash{}) {
return nil, errors.New("all transactions must contain hashes")
}
}
return NewRawBxBlock(hash, header, txs, trailer, totalDifficulty, number, size), nil
}
// NewRawBxBlock create a new BxBlock without compression restrictions. This should only be used when parsing the result of an existing BxBlock.
func NewRawBxBlock(hash SHA256Hash, header []byte, txs []*BxBlockTransaction, trailer []byte, totalDifficulty *big.Int, number *big.Int, size int) *BxBlock {
bxBlock := &BxBlock{
hash: hash,
Header: header,
Txs: txs,
Trailer: trailer,
TotalDifficulty: totalDifficulty,
Number: number,
timestamp: time.Now(),
size: size,
}
return bxBlock
}
// Serialize returns an expensive string representation of the BxBlock
func (b BxBlock) Serialize() string {
m := make(map[string]interface{})
m["header"] = hex.EncodeToString(b.Header)
m["trailer"] = hex.EncodeToString(b.Trailer)
m["totalDifficulty"] = b.TotalDifficulty.String()
m["number"] = b.Number.String()
txs := make([]string, 0, len(b.Txs))
for _, tx := range b.Txs {
txs = append(txs, hex.EncodeToString(tx.content))
}
m["txs"] = txs
jsonBytes, _ := json.Marshal(m)
return string(jsonBytes)
}
// Hash returns block hash
func (b BxBlock) Hash() SHA256Hash {
return b.hash
}
// Timestamp returns block add time
func (b BxBlock) Timestamp() time.Time {
return b.timestamp
}
// Size returns the original blockchain block
func (b BxBlock) Size() int {
return b.size
}
// SetSize sets the original blockchain block
func (b *BxBlock) SetSize(size int) {
b.size = size
}
// Equals checks the byte contents of each part of the provided BxBlock. Note that some fields are set throughout the object's lifecycle (bx block hash, transaction hash), so these fields are not checked for equality.
func (b *BxBlock) Equals(other *BxBlock) bool {
if !bytes.Equal(b.Header, other.Header) || !bytes.Equal(b.Trailer, other.Trailer) {
return false
}
for i, tx := range b.Txs {
otherTx := other.Txs[i]
if !bytes.Equal(tx.content, otherTx.content) {
return false
}
}
return b.TotalDifficulty.Cmp(other.TotalDifficulty) == 0 && b.Number.Cmp(other.Number) == 0
} | types/bxblock.go | 0.810066 | 0.415492 | bxblock.go | starcoder |
package main
import (
"github.com/ByteArena/box2d"
"github.com/wdevore/RangerGo/api"
"github.com/wdevore/RangerGo/engine/nodes/custom"
)
// FenceComponent represents both the visual and physic components
type FenceComponent struct {
bottom api.INode
right api.INode
top api.INode
left api.INode
b2Body *box2d.B2Body
b2Shape box2d.B2EdgeShape
}
// NewFenceComponent constructs a component
func NewFenceComponent(name string, parent api.INode) *FenceComponent {
o := new(FenceComponent)
o.bottom = custom.NewLineNode(name, parent.World(), parent)
gln := o.bottom.(*custom.LineNode)
gln.SetPoints(-1.0, 0.0, 1.0, 0.0) // Set by unit coordinates
o.right = custom.NewLineNode(name, parent.World(), parent)
gln = o.right.(*custom.LineNode)
gln.SetPoints(0.0, 1.0, 0.0, -1.0) // Set by unit coordinates
o.top = custom.NewLineNode(name, parent.World(), parent)
gln = o.top.(*custom.LineNode)
gln.SetPoints(1.0, 0.0, -1.0, 0.0) // Set by unit coordinates
o.left = custom.NewLineNode(name, parent.World(), parent)
gln = o.left.(*custom.LineNode)
gln.SetPoints(0.0, -1.0, 0.0, 1.0) // Set by unit coordinates
return o
}
// Configure component
func (f *FenceComponent) Configure(b2World *box2d.B2World) {
// A body def used to create bodies
bDef := box2d.MakeB2BodyDef()
bDef.Type = box2d.B2BodyType.B2_staticBody
// An instance of a body to contain Fixtures
f.b2Body = b2World.CreateBody(&bDef)
}
// SetColor sets the visual's color
func (f *FenceComponent) SetColor(color api.IPalette) {
gr := f.bottom.(*custom.LineNode)
gr.SetColor(color)
gr = f.right.(*custom.LineNode)
gr.SetColor(color)
gr = f.top.(*custom.LineNode)
gr.SetColor(color)
gr = f.left.(*custom.LineNode)
gr.SetColor(color)
}
// SetScale sets the component's length
func (f *FenceComponent) SetScale(scale float64) {
f.bottom.SetPosition(0.0, scale)
f.bottom.SetScale(scale)
f.right.SetPosition(scale, 0.0)
f.right.SetScale(scale)
f.top.SetPosition(0.0, -scale)
f.top.SetScale(scale)
f.left.SetPosition(-scale, 0.0)
f.left.SetScale(scale)
fd := box2d.MakeB2FixtureDef()
// Bottom fixture
f.b2Shape = box2d.MakeB2EdgeShape()
f.b2Shape.Set(box2d.MakeB2Vec2(-scale, scale), box2d.MakeB2Vec2(scale, scale))
fd.Shape = &f.b2Shape
f.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body
// Right fixture
f.b2Shape = box2d.MakeB2EdgeShape()
f.b2Shape.Set(box2d.MakeB2Vec2(scale, scale), box2d.MakeB2Vec2(scale, -scale))
fd.Shape = &f.b2Shape
f.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body
// Top fixture
f.b2Shape = box2d.MakeB2EdgeShape()
f.b2Shape.Set(box2d.MakeB2Vec2(scale, -scale), box2d.MakeB2Vec2(-scale, -scale))
fd.Shape = &f.b2Shape
f.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body
// Left fixture
f.b2Shape = box2d.MakeB2EdgeShape()
f.b2Shape.Set(box2d.MakeB2Vec2(-scale, -scale), box2d.MakeB2Vec2(-scale, scale))
fd.Shape = &f.b2Shape
f.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body
} | examples/physics/intermediate/target_tracking/fence_component.go | 0.675229 | 0.4206 | fence_component.go | starcoder |
package solar
import (
"container/list"
"math"
"image/color"
"github.com/golang/geo/r2"
)
// PlanetIndex used to reference array of all planets
type PlanetIndex int
// Planet indexes
const (
Sun PlanetIndex = 0
Mercury PlanetIndex = 1
Venus PlanetIndex = 2
Earth PlanetIndex = 3
Mars PlanetIndex = 4
Jupiter PlanetIndex = 5
Saturn PlanetIndex = 6
Uranus PlanetIndex = 7
Neptune PlanetIndex = 8
PlanetCount int = 9
)
// String return name of a given PlanetIndex
func (planet PlanetIndex) String() string {
if planet < Sun || planet > Neptune {
return "Unknown"
}
names := [...]string{"Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"}
return names[planet]
}
// Planet information about a planet
type Planet struct {
// position of planet on the wall
position r2.Point
// size of the planet in mm
radius float64
// number of leds
ledCount int
// angleOffset radians offset so that axis aligns with physical leds
angleOffset float64
// angleDirection -1 if led strip was installed counter clockwise
angleDirection float64
}
// System all objects that exist in the system, the state of the world
type System struct {
// The planets
planets [PlanetCount]Planet
// All of the drawable items, stored in increasing ZIndex order
drawables *list.List
}
// DefaultSystem create a solar system with all the data for the planets initialized
func DefaultSystem() *System {
system := &System{}
system.planets[Sun] = Planet{r2.Point{X: 9, Y: 11}, 6, 27, -1.18, -1.0}
system.planets[Mercury] = Planet{r2.Point{X: 7, Y: 25}, 4, 17, -0.78, 1.0}
system.planets[Venus] = Planet{r2.Point{X: 30, Y: 30}, 4, 17, -0.10, 1.0}
system.planets[Earth] = Planet{r2.Point{X: 40, Y: 10}, 4, 17, -2.79, 1.0}
system.planets[Mars] = Planet{r2.Point{X: 60, Y: 19}, 4, 17, -0.81, 1.0}
system.planets[Jupiter] = Planet{r2.Point{X: 78, Y: 30}, 6, 27, 0.26, -1.0}
system.planets[Saturn] = Planet{r2.Point{X: 94, Y: 14}, 6, 27, 0.92, -1.0}
system.planets[Uranus] = Planet{r2.Point{X: 106, Y: 45}, 6, 27, -2.78, -1.0}
system.planets[Neptune] = Planet{r2.Point{X: 126, Y: 25}, 4, 27, -1.00, 1.0}
system.drawables = list.New()
system.drawables.PushFront(&DrawLine{
startPosition: r2.Point{X: 0, Y: 0},
endPosition: r2.Point{X: 130, Y: 0},
traverseTime: 10.0,
currentPosition: r2.Point{X: 0, Y: 0},
lineDirection: r2.Point{X: 1, Y: 0},
lineWidth: 6.0,
color: color.RGBA{R: 0, G: 255, B: 255, A: 128},
zindex: 0,
})
system.drawables.PushFront(NewRotatingLine(Sun, system))
system.drawables.PushFront(NewRotatingLine(Mercury, system))
system.drawables.PushFront(NewRotatingLine(Venus, system))
system.drawables.PushFront(NewRotatingLine(Earth, system))
system.drawables.PushFront(NewRotatingLine(Mars, system))
system.drawables.PushFront(NewRotatingLine(Jupiter, system))
system.drawables.PushFront(NewRotatingLine(Saturn, system))
system.drawables.PushFront(NewRotatingLine(Uranus, system))
system.drawables.PushFront(NewRotatingLine(Neptune, system))
// system.drawables.PushFront(&DrawLine{
// startPosition: r2.Point{X: 0, Y: 0},
// endPosition: r2.Point{X: 130, Y: 50},
// traverseTime: 15.0,
// currentPosition: r2.Point{X: 0, Y: 0},
// lineDirection: r2.Point{X: .707, Y: .707},
// lineWidth: 24.0,
// color: color.RGBA{R: 255, G: 255, B: 0, A: 128},
// zindex: 3,
// })
// system.drawables.PushFront(&DrawLine{
// startPosition: r2.Point{X: 0, Y: 0},
// endPosition: r2.Point{X: 130, Y: 0},
// traverseTime: 10.0,
// currentPosition: r2.Point{X: 0, Y: 0},
// lineDirection: r2.Point{X: 1, Y: 0},
// lineWidth: 6.0,
// color: color.RGBA{R: 255, G: 0, B: 255, A: 128},
// zindex: 0,
// })
// system.drawables.PushFront(&DrawLine{
// startPosition: r2.Point{X: 0, Y: 0},
// endPosition: r2.Point{X: 0, Y: 50},
// traverseTime: 12.0,
// currentPosition: r2.Point{X: 0, Y: 0},
// lineDirection: r2.Point{X: 0, Y: 1},
// lineWidth: 12.0,
// color: color.RGBA{R: 0, G: 255, B: 0, A: 128},
// zindex: 4,
// })
return system
}
// LedCount return total number of LEDs that exist in system
func (solarSystem *System) LedCount() int {
count := 0
for _, planet := range solarSystem.planets {
count += planet.ledCount
}
return count
}
// LedPosition return XYPosition of a given Led on the planet
func (solarSystem *System) LedPosition(planetI PlanetIndex, ledIndex int) r2.Point {
planet := solarSystem.planets[planetI]
radiansPerLed := (2.0 * math.Pi) / float64(planet.ledCount)
ledOffset := r2.Point{
X: math.Cos(float64(ledIndex)*radiansPerLed*planet.angleDirection+planet.angleOffset) * planet.radius * 0.5,
Y: math.Sin(float64(ledIndex)*radiansPerLed*planet.angleDirection+planet.angleOffset) * planet.radius * 0.5}
return ledOffset.Add(planet.position)
}
// Animate moves all drawables forward in time
func (solarSystem *System) Animate(dt float64) {
for curElement := solarSystem.drawables.Front(); curElement != nil; {
drawable := curElement.Value.(Drawable)
if !drawable.Animate(dt) {
nextElement := curElement.Next()
solarSystem.drawables.Remove(curElement)
curElement = nextElement
} else {
curElement = curElement.Next()
}
}
} | solar/solarSystem.go | 0.709019 | 0.48987 | solarSystem.go | starcoder |
package stats
import (
"fmt"
"math"
"sync"
)
var defaultCutoffs = []float64{
.005,
.01,
.025,
.05,
.1,
.25,
.5,
1.,
2.5,
5.,
10.,
math.Inf(0),
}
type HistogramValue struct {
Tags map[string]string
Count int64
Sum float64
Buckets []Bucket
}
type HistogramVectorGetter interface {
Labels() []string
Cutoffs() []float64
Get() []*HistogramValue
}
type HistogramVector interface {
WithLabels(...string) Histogram
}
type histogramVector struct {
labels []string
cutoffs []float64
mu sync.RWMutex
hs map[uint64]*histogram
marshaler labelMarshaler
}
func (hv *histogramVector) Labels() []string { return hv.labels }
func (hv *histogramVector) Cutoffs() []float64 { return hv.cutoffs }
func (hv *histogramVector) buildTags(key uint64) map[string]string {
var tags = make(map[string]string, len(hv.labels))
for i, val := range hv.marshaler.unmarshal(key) {
tags[hv.labels[i]] = val
}
return tags
}
func (hv *histogramVector) Get() []*HistogramValue {
var res = make([]*HistogramValue, 0, len(hv.hs))
for k, h := range hv.hs {
res = append(
res,
&HistogramValue{
Tags: hv.buildTags(k),
Count: h.Count(),
Sum: h.Sum(),
Buckets: h.Buckets(),
},
)
}
return res
}
func (hv *histogramVector) WithLabels(ls ...string) Histogram {
if len(ls) != len(hv.labels) {
panic(
fmt.Sprintf(
"Not the correct number of labels: labels: %v, values: %v",
hv.labels,
ls,
),
)
}
k := hv.marshaler.marshal(ls)
hv.mu.RLock()
h, ok := hv.hs[k]
hv.mu.RUnlock()
if ok {
return h
}
hv.mu.Lock()
h = &histogram{
cutoffs: hv.cutoffs,
counts: make([]atomicInt64, len(hv.cutoffs)),
}
hv.hs[k] = h
hv.mu.Unlock()
return h
}
type Bucket struct {
Count int64
UpperBound float64
}
type Histogram interface {
Record(float64)
Count() int64
Sum() float64
Buckets() []Bucket
}
type histogram struct {
cutoffs []float64
sum atomicFloat64
counts []atomicInt64
}
func (h *histogram) Record(v float64) {
for i, c := range h.cutoffs {
if v <= c {
h.counts[i].Inc()
h.sum.Add(v)
break
}
}
}
func (h *histogram) Sum() float64 { return h.sum.Get() }
func (h *histogram) Count() int64 {
var res int64
for _, c := range h.counts {
res += c.Get()
}
return res
}
func (h *histogram) Buckets() []Bucket {
var bs = make([]Bucket, len(h.cutoffs))
for i, cutoff := range h.cutoffs {
bs[i].UpperBound = cutoff
bs[i].Count = h.counts[i].Get()
}
return bs
}
func StaticBuckets(cutoffs []float64) HistogramOption {
return func(hv *histogramVector) {
hv.cutoffs = append(cutoffs, math.Inf(0))
}
}
type partialHistogramVector struct {
hv HistogramVector
vs []string
}
func (phv partialHistogramVector) WithLabels(labels ...string) Histogram {
return phv.hv.WithLabels(append(phv.vs, labels...)...)
}
type reorderHistogramVector struct {
hv HistogramVector
labelOrderer
}
func (rhv reorderHistogramVector) WithLabels(ls ...string) Histogram {
return rhv.hv.WithLabels(rhv.order(ls)...)
} | vendor/github.com/upfluence/stats/histogram.go | 0.545286 | 0.471345 | histogram.go | starcoder |
package math
import (
"errors"
)
type Matrix4 struct {
M11, M12, M13, M14 float32
M21, M22, M23, M24 float32
M31, M32, M33, M34 float32
M41, M42, M43, M44 float32
}
func NewMatrix4() *Matrix4 {
return &Matrix4{}
}
func NewIdentityMatrix4() *Matrix4 {
return &Matrix4{
M11: 1.0,
M22: 1.0,
M33: 1.0,
M44: 1.0,
}
}
func NewPerspectiveMatrix4(fovy, aspectRatio, near, far float32) *Matrix4 {
fovy = fovy * DegreeToRadians
nmf := near - far
f := 1.0 / Tan(fovy/2)
return &Matrix4{
f / aspectRatio, 0, 0, 0,
0, f, 0, 0,
0, 0, (near + far) / nmf, -1,
0, 0, (2 * far * near) / nmf, 0,
}
}
func NewTranslationMatrix4(x, y, z float32) *Matrix4 {
return &Matrix4{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1}
}
// LookAt Matrix right hand
func NewLookAtMatrix4(eye, center, up Vector3) *Matrix4 {
zAxis := (eye.Sub(center)).Nor()
xAxis := (up.Cross(zAxis)).Nor()
yAxis := zAxis.Cross(xAxis)
return &Matrix4{
xAxis.X, yAxis.X, zAxis.X, 0,
xAxis.Y, yAxis.Y, zAxis.Y, 0,
xAxis.Z, yAxis.Z, zAxis.Z, 0,
-(xAxis.Dot(eye)), -(yAxis.Dot(eye)), -(zAxis.Dot(eye)), 1,
}
}
func NewRotationMatrix4(axis Vector3, angle float32) *Matrix4 {
axis = axis.Nor()
angle = DegreeToRadians * angle
c := Cos(angle)
s := Sin(angle)
k := 1 - c
return &Matrix4{axis.X*axis.X*k + c, axis.X*axis.Y*k + axis.Z*s, axis.X*axis.Z*k - axis.Y*s, 0,
axis.X*axis.Y*k - axis.Z*s, axis.Y*axis.Y*k + c, axis.Y*axis.Z*k + axis.X*s, 0,
axis.X*axis.Z*k + axis.Y*s, axis.Y*axis.Z*k - axis.X*s, axis.Z*axis.Z*k + c, 0,
0, 0, 0, 1}
}
func NewOrthoMatrix4(left, right, bottom, top, near, far float32) *Matrix4 {
xOrtho := 2 / (right - left)
yOrtho := 2 / (top - bottom)
zOrtho := -2 / (far - near)
tx := -(right + left) / (right - left)
ty := -(top + bottom) / (top - bottom)
tz := -(far + near) / (far - near)
return &Matrix4{M11: xOrtho, M22: yOrtho, M33: zOrtho, M41: tx, M42: ty, M43: tz, M44: 1}
}
func (m1 *Matrix4) Set(m2 *Matrix4) *Matrix4 {
(*m1) = (*m2)
return m1
}
// Multiplicates this matrix with m2 matrix and returns the new matrix.
func (m1 *Matrix4) Mul(m2 *Matrix4) *Matrix4 {
temp := &Matrix4{
m1.M11*m2.M11 + m1.M21*m2.M12 + m1.M31*m2.M13 + m1.M41*m2.M14,
m1.M12*m2.M11 + m1.M22*m2.M12 + m1.M32*m2.M13 + m1.M42*m2.M14,
m1.M13*m2.M11 + m1.M23*m2.M12 + m1.M33*m2.M13 + m1.M43*m2.M14,
m1.M14*m2.M11 + m1.M24*m2.M12 + m1.M34*m2.M13 + m1.M44*m2.M14,
m1.M11*m2.M21 + m1.M21*m2.M22 + m1.M31*m2.M23 + m1.M41*m2.M24,
m1.M12*m2.M21 + m1.M22*m2.M22 + m1.M32*m2.M23 + m1.M42*m2.M24,
m1.M13*m2.M21 + m1.M23*m2.M22 + m1.M33*m2.M23 + m1.M43*m2.M24,
m1.M14*m2.M21 + m1.M24*m2.M22 + m1.M34*m2.M23 + m1.M44*m2.M24,
m1.M11*m2.M31 + m1.M21*m2.M32 + m1.M31*m2.M33 + m1.M41*m2.M34,
m1.M12*m2.M31 + m1.M22*m2.M32 + m1.M32*m2.M33 + m1.M42*m2.M34,
m1.M13*m2.M31 + m1.M23*m2.M32 + m1.M33*m2.M33 + m1.M43*m2.M34,
m1.M14*m2.M31 + m1.M24*m2.M32 + m1.M34*m2.M33 + m1.M44*m2.M34,
m1.M11*m2.M41 + m1.M21*m2.M42 + m1.M31*m2.M43 + m1.M41*m2.M44,
m1.M12*m2.M41 + m1.M22*m2.M42 + m1.M32*m2.M43 + m1.M42*m2.M44,
m1.M13*m2.M41 + m1.M23*m2.M42 + m1.M33*m2.M43 + m1.M43*m2.M44,
m1.M14*m2.M41 + m1.M24*m2.M42 + m1.M34*m2.M43 + m1.M44*m2.M44}
return temp
}
func (m *Matrix4) MulVec3(vec Vector3) Vector3 {
tmp := Vector3{}
tmp.X = vec.X*m.M11 + vec.Y*m.M21 + vec.Z*m.M31 + m.M41
tmp.Y = vec.X*m.M12 + vec.Y*m.M22 + vec.Z*m.M32 + m.M42
tmp.Z = vec.X*m.M13 + vec.Y*m.M23 + vec.Z*m.M33 + m.M43
return tmp
}
func (m *Matrix4) MulVec4(vec Vector4) Vector4 {
tmp := Vector4{}
tmp.X = vec.X*m.M11 + vec.Y*m.M21 + vec.Z*m.M31 + vec.W*m.M41
tmp.Y = vec.X*m.M12 + vec.Y*m.M22 + vec.Z*m.M32 + vec.W*m.M42
tmp.Z = vec.X*m.M13 + vec.Y*m.M23 + vec.Z*m.M33 + vec.W*m.M43
tmp.W = vec.X*m.M14 + vec.Y*m.M24 + vec.Z*m.M34 + vec.W*m.M44
return tmp
}
func (m *Matrix4) Scale(scalar Vector3) *Matrix4 {
s := &Matrix4{
M11: scalar.X,
M22: scalar.Y,
M33: scalar.Z,
M44: 1,
}
return m.Mul(s)
}
func (m *Matrix4) Invert() (*Matrix4, error) {
det := m.Determinant()
if det == 0 {
return nil, errors.New("non-invertible matrix")
}
tmp := &Matrix4{}
tmp.M11 = m.M32*m.M43*m.M24 - m.M42*m.M33*m.M24 + m.M42*m.M23*m.M34 - m.M22*m.M43*m.M34 - m.M32*m.M23*m.M44 + m.M22*m.M33*m.M44
tmp.M21 = m.M41*m.M33*m.M24 - m.M31*m.M43*m.M24 - m.M41*m.M23*m.M34 + m.M21*m.M43*m.M34 + m.M31*m.M23*m.M44 - m.M21*m.M33*m.M44
tmp.M31 = m.M31*m.M42*m.M24 - m.M41*m.M32*m.M24 + m.M41*m.M22*m.M34 - m.M21*m.M42*m.M34 - m.M31*m.M22*m.M44 + m.M21*m.M32*m.M44
tmp.M41 = m.M41*m.M32*m.M23 - m.M31*m.M42*m.M23 - m.M41*m.M22*m.M33 + m.M21*m.M42*m.M33 + m.M31*m.M22*m.M43 - m.M21*m.M32*m.M43
tmp.M12 = m.M42*m.M33*m.M14 - m.M32*m.M43*m.M14 - m.M42*m.M13*m.M34 + m.M12*m.M43*m.M34 + m.M32*m.M13*m.M44 - m.M12*m.M33*m.M44
tmp.M22 = m.M31*m.M43*m.M14 - m.M41*m.M33*m.M14 + m.M41*m.M13*m.M34 - m.M11*m.M43*m.M34 - m.M31*m.M13*m.M44 + m.M11*m.M33*m.M44
tmp.M32 = m.M41*m.M32*m.M14 - m.M31*m.M42*m.M14 - m.M41*m.M12*m.M34 + m.M11*m.M42*m.M34 + m.M31*m.M12*m.M44 - m.M11*m.M32*m.M44
tmp.M42 = m.M31*m.M42*m.M13 - m.M41*m.M32*m.M13 + m.M41*m.M12*m.M33 - m.M11*m.M42*m.M33 - m.M31*m.M12*m.M43 + m.M11*m.M32*m.M43
tmp.M13 = m.M22*m.M43*m.M14 - m.M42*m.M23*m.M14 + m.M42*m.M13*m.M24 - m.M12*m.M43*m.M24 - m.M22*m.M13*m.M44 + m.M12*m.M23*m.M44
tmp.M23 = m.M41*m.M23*m.M14 - m.M21*m.M43*m.M14 - m.M41*m.M13*m.M24 + m.M11*m.M43*m.M24 + m.M21*m.M13*m.M44 - m.M11*m.M23*m.M44
tmp.M33 = m.M21*m.M42*m.M14 - m.M41*m.M22*m.M14 + m.M41*m.M12*m.M24 - m.M11*m.M42*m.M24 - m.M21*m.M12*m.M44 + m.M11*m.M22*m.M44
tmp.M43 = m.M41*m.M22*m.M13 - m.M21*m.M42*m.M13 - m.M41*m.M12*m.M23 + m.M11*m.M42*m.M23 + m.M21*m.M12*m.M43 - m.M11*m.M22*m.M43
tmp.M14 = m.M32*m.M23*m.M14 - m.M22*m.M33*m.M14 - m.M32*m.M13*m.M24 + m.M12*m.M33*m.M24 + m.M22*m.M13*m.M34 - m.M12*m.M23*m.M34
tmp.M24 = m.M21*m.M33*m.M14 - m.M31*m.M23*m.M14 + m.M31*m.M13*m.M24 - m.M11*m.M33*m.M24 - m.M21*m.M13*m.M34 + m.M11*m.M23*m.M34
tmp.M34 = m.M31*m.M22*m.M14 - m.M21*m.M32*m.M14 - m.M31*m.M12*m.M24 + m.M11*m.M32*m.M24 + m.M21*m.M12*m.M34 - m.M11*m.M22*m.M34
tmp.M44 = m.M21*m.M32*m.M13 - m.M31*m.M22*m.M13 + m.M31*m.M12*m.M23 - m.M11*m.M32*m.M23 - m.M21*m.M12*m.M33 + m.M11*m.M22*m.M33
inv_det := 1.0 / det
m.M11 = tmp.M11 * inv_det
m.M21 = tmp.M21 * inv_det
m.M31 = tmp.M31 * inv_det
m.M41 = tmp.M41 * inv_det
m.M12 = tmp.M12 * inv_det
m.M22 = tmp.M22 * inv_det
m.M32 = tmp.M32 * inv_det
m.M42 = tmp.M42 * inv_det
m.M13 = tmp.M13 * inv_det
m.M23 = tmp.M23 * inv_det
m.M33 = tmp.M33 * inv_det
m.M43 = tmp.M43 * inv_det
m.M14 = tmp.M14 * inv_det
m.M24 = tmp.M24 * inv_det
m.M34 = tmp.M34 * inv_det
m.M44 = tmp.M44 * inv_det
return m, nil
}
// The determinant of this matrix.
func (m *Matrix4) Determinant() float32 {
return m.M14*m.M23*m.M32*m.M41 -
m.M13*m.M24*m.M32*m.M41 -
m.M14*m.M22*m.M33*m.M41 +
m.M12*m.M24*m.M33*m.M41 +
m.M13*m.M22*m.M34*m.M41 -
m.M12*m.M23*m.M34*m.M41 -
m.M14*m.M23*m.M31*m.M41 +
m.M13*m.M24*m.M31*m.M41 +
m.M14*m.M21*m.M33*m.M41 -
m.M11*m.M24*m.M33*m.M41 -
m.M13*m.M21*m.M34*m.M41 +
m.M11*m.M23*m.M34*m.M41 +
m.M14*m.M22*m.M31*m.M43 -
m.M12*m.M24*m.M31*m.M43 -
m.M14*m.M21*m.M32*m.M43 +
m.M11*m.M24*m.M32*m.M43 +
m.M12*m.M21*m.M34*m.M43 -
m.M11*m.M22*m.M34*m.M43 -
m.M13*m.M22*m.M31*m.M44 +
m.M12*m.M23*m.M31*m.M44 +
m.M13*m.M21*m.M32*m.M44 -
m.M11*m.M23*m.M32*m.M44 -
m.M12*m.M21*m.M33*m.M44 +
m.M11*m.M22*m.M33*m.M44
}
// Equal to gluProject
func Project(obj Vector3, modelview, projection *Matrix4, viewport Vector4) Vector3 {
// Modelview transform
ft0 := modelview.M11*obj.X + modelview.M21*obj.Y + modelview.M31*obj.Z + modelview.M41
ft1 := modelview.M12*obj.X + modelview.M22*obj.Y + modelview.M32*obj.Z + modelview.M42
ft2 := modelview.M13*obj.X + modelview.M23*obj.Y + modelview.M33*obj.Z + modelview.M43
ft3 := modelview.M14*obj.X + modelview.M24*obj.Y + modelview.M34*obj.Z + modelview.M44
// Projection transform, the final row of projection matrix is always [0,0,-1,0]
// so we optimize for that.
ft4 := projection.M11*ft0 + projection.M21*ft1 + projection.M31*ft2 + projection.M41*ft3
ft5 := projection.M12*ft0 + projection.M22*ft1 + projection.M32*ft2 + projection.M42*ft3
ft6 := projection.M13*ft0 + projection.M23*ft1 + projection.M33*ft2 + projection.M43*ft3
ft7 := -ft2
// The result normalizes between -1 and 1
if ft7 == 0.0 { // The w value
return Vec3(0, 0, 0)
}
ft7 = 1.0 / ft7
// Perspective division
ft4 *= ft7
ft5 *= ft7
ft6 *= ft7
// Window coordinates
// Map x, y to range 0-1
x := (ft4*0.5+0.5)*viewport.Z + viewport.X
y := (ft5*0.5+0.5)*viewport.W + viewport.Y
z := (1.0 + ft6) * 0.5
return Vec3(x, y, z)
}
func UnProject(window Vector3, modelview, projection *Matrix4, viewport Vector4) (Vector3, error) {
a := projection.Mul(modelview)
// Compute the inverse of matrix a
inverse, err := a.Invert()
if err != nil {
return Vec3(0, 0, 0), err
}
tmp := Vec4(window.X, window.Y, window.Z, 1)
tmp.X = (tmp.X - viewport.X) / viewport.Z
tmp.Y = (tmp.Y - viewport.Y) / viewport.W
tmp = tmp.Scale(2).Sub(Vec4(1, 1, 1, 1))
obj := inverse.MulVec4(tmp)
obj = obj.Scale(1.0 / obj.W)
return Vec3(obj.X, obj.Y, obj.Z), nil
} | matrix4.go | 0.808294 | 0.54583 | matrix4.go | starcoder |
package partial
import (
"errors"
"fmt"
"reflect"
)
// structField defines the structure of a struct field. name = field name, tag = tag value
type structField struct {
name string
tag string
index int
}
// Partials interface allows for custom types.
// If the value type isn't of Go's basic types, implementing the Partials interface is required otherwise an error will be returned.
type Partials interface {
// Parameter is the reflect.Value as an interface and the returning arg is the value, asserted based on the interface implementation.
Value(i interface{}) (interface{}, error)
}
// getFieldsWithTag will get all the fields from a struct where the tag is present.
func getFieldsWithTag(tag string, t reflect.Type) ([]structField, error) {
amt := t.NumField()
// We don't know how many fields have the requested tag. Size must be zero.
fields := make([]structField, 0)
// Add fields that have the tag into a list. Fields that don't have this tag will be ignored.
for i := 0; i < amt; i++ {
field := t.Field(i)
// Only add fields where the requested tag is present.
v, found := field.Tag.Lookup(tag)
if found {
fields = append(fields, structField{
name: field.Name,
tag: v,
index: i,
})
}
}
return fields, nil
}
// Get will return all of the fields with the tag and that don't have a zero value.
func Get(i interface{}, tag string) (map[string]interface{}, error) {
if reflect.ValueOf(i).Kind() != reflect.Struct {
return nil, fmt.Errorf("expected type struct got %T", i)
}
t := reflect.TypeOf(i)
if t == nil {
return nil, errors.New("interface is nil")
}
// Get all fields with the matching tag.
fields, err := getFieldsWithTag(tag, t)
if err != nil {
return nil, err
}
values := make(map[string]interface{}, len(fields))
// Loop through fields that have the tag and not a zero value, create map with values. K = field name, V = value of field.
for _, field := range fields {
_, found := values[field.tag]
if found {
return nil, errors.New("cannot have duplicate key")
}
v := reflect.ValueOf(i).Field(field.index)
// We don't want fields that don't have a value.
if v.IsZero() {
continue
}
switch v.Kind() {
case reflect.Bool:
values[field.tag] = v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
values[field.tag] = v.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
values[field.tag] = v.Uint()
case reflect.Float32, reflect.Float64:
values[field.tag] = v.Float()
case reflect.Complex64, reflect.Complex128:
values[field.tag] = v.Complex()
case reflect.String:
values[field.tag] = v.String()
default:
// Check if interface can be used.
if !v.CanInterface() {
return nil, errors.New("unable to determine kind and cannot interface on value")
}
// Check if the value implements the Partials interface.
p, ok := v.Interface().(Partials)
if !ok {
return nil, fmt.Errorf("%v does not implement the Partials interface", v.Type().Name())
}
// Run the interface implementation and set the value.
iv, err := p.Value(v.Interface())
if err != nil {
return nil, err
}
values[field.tag] = iv
}
}
return values, nil
} | reflect.go | 0.673084 | 0.478224 | reflect.go | starcoder |
package create
import (
"encoding/json"
"testing"
"time"
"github.com/infracloudio/botkube/pkg/config"
"github.com/infracloudio/botkube/pkg/utils"
"github.com/infracloudio/botkube/test/e2e/env"
testutils "github.com/infracloudio/botkube/test/e2e/utils"
"github.com/nlopes/slack"
"github.com/stretchr/testify/assert"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
type context struct {
*env.TestEnv
}
// Test if BotKube sends notification when a resource is created
func (c *context) testCreateResource(t *testing.T) {
// Test cases
tests := map[string]testutils.CreateObjects{
"create pod in configured namespace": {
Kind: "pod",
Namespace: "test",
Specs: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test-pod"}},
Expected: testutils.SlackMessage{
Attachments: []slack.Attachment{{Color: "good", Fields: []slack.AttachmentField{{Title: "Pod create", Value: "Pod `test-pod` in of cluster `test-cluster-1`, namespace `test` has been created:\n```Resource created\nRecommendations:\n- pod 'test-pod' creation without labels should be avoided.\n```", Short: false}}, Footer: "BotKube"}},
},
},
"create service in configured namespace": {
Kind: "service",
Namespace: "test",
Specs: &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "test-service"}},
Expected: testutils.SlackMessage{
Attachments: []slack.Attachment{{Color: "good", Fields: []slack.AttachmentField{{Title: "Service create", Value: "Service `test-service` in of cluster `test-cluster-1`, namespace `test` has been created:\n```Resource created\n```", Short: false}}, Footer: "BotKube"}},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
// Inject an event into the fake client.
testutils.CreateResource(t, test)
// Get last seen slack message
time.Sleep(time.Second)
lastSeenMsg := c.GetLastSeenSlackMessage()
// Convert text message into Slack message structure
m := slack.Message{}
err := json.Unmarshal([]byte(lastSeenMsg), &m)
assert.NoError(t, err, "message should decode properly")
assert.Equal(t, c.Config.Communications.Slack.Channel, m.Channel)
assert.Equal(t, c.Config.Communications.Slack.Channel, m.Channel)
assert.Equal(t, test.Expected.Attachments, m.Attachments)
isAllowed := utils.AllowedEventKindsMap[utils.EventKind{Resource: test.Kind, Namespace: "all", EventType: config.CreateEvent}] ||
utils.AllowedEventKindsMap[utils.EventKind{Resource: test.Kind, Namespace: test.Namespace, EventType: config.CreateEvent}]
assert.Equal(t, isAllowed, true)
})
}
}
// Run tests
func (c *context) Run(t *testing.T) {
t.Run("create resource", c.testCreateResource)
}
// E2ETests runs create notification tests
func E2ETests(testEnv *env.TestEnv) env.E2ETest {
return &context{
testEnv,
}
} | test/e2e/notifier/create/create.go | 0.646349 | 0.666638 | create.go | starcoder |
package geos
/*
#include "geos.h"
*/
import "C"
import (
"errors"
"runtime"
)
// PGeometry represents a "prepared geometry", a type of geometry object that is
// optimized for a limited set of operations.
type PGeometry struct {
p *C.GEOSPreparedGeometry
}
// PrepareGeometry constructs a prepared geometry from a normal geometry object.
func PrepareGeometry(g *Geometry) *PGeometry {
ptr := cGEOSPrepare(g.g)
p := &PGeometry{ptr}
runtime.SetFinalizer(p, (*PGeometry).destroy)
return p
}
func (p *PGeometry) destroy() {
cGEOSPreparedGeom_destroy(p.p)
p.p = nil
}
// Prepared geometry binary predicates
// Contains computes whether the prepared geometry contains the other prepared
// geometry.
func (p *PGeometry) Contains(other *Geometry) (bool, error) {
return p.predicate("contains", cGEOSPreparedContains, other)
}
// ContainsP computes whether the prepared geometry properly contains the other
// prepared geometry.
func (p *PGeometry) ContainsP(other *Geometry) (bool, error) {
return p.predicate("contains", cGEOSPreparedContainsProperly, other)
}
// CoveredBy computes whether the prepared geometry is covered by the other
// prepared geometry.
func (p *PGeometry) CoveredBy(other *Geometry) (bool, error) {
return p.predicate("covered by", cGEOSPreparedCoveredBy, other)
}
// Covers computes whether the prepared geometry covers the other prepared
// geometry.
func (p *PGeometry) Covers(other *Geometry) (bool, error) {
return p.predicate("covers", cGEOSPreparedCovers, other)
}
// Crosses computes whether the prepared geometry crosses the other prepared
// geometry.
func (p *PGeometry) Crosses(other *Geometry) (bool, error) {
return p.predicate("crosses", cGEOSPreparedCrosses, other)
}
// Disjoint computes whether the prepared geometry is disjoint from the other
// prepared geometry.
func (p *PGeometry) Disjoint(other *Geometry) (bool, error) {
return p.predicate("disjoint", cGEOSPreparedDisjoint, other)
}
// Intersects computes whether the prepared geometry intersects the other
// prepared geometry.
func (p *PGeometry) Intersects(other *Geometry) (bool, error) {
return p.predicate("intersects", cGEOSPreparedIntersects, other)
}
// Overlaps computes whether the prepared geometry overlaps the other
// prepared geometry.
func (p *PGeometry) Overlaps(other *Geometry) (bool, error) {
return p.predicate("overlaps", cGEOSPreparedOverlaps, other)
}
// Touches computes whether the prepared geometry touches the other
// prepared geometry.
func (p *PGeometry) Touches(other *Geometry) (bool, error) {
return p.predicate("touches", cGEOSPreparedTouches, other)
}
// Within computes whether the prepared geometry is within the other
// prepared geometry.
func (p *PGeometry) Within(other *Geometry) (bool, error) {
return p.predicate("within", cGEOSPreparedWithin, other)
}
func (p *PGeometry) predicate(name string, fn func(*C.GEOSPreparedGeometry, *C.GEOSGeometry) C.char, other *Geometry) (bool, error) {
i := fn(p.p, other.g)
if i == 2 {
return false, errors.New("geos: prepared " + name)
}
return i == 1, nil
} | vendor/github.com/paulsmith/gogeos/geos/prepared.go | 0.823364 | 0.425009 | prepared.go | starcoder |
package parser
import (
"io"
"github.com/zoncoen/scenarigo/template/ast"
"github.com/zoncoen/scenarigo/template/token"
)
// Parser represents a parser.
type Parser struct {
s *scanner
cal *posCalculator
pos int
tok token.Token
lit string
errors Errors
}
// NewParser returns a new parser.
func NewParser(r io.Reader) *Parser {
cal := &posCalculator{}
return &Parser{
s: newScanner(io.TeeReader(r, cal)),
cal: cal,
}
}
// Parse parses the template string and returns the corresponding ast.Node.
func (p *Parser) Parse() (ast.Node, error) {
p.next()
if p.tok == token.EOF {
// empty string
return &ast.BasicLit{
ValuePos: 0,
Kind: token.STRING,
Value: "",
}, nil
}
return p.parseExpr(), p.errors.Err()
}
func (p *Parser) next() {
p.pos, p.tok, p.lit = p.s.scan()
}
func (p *Parser) parseExpr() ast.Expr {
return p.parseBinaryExpr(token.LowestPrec + 1)
}
func (p *Parser) parseBinaryExpr(prec int) ast.Expr {
x := p.parseOperand()
L:
for {
if p.tok == token.LINEBREAK {
return x
}
oprec := p.tok.Precedence()
if oprec < prec {
return x
}
switch p.tok {
case token.ADD:
pos := p.pos
p.next()
y := p.parseBinaryExpr(oprec + 1)
x = &ast.BinaryExpr{
X: x,
OpPos: pos,
Op: token.ADD,
Y: y,
}
case token.CALL:
pos := p.pos
p.next()
args := make([]ast.Expr, 0, 1)
if y := p.parseExpr(); y != nil {
args = append(args, y)
}
x = &ast.CallExpr{
Fun: x,
Lparen: pos,
Args: args,
Rparen: pos,
}
case token.LARROW:
pos := p.pos
p.next()
x = &ast.LeftArrowExpr{
Fun: x,
Larrow: pos,
Rdbrace: p.expect(token.RDBRACE),
Arg: p.parseExpr(),
}
if p.tok == token.LINEBREAK {
if p.lit != "" {
p.tok = token.STRING
return x
}
p.next()
return x
}
case token.LDBRACE, token.STRING:
pos := p.pos
y := p.parseBinaryExpr(oprec + 1)
x = &ast.BinaryExpr{
X: x,
OpPos: pos,
Op: token.ADD,
Y: y,
}
default:
break L
}
}
return x
}
func (p *Parser) parseIdent() *ast.Ident {
pos := p.pos
name := "_"
if p.tok == token.IDENT {
name = p.lit
p.next()
} else {
p.expect(token.IDENT)
}
return &ast.Ident{NamePos: pos, Name: name}
}
func (p *Parser) parseOperand() ast.Expr {
var e ast.Expr
switch p.tok {
case token.STRING, token.INT:
e = &ast.BasicLit{
ValuePos: p.pos,
Kind: p.tok,
Value: p.lit,
}
p.next()
case token.IDENT:
e = p.parseIdent()
L:
for {
switch p.tok {
case token.PERIOD:
p.next()
e = &ast.SelectorExpr{
X: e,
Sel: p.parseIdent(),
}
case token.LBRACK:
lbrack := p.pos
p.next()
index := p.parseExpr()
e = &ast.IndexExpr{
X: e,
Lbrack: lbrack,
Index: index,
Rbrack: p.expect(token.RBRACK),
}
case token.LPAREN:
lparen := p.pos
p.next()
e = &ast.CallExpr{
Fun: e,
Lparen: lparen,
Args: p.parseArgs(),
Rparen: p.expect(token.RPAREN),
}
default:
break L
}
}
case token.LDBRACE:
e = p.parseParameter()
default:
return nil
}
return e
}
func (p *Parser) parseParameter() ast.Expr {
param := &ast.ParameterExpr{
Ldbrace: p.pos,
Quoted: p.s.quoted(),
}
p.next()
param.X = p.parseExpr()
if lae, ok := param.X.(*ast.LeftArrowExpr); ok {
param.Rdbrace = lae.Rdbrace
return param
}
param.Rdbrace = p.expect(token.RDBRACE)
return param
}
func (p *Parser) parseArgs() []ast.Expr {
args := []ast.Expr{}
if p.tok == token.RPAREN {
return args
}
args = append(args, p.parseExpr())
for p.tok == token.COMMA {
p.next()
args = append(args, p.parseExpr())
}
return args
}
func (p *Parser) error(pos int, msg string) {
p.errors.Append(pos, msg)
}
func (p *Parser) errorExpected(pos int, msg string) {
msg = "expected " + msg
if pos == p.pos {
msg += ", found '" + p.tok.String() + "'"
}
p.error(pos, msg)
}
func (p *Parser) expect(tok token.Token) int {
pos := p.pos
if p.tok != tok {
p.errorExpected(pos, "'"+tok.String()+"'")
}
p.next() // make progress
return pos
}
// Pos returns the Position value for the given offset.
func (p *Parser) Pos(pos int) *Position {
return p.cal.Pos(pos)
} | template/parser/parser.go | 0.617859 | 0.435121 | parser.go | starcoder |
package bfv
import (
"github.com/ldsec/lattigo/ring"
)
// GaloisGen is an integer of order N/2 modulo M and that spans Z_M with the integer -1. The j-th ring automorphism takes the root zeta to zeta^(5j).
// Any other integer or order N/2 modulo M and congruent with 1 modulo 4 could be used instead.
const GaloisGen uint64 = 5
// bfvContext is a struct which contains all the elements required to instantiate the BFV Scheme. This includes the parameters (polynomial degree, plaintext modulus, ciphertext modulus,
// Gaussian sampler, polynomial contexts and other parameters required for the homomorphic operations).
type bfvContext struct {
params *Parameters
// Polynomial degree
n uint64
gaussianSampler *ring.KYSampler
// Polynomial contexts
contextT *ring.Context
contextQ *ring.Context
contextQMul *ring.Context
contextP *ring.Context
contextQP *ring.Context
galElRotRow uint64
galElRotColLeft []uint64
galElRotColRight []uint64
}
func newBFVContext(params *Parameters) (context *bfvContext) {
if !params.isValid {
panic("cannot newBFVContext: params not valid (check if they were generated properly)")
}
context = new(bfvContext)
var err error
LogN := params.LogN
N := uint64(1 << LogN)
context.n = N
if context.contextT, err = ring.NewContextWithParams(N, []uint64{params.T}); err != nil {
panic(err)
}
if context.contextQ, err = ring.NewContextWithParams(N, params.Qi); err != nil {
panic(err)
}
if context.contextQMul, err = ring.NewContextWithParams(N, params.QiMul); err != nil {
panic(err)
}
if len(params.Pi) != 0 {
if context.contextP, err = ring.NewContextWithParams(N, params.Pi); err != nil {
panic(err)
}
}
if context.contextQP, err = ring.NewContextWithParams(N, append(params.Qi, params.Pi...)); err != nil {
panic(err)
}
context.gaussianSampler = context.contextQP.NewKYSampler(params.Sigma, int(6*params.Sigma))
context.galElRotColLeft = ring.GenGaloisParams(context.n, GaloisGen)
context.galElRotColRight = ring.GenGaloisParams(context.n, ring.ModExp(GaloisGen, 2*context.n-1, 2*context.n))
context.galElRotRow = 2*context.n - 1
return
} | bfv/bfv.go | 0.687735 | 0.42471 | bfv.go | starcoder |
package ACO
import (
"fmt"
"math"
"math/rand"
)
// Checks if the output is correct.
func isCorrect(output float64, expectedOutput float64, functionCall string) {
if output != expectedOutput {
fmt.Printf("%v : %v, Expected: %v\n", functionCall, output, expectedOutput)
}
}
// Generates a graph with random weights sampled from U(0,1).
func generateGraph(n int) [][]float64 {
graph := make([][]float64, n)
for i := 0; i < n; i++ {
graph[i] = make([]float64, n)
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
graph[i][j] = rand.Float64()
}
}
return graph
}
// Prints elements in matrix.
func printMatrix(matrix [][]float64) {
for _, row := range matrix {
for _, element := range row {
fmt.Print(math.Round(element*1000)/1000, "\t")
}
fmt.Println()
}
}
// Example usage and testing.
func main() {
graph, optimalCost := cities26()
cost, _ := SolveAS(graph, 1, 10, 0.5, 1000, 50, 1)
isCorrect(cost, optimalCost, "SolveATSP")
graph = ReadATSP("ATSP/ftv38.atsp")
cost, solution := SolveAS(graph, 1, 10, 0.5, 1000, 500, 100)
fmt.Println("Cost:", cost)
fmt.Print("Solution: ")
fmt.Println(solution)
cost, solution = SolveMMAS(graph, 1, 10, 0.5, 1000, 500, 10, 1, 100)
fmt.Println("Cost:", cost)
fmt.Print("Solution: ")
fmt.Println(solution)
cost, solution = SolveACS(graph, 1, 10, 0.1, 10, 10, 1000, 0.1, 0.1, 100)
fmt.Println("Cost:", cost)
fmt.Print("Solution: ")
fmt.Println(solution)
}
// A known instance of TSP with 26 nodes and least known solution 937.
func cities26() ([][]float64, float64) {
graph := [][]float64{
{0, 83, 93, 129, 133, 139, 151, 169, 135, 114, 110, 98, 99, 95, 81, 152, 159, 181, 172, 185, 147, 157, 185, 220, 127, 181},
{83, 0, 40, 53, 62, 64, 91, 116, 93, 84, 95, 98, 89, 68, 67, 127, 156, 175, 152, 165, 160, 180, 223, 268, 179, 197},
{93, 40, 0, 42, 42, 49, 59, 81, 54, 44, 58, 64, 54, 31, 36, 86, 117, 135, 112, 125, 124, 147, 193, 241, 157, 161},
{129, 53, 42, 0, 11, 11, 46, 72, 65, 70, 88, 100, 89, 66, 76, 102, 142, 156, 127, 139, 155, 180, 228, 278, 197, 190},
{133, 62, 42, 11, 0, 9, 35, 61, 55, 62, 82, 95, 84, 62, 74, 93, 133, 146, 117, 128, 148, 173, 222, 272, 194, 182},
{139, 64, 49, 11, 9, 0, 39, 65, 63, 71, 90, 103, 92, 71, 82, 100, 141, 153, 124, 135, 156, 181, 230, 280, 202, 190},
{151, 91, 59, 46, 35, 39, 0, 26, 34, 52, 71, 88, 77, 63, 78, 66, 110, 119, 88, 98, 130, 156, 206, 257, 188, 160},
{169, 116, 81, 72, 61, 65, 26, 0, 37, 59, 75, 92, 83, 76, 91, 54, 98, 103, 70, 78, 122, 148, 198, 250, 188, 148},
{135, 93, 54, 65, 55, 63, 34, 37, 0, 22, 39, 56, 47, 40, 55, 37, 78, 91, 62, 74, 96, 122, 172, 223, 155, 128},
{114, 84, 44, 70, 62, 71, 52, 59, 22, 0, 20, 36, 26, 20, 34, 43, 74, 91, 68, 82, 86, 111, 160, 210, 136, 121},
{110, 95, 58, 88, 82, 90, 71, 75, 39, 20, 0, 18, 11, 27, 32, 42, 61, 80, 64, 77, 68, 92, 140, 190, 116, 103},
{98, 98, 64, 100, 95, 103, 88, 92, 56, 36, 18, 0, 11, 34, 31, 56, 63, 85, 75, 87, 62, 83, 129, 178, 100, 99},
{99, 89, 54, 89, 84, 92, 77, 83, 47, 26, 11, 11, 0, 23, 24, 53, 68, 89, 74, 87, 71, 93, 140, 189, 111, 107},
{95, 68, 31, 66, 62, 71, 63, 76, 40, 20, 27, 34, 23, 0, 15, 62, 87, 106, 87, 100, 93, 116, 163, 212, 132, 130},
{81, 67, 36, 76, 74, 82, 78, 91, 55, 34, 32, 31, 24, 15, 0, 73, 92, 112, 96, 109, 93, 113, 158, 205, 122, 130},
{152, 127, 86, 102, 93, 100, 66, 54, 37, 43, 42, 56, 53, 62, 73, 0, 44, 54, 26, 39, 68, 94, 144, 196, 139, 95},
{159, 156, 117, 142, 133, 141, 110, 98, 78, 74, 61, 63, 68, 87, 92, 44, 0, 22, 34, 38, 30, 53, 102, 154, 109, 51},
{181, 175, 135, 156, 146, 153, 119, 103, 91, 91, 80, 85, 89, 106, 112, 54, 22, 0, 33, 29, 46, 64, 107, 157, 125, 51},
{172, 152, 112, 127, 117, 124, 88, 70, 62, 68, 64, 75, 74, 87, 96, 26, 34, 33, 0, 13, 63, 87, 135, 186, 141, 81},
{185, 165, 125, 139, 128, 135, 98, 78, 74, 82, 77, 87, 87, 100, 109, 39, 38, 29, 13, 0, 68, 90, 136, 186, 148, 79},
{147, 160, 124, 155, 148, 156, 130, 122, 96, 86, 68, 62, 71, 93, 93, 68, 30, 46, 63, 68, 0, 26, 77, 128, 80, 37},
{157, 180, 147, 180, 173, 181, 156, 148, 122, 111, 92, 83, 93, 116, 113, 94, 53, 64, 87, 90, 26, 0, 50, 102, 65, 27},
{185, 223, 193, 228, 222, 230, 206, 198, 172, 160, 140, 129, 140, 163, 158, 144, 102, 107, 135, 136, 77, 50, 0, 51, 64, 58},
{220, 268, 241, 278, 272, 280, 257, 250, 223, 210, 190, 178, 189, 212, 205, 196, 154, 157, 186, 186, 128, 102, 51, 0, 93, 107},
{127, 179, 157, 197, 194, 202, 188, 188, 155, 136, 116, 100, 111, 132, 122, 139, 109, 125, 141, 148, 80, 65, 64, 93, 0, 90},
{181, 197, 161, 190, 182, 190, 160, 148, 128, 121, 103, 99, 107, 130, 130, 95, 51, 51, 81, 79, 37, 27, 58, 107, 90, 0}}
var cost float64 = 937
return graph, cost
} | main.go | 0.720172 | 0.454593 | main.go | starcoder |
package sign
import (
"errors"
"fmt"
"github.com/drand/kyber"
"github.com/drand/kyber/pairing"
)
// Mask is a bitmask of the participation to a collective signature.
type Mask struct {
mask []byte
publics []kyber.Point
}
// NewMask creates a new mask from a list of public keys. If a key is provided, it
// will set the bit of the key to 1 or return an error if it is not found.
func NewMask(suite pairing.Suite, publics []kyber.Point, myKey kyber.Point) (*Mask, error) {
m := &Mask{
publics: publics,
}
m.mask = make([]byte, m.Len())
if myKey != nil {
for i, key := range publics {
if key.Equal(myKey) {
m.SetBit(i, true)
return m, nil
}
}
return nil, errors.New("key not found")
}
return m, nil
}
// Mask returns the bitmask as a byte array.
func (m *Mask) Mask() []byte {
clone := make([]byte, len(m.mask))
copy(clone[:], m.mask)
return clone
}
// Len returns the length of the byte array necessary to store the bitmask.
func (m *Mask) Len() int {
return (len(m.publics) + 7) / 8
}
// SetMask replaces the current mask by the new one if the length matches.
func (m *Mask) SetMask(mask []byte) error {
if m.Len() != len(mask) {
return fmt.Errorf("mismatching mask lengths")
}
m.mask = mask
return nil
}
// SetBit turns on or off the bit at the given index.
func (m *Mask) SetBit(i int, enable bool) error {
if i >= len(m.publics) || i < 0 {
return errors.New("index out of range")
}
byteIndex := i / 8
mask := byte(1) << uint(i&7)
if enable {
m.mask[byteIndex] ^= mask
} else {
m.mask[byteIndex] ^= mask
}
return nil
}
// forEachBitEnabled is a helper to iterate over the bits set to 1 in the mask
// and to return the result of the callback only if it is positive.
func (m *Mask) forEachBitEnabled(f func(i, j, n int) int) int {
n := 0
for i, b := range m.mask {
for j := uint(0); j < 8; j++ {
mm := byte(1) << (j & 7)
if b&mm != 0 {
if res := f(i, int(j), n); res >= 0 {
return res
}
n++
}
}
}
return -1
}
// IndexOfNthEnabled returns the index of the nth enabled bit or -1 if out of bounds.
func (m *Mask) IndexOfNthEnabled(nth int) int {
return m.forEachBitEnabled(func(i, j, n int) int {
if n == nth {
return i*8 + int(j)
}
return -1
})
}
// NthEnabledAtIndex returns the sum of bits set to 1 until the given index. In other
// words, it returns how many bits are enabled before the given index.
func (m *Mask) NthEnabledAtIndex(idx int) int {
return m.forEachBitEnabled(func(i, j, n int) int {
if i*8+int(j) == idx {
return n
}
return -1
})
}
// Publics returns a copy of the list of public keys.
func (m *Mask) Publics() []kyber.Point {
pubs := make([]kyber.Point, len(m.publics))
copy(pubs, m.publics)
return pubs
}
// Participants returns the list of public keys participating.
func (m *Mask) Participants() []kyber.Point {
pp := []kyber.Point{}
for i, p := range m.publics {
byteIndex := i / 8
mask := byte(1) << uint(i&7)
if (m.mask[byteIndex] & mask) != 0 {
pp = append(pp, p)
}
}
return pp
}
// CountEnabled returns the number of bit set to 1
func (m *Mask) CountEnabled() int {
count := 0
for i := range m.publics {
byteIndex := i / 8
mask := byte(1) << uint(i&7)
if (m.mask[byteIndex] & mask) != 0 {
count++
}
}
return count
}
// CountTotal returns the number of potential participants
func (m *Mask) CountTotal() int {
return len(m.publics)
}
// Merge merges the given mask to the current one only if
// the length matches
func (m *Mask) Merge(mask []byte) error {
if len(m.mask) != len(mask) {
return errors.New("mismatching mask length")
}
for i := range m.mask {
m.mask[i] |= mask[i]
}
return nil
} | vendor/github.com/drand/kyber/sign/mask.go | 0.752922 | 0.44348 | mask.go | starcoder |
package goluhn
/* Package goluhn provides own implementation of Luhn algo checksum checking for
given number and some related functions. These functions are:
// LuhnInRange returns a slice of integers with correct Lun checksum in given range
func LuhnInRange(start, end int) []int {}
// LuhnByLen returns random int with correct Lun checksum and given length
func LuhnByLen(len int) int {}
*/
import (
"log"
"math"
"math/rand"
"strconv"
"time"
)
// ErrFatal is a basic error handler
func errFatal(err error) {
if err != nil {
log.Fatal(err)
}
}
// Chod simply checks if number is even or odd. It returns true if even
func chod(num int) bool {
// odd
check := false
if num%2 == 0 {
// even
check = true
}
return check
}
// Powt returns int converted 10**p
func powt(p int) int {
return int(math.Pow10(p))
}
func randt(num int) int {
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
random := r.Intn(num)
return random
}
// AToi converts string to int
func aToi(str string) int {
atoi, err := strconv.Atoi(str)
errFatal(err)
return atoi
}
// Base10 simply checks if given num is divisible by 10
func base10(num int) bool {
var check bool
if num%10 == 0 {
check = true
} else {
check = false
}
return check
}
// Base9 makes Lun check's performans with given int
func base9(num int) int {
var check int
if 2*num > 9 {
check = (2 * num) - 9
} else {
check = 2 * num
}
return check
}
// CheckLuhn returns true if Lun checksum of given value is correct
func CheckLuhn(num int) bool {
var check int
numstring := strconv.Itoa(num)
switch {
case chod(len(numstring)) == true:
for i, n := range numstring {
if chod(i+1) == false {
check += base9(aToi(string(n)))
} else {
check += aToi(string(n))
}
}
case chod(len(numstring)) != true:
for i, n := range numstring {
if chod(i+1) == true {
check += base9(aToi(string(n)))
} else {
check += aToi(string(n))
}
}
}
return base10(check)
}
// LuhnInRange returns a slice of integers with correct Lun checksum in given range
func LuhnInRange(start, end int) []int {
var nums []int
for i := start; i <= end; i++ {
if CheckLuhn(i) == true {
nums = append(nums, i)
}
}
return nums
}
// LuhnByLen returns random int with correct Lun checksum and given length
func LuhnByLen(len int) int {
var luhn int
base := powt(len - 1)
rangenums := (powt(len) - 1) - powt(len-1)
preluhn := base + randt(rangenums)
switch {
case CheckLuhn(preluhn):
luhn = preluhn
default:
luhn = LuhnByLen(len)
}
return luhn
} | goluhn.go | 0.710729 | 0.41401 | goluhn.go | starcoder |
package neko
import (
lexer "github.com/hedarikun/neko/lexer"
)
type Node interface {
TokenLiteral() string
}
type Statement interface {
Node
statementNode()
}
type Expression interface {
Node
expressionNode()
}
type Program struct {
Statements []Statement
}
type LetStatement struct {
Token lexer.Token
Mut bool
Name Identifier
Value Expression
}
func (ls LetStatement) TokenLiteral() string {
return ls.Token.Type
}
func (ls LetStatement) statementNode() {}
type StructStatement struct {
Token lexer.Token
Name Identifier
Props []Identifier
}
func (ss StructStatement) TokenLiteral() string {
return ss.Token.Type
}
func (ss StructStatement) statementNode() {}
type ImplStatement struct {
Token lexer.Token
Struct Identifier
Funs []Expression
}
func (is ImplStatement) TokenLiteral() string {
return is.Token.Type
}
func (is ImplStatement) statementNode() {}
type AssignmentExpression struct {
Token lexer.Token
Ident Identifier
Value Expression
}
func (ae AssignmentExpression) TokenLiteral() string {
return ae.Token.Value
}
func (ae AssignmentExpression) expressionNode() {}
type BlockExpression struct {
Statements []Statement
}
func (bs BlockExpression) TokenLiteral() string {
if len(bs.Statements) > 0 {
return bs.Statements[0].TokenLiteral()
}
return ""
}
func (bs BlockExpression) expressionNode() {}
type ExpressionStatment struct {
Value Expression
}
func (es ExpressionStatment) TokenLiteral() string {
return es.Value.TokenLiteral()
}
func (es ExpressionStatment) statementNode() {}
type PrefixExpression struct {
Prefix lexer.Token
Value Expression
}
func (pe PrefixExpression) TokenLiteral() string {
return pe.Prefix.Type
}
func (pe PrefixExpression) expressionNode() {}
type NumberExpression struct {
Token lexer.Token
Value float64
}
func (ne NumberExpression) TokenLiteral() string {
return ne.Token.Type
}
func (ne NumberExpression) expressionNode() {}
type StringExpression struct {
Token lexer.Token
Value string
}
func (se StringExpression) TokenLiteral() string {
return se.Token.Type
}
func (se StringExpression) expressionNode() {}
type BoolExpression struct {
Token lexer.Token
Value bool
}
func (be BoolExpression) TokenLiteral() string {
return be.Token.Type
}
func (be BoolExpression) expressionNode() {}
type ArrayExpression struct {
Token lexer.Token
Values []Expression
}
func (ae ArrayExpression) TokenLiteral() string {
return ae.Token.Value
}
func (ae ArrayExpression) expressionNode() {}
type OperationExpression struct {
Operator lexer.Token
Left Expression
Right Expression
}
func (oe OperationExpression) TokenLiteral() string {
return oe.Operator.Type
}
func (oe OperationExpression) expressionNode() {}
type IfExpression struct {
Condition Expression
IfBlock Expression
ElseBlock Expression
}
func (ie IfExpression) TokenLiteral() string {
return ie.Condition.TokenLiteral()
}
func (ie IfExpression) expressionNode() {}
type Identifier struct {
Token lexer.Token
Value string
}
func (ie Identifier) TokenLiteral() string {
return ie.Token.Type
}
func (ie Identifier) expressionNode() {}
type FunExpression struct {
Token lexer.Token
Name Identifier
Parameters []Identifier
Body Expression
}
func (fe FunExpression) TokenLiteral() string {
return fe.Token.Type
}
func (fe FunExpression) expressionNode() {}
type CallExpression struct {
Token lexer.Token
Object Expression
Args []Expression
}
func (ce CallExpression) TokenLiteral() string {
return ce.Token.Value
}
func (ce CallExpression) expressionNode() {}
type ArrayCallExpression struct {
Token lexer.Token
Object Expression
Index Expression
}
func (ae ArrayCallExpression) TokenLiteral() string {
return ae.Token.Value
}
func (ae ArrayCallExpression) expressionNode() {}
type FieldCallExpression struct {
Token lexer.Token
Object Expression
Child Identifier
}
func (fe FieldCallExpression) TokenLiteral() string {
return fe.Token.Value
}
func (fe FieldCallExpression) expressionNode() {} | ast/ast.go | 0.667798 | 0.426799 | ast.go | starcoder |
package commitment
import (
"encoding/binary"
"math/big"
"../group"
)
//NewElGamalFactory creates a new ElGamal-type Commitments factory
func NewElGamalFactory(h group.Elem) *ElGamalFactory {
egf := &ElGamalFactory{h: h}
egf.neutral = egf.Create(big.NewInt(0), big.NewInt(0))
return egf
}
//ElGamalFactory is a factory for ElGamal-type Commitment
type ElGamalFactory struct {
h group.Elem
neutral *ElGamal
}
//NewElGamal creates a new ElGamal-type Commitment
func NewElGamal(a, b *big.Int) *ElGamal {
return &ElGamal{group.NewElem(a), group.NewElem(b)}
}
//ElGamal is an implementation of ElGamal-type Commitments
type ElGamal struct {
first, second group.Elem
}
//Create creates new ElGamal Commitment
func (e *ElGamalFactory) Create(value, r *big.Int) *ElGamal {
return &ElGamal{
first: group.NewElem(big.NewInt(0)).Mult(group.Gen, r),
second: group.NewElem(big.NewInt(0)).Add(group.NewElem(big.NewInt(0)).Mult(e.h, r), group.NewElem(big.NewInt(0)).Mult(group.Gen, value)),
}
}
//Neutral creates neutral element for compose operation of ElGamal Commitments
func (e *ElGamalFactory) Neutral() *ElGamal {
return e.Create(big.NewInt(0), big.NewInt(0))
}
//IsNeutral Chackes if element is equal to neutral one
func (e *ElGamalFactory) IsNeutral(a *ElGamal) bool {
return a.Cmp(e.neutral, a)
}
//Compose composes two ElGamal Commitments
func (c *ElGamal) Compose(a, b *ElGamal) *ElGamal {
c.first.Add(a.first, b.first)
c.second.Add(a.second, b.second)
return c
}
//Exp performs exp operation on ElGamal Commitments
func (c *ElGamal) Exp(x *ElGamal, n *big.Int) *ElGamal {
c.first.Mult(x.first, n)
c.second.Mult(x.second, n)
return c
}
//Inverse returns inversed element for given ElGamal Commitment
func (c *ElGamal) Inverse(a *ElGamal) *ElGamal {
c.first.Inverse(a.first)
c.second.Inverse(a.second)
return c
}
//Cmp compares to ElGamal ElGamals (maybe should be called equal)
func (*ElGamal) Cmp(a, b *ElGamal) bool {
return (a.first).Cmp(a.first, b.first) && (a.second).Cmp(a.second, b.second)
}
//Marshal marshals ElGamal Commitment
func (c *ElGamal) Marshal() []byte {
firstBytes := c.first.Marshal()
secondBytes := c.second.Marshal()
result := make([]byte, 4, 4+len(firstBytes)+len(secondBytes))
binary.LittleEndian.PutUint32(result, uint32(len(firstBytes)))
result = append(result, firstBytes...)
result = append(result, secondBytes...)
return result
}
//Unmarshal unmarshals ElGamal Commitment
func (c *ElGamal) Unmarshal(b []byte) *ElGamal {
firstLen := binary.LittleEndian.Uint32(b[0:4])
c.first.Unmarshal(b[4 : 4+firstLen])
c.second.Unmarshal(b[4+firstLen:])
return c
} | poc/tecdsa/pkg/crypto/commitment/commitment.go | 0.694199 | 0.432902 | commitment.go | starcoder |
package ansigo
import (
"fmt"
"strings"
)
// capabilityCheck builds an object testing out every ANSI capability that
// gotui knows about.
func capabilityCheck() check {
test := map[string][]string{
"8 Color": make([]string, 8),
"8 Color - Bright": make([]string, 8),
"256 Color": make([]string, 256),
"24-bit Color": make([]string, 1),
}
for name, num := range Colors8 {
c, _ := Colors8.Find(name)
if num < 60 {
test["8 Color"][num] = fmt.Sprintf("%-30s\t%-30s", c.FG(name), c.BG(name))
} else {
test["8 Color - Bright"][num-60] = fmt.Sprintf("%-30s\t%-30s", c.FG(name), c.BG(name))
}
}
for i, c := range Colors256 {
test["256 Color"][i] = fmt.Sprintf("%-30s\t%-30s", c.FG(c.Name), c.BG(c.Name))
}
test["Attribute"] = []string{
Bold.Apply("Bold"),
Faint.Apply("Faint"),
Italic.Apply("Italic"),
Underline.Apply("Underline"),
Blink.Apply("Blink"),
Flash.Apply("Flash"),
Reverse.Apply("Reverse"),
Conceal.Apply("Conceal"),
CrossedOut.Apply("CrossedOut"),
AltFont1.Apply("AltFont1"),
AltFont2.Apply("AltFont2"),
AltFont3.Apply("AltFont3"),
AltFont4.Apply("AltFont4"),
AltFont5.Apply("AltFont5"),
AltFont6.Apply("AltFont6"),
AltFont7.Apply("AltFont7"),
AltFont8.Apply("AltFont8"),
AltFont9.Apply("AltFont9"),
Fraktur.Apply("Fraktur"),
DoubleUnderline.Apply("DoubleUnderline"),
Framed.Apply("Framed"),
Encircled.Apply("Encircled"),
Overlined.Apply("Overlined"),
IdeogramUnderline.Apply("IdeogramUnderline"),
IdeogramDoubleUnderline.Apply("IdeogramDoubleUnderline"),
IdeogramOverline.Apply("IdeogramOverline"),
IdeogramDoubleOverline.Apply("IdeogramDoubleOverline"),
IdeogramStressMarking.Apply("IdeogramStressMarking"),
}
hex, _ := Colors24bit.Find("#422670")
hsl, _ := Colors24bit.Find("hsl(166, 47%, 75%)")
rgb, _ := Colors24bit.Find("rgb(69, 35, 116)")
test["24-bit Color"][0] = fmt.Sprintf("%s%s", hex.BG(hsl.FG("This BG is two ")), rgb.BG(hsl.FG(" different colors")))
return test
}
type check map[string][]string
func (c check) String() string {
var result strings.Builder
fmt.Fprintln(&result, "8 Color")
fmt.Fprintln(&result, "=======")
fmt.Fprint(&result, "\n")
for _, col := range c["8 Color"] {
fmt.Fprintln(&result, col)
}
fmt.Fprint(&result, "\n\n")
fmt.Fprintln(&result, "8 Color - Bright")
fmt.Fprintln(&result, "================")
fmt.Fprint(&result, "\n")
for _, col := range c["8 Color - Bright"] {
fmt.Fprintln(&result, col)
}
fmt.Fprint(&result, "\n\n")
fmt.Fprintln(&result, "256 Color")
fmt.Fprintln(&result, "=========")
fmt.Fprint(&result, "\n")
for _, col := range c["256 Color"] {
fmt.Fprintln(&result, col)
}
fmt.Fprint(&result, "\n\n")
fmt.Fprintln(&result, "Attribute")
fmt.Fprintln(&result, "=========")
fmt.Fprint(&result, "\n")
for _, col := range c["Attribute"] {
fmt.Fprintln(&result, col)
}
fmt.Fprint(&result, "\n\n")
fmt.Fprintln(&result, "24-bit Color")
fmt.Fprintln(&result, "============")
fmt.Fprint(&result, "\n")
fmt.Fprintln(&result, c["24-bit Color"][0])
return result.String()
}
// CapabilityCheck is a map of all ANSI codes that gotui knows about. It is
// intended to be used as a reference to see what capabilities one's terminal
// supports.
var CapabilityCheck = capabilityCheck() | capability_check.go | 0.571408 | 0.404566 | capability_check.go | starcoder |
package main
// @docs.go contains the how to use this worker service. which is accessible from the root web interface.
const version = " <jobs-worker-service> β’ version 1.1 By <NAME>"
const webv1docs = `
$$\ $$\
$$ | $$ |
$$\ $$$$$$\ $$$$$$$\ $$$$$$$\ $$\ $$\ $$\ $$$$$$\ $$$$$$\ $$ | $$\ $$$$$$\ $$$$$$\
\__|$$ __$$\ $$ __$$\ $$ _____| $$ | $$ | $$ |$$ __$$\ $$ __$$\ $$ | $$ |$$ __$$\ $$ __$$\
$$\ $$ / $$ |$$ | $$ |\$$$$$$\ $$ | $$ | $$ |$$ / $$ |$$ | \__|$$$$$$ / $$$$$$$$ |$$ | \__|
$$ |$$ | $$ |$$ | $$ | \____$$\ $$ | $$ | $$ |$$ | $$ |$$ | $$ _$$< $$ ____|$$ |
$$ |\$$$$$$ |$$$$$$$ |$$$$$$$ | \$$$$$\$$$$ |\$$$$$$ |$$ | $$ | \$$\ \$$$$$$$\ $$ |
$$ | \______/ \_______/ \_______/ \_____\____/ \______/ \__| \__| \__| \_______|\__|
$$\ $$ |
\$$$$$$ |
\______/
----------------------------------------------------------------------------------------------
[current version 1.1 By <NAME> - <EMAIL>]
----------------------------------------------------------------------------------------------
[00] Find below command line options dedicated to the worker service :
[+] On Windows Operating System.
worker.exe [ start | stop | restart | status | help | version]
[+] On Linux Operating System.
./worker [ start | stop | restart | status | help | version]
----------
[01] Execute a quick remote command (optionally with timeout in secs) and get the realtime output:
https://<server-ip-address>:<port>/worker/web/v1/cmd/execute?cmd=<command+argument>
[+] On Windows Operating System.
example: https://127.0.0.1:8080/worker/web/v1/cmd/execute?cmd=systeminfo
example: https://127.0.0.1:8080/worker/web/v1/cmd/execute?cmd=ipconfig+/all
example: https://127.0.0.1:8080/worker/web/v1/cmd/execute?cmd=netstat+-an+|+findstr+ESTAB&timeout=45
[+] On Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/cmd/execute?cmd=ls+-la
example: https://127.0.0.1:8080/worker/web/v1/cmd/execute?cmd=ip+a
example: https://127.0.0.1:8080/worker/web/v1/cmd/execute?cmd=ps
----------
[02] Execute a long running remote job (with timeout in mins and dumping to file) and stream its output:
https://<server-ip-address>:<port>/worker/web/v1/jobs/long/stream/schedule?cmd=<command+argument>&timeout=<value>&dump=<true|false>
[+] On Windows Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=ping+127.0.0.1+-t&dump=true
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=netstat+-an+|+findstr+ESTAB&timeout=60
[+] On Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=ping+127.0.0.1&dump=true
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=top&timeout=10&dump=true
----------
[03] Execute multiple long running remote jobs (with timeout in mins) and use their ids to stream their realtime outputs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/long/stream/schedule?cmd=<command+argument>&cmd=<command+argument>&timeout=<value>
[+] On Windows Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=ping+4.4.4.4+-t&cmd=ping+8.8.8.8+-t&timeout=30
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=netstat+-an+|+findstr+ESTAB&netstat+-an+|+findstr+ESTAB&timeout=15
[+] On Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=ping+4.4.4.4&cmd=ping+8.8.8.8&cmd=ping+1.1.1.1&timeout=30
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/stream/schedule?cmd=&cmd=tail+-f/var/log/syslog&cmd=tail+-f+/var/log/messages&timeout=30
----------
[04] To stream the output of a single long running job by its id:
https://<server-ip-address>:<port>/worker/web/v1/jobs/long/output/stream?id=<job-id>
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/long/output/stream?id=abe478954cef4125
----------
[05] Execute one or multiple short running jobs (optionally with timeout in seconds) and later use their ids to fetch their outputs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/short/schedule?cmd=<command+argument>&cmd=<command+argument>&timeout=<value>
[+] On Windows Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/short/schedule?cmd=systeminfo&cmd=ipconfig+/all&cmd=tasklist
example: https://127.0.0.1:8080/worker/web/v1/jobs/short/schedule?cmd=ipconfig+/all
[+] On Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/short/schedule?cmd=ls+-la&cmd=ip+a&cmd=ps
----------
[06] To fetch the output of a single short running job by its id:
https://<server-ip-address>:<port>/worker/web/v1/jobs/short/output/fetch?id=<job-id>
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/short/output/fetch?id=abe478954cef4125
----------
[07] To check the detailed status of one or multiple submitted jobs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/x/status/check?id=<job-1-id>&id=<job-2-id>
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/status/check?id=abe478954cef4125&id=cde478910cef4125
----------
[08] To check the status of all (short and long running) submitted jobs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/x/stop/all?order=[asc|desc]
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/status/check/all
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/status/check/all?order=asc
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/status/check/all?order=desc
----------
[09] To fetch the output of a single short running job by its id:
https://<server-ip-address>:<port>/worker/web/v1/jobs/short/output/fetch?id=<job-id>
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/short/output/fetch?id=abe478954cef4125
----------
[10] To stop one or multiple submitted and running jobs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/x/stop?id=<job-1-id>&id=<job-2-id>
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/stop?id=abe478954cef4125&id=cde478910cef4125
----------
[11] To stop of all (short and long) submitted running jobs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/x/stop/all
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/stop/all
----------
[12] To restart one or multiple submitted jobs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/x/restart?id=<job-1-id>&id=<job-2-id>
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/restart?id=abe478954cef4125&id=cde478910cef4125
----------
[13] To restart all (only short running) submitted jobs:
https://<server-ip-address>:<port>/worker/web/v1/jobs/x/restart/all
[+] On Windows or Linux Operating System.
example: https://127.0.0.1:8080/worker/web/v1/jobs/x/restart/all
----------
` | docs.go | 0.516108 | 0.566978 | docs.go | starcoder |
package main
import (
"fmt"
"strconv"
s "strings"
"github.com/theatlasroom/advent-of-code/go/utils"
)
/**
--- Day 2: Dive! ---
Now, you need to figure out how to pilot this thing.
It seems like the submarine can take a series of commands like forward 1, down 2, or up 3:
forward X increases the horizontal position by X units.
down X increases the depth by X units.
up X decreases the depth by X units.
Note that since you're on a submarine, down and up affect your depth, and so they have the opposite result of what you might expect.
The submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example:
forward 5
down 5
forward 8
up 3
down 8
forward 2
Your horizontal position and depth both start at 0. The steps above would then modify them as follows:
forward 5 adds 5 to your horizontal position, a total of 5.
down 5 adds 5 to your depth, resulting in a value of 5.
forward 8 adds 8 to your horizontal position, a total of 13.
up 3 decreases your depth by 3, resulting in a value of 2.
down 8 adds 8 to your depth, resulting in a value of 10.
forward 2 adds 2 to your horizontal position, a total of 15.
After following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces 150.)
Calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?
--- Part Two ---
Based on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated.
In addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought:
down X increases your aim by X units.
up X decreases your aim by X units.
forward X does two things:
It increases your horizontal position by X units.
It increases your depth by your aim multiplied by X.
Again note that since you're on a submarine, down and up do the opposite of what you might expect: "down" means aiming in the positive direction.
Now, the above example does something different:
forward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change.
down 5 adds 5 to your aim, resulting in a value of 5.
forward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40.
up 3 decreases your aim by 3, resulting in a value of 2.
down 8 adds 8 to your aim, resulting in a value of 10.
forward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60.
After following these new instructions, you would have a horizontal position of 15 and a depth of 60. (Multiplying these produces 900.)
Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?
*/
type vector struct {
XPos, ZPos int
}
type aimVector struct {
XPos, ZPos, Aim int
}
type moveable interface {
Forward(int)
Up(int)
Down(int)
}
type positionable interface {
Position() int
}
type positionableMoveable interface {
moveable
positionable
}
type direction int
const (
DIR_FORWARD direction = iota
DIR_UP
DIR_DOWN
)
type instruction struct {
Direction direction
Delta int
}
func (v *vector) Forward(delta int) {
v.XPos += delta
}
func (v *vector) Up(delta int) {
v.ZPos -= delta
}
func (v *vector) Down(delta int) {
v.ZPos += delta
}
func (v vector) Position() int {
return v.ZPos * v.XPos
}
func (v *aimVector) Forward(delta int) {
v.XPos += delta
v.ZPos += delta * v.Aim
}
func (v *aimVector) Up(delta int) {
v.Aim -= delta
}
func (v *aimVector) Down(delta int) {
v.Aim += delta
}
func (v aimVector) Position() int {
return v.ZPos * v.XPos
}
func parseInstruction(str string) instruction {
strArr := s.Split(str, " ")
var d direction
switch strArr[0] {
case "down":
d = DIR_DOWN
case "up":
d = DIR_UP
default:
d = DIR_FORWARD
}
delta, err := strconv.Atoi(strArr[1])
if err != nil {
delta = 0
}
return instruction{
Direction: d,
Delta: delta,
}
}
func computePosition(sub positionableMoveable, data []string) int {
for _, line := range data {
i := parseInstruction(line)
switch i.Direction {
case DIR_DOWN:
sub.Down(i.Delta)
case DIR_UP:
sub.Up(i.Delta)
default:
sub.Forward(i.Delta)
}
}
return sub.Position()
}
func part2(data []string) {
var submarine aimVector
pos := computePosition(&submarine, data)
fmt.Printf("Part 2: Final position %d\n", pos)
}
func part1(data []string) {
var submarine vector
pos := computePosition(&submarine, data)
fmt.Printf("Part 1: Final position %d\n", pos)
}
func main() {
cfg := utils.BannerConfig{Year: 2021, Day: 2}
utils.Banner(cfg)
// Read all the numbers
input := utils.LoadData("2.txt")
part1(input)
part2(input)
} | go/2021/2.go | 0.720958 | 0.756852 | 2.go | starcoder |
package serving
import (
"fmt"
"reflect"
"github.com/Applifier/go-tensorflow/types/tensorflow/core/framework"
)
// Tensor a tensorflow tensor
type Tensor = framework.TensorProto
// TensorMap map of tensors
type TensorMap = map[string]*framework.TensorProto
// Shape tensor shape
type Shape = framework.TensorShapeProto
// ShapeDim shape dimension
type ShapeDim = framework.TensorShapeProto_Dim
// NewShape creates a new Shape
func NewShape(dims []int64) *Shape {
dim := make([]*framework.TensorShapeProto_Dim, len(dims))
for i, size := range dims {
dim[i] = &framework.TensorShapeProto_Dim{
Size_: size,
}
}
return &Shape{
Dim: dim,
}
}
// NewTensorWithShape returns a tensor with a specific shape
func NewTensorWithShape(value interface{}, shape []int64) (*Tensor, error) {
if tensor, ok := value.(*Tensor); ok {
return NewTensorWithShape(ValueFromTensor(tensor), shape)
}
// TODO figure out if this actually causes more issues that it solves
if byteSliceSlize, ok := value.([][]byte); ok {
newValue := make([]string, len(byteSliceSlize))
for i, b := range byteSliceSlize {
// TODO optimize this for alloc
newValue[i] = string(b)
}
value = newValue
}
val := reflect.ValueOf(value)
sourceShape, dataType, err := shapeAndDataTypeOf(val)
if err != nil {
return nil, err
}
flattened := numElements(sourceShape)
return createTensor(value, sourceShape, shape, dataType, flattened)
}
// NewTensor returns a Tensor for a given go value
func NewTensor(value interface{}) (*Tensor, error) {
if tensor, ok := value.(*Tensor); ok {
return tensor, nil
}
// TODO figure out if this actually causes more issues that it solves
if byteSliceSlize, ok := value.([][]byte); ok {
newValue := make([]string, len(byteSliceSlize))
for i, b := range byteSliceSlize {
// TODO optimize this for alloc
newValue[i] = string(b)
}
value = newValue
}
val := reflect.ValueOf(value)
shape, dataType, err := shapeAndDataTypeOf(val)
if err != nil {
return nil, err
}
flattened := numElements(shape)
return createTensor(value, shape, shape, dataType, flattened)
}
func createTensor(value interface{}, sourceShape []int64, tensorShape []int64, dataType framework.DataType, flattened int64) (*Tensor, error) {
// TODO optimize by memory pooling
tensor := &Tensor{
Dtype: dataType,
TensorShape: NewShape(tensorShape),
}
switch dataType {
case framework.DataType_DT_FLOAT:
tensor.FloatVal = singleDimFloat32Slice(value, sourceShape, flattened)
case framework.DataType_DT_DOUBLE:
tensor.DoubleVal = singleDimFloat64Slice(value, sourceShape, flattened)
case framework.DataType_DT_INT32:
tensor.IntVal = singleDimInt32Slice(value, sourceShape, flattened)
case framework.DataType_DT_UINT32:
tensor.Uint32Val = singleDimUInt32Slice(value, sourceShape, flattened)
case framework.DataType_DT_UINT8:
tensor.IntVal = singleDimUInt8Slice(value, sourceShape, flattened)
case framework.DataType_DT_STRING:
flattenedArr := singleDimStringSlice(value, sourceShape, flattened)
if flattenedArr != nil {
value = flattenedArr
}
switch v := value.(type) {
case []string:
byteArrArr := make([][]byte, len(v))
for i, s := range v {
// TODO optimize for memory consumtion
byteArrArr[i] = []byte(s)
}
tensor.StringVal = byteArrArr
}
case framework.DataType_DT_INT64:
tensor.Int64Val = singleDimInt64Slice(value, sourceShape, flattened)
case framework.DataType_DT_UINT64:
tensor.Uint64Val = singleDimUInt64Slice(value, sourceShape, flattened)
case framework.DataType_DT_BOOL:
tensor.BoolVal = singleDimBoolSlice(value, sourceShape, flattened)
case framework.DataType_DT_COMPLEX64:
vals := value.([]complex64)
scomplex := make([]float32, len(vals)*2)
for i := 0; i < len(vals); i += 2 {
scomplex[i] = real(vals[i])
scomplex[i+1] = real(vals[i])
}
tensor.ScomplexVal = scomplex
case framework.DataType_DT_COMPLEX128:
vals := value.([]complex128)
dcomplex := make([]float64, len(vals)*2)
for i := 0; i < len(vals); i += 2 {
dcomplex[i] = real(vals[i])
dcomplex[i+1] = real(vals[i])
}
tensor.DcomplexVal = dcomplex
default:
return nil, fmt.Errorf("unsupported type %T", value)
}
return tensor, nil
}
// ShapeFromTensor returns shape from a tensor
func ShapeFromTensor(t *Tensor) []int64 {
dims := make([]int64, 0, len(t.TensorShape.Dim))
for _, d := range t.TensorShape.Dim {
dims = append(dims, d.Size_)
}
return dims
}
// ValueFromTensor returns value from a given tensor
func ValueFromTensor(t *Tensor) interface{} {
typ := typeOf(t.Dtype, t.TensorShape.Dim)
dims := ShapeFromTensor(t)
val := reflect.New(typ)
switch t.Dtype {
case framework.DataType_DT_FLOAT:
arr := t.FloatVal
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return arr[i]
})
case framework.DataType_DT_DOUBLE:
arr := t.DoubleVal
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return arr[i]
})
case framework.DataType_DT_INT32:
arr := t.IntVal
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return arr[i]
})
case framework.DataType_DT_UINT32:
arr := t.Uint32Val
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return arr[i]
})
case framework.DataType_DT_STRING:
arr := t.StringVal
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return string(arr[i])
})
case framework.DataType_DT_INT64:
arr := t.Int64Val
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return arr[i]
})
case framework.DataType_DT_UINT64:
arr := t.Uint64Val
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return arr[i]
})
case framework.DataType_DT_BOOL:
arr := t.BoolVal
populateMultiDimensionalSlice(val, dims, func(i int) interface{} {
return arr[i]
})
case framework.DataType_DT_COMPLEX64:
fallthrough
case framework.DataType_DT_COMPLEX128:
fallthrough
default:
panic(fmt.Errorf("unsupported type %v", t.Dtype))
}
return reflect.Indirect(val).Interface()
}
func numElements(shape []int64) int64 {
n := int64(1)
for _, d := range shape {
n *= d
}
return n
}
// shapeAndDataTypeOf returns the data type and shape of the Tensor
// corresponding to a Go type.
func shapeAndDataTypeOf(val reflect.Value) (shape []int64, dt framework.DataType, err error) {
typ := val.Type()
for typ.Kind() == reflect.Array || typ.Kind() == reflect.Slice {
shape = append(shape, int64(val.Len()))
if val.Len() > 0 {
// In order to check tensor structure properly in general case we need to iterate over all slices of the tensor to check sizes match
// Since we already going to iterate over all elements in encodeTensor() let's
// 1) do the actual check in encodeTensor() to save some cpu cycles here
// 2) assume the shape is represented by lengths of elements with zero index in each dimension
val = val.Index(0)
}
typ = typ.Elem()
}
for _, t := range types {
if typ.Kind() == t.typ.Kind() {
return shape, t.dataType, nil
}
}
return shape, dt, fmt.Errorf("unsupported type %v", typ)
}
func populateMultiDimensionalSlice(val reflect.Value, dims []int64, getValue func(i int) interface{}) {
typ := val.Type()
if typ.Elem().Kind() == reflect.Slice {
itemOffset := 0
var traverse func(reflect.Type, []int64) reflect.Value
traverse = func(typ reflect.Type, dims []int64) reflect.Value {
sli := reflect.MakeSlice(typ, int(dims[0]), int(dims[0]))
for i := 0; i < int(dims[0]); i++ {
elemType := typ.Elem()
if elemType.Kind() == reflect.Slice {
sli.Index(i).Set(traverse(elemType, dims[1:]))
} else {
sli.Index(i).Set(reflect.ValueOf(getValue(itemOffset)))
itemOffset++
}
}
return sli
}
val.Elem().Set(traverse(typ.Elem(), dims))
} else {
val.Elem().Set(reflect.ValueOf(getValue(0)))
}
}
// typeOf converts from a DataType and Shape to the equivalent Go type.
func typeOf(dt framework.DataType, shape []*framework.TensorShapeProto_Dim) reflect.Type {
var ret reflect.Type
for _, t := range types {
if dt == t.dataType {
ret = t.typ
break
}
}
if ret == nil {
panic(fmt.Sprintf("DataType %v is not supported", dt))
}
for range shape {
ret = reflect.SliceOf(ret)
}
return ret
}
var types = []struct {
typ reflect.Type
dataType framework.DataType
}{
{reflect.TypeOf(float32(0)), framework.DataType_DT_FLOAT},
{reflect.TypeOf(float64(0)), framework.DataType_DT_DOUBLE},
{reflect.TypeOf(int32(0)), framework.DataType_DT_INT32},
{reflect.TypeOf(uint32(0)), framework.DataType_DT_UINT32},
{reflect.TypeOf(int16(0)), framework.DataType_DT_INT16},
{reflect.TypeOf(int8(0)), framework.DataType_DT_INT8},
{reflect.TypeOf(uint8(0)), framework.DataType_DT_UINT8},
{reflect.TypeOf(""), framework.DataType_DT_STRING},
{reflect.TypeOf(complex(float32(0), float32(0))), framework.DataType_DT_COMPLEX64},
{reflect.TypeOf(int64(0)), framework.DataType_DT_INT64},
{reflect.TypeOf(uint64(0)), framework.DataType_DT_UINT64},
{reflect.TypeOf(false), framework.DataType_DT_BOOL},
{reflect.TypeOf(complex(float64(0), float64(0))), framework.DataType_DT_COMPLEX128},
// TODO: support DT_RESOURCE representation in go.
// TODO: support DT_VARIANT representation in go.
}
func flattenNDArray(val interface{}, resSlice interface{}) {
resI := 0
res := reflect.ValueOf(resSlice)
var traverse func(val reflect.Value)
traverse = func(val reflect.Value) {
typ := val.Type()
kind := typ.Elem().Kind()
len := val.Len()
if kind == reflect.Slice || kind == reflect.Array {
for i := 0; i < len; i++ {
traverse(val.Index(i))
}
} else {
for i := 0; i < len; i++ {
res.Index(resI).Set(val.Index(i))
resI++
}
}
}
traverse(reflect.ValueOf(val))
}
func flatten2DInt32Slice(in [][]int32, out []int32) []int32 {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func flatten2DUInt8Slice(in [][]uint8, out []int32) []int32 {
for _, vals := range in {
arr := make([]int32, len(vals))
for i, v := range vals {
arr[i] = int32(v)
}
out = append(out, arr...)
}
return out
}
func flatten2DInt64Slice(in [][]int64, out []int64) []int64 {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func flatten2DUInt32Slice(in [][]uint32, out []uint32) []uint32 {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func flatten2DUInt64Slice(in [][]uint64, out []uint64) []uint64 {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func flatten2DFloat32Slice(in [][]float32, out []float32) []float32 {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func flatten2DFloat64Slice(in [][]float64, out []float64) []float64 {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func flatten2DStringSlice(in [][]string, out []string) []string {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func flatten2DBoolSlice(in [][]bool, out []bool) []bool {
for _, vals := range in {
out = append(out, vals...)
}
return out
}
func singleDimBoolSlice(val interface{}, dims []int64, flatN int64) []bool {
switch v := val.(type) {
case bool:
return []bool{v}
case []bool:
return v
case [][]bool:
flat := make([]bool, 0, flatN)
return flatten2DBoolSlice(v, flat)
case [][][]bool:
flat := make([]bool, 0, flatN)
for _, dSlice := range v {
flat = flatten2DBoolSlice(dSlice, flat)
}
return flat
}
flat := make([]bool, flatN, flatN)
flattenNDArray(val, flat)
return flat
}
func singleDimStringSlice(val interface{}, dims []int64, flatN int64) []string {
switch v := val.(type) {
case string:
return []string{v}
case []string:
return v
case [][]string:
flat := make([]string, 0, flatN)
return flatten2DStringSlice(v, flat)
case [][][]string:
flat := make([]string, 0, flatN)
for _, dSlice := range v {
flat = flatten2DStringSlice(dSlice, flat)
}
return flat
}
flat := make([]string, flatN, flatN)
flattenNDArray(val, flat)
return flat
}
func singleDimInt32Slice(val interface{}, dims []int64, flatN int64) []int32 {
switch v := val.(type) {
case int32:
return []int32{v}
case []int32:
return v
case [][]int32:
flat := make([]int32, 0, flatN)
return flatten2DInt32Slice(v, flat)
case [][][]int32:
flat := make([]int32, 0, flatN)
for _, dSlice := range v {
flat = flatten2DInt32Slice(dSlice, flat)
}
return flat
}
flat := make([]int32, flatN, flatN)
flattenNDArray(val, flat)
return flat
}
func singleDimUInt8Slice(val interface{}, dims []int64, flatN int64) []int32 {
switch v := val.(type) {
case uint8:
return []int32{int32(v)}
case []uint8:
flat := make([]int32, flatN)
for i, v := range v {
flat[i] = int32(v)
}
return flat
case [][]uint8:
flat := make([]int32, 0, flatN)
return flatten2DUInt8Slice(v, flat)
case [][][]uint8:
flat := make([]int32, 0, flatN)
for _, dSlice := range v {
flat = flatten2DUInt8Slice(dSlice, flat)
}
return flat
}
flat := make([]uint8, flatN, flatN)
flattenNDArray(val, flat)
// TODO optimize this
returnArr := make([]int32, flatN)
for i, v := range flat {
returnArr[i] = int32(v)
}
return returnArr
}
func singleDimInt64Slice(val interface{}, dims []int64, flatN int64) []int64 {
switch v := val.(type) {
case int64:
return []int64{v}
case []int64:
return v
case [][]int64:
flat := make([]int64, 0, flatN)
return flatten2DInt64Slice(v, flat)
case [][][]int64:
flat := make([]int64, 0, flatN)
for _, dSlice := range v {
flat = flatten2DInt64Slice(dSlice, flat)
}
return flat
}
flat := make([]int64, flatN, flatN)
flattenNDArray(val, flat)
return flat
}
func singleDimUInt32Slice(val interface{}, dims []int64, flatN int64) []uint32 {
switch v := val.(type) {
case uint32:
return []uint32{v}
case []uint32:
return v
case [][]uint32:
flat := make([]uint32, 0, flatN)
return flatten2DUInt32Slice(v, flat)
case [][][]uint32:
flat := make([]uint32, 0, flatN)
for _, dSlice := range v {
flat = flatten2DUInt32Slice(dSlice, flat)
}
return flat
}
flat := make([]uint32, flatN, flatN)
flattenNDArray(val, flat)
return flat
}
func singleDimUInt64Slice(val interface{}, dims []int64, flatN int64) []uint64 {
switch v := val.(type) {
case uint64:
return []uint64{v}
case []uint64:
return v
case [][]uint64:
flat := make([]uint64, 0, flatN)
return flatten2DUInt64Slice(v, flat)
case [][][]uint64:
flat := make([]uint64, 0, flatN)
for _, dSlice := range v {
flat = flatten2DUInt64Slice(dSlice, flat)
}
return flat
}
flat := make([]uint64, flatN, flatN)
flattenNDArray(val, flat)
return flat
}
func singleDimFloat32Slice(val interface{}, dims []int64, flatN int64) []float32 {
switch v := val.(type) {
case float32:
return []float32{v}
case []float32:
return v
case [][]float32:
flat := make([]float32, 0, flatN)
return flatten2DFloat32Slice(v, flat)
case [][][]float32:
flat := make([]float32, 0, flatN)
for _, dSlice := range v {
flat = flatten2DFloat32Slice(dSlice, flat)
}
return flat
}
flat := make([]float32, flatN, flatN)
flattenNDArray(val, flat)
return flat
}
func singleDimFloat64Slice(val interface{}, dims []int64, flatN int64) []float64 {
switch v := val.(type) {
case float64:
return []float64{v}
case []float64:
return v
case [][]float64:
flat := make([]float64, 0, flatN)
return flatten2DFloat64Slice(v, flat)
case [][][]float64:
flat := make([]float64, 0, flatN)
for _, dSlice := range v {
flat = flatten2DFloat64Slice(dSlice, flat)
}
return flat
}
flat := make([]float64, flatN, flatN)
flattenNDArray(val, flat)
return flat
} | serving/tensor.go | 0.520009 | 0.662998 | tensor.go | starcoder |
package math
import (
"errors"
)
type Matrix3 struct {
M11, M12, M13 float32
M21, M22, M23 float32
M31, M32, M33 float32
}
func NewMatrix3(m11, m12, m13, m21, m22, m23, m31, m32, m33 float32) *Matrix3 {
return &Matrix3{m11, m12, m13, m21, m22, m23, m31, m32, m33}
}
func NewIdentityMatrix3() *Matrix3 {
return &Matrix3{M11: 1.0, M22: 1.0, M33: 1.0}
}
func NewXRotationMatrix3(angle float32) *Matrix3 {
angle = DegreeToRadians * angle
c := Cos(angle)
s := Sin(angle)
return &Matrix3{
1, 0, 0,
0, c, -s,
0, s, c,
}
}
func NewYRotationMatrix3(angle float32) *Matrix3 {
angle = DegreeToRadians * angle
c := Cos(angle)
s := Sin(angle)
return &Matrix3{
c, 0, s,
0, 1, 0,
-s, 0, c,
}
}
// Returns a rotation matrix that will rotate any vector in counter-clockwise order around the z-axis.
func NewZRotationMatrix3(angle float32) *Matrix3 {
angle = DegreeToRadians * angle
c := Cos(angle)
s := Sin(angle)
return &Matrix3{
c, -s, 0,
s, c, 0,
0, 0, 1,
}
}
func NewRotationMatrix3(axis Vector3, angle float32) *Matrix3 {
axis = axis.Nor()
angle = DegreeToRadians * angle
c := Cos(angle)
s := Sin(angle)
k := 1 - c
return &Matrix3{axis.X*axis.X*k + c, axis.X*axis.Y*k + axis.Z*s, axis.X*axis.Z*k - axis.Y*s,
axis.X*axis.Y*k - axis.Z*s, axis.Y*axis.Y*k + c, axis.Y*axis.Z*k + axis.X*s,
axis.X*axis.Z*k + axis.Y*s, axis.Y*axis.Z*k - axis.X*s, axis.Z*axis.Z*k + c}
}
func NewTranslationMatrix3(x, y float32) *Matrix3 {
return &Matrix3{
1, 0, 0,
0, 1, 0,
x, y, 1,
}
}
func NewScaleMatrix3(scaleX, scaleY float32) *Matrix3 {
return &Matrix3{
scaleX, 0, 0,
0, scaleY, 0,
0, 0, 1,
}
}
// Copies the values from the provided matrix to this matrix.
func (m *Matrix3) Set(mat *Matrix3) *Matrix3 {
m.M11 = mat.M11
m.M12 = mat.M12
m.M13 = mat.M13
m.M21 = mat.M21
m.M22 = mat.M22
m.M23 = mat.M23
m.M31 = mat.M31
m.M32 = mat.M32
m.M33 = mat.M33
return m
}
// Multiplies this matrix with the provided matrix and returns a new matrix.
func (m *Matrix3) Mul(mat *Matrix3) *Matrix3 {
temp := &Matrix3{}
temp.M11 = m.M11*mat.M11 + m.M21*mat.M12 + m.M31*mat.M13
temp.M12 = m.M12*mat.M11 + m.M22*mat.M12 + m.M32*mat.M13
temp.M13 = m.M13*mat.M11 + m.M23*mat.M12 + m.M33*mat.M13
temp.M21 = m.M11*mat.M21 + m.M21*mat.M22 + m.M31*mat.M23
temp.M22 = m.M12*mat.M21 + m.M22*mat.M22 + m.M32*mat.M23
temp.M23 = m.M13*mat.M21 + m.M23*mat.M22 + m.M33*mat.M23
temp.M31 = m.M11*mat.M31 + m.M21*mat.M32 + m.M31*mat.M33
temp.M32 = m.M12*mat.M31 + m.M22*mat.M32 + m.M32*mat.M33
temp.M33 = m.M13*mat.M31 + m.M23*mat.M32 + m.M33*mat.M33
return temp
}
// Returns tThe determinant of this matrix
func (m *Matrix3) Determinant() float32 {
return m.M11*m.M22*m.M33 + m.M21*m.M32*m.M13 + m.M31*m.M12*m.M23 - m.M11*m.M32*m.M23 - m.M21*m.M12*m.M33 - m.M31*m.M22*m.M13
}
// Returns the inverse matrix given that the determinant is != 0
func (m *Matrix3) Inverse() (*Matrix3, error) {
det := m.Determinant()
if det == 0 {
return nil, errors.New("Can't invert a singular matrix")
}
invDet := 1.0 / det
return &Matrix3{
invDet * (m.M22*m.M33 - m.M23*m.M32), invDet * (m.M13*m.M32 - m.M12*m.M33), invDet * (m.M12*m.M23 - m.M13*m.M22),
invDet * (m.M23*m.M31 - m.M21*m.M33), invDet * (m.M11*m.M33 - m.M13*m.M31), invDet * (m.M13*m.M21 - m.M11*m.M23),
invDet * (m.M21*m.M32 - m.M22*m.M31), invDet * (m.M12*m.M31 - m.M11*m.M32), invDet * (m.M11*m.M22 - m.M12*m.M21),
}, nil
}
func (m *Matrix3) ToArray() []float32 {
return []float32{m.M11, m.M12, m.M13, m.M21, m.M22, m.M23, m.M31, m.M32, m.M33}
}
// Returns this matrix transposed.
func (m *Matrix3) Transpose() *Matrix3 {
return &Matrix3{
m.M11, m.M21, m.M31,
m.M12, m.M22, m.M32,
m.M13, m.M23, m.M33,
}
}
// Build planar projection matrix along normal axis.
func (m *Matrix3) Proj2D(normal Vector3) *Matrix3 {
r := &Matrix3{
1 - normal.X*normal.X, -normal.X * normal.Y, 0,
-normal.X * normal.Y, 1 - normal.Y*normal.Y, 0,
0, 0, 1,
}
return m.Mul(r)
}
// Returns a transformed matrix with a shearing on X axis.
func (m *Matrix3) ShearX2D(y float32) *Matrix3 {
r := &Matrix3{
1, y, 0,
0, 1, 0,
0, 0, 1,
}
return m.Mul(r)
}
// Returns a transformed matrix with a shearing on Y axis.
func (m *Matrix3) ShearY2D(x float32) *Matrix3 {
r := &Matrix3{
1, 0, 0,
x, 1, 0,
0, 0, 1,
}
return m.Mul(r)
} | matrix3.go | 0.880502 | 0.710727 | matrix3.go | starcoder |
package main
import (
"log"
"os"
"strconv"
"github.com/TomasCruz/projecteuler"
)
/*
Problem 25; 1000-digit Fibonacci number
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fnβ1 + Fnβ2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
*/
func main() {
var limit int
if len(os.Args) > 1 {
limit64, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil {
log.Fatal("bad argument")
}
limit = int(limit64)
} else {
limit = 1000
}
projecteuler.Timed(calc, limit)
}
func calc(args ...interface{}) (result string, err error) {
limit := args[0].(int)
var biggestIndex int
powerMatrices, biggestIndex := buildFibPowerIndices(limit)
firstIndex := biggestIndex / 2
lastIndex := biggestIndex
index := binarySearch(limit, powerMatrices, firstIndex, lastIndex)
result = strconv.Itoa(index)
return
}
func buildFibPowerIndices(limit int) (powerMatrices map[int]*projecteuler.BigIntMatrix, biggestIndex int) {
powerMatrices = make(map[int]*projecteuler.BigIntMatrix)
one, _ := projecteuler.NewBigIntMatrix(2, 2, []int64{1, 1, 1, 0})
powerMatrices[1] = one
biggestIndex = 1
for {
prev := powerMatrices[biggestIndex]
biggestIndex *= 2
curr := projecteuler.MulBigIntMatrix(prev, prev)
powerMatrices[biggestIndex] = curr
fn, _ := curr.At(0, 1)
if len(fn.String()) >= limit {
break
}
}
return
}
func binarySearch(limit int, powerMatrices map[int]*projecteuler.BigIntMatrix, firstIndex, lastIndex int) int {
if lastIndex-firstIndex <= 1 {
return lastIndex
}
middleIndex := (firstIndex + lastIndex) / 2
insertIndex(powerMatrices, middleIndex)
found, belowLimit, offset := checkMatrix(limit, powerMatrices[middleIndex])
if found {
return middleIndex + offset
}
if belowLimit {
return binarySearch(limit, powerMatrices, middleIndex, lastIndex)
}
return binarySearch(limit, powerMatrices, firstIndex, middleIndex)
}
func insertIndex(powerMatrices map[int]*projecteuler.BigIntMatrix, middleIndex int) {
if _, ok := powerMatrices[middleIndex]; ok {
return
}
sl := make([]int, 0)
powerTwoAdditionTerms(middleIndex, &sl)
result := powerMatrices[sl[0]]
for i := 1; i < len(sl); i++ {
temp := projecteuler.MulBigIntMatrix(result, powerMatrices[sl[i]])
result = temp.Clone()
}
powerMatrices[middleIndex] = result
}
func powerTwoAdditionTerms(middleIndex int, slice *[]int) {
if middleIndex == 0 {
return
}
biggest := middleIndex
cnt := 0
for biggest != 1 {
biggest >>= 1
cnt++
}
for cnt != 0 {
biggest <<= 1
cnt--
}
*slice = append(*slice, biggest)
powerTwoAdditionTerms(middleIndex-biggest, slice)
}
func checkMatrix(limit int, matrix *projecteuler.BigIntMatrix) (found, belowLimit bool, offset int) {
fn, _ := matrix.At(0, 1)
fPrev, _ := matrix.At(1, 1)
fNext, _ := matrix.At(0, 0)
digitsN := len(fn.String())
digitsPrev := len(fPrev.String())
digitsNext := len(fNext.String())
if digitsPrev >= limit {
return
}
if digitsN == limit {
found = true
offset = 0
return
}
if digitsNext == limit {
if digitsN < limit {
found = true
offset = 1
return
}
} else {
// digitsNext < limit
belowLimit = true
return
}
return
} | 001-100/021-030/025/main.go | 0.548674 | 0.479077 | main.go | starcoder |
package db
import (
"github.com/alecthomas/participle"
"github.com/alecthomas/participle/lexer"
)
var schemaLexer = lexer.Must(lexer.Regexp(`(?P<Newline>\n)` +
`|(?m)(\s+)` +
`|(#.*$)` +
`|(?P<Keyword>struct)` +
`|(?P<Ident>[\p{L}\p{M}_-][\p{L}\p{M}\d_-]*)` +
`|(?P<Punctuation>[:{}\[\]<>])`,
))
// SchemaParser parses schemas.
var SchemaParser *participle.Parser
func init() {
parser, err := participle.Build(&Schema{}, participle.Lexer(schemaLexer))
if err != nil {
panic(err)
}
SchemaParser = parser
}
// A Schema is used to specify the structure and field types of a database.
type Schema struct {
Sections []*SchemaSection `{ { Newline } @@ }`
}
// A SchemaSection is a field or struct definition in a schema.
type SchemaSection struct {
Field *SchemaField ` @@`
Struct *SchemaStruct `| @@`
}
// A SchemaField defines a field in the schema or in a struct.
type SchemaField struct {
Name string `@Ident`
Type *SchemaType `":" @@ Newline`
}
// A SchemaType specifies the type of a field.
type SchemaType struct {
Ident string ` @Ident`
List *SchemaType `| "[" @@ "]"`
Hashmap *SchemaMapType `| @@`
}
// A SchemaMapType represents a hashmap field.
type SchemaMapType struct {
KeyType *SchemaType `"<" @@ ":"`
ValueType *SchemaType `@@ ">"`
}
// A SchemaStruct defines a new type, similar to a Go struct.
type SchemaStruct struct {
Name string `"struct" @Ident`
Fields []*SchemaField `"{" { { Newline } @@ { Newline } } "}"`
}
// MakeZeroValue makes a new Item which has the zero value of the
// given type.
func MakeZeroValue(t Type) Item {
switch ty := t.(type) {
case *StructType:
return NewStruct(ty)
case *ListType:
return NewList(ty.ElemType)
case *HashmapType:
return NewHashmap(ty.KeyType, ty.ValType)
case *FloatType:
return NewFloat(0)
case *Float32Type:
return NewFloat32(0)
case *IntType:
return NewInt(0)
case *Int32Type:
return NewInt32(0)
case *Int16Type:
return NewInt16(0)
case *Int8Type:
return NewInt8(0)
case *UintType:
return NewUint(0)
case *Uint32Type:
return NewUint32(0)
case *Uint16Type:
return NewUint16(0)
case *Uint8Type:
return NewUint8(0)
case *StringType:
return NewString("")
case *BoolType:
return NewBool(false)
case *RegexpType:
return NewRegexp("")
default:
return nil
}
}
// GetActualType takes a parsed schema type and returns an actual
// Type instance.
func GetActualType(st *SchemaType, structs map[string]*StructType) Type {
if li := st.List; li != nil {
ty := GetActualType(li, structs)
if ty == nil {
return nil
}
return &ListType{
ElemType: ty,
}
} else if hm := st.Hashmap; hm != nil {
kt := GetActualType(hm.KeyType, structs)
if kt == nil {
return nil
}
vt := GetActualType(hm.ValueType, structs)
if vt == nil {
return nil
}
return &HashmapType{
KeyType: kt,
ValType: vt,
}
}
switch id := st.Ident; id {
case "float":
return &FloatType{}
case "float32":
return &Float32Type{}
case "int":
return &IntType{}
case "int32":
return &Int32Type{}
case "int16":
return &Int16Type{}
case "int8":
return &Int8Type{}
case "uint":
return &UintType{}
case "uint32":
return &Uint32Type{}
case "uint16":
return &Uint16Type{}
case "uint8":
return &Uint8Type{}
case "string":
return &StringType{}
case "bool":
return &BoolType{}
case "regexp":
return &RegexpType{}
default:
str, ok := structs[id]
if ok {
return str
}
}
return nil
} | db/schema.go | 0.627152 | 0.425307 | schema.go | starcoder |
package main
import "math"
// Evaluator is the default evaluator to be used across the neural network
var Evaluator = &DefaultEvaluator{}
// DefaultEvaluator is the default evaluator for our neural networks
type DefaultEvaluator struct{}
// AdjustLayer performs the actual fine tuning of the current layer given a base
// error mapping. This returns the error mapping for the current layer
func (e *DefaultEvaluator) AdjustLayer(layer *NetworkLayer, errMap map[*Neuron]*NeuronError) (map[*Neuron]*NeuronError, error) {
currErrMap := make(map[*Neuron]*NeuronError)
// Go through each neuron in the current layer and adjust the outgoing
// weights accordingly. Track how much adjustment it takes overall
layer.EachNeuron(func(n *Neuron) {
currErrMap[n] = &NeuronError{Direction: 1}
// Get the total weight coming in to this neuron and stored that for future
// usage
for _, conn := range n.In {
currErrMap[n].TotalWeight += conn.Weight
}
// Now, figure out how much to adjust the incoming weights
for _, conn := range n.Out {
err := errMap[conn.Target]
// How much of the error is this connection responsible for?
proportionalWeight := conn.Weight / conn.Target.TotalInputWeight()
// Now, it's proportional, but we need to adjust from gross to fine tuning
// and taking our current weight into account alongside the sigmoid helps.
// Right now we've got the scaling value cranked all the way up because it
// makes things converge more rapidly
adjStep := 0.1 * proportionalWeight * err.Sigmoid()
// adjStep := 0.2 * conn.Weight * proportionalWeight * err.Sigmoid()
// Keep track of how much error we have at this layer so we can percolate
// that up
currErrMap[n].Error += adjStep
// Now do the actual adjustment
conn.Weight += adjStep * float64(err.Direction)
}
// Make sure we keep our logic consistent (ie separate magnitude and direction)
if currErrMap[n].Error < 0 {
currErrMap[n].Direction = -1
currErrMap[n].Error *= -1
}
// Make sure we scale the error appropriately
// currErrMap[n].Error = e.MeanSquaredError(0.0, currErrMap[n].Error)
})
return currErrMap, nil
}
// PerformBackPropagation performs traditional back propagation of the network signal
func (e *DefaultEvaluator) PerformBackPropagation(expected [][]float64, network NetworkConfiguration) error {
baseError, err := e.CalculateError(expected, network)
if err != nil {
Error.Println("Error while attempting to backpropagate:", err)
return err
}
layers := network.GetLayers()
// No point trying to adjust the outgoing weights on the last layer amirite
for i := len(layers) - 2; i >= 0; i-- {
layer := layers[i]
baseError, err = e.AdjustLayer(layer, baseError)
// Make sure we capture any failures in the layers
if err != nil {
Error.Println("Error while attempting to backpropagate:", err)
return err
}
}
return nil
}
// CalculateError calculates the error of the output layer versuses the provided
// set of expected values
func (e *DefaultEvaluator) CalculateError(expected [][]float64, network NetworkConfiguration) (map[*Neuron]*NeuronError, error) {
layer := network.GetOutput()
if len(expected) != len(layer.Neurons) ||
len(expected[0]) != len(layer.Neurons[0]) {
return nil, ErrArraySizeMismatch
}
errMap := make(map[*Neuron]*NeuronError)
for i, row := range expected {
for j, val := range row {
weight := 0.0
neuron := layer.Neurons[i][j]
for _, input := range neuron.In {
weight += input.Weight
}
direction := 1
if val < neuron.Potential {
direction = -1
}
err := &NeuronError{
Direction: direction,
Error: e.MeanSquaredError(val, neuron.Potential),
TotalWeight: weight,
}
errMap[neuron] = err
}
}
return errMap, nil
}
// Train runs the given network with
func (e *DefaultEvaluator) Train(iterations int, config *TrainingConfiguration) {
// func (e *DefaultEvaluator) Train(iterations int, input, expected [][]float64, network NetworkConfiguration) {
network := config.Network
// Log 100 frames if we're debugging
debugLogTick := iterations / 100
for i := 0; i < iterations; i++ {
// If we're debugging, log every 1/100th of the set as well as the final
// state
if config.Debug && (i%debugLogTick == 0 || i == iterations-1) {
network.SetDebug(true)
} else {
network.SetDebug(false)
}
input := config.PickInput()
network.Run(input.Values)
e.PerformBackPropagation(input.Expected, network)
if network.GetDebug() {
totalError := 0.0
for i, row := range input.Expected {
for j, val := range row {
totalError += math.Abs(
Evaluator.LinearError(val, network.GetOutput().Neurons[i][j].Potential))
}
}
Debug.Printf("Total error: %.3f\n", totalError)
}
}
}
// LinearError calculates the linear error between two float values
func (e *DefaultEvaluator) LinearError(expected, actual float64) float64 {
return actual - expected
}
// MeanSquaredError calculates the mean squared error between two float values
func (e *DefaultEvaluator) MeanSquaredError(expected, actual float64) float64 {
return 0.5 * math.Pow(expected-actual, 2)
} | evaluator.go | 0.77081 | 0.562777 | evaluator.go | starcoder |
package gollection
const defaultElementsSize = 10
func ArrayListOf[T any](elements ...T) ArrayList[T] {
var size = len(elements)
var list = MakeArrayList[T](size)
copy(list.inner.elements, elements)
list.inner.size = size
return list
}
func MakeArrayList[T any](capacity int) ArrayList[T] {
if capacity < defaultElementsSize {
capacity = defaultElementsSize
}
var inner = &arrayList[T]{make([]T, capacity), 0}
return ArrayList[T]{inner}
}
func ArrayListFrom[T any, I Collection[T]](collection I) ArrayList[T] {
var inner = &arrayList[T]{collection.ToSlice(), collection.Size()}
return ArrayList[T]{inner}
}
type ArrayList[T any] struct {
inner *arrayList[T]
}
type arrayList[T any] struct {
elements []T
size int
}
func (a ArrayList[T]) Prepend(element T) {
if growSize := a.inner.size + 1; len(a.inner.elements) < growSize {
a.grow(growSize)
}
copy(a.inner.elements[1:], a.inner.elements[0:])
a.inner.elements[0] = element
}
func (a ArrayList[T]) PrependAll(elements Collection[T]) {
var additional = elements.Size()
if growSize := a.inner.size + additional; len(a.inner.elements) < growSize {
a.grow(growSize)
}
copy(a.inner.elements[additional:], a.inner.elements[0:])
var i = 0
ForEach(func(item T) {
a.inner.elements[i] = item
a.inner.size++
i++
}, elements.Iter())
}
func (a ArrayList[T]) Append(element T) {
if growSize := a.inner.size + 1; len(a.inner.elements) < growSize {
a.grow(growSize)
}
a.inner.elements[a.inner.size] = element
a.inner.size++
}
func (a ArrayList[T]) AppendAll(elements Collection[T]) {
var additional = elements.Size()
if growSize := a.inner.size + additional; len(a.inner.elements) < growSize {
a.grow(growSize)
}
var i = a.inner.size
ForEach(func(item T) {
a.inner.elements[i] = item
a.inner.size++
i++
}, elements.Iter())
}
func (a ArrayList[T]) Insert(index int, element T) {
if index < 0 || index > a.inner.size {
panic(OutOfBounds)
}
if growSize := a.inner.size + 1; len(a.inner.elements) < growSize {
a.grow(growSize)
}
copy(a.inner.elements[index+1:], a.inner.elements[index:])
a.inner.elements[index] = element
}
func (a ArrayList[T]) InsertAll(index int, elements Collection[T]) {
if index < 0 || index > a.inner.size {
panic(OutOfBounds)
}
var additional = elements.Size()
if growSize := a.inner.size + additional; len(a.inner.elements) < growSize {
a.grow(growSize)
}
copy(a.inner.elements[index+additional:], a.inner.elements[index:])
var i = index
ForEach(func(item T) {
a.inner.elements[i] = item
a.inner.size++
i++
}, elements.Iter())
}
func (a ArrayList[T]) Remove(index int) T {
if a.isOutOfBounds(index) {
panic(OutOfBounds)
}
var removed = a.inner.elements[index]
copy(a.inner.elements[:index], a.inner.elements[index+1:])
var emptyValue T
a.inner.elements[a.inner.size-1] = emptyValue
a.inner.size--
return removed
}
func (a ArrayList[T]) Reserve(additional int) {
if addable := len(a.inner.elements) - a.inner.size; addable < additional {
a.grow(a.inner.size + additional)
}
}
func (a ArrayList[T]) Get(index int) T {
if v, ok := a.TryGet(index).Get(); ok {
return v
}
panic(OutOfBounds)
}
func (a ArrayList[T]) Set(index int, newElement T) T {
if v, ok := a.TrySet(index, newElement).Get(); ok {
return v
}
panic(OutOfBounds)
}
func (a ArrayList[T]) GetAndSet(index int, set func(oldElement T) T) Pair[T, T] {
if a.isOutOfBounds(index) {
panic(OutOfBounds)
}
var oldElement = a.inner.elements[index]
var newElement = set(oldElement)
return PairOf(newElement, oldElement)
}
func (a ArrayList[T]) TryGet(index int) Option[T] {
if a.isOutOfBounds(index) {
return None[T]()
}
return Some(a.inner.elements[index])
}
func (a ArrayList[T]) TrySet(index int, newElement T) Option[T] {
if a.isOutOfBounds(index) {
return None[T]()
}
var oldElement = a.inner.elements[index]
a.inner.elements[index] = newElement
return Some(oldElement)
}
func (a ArrayList[T]) Clear() {
var emptyValue T
for i := 0; i < a.inner.size; i++ {
a.inner.elements[i] = emptyValue
}
a.inner.size = 0
}
func (a ArrayList[T]) Size() int {
return a.inner.size
}
func (a ArrayList[T]) IsEmpty() bool {
return a.inner.size == 0
}
func (a ArrayList[T]) Iter() Iterator[T] {
return &arrayListIterator[T]{-1, a}
}
func (a ArrayList[T]) ToSlice() []T {
var slice = make([]T, a.Size())
copy(slice, a.inner.elements)
return slice
}
func (a ArrayList[T]) Clone() ArrayList[T] {
var elements = make([]T, len(a.inner.elements))
copy(elements, a.inner.elements)
var inner = &arrayList[T]{
elements: elements,
size: a.inner.size,
}
return ArrayList[T]{inner}
}
func (a ArrayList[T]) Capacity() int {
return len(a.inner.elements)
}
func (a ArrayList[T]) isOutOfBounds(index int) bool {
if index < 0 || index >= a.inner.size {
return true
}
return false
}
func (a ArrayList[T]) grow(minCapacity int) {
var newSize = arrayGrow(a.inner.size)
if newSize < minCapacity {
newSize = minCapacity
}
var newSource = make([]T, newSize)
copy(newSource, a.inner.elements)
a.inner.elements = newSource
}
func arrayGrow(size int) int {
var newSize = size + (size >> 1)
if newSize < defaultElementsSize {
newSize = defaultElementsSize
}
return newSize
}
type arrayListIterator[T any] struct {
index int
source ArrayList[T]
}
func (a *arrayListIterator[T]) Next() Option[T] {
if a.index < a.source.Size()-1 {
a.index++
return Some(a.source.inner.elements[a.index])
}
return None[T]()
} | array_list.go | 0.624752 | 0.444565 | array_list.go | starcoder |
package datum
import (
"fmt"
"sync/atomic"
"time"
)
// Type describes the type of value stored in a Datum.
type Type int
const (
// Int describes an integer datum
Int Type = iota
// Float describes a floating point datum
Float
)
func (t Type) String() string {
switch t {
case Int:
return "Int"
case Float:
return "Float"
}
return "?"
}
// Datum is an interface for metric datums, with a type, value and timestamp to be exported.
type Datum interface {
// Type returns the Datum type.
Type() Type
// ValueString returns the value of a Datum as a string.
ValueString() string
// TimeString returns the timestamp of a Datum as a string.
TimeString() string
}
// BaseDatum is a struct used to record timestamps across all Datum implementations.
type BaseDatum struct {
Time int64 // nanoseconds since unix epoch
}
var zeroTime time.Time
func (d *BaseDatum) stamp(timestamp time.Time) {
if timestamp.IsZero() {
atomic.StoreInt64(&d.Time, time.Now().UTC().UnixNano())
} else {
atomic.StoreInt64(&d.Time, timestamp.UnixNano())
}
}
// TimeString returns the timestamp of this Datum as a string.
func (d *BaseDatum) TimeString() string {
return fmt.Sprintf("%d", atomic.LoadInt64(&d.Time)/1e9)
}
// NewInt creates a new zero integer datum.
func NewInt() Datum {
return MakeInt(0, zeroTime)
}
// NewFloat creates a new zero floating-point datum.
func NewFloat() Datum {
return MakeFloat(0., zeroTime)
}
// MakeInt creates a new integer datum with the provided value and timestamp.
func MakeInt(v int64, ts time.Time) Datum {
d := &IntDatum{}
d.Set(v, ts)
return d
}
// MakeFloat creates a new floating-point datum with the provided value and timestamp.
func MakeFloat(v float64, ts time.Time) Datum {
d := &FloatDatum{}
d.Set(v, ts)
return d
}
// GetInt returns the integer value of a datum, or error.
func GetInt(d Datum) int64 {
switch d := d.(type) {
case *IntDatum:
return d.Get()
default:
panic(fmt.Sprintf("datum %v is not an Int", d))
}
}
// GetFloat returns the floating-point value of a datum, or error.
func GetFloat(d Datum) float64 {
switch d := d.(type) {
case *FloatDatum:
return d.Get()
default:
panic(fmt.Sprintf("datum %v is not a Float", d))
}
}
// SetInt sets an integer datum to the provided value and timestamp, or panics if the Datum is not an IntDatum.
func SetInt(d Datum, v int64, ts time.Time) {
switch d := d.(type) {
case *IntDatum:
d.Set(v, ts)
default:
panic(fmt.Sprintf("datum %v is not an Int", d))
}
}
// SetFloat sets a floating-point Datum to the provided value and timestamp, or panics if the Datum is not a FloatDatum.
func SetFloat(d Datum, v float64, ts time.Time) {
switch d := d.(type) {
case *FloatDatum:
d.Set(v, ts)
default:
panic(fmt.Sprintf("datum %v is not a Float", d))
}
}
// IncIntBy increments an integer Datum by the provided value, at time ts, or panics if the Datum is not an IntDatum.
func IncIntBy(d Datum, v int64, ts time.Time) {
switch d := d.(type) {
case *IntDatum:
d.IncBy(v, ts)
default:
panic(fmt.Sprintf("datum %v is not an Int", d))
}
} | metrics/datum/datum.go | 0.865395 | 0.519704 | datum.go | starcoder |
package basic
import (
"bytes"
"github.com/zhukovaskychina/xmysql-server/util"
"strconv"
)
type BigIntValue struct {
value []byte
}
func (b BigIntValue) ToDatum() Datum {
panic("implement me")
}
func (b BigIntValue) ToString() string {
uint := util.ReadUB8Byte2Long(b.value)
return strconv.FormatUint(uint, 10)
}
func NewBigIntValue(value []byte) Value {
var bigIntValue = new(BigIntValue)
bigIntValue.value = value
return bigIntValue
}
func (b BigIntValue) Raw() interface{} {
return util.ReadUB8Bytes2Long(b.value)
}
func (b BigIntValue) ToByte() []byte {
return b.value
}
func (b BigIntValue) DataType() ValType {
return RowIdVal
}
func (b BigIntValue) Compare(x Value) (CompareType, error) {
panic("implement me")
}
func (b BigIntValue) UnaryPlus() (Value, error) {
panic("implement me")
}
func (b BigIntValue) UnaryMinus() (Value, error) {
panic("implement me")
}
func (b BigIntValue) Add(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) Sub(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) Mul(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) Div(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) Pow(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) Mod(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) Equal(value Value) (Value, error) {
return NewBoolValue(bytes.Compare(b.value, value.ToByte()) == 0), nil
}
func (b BigIntValue) NotEqual(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) GreaterThan(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) LessThan(value Value) (Value, error) {
second := value.Raw().(int64)
first := b.Raw().(int64)
return NewBoolValue(first < second), nil
}
func (b BigIntValue) GreaterOrEqual(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) LessOrEqual(value Value) (Value, error) {
second := value.Raw().(int64)
first := b.Raw().(int64)
return NewBoolValue(first <= second), nil
}
func (b BigIntValue) And(value Value) (Value, error) {
panic("implement me")
}
func (b BigIntValue) Or(value Value) (Value, error) {
panic("implement me")
} | server/innodb/basic/bigint_value.go | 0.58439 | 0.459137 | bigint_value.go | starcoder |
package hexutil
import (
"errors"
"fmt"
"math"
"math/big"
"regexp"
"strconv"
"strings"
"github.com/coming-chat/wallet-SDK/util/mathutil"
)
var (
// Prefix hex prefix
Prefix = "0x"
// ErrInvalidHex is error for invalid hex
ErrInvalidHex = errors.New("invalid hex")
)
// HasPrefix tests for the existence of a `0x` prefix. Checks for a valid hex input value and if the start matched `0x`.
func HasPrefix(hexStr string) bool {
if len(hexStr) < 2 {
return false
}
return len(hexStr) >= 2 && hexStr[0:2] == "0x"
}
// ValidHex tests that the value is a valid string. The `0x` prefix is optional in the test. Empty string returns false.
func ValidHex(hexStr string) bool {
if len(hexStr) == 0 {
return false
}
regex := regexp.MustCompile(`^(0x)?[\da-fA-F]*$`)
return regex.Match([]byte(hexStr))
}
// AddPrefix adds the `0x` prefix to string values.
// Returns a `0x` prefixed string from the input value. If the input is already prefixed, it is returned unchanged. Adds extra 0 when `length % 2 == 1`.
func AddPrefix(hexStr string) string {
if HasPrefix(hexStr) {
return hexStr
}
if len(hexStr)%2 == 1 {
hexStr = fmt.Sprintf("0%s", hexStr)
}
return fmt.Sprintf("%s%s", Prefix, hexStr)
}
// StripPrefix strips any leading `0x` prefix. Tests for the existence of a `0x` prefix, and returns the value without the prefix. Un-prefixed values are returned as-is.
func StripPrefix(hexStr string) string {
return strings.TrimPrefix(hexStr, Prefix)
}
// HexFixLength shifts a hex string to a specific bitLength.
// Returns a `0x` prefixed string with the specified number of bits contained in the return value. (If bitLength is -1, length checking is not done). Values with more bits are trimmed to the specified length. Input values with less bits are returned as-is by default. When `withPadding` is set, shorter values are padded with `0`.
func HexFixLength(hexStr string, bitLength int, withPadding bool) string {
strLen := int(math.Ceil(float64(bitLength) / float64(4)))
hexLen := strLen + 2
if bitLength == -1 || len(hexStr) == hexLen ||
(!withPadding && len(hexStr) < hexLen) {
return AddPrefix(hexStr)
}
strippedHexStr := StripPrefix(hexStr)
strippedHexLen := len(strippedHexStr)
if len(hexStr) > hexLen {
return AddPrefix(
strippedHexStr[strippedHexLen-strLen : strippedHexLen],
)
}
paddedHexStr := fmt.Sprintf("%s%s", strings.Repeat("0", strLen), strippedHexStr)
return AddPrefix(
paddedHexStr[len(paddedHexStr)-strLen:],
)
}
// ToBN creates a math/big big number from a hex string.
func ToBN(hexStr string, isLittleEndian bool, isNegative bool) (*big.Int, error) {
i := new(big.Int)
hx := StripPrefix(hexStr)
if hx == "" {
return big.NewInt(0), nil
}
if isLittleEndian {
hx = Reverse(hx)
}
if _, ok := i.SetString(hx, 16); !ok {
return nil, errors.New("could not decode to big.Int")
}
// NOTE: fromTwos takes as parameter the number of bits,
// which is the hex length multiplied by 4.
if isNegative {
return mathutil.FromTwos(i, i.BitLen()), nil
}
return i, nil
}
// ToUint8Slice creates a uint8 array from a hex string. empty inputs returns an empty array result. Hex input values return the actual bytes value converted to a uint8. Anything that is not a hex string (including the `0x` prefix) returns an error.
func ToUint8Slice(hexStr string, bitLength int) ([]uint8, error) {
if hexStr == "" {
return []uint8{}, nil
}
if !ValidHex(hexStr) {
return nil, ErrInvalidHex
}
value := StripPrefix(hexStr)
valLength := len(value) / 2
var bufLength int
if bitLength == -1 {
bufLength = int(math.Ceil(float64(valLength)))
} else {
bufLength = int(math.Ceil(float64(bitLength) / float64(8)))
}
result := make([]uint8, bufLength)
offset := int(math.Max(float64(0), float64(bufLength-valLength)))
for index := 0; index < bufLength; index++ {
n := (index * 2) + 2
if n > len(value) {
continue
}
s := value[index*2 : n]
v, err := strconv.ParseInt(s, 16, 64)
if err != nil {
return nil, err
}
result[index+offset] = uint8(v)
}
return result, nil
}
// Reverse reverses a hex string
func Reverse(s string) string {
s = StripPrefix(s)
regex := regexp.MustCompile(`.{1,2}`)
in := regex.FindAllString(s, -1)
var out []string
for i := range in {
v := in[len(in)-1-i]
out = append(out, v)
}
return strings.Join(out, "")
} | util/hexutil/hexutil.go | 0.823186 | 0.45181 | hexutil.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric
type UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric struct {
Entity
// The percentage of devices for which OS check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
osCheckFailedPercentage *float64
// The percentage of devices for which processor hardware 64-bit architecture check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
processor64BitCheckFailedPercentage *float64
// The percentage of devices for which processor hardware core count check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
processorCoreCountCheckFailedPercentage *float64
// The percentage of devices for which processor hardware family check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
processorFamilyCheckFailedPercentage *float64
// The percentage of devices for which processor hardware speed check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
processorSpeedCheckFailedPercentage *float64
// The percentage of devices for which RAM hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
ramCheckFailedPercentage *float64
// The percentage of devices for which secure boot hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
secureBootCheckFailedPercentage *float64
// The percentage of devices for which storage hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
storageCheckFailedPercentage *float64
// The count of total devices in an organization. Valid values -2147483648 to 2147483647
totalDeviceCount *int32
// The percentage of devices for which Trusted Platform Module (TPM) hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
tpmCheckFailedPercentage *float64
// The count of devices in an organization eligible for windows upgrade. Valid values -2147483648 to 2147483647
upgradeEligibleDeviceCount *int32
}
// NewUserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric instantiates a new userExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric and sets the default values.
func NewUserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric()(*UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) {
m := &UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric{
Entity: *NewEntity(),
}
return m
}
// CreateUserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetricFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateUserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetricFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewUserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric(), nil
}
// GetFieldDeserializers the deserialization information for the current model
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["osCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetOsCheckFailedPercentage(val)
}
return nil
}
res["processor64BitCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetProcessor64BitCheckFailedPercentage(val)
}
return nil
}
res["processorCoreCountCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetProcessorCoreCountCheckFailedPercentage(val)
}
return nil
}
res["processorFamilyCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetProcessorFamilyCheckFailedPercentage(val)
}
return nil
}
res["processorSpeedCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetProcessorSpeedCheckFailedPercentage(val)
}
return nil
}
res["ramCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetRamCheckFailedPercentage(val)
}
return nil
}
res["secureBootCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetSecureBootCheckFailedPercentage(val)
}
return nil
}
res["storageCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetStorageCheckFailedPercentage(val)
}
return nil
}
res["totalDeviceCount"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetTotalDeviceCount(val)
}
return nil
}
res["tpmCheckFailedPercentage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetFloat64Value()
if err != nil {
return err
}
if val != nil {
m.SetTpmCheckFailedPercentage(val)
}
return nil
}
res["upgradeEligibleDeviceCount"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetUpgradeEligibleDeviceCount(val)
}
return nil
}
return res
}
// GetOsCheckFailedPercentage gets the osCheckFailedPercentage property value. The percentage of devices for which OS check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetOsCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.osCheckFailedPercentage
}
}
// GetProcessor64BitCheckFailedPercentage gets the processor64BitCheckFailedPercentage property value. The percentage of devices for which processor hardware 64-bit architecture check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetProcessor64BitCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.processor64BitCheckFailedPercentage
}
}
// GetProcessorCoreCountCheckFailedPercentage gets the processorCoreCountCheckFailedPercentage property value. The percentage of devices for which processor hardware core count check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetProcessorCoreCountCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.processorCoreCountCheckFailedPercentage
}
}
// GetProcessorFamilyCheckFailedPercentage gets the processorFamilyCheckFailedPercentage property value. The percentage of devices for which processor hardware family check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetProcessorFamilyCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.processorFamilyCheckFailedPercentage
}
}
// GetProcessorSpeedCheckFailedPercentage gets the processorSpeedCheckFailedPercentage property value. The percentage of devices for which processor hardware speed check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetProcessorSpeedCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.processorSpeedCheckFailedPercentage
}
}
// GetRamCheckFailedPercentage gets the ramCheckFailedPercentage property value. The percentage of devices for which RAM hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetRamCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.ramCheckFailedPercentage
}
}
// GetSecureBootCheckFailedPercentage gets the secureBootCheckFailedPercentage property value. The percentage of devices for which secure boot hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetSecureBootCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.secureBootCheckFailedPercentage
}
}
// GetStorageCheckFailedPercentage gets the storageCheckFailedPercentage property value. The percentage of devices for which storage hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetStorageCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.storageCheckFailedPercentage
}
}
// GetTotalDeviceCount gets the totalDeviceCount property value. The count of total devices in an organization. Valid values -2147483648 to 2147483647
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetTotalDeviceCount()(*int32) {
if m == nil {
return nil
} else {
return m.totalDeviceCount
}
}
// GetTpmCheckFailedPercentage gets the tpmCheckFailedPercentage property value. The percentage of devices for which Trusted Platform Module (TPM) hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetTpmCheckFailedPercentage()(*float64) {
if m == nil {
return nil
} else {
return m.tpmCheckFailedPercentage
}
}
// GetUpgradeEligibleDeviceCount gets the upgradeEligibleDeviceCount property value. The count of devices in an organization eligible for windows upgrade. Valid values -2147483648 to 2147483647
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) GetUpgradeEligibleDeviceCount()(*int32) {
if m == nil {
return nil
} else {
return m.upgradeEligibleDeviceCount
}
}
// Serialize serializes information the current object
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteFloat64Value("osCheckFailedPercentage", m.GetOsCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("processor64BitCheckFailedPercentage", m.GetProcessor64BitCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("processorCoreCountCheckFailedPercentage", m.GetProcessorCoreCountCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("processorFamilyCheckFailedPercentage", m.GetProcessorFamilyCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("processorSpeedCheckFailedPercentage", m.GetProcessorSpeedCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("ramCheckFailedPercentage", m.GetRamCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("secureBootCheckFailedPercentage", m.GetSecureBootCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("storageCheckFailedPercentage", m.GetStorageCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("totalDeviceCount", m.GetTotalDeviceCount())
if err != nil {
return err
}
}
{
err = writer.WriteFloat64Value("tpmCheckFailedPercentage", m.GetTpmCheckFailedPercentage())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("upgradeEligibleDeviceCount", m.GetUpgradeEligibleDeviceCount())
if err != nil {
return err
}
}
return nil
}
// SetOsCheckFailedPercentage sets the osCheckFailedPercentage property value. The percentage of devices for which OS check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetOsCheckFailedPercentage(value *float64)() {
if m != nil {
m.osCheckFailedPercentage = value
}
}
// SetProcessor64BitCheckFailedPercentage sets the processor64BitCheckFailedPercentage property value. The percentage of devices for which processor hardware 64-bit architecture check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetProcessor64BitCheckFailedPercentage(value *float64)() {
if m != nil {
m.processor64BitCheckFailedPercentage = value
}
}
// SetProcessorCoreCountCheckFailedPercentage sets the processorCoreCountCheckFailedPercentage property value. The percentage of devices for which processor hardware core count check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetProcessorCoreCountCheckFailedPercentage(value *float64)() {
if m != nil {
m.processorCoreCountCheckFailedPercentage = value
}
}
// SetProcessorFamilyCheckFailedPercentage sets the processorFamilyCheckFailedPercentage property value. The percentage of devices for which processor hardware family check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetProcessorFamilyCheckFailedPercentage(value *float64)() {
if m != nil {
m.processorFamilyCheckFailedPercentage = value
}
}
// SetProcessorSpeedCheckFailedPercentage sets the processorSpeedCheckFailedPercentage property value. The percentage of devices for which processor hardware speed check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetProcessorSpeedCheckFailedPercentage(value *float64)() {
if m != nil {
m.processorSpeedCheckFailedPercentage = value
}
}
// SetRamCheckFailedPercentage sets the ramCheckFailedPercentage property value. The percentage of devices for which RAM hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetRamCheckFailedPercentage(value *float64)() {
if m != nil {
m.ramCheckFailedPercentage = value
}
}
// SetSecureBootCheckFailedPercentage sets the secureBootCheckFailedPercentage property value. The percentage of devices for which secure boot hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetSecureBootCheckFailedPercentage(value *float64)() {
if m != nil {
m.secureBootCheckFailedPercentage = value
}
}
// SetStorageCheckFailedPercentage sets the storageCheckFailedPercentage property value. The percentage of devices for which storage hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetStorageCheckFailedPercentage(value *float64)() {
if m != nil {
m.storageCheckFailedPercentage = value
}
}
// SetTotalDeviceCount sets the totalDeviceCount property value. The count of total devices in an organization. Valid values -2147483648 to 2147483647
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetTotalDeviceCount(value *int32)() {
if m != nil {
m.totalDeviceCount = value
}
}
// SetTpmCheckFailedPercentage sets the tpmCheckFailedPercentage property value. The percentage of devices for which Trusted Platform Module (TPM) hardware check has failed. Valid values -1.79769313486232E+308 to 1.79769313486232E+308
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetTpmCheckFailedPercentage(value *float64)() {
if m != nil {
m.tpmCheckFailedPercentage = value
}
}
// SetUpgradeEligibleDeviceCount sets the upgradeEligibleDeviceCount property value. The count of devices in an organization eligible for windows upgrade. Valid values -2147483648 to 2147483647
func (m *UserExperienceAnalyticsWorkFromAnywhereHardwareReadinessMetric) SetUpgradeEligibleDeviceCount(value *int32)() {
if m != nil {
m.upgradeEligibleDeviceCount = value
}
} | models/user_experience_analytics_work_from_anywhere_hardware_readiness_metric.go | 0.654784 | 0.442034 | user_experience_analytics_work_from_anywhere_hardware_readiness_metric.go | starcoder |
package gofromto
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
)
//go:generate go run ./conversions/generate.go
// Measure holds the information on the amount and unit of a measure and allows conversions
type Measure struct {
Amount float64
Unit Unit
Name string
Imprecise bool
}
// NewMeasure creates a new Measure
func NewMeasure(amount float64, u Unit, name string) Measure {
return Measure{amount, u, name, false}
}
// measureMatcher a regular expression to parse a string into components suitable for turning into a Measure
var measureMatcher = regexp.MustCompile(`^(\d+(?:\.\d+)?)\s*(?:(\d+)/(\d+))?\s*(\w+)\s*(.*)$`)
// ParseMeasure parse a string and return a Measure
func ParseMeasure(measureString string) (Measure, error) {
matched := measureMatcher.FindStringSubmatch(strings.TrimSpace(measureString))
var measure Measure
if len(matched) < 6 {
return measure, errors.New("measure in unknown format")
}
amount, err := strconv.ParseFloat(matched[1], 64)
if err != nil {
return measure, errors.New("unable to parse amount")
}
numerator, err1 := strconv.ParseFloat(matched[2], 64)
denominator, err2 := strconv.ParseFloat(matched[3], 64)
if err1 == nil && err2 == nil && denominator > 0 {
amount = amount + numerator/denominator
}
for unit, symbol := range UnitSymbol {
if symbol == matched[4] {
return Measure{amount, unit, matched[5], false}, nil
}
}
for unit, name := range UnitName {
if name == matched[4] {
return Measure{amount, unit, matched[5], false}, nil
}
}
return measure, fmt.Errorf("unknown unit %v", matched[4])
}
// To converts the current measure to the given unit and returns a new Measure with the result
func (m Measure) To(targetUnit Unit) (Measure, error) {
if m.Unit == targetUnit {
return m, nil
}
if toMap, prs := ConversionMap[m.Unit]; prs {
if toConversion, prs := toMap[targetUnit]; prs {
return Measure{toConversion.Conversion(m.Amount), targetUnit, m.Name, m.Imprecise || !toConversion.Precise}, nil
}
}
var measure Measure
return measure, errors.New("no conversion found")
}
// Nice returns a copy in a related unit providing a nicer number
func (m Measure) Nice() Measure {
groupings := append(MetricGroupings, ImperialGroupings...)
var foundGrouping []Unit
for _, grouping := range groupings {
for _, unit := range grouping {
if unit == m.Unit {
foundGrouping = grouping
break
}
}
if foundGrouping != nil {
break
}
}
if foundGrouping == nil {
mCopy := m
return mCopy
}
var newMeasure Measure
for _, unit := range foundGrouping {
measure, err := m.To(unit)
if err != nil {
continue
}
if measure.Amount >= 1 && (newMeasure == Measure{} || measure.Amount < newMeasure.Amount) {
newMeasure = measure
}
}
return newMeasure
}
// AmountString returns a human-readable string of the amount only
func (m Measure) AmountString() string {
numerator, denominator := FloatToFraction(m.Amount)
if numerator > 0 {
if m.Amount < 1 {
return fmt.Sprintf("%d/%d", numerator, denominator)
}
return fmt.Sprintf("%.0f %d/%d", m.Amount, numerator, denominator)
}
return fmt.Sprintf("%.0f", m.Amount)
}
// String returns a human-readable string of the measure
func (m Measure) String() string {
return strings.TrimSpace(m.AmountString() + m.Unit.Symbol() + " " + m.Name)
} | measure.go | 0.760473 | 0.567218 | measure.go | starcoder |
package asserts
import (
"Tiny-Godis/interface/redis"
"Tiny-Godis/lib/utils"
"Tiny-Godis/redis/reply"
"fmt"
"runtime"
"testing"
)
// AssertIntReply checks if the given redis.Reply is the expected integer
func AssertIntReply(t *testing.T, actual redis.Reply, expected int) {
intResult, ok := actual.(*reply.IntReply)
if !ok {
t.Errorf("expected int reply, actually %s, %s", actual.ToBytes(), printStack())
return
}
if intResult.Code != int64(expected) {
t.Errorf("expected %d, actually %d, %s", expected, intResult.Code, printStack())
}
}
// AssertBulkReply checks if the given redis.Reply is the expected string
func AssertBulkReply(t *testing.T, actual redis.Reply, expected string) {
bulkReply, ok := actual.(*reply.BulkReply)
if !ok {
t.Errorf("expected bulk reply, actually %s, %s", actual.ToBytes(), printStack())
return
}
if !utils.BytesEquals(bulkReply.Arg, []byte(expected)) {
t.Errorf("expected %s, actually %s, %s", expected, actual.ToBytes(), printStack())
}
}
// AssertStatusReply checks if the given redis.Reply is the expected status
func AssertStatusReply(t *testing.T, actual redis.Reply, expected string) {
statusReply, ok := actual.(*reply.StatusReply)
if !ok {
// may be a reply.OkReply e.g.
expectBytes := reply.MakeStatusReply(expected).ToBytes()
if utils.BytesEquals(actual.ToBytes(), expectBytes) {
return
}
t.Errorf("expected bulk reply, actually %s, %s", actual.ToBytes(), printStack())
return
}
if statusReply.Status != expected {
t.Errorf("expected %s, actually %s, %s", expected, actual.ToBytes(), printStack())
}
}
// AssertErrReply checks if the given redis.Reply is the expected error
func AssertErrReply(t *testing.T, actual redis.Reply, expected string) {
errReply, ok := actual.(reply.ErrorReply)
if !ok {
expectBytes := reply.MakeErrReply(expected).ToBytes()
if utils.BytesEquals(actual.ToBytes(), expectBytes) {
return
}
t.Errorf("expected err reply, actually %s, %s", actual.ToBytes(), printStack())
return
}
if errReply.Error() != expected {
t.Errorf("expected %s, actually %s, %s", expected, actual.ToBytes(), printStack())
}
}
// AssertNotError checks if the given redis.Reply is not error reply
func AssertNotError(t *testing.T, result redis.Reply) {
if result == nil {
t.Errorf("result is nil %s", printStack())
return
}
bytes := result.ToBytes()
if len(bytes) == 0 {
t.Errorf("result is empty %s", printStack())
return
}
if bytes[0] == '-' {
t.Errorf("result is err reply %s", printStack())
}
}
// AssertNullBulk checks if the given redis.Reply is reply.NullBulkReply
func AssertNullBulk(t *testing.T, result redis.Reply) {
if result == nil {
t.Errorf("result is nil %s", printStack())
return
}
bytes := result.ToBytes()
if len(bytes) == 0 {
t.Errorf("result is empty %s", printStack())
return
}
expect := (&reply.NullBulkReply{}).ToBytes()
if !utils.BytesEquals(expect, bytes) {
t.Errorf("result is not null-bulk-reply %s", printStack())
}
}
// AssertMultiBulkReply checks if the given redis.Reply has the expected content
func AssertMultiBulkReply(t *testing.T, actual redis.Reply, expected []string) {
multiBulk, ok := actual.(*reply.MultiBulkReply)
if !ok {
t.Errorf("expected bulk reply, actually %s, %s", actual.ToBytes(), printStack())
return
}
if len(multiBulk.Args) != len(expected) {
t.Errorf("expected %d elements, actually %d, %s",
len(expected), len(multiBulk.Args), printStack())
return
}
for i, v := range multiBulk.Args {
str := string(v)
if str != expected[i] {
t.Errorf("expected %s, actually %s, %s", expected[i], actual, printStack())
}
}
}
// AssertMultiBulkReplySize check if redis.Reply has expected length
func AssertMultiBulkReplySize(t *testing.T, actual redis.Reply, expected int) {
multiBulk, ok := actual.(*reply.MultiBulkReply)
if !ok {
if expected == 0 &&
utils.BytesEquals(actual.ToBytes(), reply.MakeEmptyMultiBulkReply().ToBytes()) {
return
}
t.Errorf("expected bulk reply, actually %s, %s", actual.ToBytes(), printStack())
return
}
if len(multiBulk.Args) != expected {
t.Errorf("expected %d elements, actually %d, %s", expected, len(multiBulk.Args), printStack())
return
}
}
func printStack() string {
_, file, no, ok := runtime.Caller(2)
if ok {
return fmt.Sprintf("at %s#%d", file, no)
}
return ""
} | redis/reply/asserts/assert.go | 0.606149 | 0.542318 | assert.go | starcoder |
package main
import (
"math"
"math/rand"
)
const deg = math.Pi / 180
type measurement []float64 // A magnetometer measurement like [m1, m2, m3]
type direction []float64 // Angles pointing in a direction like [theta, phi], in degrees
type measurer func(a direction) (m measurement)
// makeRandomMeasurer creates a function that returns a new measurement of m, the magnetometer measurement.
// Inputs:
// n: number of dimensions (1, 2, or 3)
// n0: Earth's magnetic field (1.0 is fine for testing)
// k: n-vector of the scaling factors
// l: n-vector of the additive factors
// r: noise level
// equation is n = k*(m-l)
// The returned function takes a rough measurement just to satisfy the interface, but doesn't use it.
func makeRandomMeasurer(n int, n0 float64, k, l []float64, r float64) (m measurer, err error) {
var theta, phi float64
if n == 1 {
return func(a direction) (m measurement) {
theta = 360 * deg * (rand.Float64() - 0.5)
if theta < 0 {
return measurement{-n0/k[0] + l[0] + r*rand.NormFloat64()}
}
return measurement{n0/k[0] + l[0] + r*rand.NormFloat64()}
}, nil
}
if n == 2 {
const w = 0.01
var (
theta = 0.0
rot = 5 * deg
)
return func(a direction) (m measurement) {
rot = (1-w)*rot + w*5*deg*2*(rand.Float64()-0.5)
if rand.Float64() < w {
if rand.Float64() < 0.5 {
rot += 5 * deg
} else {
rot -= 5 * deg
}
}
theta += rot
nx := n0 * math.Cos(theta)
ny := n0 * math.Sin(theta)
return measurement{
nx/k[0] + l[0] + r*rand.NormFloat64(),
ny/k[1] + l[1] + r*rand.NormFloat64(),
}
}, nil
}
return func(a direction) (m measurement) {
phi = 2 * math.Pi * (rand.Float64() - 0.5)
theta = math.Asin(2*rand.Float64() - 1)
nx := n0 * math.Cos(phi) * math.Cos(theta)
ny := n0 * math.Sin(phi) * math.Cos(theta)
nz := n0 * math.Sin(theta)
return measurement{
nx/k[0] + l[0] + r*rand.NormFloat64(),
ny/k[1] + l[1] + r*rand.NormFloat64(),
nz/k[2] + l[2] + r*rand.NormFloat64(),
}
}, nil
}
// makeManualMeasurer creates a function that returns a new measurement of m, the magnetometer measurement.
// Inputs:
// n: number of dimensions (1, 2, or 3)
// n0: Earth's magnetic field (1.0 is fine for testing)
// k: n-vector of the scaling factors
// l: n-vector of the additive factors
// r: noise level
// equation is n = k*(m-l)
// The returned function takes a rough measurement and computes the corresponding angles, then computes
// a corrected measurement including noise.
func makeManualMeasurer(n int, n0 float64, k, l []float64, r float64) (m measurer, err error) {
if n == 1 {
return func(a direction) (m measurement) {
var theta float64
if a != nil && len(a) >= 1 {
theta = a[0] * deg
} else {
theta = 2 * math.Pi * rand.Float64()
}
if theta > math.Pi/2 && theta < 3*math.Pi/2 {
return []float64{-n0/k[0] + l[0] + r*rand.NormFloat64()}
}
return []float64{n0/k[0] + l[0] + r*rand.NormFloat64()}
}, nil
}
if n == 2 {
return func(a direction) (m measurement) {
var theta float64
if a != nil && len(a) >= 1 {
theta = a[0] * math.Pi / 180
} else {
theta = 2 * math.Pi * rand.Float64()
}
nx := n0 * math.Cos(theta)
ny := n0 * math.Sin(theta)
return []float64{
nx/k[0] + l[0] + r*rand.NormFloat64(),
ny/k[1] + l[1] + r*rand.NormFloat64(),
}
}, nil
}
return func(a direction) (m measurement) {
var theta, phi float64
if a != nil && len(a) >= 2 {
theta = a[0] * math.Pi / 180
phi = a[1] * math.Pi / 180
} else {
theta = 2 * math.Pi * rand.Float64()
phi = math.Acos(2*rand.Float64() - 1)
}
nx := n0 * math.Cos(theta) * math.Cos(phi)
ny := n0 * math.Sin(theta) * math.Cos(phi)
nz := n0 * math.Sin(phi)
return []float64{
nx/k[0] + l[0] + r*rand.NormFloat64(),
ny/k[1] + l[1] + r*rand.NormFloat64(),
nz/k[2] + l[2] + r*rand.NormFloat64(),
}
}, nil
}
// makeActualMeasurer creates a function that returns a new measurement of m, the magnetometer measurement.
// Inputs:
// r: noise level
// The returned function takes a rough measurement just to satisfy the interface, but doesn't use it.
/*
func makeActualMeasurer() (m measurer, err error) {
mpu, err := mpu9250.NewMPU9250(nil, 0, 250, 4, 50, true, false)
if err != nil {
return nil, err
}
// defer mpu.CloseMPU() // This really should be closed. Move into goroutine.
var data *sensors.IMUData
return func(a direction) (m measurement) {
data = <-mpu.C
return []float64{data.M1, data.M2, data.M3}
}, nil
}
*/ | cmd/websim/measurer.go | 0.73678 | 0.75158 | measurer.go | starcoder |
package assertjson
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"github.com/bool64/shared"
"github.com/stretchr/testify/assert"
"github.com/yudai/gojsondiff"
"github.com/yudai/gojsondiff/formatter"
)
// Comparer compares JSON documents.
type Comparer struct {
// IgnoreDiff is a value in expected document to ignore difference with actual document.
IgnoreDiff string
// Vars keeps state of found variables.
Vars *shared.Vars
// FormatterConfig controls diff formatter configuration.
FormatterConfig formatter.AsciiFormatterConfig
// KeepFullDiff shows full diff in error message.
KeepFullDiff bool
// FullDiffMaxLines is a maximum number of lines to show without reductions, default 50.
// Ignored if KeepFullDiff is true.
FullDiffMaxLines int
// DiffSurroundingLines is a number of lines to add before and after diff line, default 5.
// Ignored if KeepFullDiff is true.
DiffSurroundingLines int
}
// IgnoreDiff is a marker to ignore difference in JSON.
const IgnoreDiff = "<ignore-diff>"
var defaultComparer = Comparer{
IgnoreDiff: IgnoreDiff,
}
// TestingT is an interface wrapper around *testing.T.
type TestingT interface {
Errorf(format string, args ...interface{})
}
type tHelper interface {
Helper()
}
// Equal compares two JSON documents ignoring string values "<ignore-diff>".
func Equal(t TestingT, expected, actual []byte, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return defaultComparer.Equal(t, expected, actual, msgAndArgs...)
}
// EqualMarshal marshals actual value and compares two JSON documents ignoring string values "<ignore-diff>".
func EqualMarshal(t TestingT, expected []byte, actualValue interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return defaultComparer.EqualMarshal(t, expected, actualValue, msgAndArgs...)
}
// Equal compares two JSON payloads.
func (c Comparer) Equal(t TestingT, expected, actual []byte, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
err := c.FailNotEqual(expected, actual)
if err == nil {
return true
}
msg := err.Error()
msg = strings.ToUpper(msg[0:1]) + msg[1:]
assert.Fail(t, msg, msgAndArgs...)
return false
}
// EqualMarshal marshals actual JSON payload and compares it with expected payload.
func (c Comparer) EqualMarshal(t TestingT, expected []byte, actualValue interface{}, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
actual, err := MarshalIndentCompact(actualValue, "", " ", 80)
assert.NoError(t, err, "failed to marshal actual value")
if len(msgAndArgs) == 0 {
msgAndArgs = append(msgAndArgs, string(actual))
}
return c.Equal(t, expected, actual, msgAndArgs...)
}
func (c Comparer) varCollected(s string, v interface{}) bool {
if c.Vars != nil && c.Vars.IsVar(s) {
if _, found := c.Vars.Get(s); !found {
if f, ok := v.(float64); ok && f == float64(int64(f)) {
v = int64(f)
}
c.Vars.Set(s, v)
return true
}
}
return false
}
func (c Comparer) filterDeltas(deltas []gojsondiff.Delta) []gojsondiff.Delta {
result := make([]gojsondiff.Delta, 0, len(deltas))
for _, delta := range deltas {
switch v := delta.(type) {
case *gojsondiff.Modified:
if c.IgnoreDiff == "" && c.Vars == nil {
break
}
if s, ok := v.OldValue.(string); ok {
if s == c.IgnoreDiff { // discarding ignored diff
continue
}
if c.varCollected(s, v.NewValue) {
continue
}
}
case *gojsondiff.Object:
v.Deltas = c.filterDeltas(v.Deltas)
if len(v.Deltas) == 0 {
continue
}
delta = v
case *gojsondiff.Array:
v.Deltas = c.filterDeltas(v.Deltas)
if len(v.Deltas) == 0 {
continue
}
delta = v
}
result = append(result, delta)
}
return result
}
type diff struct {
deltas []gojsondiff.Delta
}
func (diff *diff) Deltas() []gojsondiff.Delta {
return diff.deltas
}
func (diff *diff) Modified() bool {
return len(diff.deltas) > 0
}
// FailNotEqual returns error if JSON payloads are different, nil otherwise.
func FailNotEqual(expected, actual []byte) error {
return defaultComparer.FailNotEqual(expected, actual)
}
func (c Comparer) filterExpected(expected []byte) ([]byte, error) {
if c.Vars != nil {
for k, v := range c.Vars.GetAll() {
j, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("failed to marshal var %s: %v", k, err) // Not wrapping to support go1.12.
}
expected = bytes.Replace(expected, []byte(`"`+k+`"`), j, -1) // nolint:gocritic // To support go1.11.
}
}
return expected, nil
}
func (c Comparer) compare(expDecoded, actDecoded interface{}) (gojsondiff.Diff, error) {
switch v := expDecoded.(type) {
case []interface{}:
if actArray, ok := actDecoded.([]interface{}); ok {
return gojsondiff.New().CompareArrays(v, actArray), nil
}
return nil, errors.New("types mismatch, array expected")
case map[string]interface{}:
if actObject, ok := actDecoded.(map[string]interface{}); ok {
return gojsondiff.New().CompareObjects(v, actObject), nil
}
return nil, errors.New("types mismatch, object expected")
default:
if !reflect.DeepEqual(expDecoded, actDecoded) { // scalar value comparison
return nil, fmt.Errorf("values %v and %v are not equal", expDecoded, actDecoded)
}
}
return nil, nil
}
// FailNotEqual returns error if JSON payloads are different, nil otherwise.
func (c Comparer) FailNotEqual(expected, actual []byte) error {
var expDecoded, actDecoded interface{}
expected, err := c.filterExpected(expected)
if err != nil {
return err
}
err = json.Unmarshal(expected, &expDecoded)
if err != nil {
return fmt.Errorf("failed to unmarshal expected:\n%+v", err)
}
err = json.Unmarshal(actual, &actDecoded)
if err != nil {
return fmt.Errorf("failed to unmarshal actual:\n%+v", err)
}
if s, ok := expDecoded.(string); ok && c.Vars != nil && c.Vars.IsVar(s) {
if c.varCollected(s, actDecoded) {
return nil
}
if v, found := c.Vars.Get(s); found {
expDecoded = v
}
}
diffValue, err := c.compare(expDecoded, actDecoded)
if err != nil {
return err
}
if diffValue == nil {
return nil
}
if !diffValue.Modified() {
return nil
}
diffValue = &diff{deltas: c.filterDeltas(diffValue.Deltas())}
if !diffValue.Modified() {
return nil
}
diffText, err := formatter.NewAsciiFormatter(expDecoded, c.FormatterConfig).Format(diffValue)
if err != nil {
return fmt.Errorf("failed to format diff:\n%+v", err)
}
diffText = c.reduceDiff(diffText)
return errors.New("not equal:\n" + diffText)
}
func (c Comparer) reduceDiff(diffText string) string {
if c.KeepFullDiff {
return diffText
}
if c.FullDiffMaxLines == 0 {
c.FullDiffMaxLines = 50
}
if c.DiffSurroundingLines == 0 {
c.DiffSurroundingLines = 5
}
diffRows := strings.Split(diffText, "\n")
if len(diffRows) <= c.FullDiffMaxLines {
return diffText
}
var result []string
prev := 0
for i, r := range diffRows {
if len(r) == 0 {
continue
}
if r[0] == '-' || r[0] == '+' {
start := i - c.DiffSurroundingLines
if start < prev {
start = prev
} else if start > prev {
result = append(result, "...")
}
end := i + c.DiffSurroundingLines
if end >= len(diffRows) {
end = len(diffRows) - 1
}
prev = end
for k := start; k < end; k++ {
result = append(result, diffRows[k])
}
}
}
if prev < len(diffRows)-1 {
result = append(result, "...")
}
return strings.Join(result, "\n")
} | equal.go | 0.71113 | 0.487429 | equal.go | starcoder |
package crf
import (
"github.com/nlpodyssey/spago/ag"
"github.com/nlpodyssey/spago/mat"
)
// ViterbiStructure implements Viterbi decoding.
type ViterbiStructure[T mat.DType] struct {
scores mat.Matrix[T]
backpointers []int
}
// NewViterbiStructure returns a new ViterbiStructure ready to use.
func NewViterbiStructure[T mat.DType](size int) *ViterbiStructure[T] {
return &ViterbiStructure[T]{
scores: mat.NewInitVecDense(size, mat.Inf[T](-1)),
backpointers: make([]int, size),
}
}
// Viterbi decodes the xs sequence according to the transitionMatrix.
func Viterbi[T mat.DType](transitionMatrix mat.Matrix[T], xs []ag.Node[T]) []int {
alpha := make([]*ViterbiStructure[T], len(xs)+1)
alpha[0] = viterbiStepStart(transitionMatrix, xs[0].Value())
for i := 1; i < len(xs); i++ {
alpha[i] = viterbiStep(transitionMatrix, alpha[i-1].scores, xs[i].Value())
}
alpha[len(xs)] = viterbiStepEnd(transitionMatrix, alpha[len(xs)-1].scores)
ys := make([]int, len(xs))
ys[len(xs)-1] = alpha[len(xs)].scores.ArgMax()
for i := len(xs) - 2; i >= 0; i-- {
ys[i] = alpha[i+1].backpointers[ys[i+1]]
}
return ys
}
func viterbiStepStart[T mat.DType](transitionMatrix, maxVec mat.Matrix[T]) *ViterbiStructure[T] {
y := NewViterbiStructure[T](transitionMatrix.Rows() - 1)
for i := 0; i < transitionMatrix.Rows()-1; i++ {
score := maxVec.At(i, 0) + transitionMatrix.At(0, i+1)
if score > y.scores.At(i, 0) {
y.scores.SetVec(i, score)
y.backpointers[i] = i
}
}
return y
}
func viterbiStepEnd[T mat.DType](transitionMatrix, maxVec mat.Matrix[T]) *ViterbiStructure[T] {
y := NewViterbiStructure[T](transitionMatrix.Rows() - 1)
for i := 0; i < transitionMatrix.Rows()-1; i++ {
score := maxVec.At(i, 0) + transitionMatrix.At(i+1, 0)
if score > y.scores.At(i, 0) {
y.scores.SetVec(i, score)
y.backpointers[i] = i
}
}
return y
}
func viterbiStep[T mat.DType](transitionMatrix, maxVec, stepVec mat.Matrix[T]) *ViterbiStructure[T] {
y := NewViterbiStructure[T](transitionMatrix.Rows() - 1)
for i := 0; i < transitionMatrix.Rows()-1; i++ {
for j := 0; j < transitionMatrix.Columns()-1; j++ {
score := maxVec.At(i, 0) + stepVec.At(j, 0) + transitionMatrix.At(i+1, j+1)
if score > y.scores.At(j, 0) {
y.scores.SetVec(j, score)
y.backpointers[j] = i
}
}
}
return y
} | nn/crf/viterbi.go | 0.747616 | 0.555435 | viterbi.go | starcoder |
package column
import (
"bytes"
"encoding/binary"
"strconv"
"strings"
"github.com/RoaringBitmap/roaring"
"github.com/bytehouse-cloud/driver-go/driver/lib/bytepool"
"github.com/bytehouse-cloud/driver-go/driver/lib/ch_encoding"
)
var bitmapZeroValue = []uint64{}
// BitMapColumnData
// Data representation is an uint64 array
type BitMapColumnData struct {
raw [][]byte
}
func (b *BitMapColumnData) ReadFromValues(values []interface{}) (int, error) {
var (
value64 uint64
err error
row []uint64
ok bool
)
valueBuf := new(bytes.Buffer)
for idx, value := range values {
row, ok = value.([]uint64)
if !ok {
return idx, NewErrInvalidColumnType(value, row)
}
// 1. Make keymap
keymap := make(map[uint32][]uint32)
for _, value64 = range row {
high := uint32(value64 >> 32)
low := uint32(value64)
_, exist := keymap[high]
if !exist {
keymap[high] = []uint32{}
}
keymap[high] = append(keymap[high], low)
}
// 2. Write size of keymap
mapSize := uint64(len(keymap))
// a. Allocate space for b.raw[idx]
// length = uint64ByteSize initially to allow allocation of mapSize
// cap = 8 bytes + 4 bytes * number of keys + size of values (max = 4 bytes * len(texts))
b.raw[idx] = make([]byte, uint64ByteSize, uint64ByteSize+uint32ByteSize*len(keymap)+uint32ByteSize*len(values))
binary.LittleEndian.PutUint64(b.raw[idx], mapSize)
// 3. Write key and values
for key, v := range keymap {
// a. Write key
// Grow raw[idx].len by 4 bytes to allow assignment of key
b.raw[idx] = append(b.raw[idx], 0, 0, 0, 0)
binary.LittleEndian.PutUint32(b.raw[idx][len(b.raw[idx])-4:], key)
// b. Push values in roaring bitmap form
if _, err = roaring.BitmapOf(v...).WriteTo(valueBuf); err != nil {
return idx, err
}
for _, byt := range valueBuf.Bytes() {
b.raw[idx] = append(b.raw[idx], byt)
}
valueBuf.Reset()
}
}
return len(values), nil
}
// ReadFromTexts reads from text and assigns to bitmap data
// Bitmap is represented as array of uint64
// E.g. [1, 3, 4]
func (b *BitMapColumnData) ReadFromTexts(texts []string) (int, error) {
var (
value64 uint64
err error
row []string // row is []uint64 in string representation
)
valueBuf := new(bytes.Buffer)
for idx, text := range texts {
if text == "" {
continue
}
if text, err = removeSquareBraces(text); err != nil {
return idx, err
}
// If array is empty skip
if strings.TrimSpace(text) == "" {
continue
}
row = splitIgnoreBraces(text, comma, row)
// 1. Make keymap
keymap := make(map[uint32][]uint32)
for _, value := range row {
if value64, err = strconv.ParseUint(value, 10, 64); err != nil {
return idx, NewErrInvalidColumnTypeCustomText("data should be []uint64")
}
high := uint32(value64 >> 32)
low := uint32(value64)
_, exist := keymap[high]
if !exist {
keymap[high] = []uint32{}
}
keymap[high] = append(keymap[high], low)
}
// 2. Write size of keymap
mapSize := uint64(len(keymap))
// a. Allocate space for b.raw[idx]
// length = uint64ByteSize initially to allow allocation of mapSize
// cap = 8 bytes + 4 bytes * number of keys + size of values (max = 4 bytes * len(texts))
b.raw[idx] = make([]byte, uint64ByteSize, uint64ByteSize+uint32ByteSize*len(keymap)+uint32ByteSize*len(texts))
binary.LittleEndian.PutUint64(b.raw[idx], mapSize)
// 3. Write key and values
for key, values := range keymap {
// a. Write key
// Grow raw[idx].len by 4 bytes to allow assignment of key
b.raw[idx] = append(b.raw[idx], 0, 0, 0, 0)
binary.LittleEndian.PutUint32(b.raw[idx][len(b.raw[idx])-4:], key)
// b. Push values in roaring bitmap form
if _, err = roaring.BitmapOf(values...).WriteTo(valueBuf); err != nil {
return idx, err
}
for _, byt := range valueBuf.Bytes() {
b.raw[idx] = append(b.raw[idx], byt)
}
valueBuf.Reset()
}
}
return len(texts), nil
}
// ReadFromDecoder populates data with value from decoder
func (b *BitMapColumnData) ReadFromDecoder(decoder *ch_encoding.Decoder) error {
for i := range b.raw {
// Get length of data bytes
length, err := decoder.Uvarint()
if err != nil {
return err
}
data := make([]byte, length)
if _, err = decoder.Read(data); err != nil {
return err
}
b.raw[i] = data
}
return nil
}
func (b *BitMapColumnData) WriteToEncoder(encoder *ch_encoding.Encoder) error {
var err error
for _, data := range b.raw {
// Push byte size
if err = encoder.Uvarint(uint64(len(data))); err != nil {
return err
}
// Push data
if _, err = encoder.Write(data); err != nil {
return err
}
}
return nil
}
func (b *BitMapColumnData) GetValue(row int) interface{} {
data := b.raw[row]
if data == nil || len(data) == 0 {
return bitmapZeroValue
}
// Bitmap size
rb := roaring.New()
mapSize := binary.LittleEndian.Uint64(data[:8])
// Actual data
dataBuf := bytes.NewBuffer(data[8:])
scratch := make([]byte, 4)
// Read indices - can add a capacity
var result []uint64
for i := uint64(0); i < mapSize; i++ {
if _, err := dataBuf.Read(scratch); err != nil {
return bitmapZeroValue
}
key := binary.LittleEndian.Uint32(scratch)
if _, err := rb.ReadFrom(dataBuf); err != nil {
return bitmapZeroValue
}
values := rb.ToArray()
rb.Clear()
for _, value := range values {
result = append(result, uint64(key)<<32|uint64(value))
}
}
return result
}
func (b *BitMapColumnData) GetString(row int) string {
var builder strings.Builder
array := b.GetValue(row).([]uint64)
builder.WriteByte(squareOpenBracket)
if len(array) > 0 {
builder.WriteString(strconv.Itoa(int(array[0])))
}
for i := 1; i < len(array); i++ {
builder.WriteString(listSeparator)
builder.WriteString(strconv.Itoa(int(array[i])))
}
builder.WriteByte(squareCloseBracket)
return builder.String()
}
func (b *BitMapColumnData) Zero() interface{} {
return bitmapZeroValue
}
func (b *BitMapColumnData) ZeroString() string {
return emptyArray
}
func (b *BitMapColumnData) Len() int {
return len(b.raw)
}
func (b *BitMapColumnData) Close() error {
for _, d := range b.raw {
bytepool.PutBytes(d)
}
return nil
} | driver/lib/data/column/bitmap.go | 0.606732 | 0.476032 | bitmap.go | starcoder |
package finnhub
import (
"encoding/json"
)
// ForexCandles struct for ForexCandles
type ForexCandles struct {
// List of open prices for returned candles.
O *[]float32 `json:"o,omitempty"`
// List of high prices for returned candles.
H *[]float32 `json:"h,omitempty"`
// List of low prices for returned candles.
L *[]float32 `json:"l,omitempty"`
// List of close prices for returned candles.
C *[]float32 `json:"c,omitempty"`
// List of volume data for returned candles.
V *[]float32 `json:"v,omitempty"`
// List of timestamp for returned candles.
T *[]float32 `json:"t,omitempty"`
// Status of the response. This field can either be ok or no_data.
S *string `json:"s,omitempty"`
}
// NewForexCandles instantiates a new ForexCandles object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewForexCandles() *ForexCandles {
this := ForexCandles{}
return &this
}
// NewForexCandlesWithDefaults instantiates a new ForexCandles object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewForexCandlesWithDefaults() *ForexCandles {
this := ForexCandles{}
return &this
}
// GetO returns the O field value if set, zero value otherwise.
func (o *ForexCandles) GetO() []float32 {
if o == nil || o.O == nil {
var ret []float32
return ret
}
return *o.O
}
// GetOOk returns a tuple with the O field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ForexCandles) GetOOk() (*[]float32, bool) {
if o == nil || o.O == nil {
return nil, false
}
return o.O, true
}
// HasO returns a boolean if a field has been set.
func (o *ForexCandles) HasO() bool {
if o != nil && o.O != nil {
return true
}
return false
}
// SetO gets a reference to the given []float32 and assigns it to the O field.
func (o *ForexCandles) SetO(v []float32) {
o.O = &v
}
// GetH returns the H field value if set, zero value otherwise.
func (o *ForexCandles) GetH() []float32 {
if o == nil || o.H == nil {
var ret []float32
return ret
}
return *o.H
}
// GetHOk returns a tuple with the H field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ForexCandles) GetHOk() (*[]float32, bool) {
if o == nil || o.H == nil {
return nil, false
}
return o.H, true
}
// HasH returns a boolean if a field has been set.
func (o *ForexCandles) HasH() bool {
if o != nil && o.H != nil {
return true
}
return false
}
// SetH gets a reference to the given []float32 and assigns it to the H field.
func (o *ForexCandles) SetH(v []float32) {
o.H = &v
}
// GetL returns the L field value if set, zero value otherwise.
func (o *ForexCandles) GetL() []float32 {
if o == nil || o.L == nil {
var ret []float32
return ret
}
return *o.L
}
// GetLOk returns a tuple with the L field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ForexCandles) GetLOk() (*[]float32, bool) {
if o == nil || o.L == nil {
return nil, false
}
return o.L, true
}
// HasL returns a boolean if a field has been set.
func (o *ForexCandles) HasL() bool {
if o != nil && o.L != nil {
return true
}
return false
}
// SetL gets a reference to the given []float32 and assigns it to the L field.
func (o *ForexCandles) SetL(v []float32) {
o.L = &v
}
// GetC returns the C field value if set, zero value otherwise.
func (o *ForexCandles) GetC() []float32 {
if o == nil || o.C == nil {
var ret []float32
return ret
}
return *o.C
}
// GetCOk returns a tuple with the C field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ForexCandles) GetCOk() (*[]float32, bool) {
if o == nil || o.C == nil {
return nil, false
}
return o.C, true
}
// HasC returns a boolean if a field has been set.
func (o *ForexCandles) HasC() bool {
if o != nil && o.C != nil {
return true
}
return false
}
// SetC gets a reference to the given []float32 and assigns it to the C field.
func (o *ForexCandles) SetC(v []float32) {
o.C = &v
}
// GetV returns the V field value if set, zero value otherwise.
func (o *ForexCandles) GetV() []float32 {
if o == nil || o.V == nil {
var ret []float32
return ret
}
return *o.V
}
// GetVOk returns a tuple with the V field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ForexCandles) GetVOk() (*[]float32, bool) {
if o == nil || o.V == nil {
return nil, false
}
return o.V, true
}
// HasV returns a boolean if a field has been set.
func (o *ForexCandles) HasV() bool {
if o != nil && o.V != nil {
return true
}
return false
}
// SetV gets a reference to the given []float32 and assigns it to the V field.
func (o *ForexCandles) SetV(v []float32) {
o.V = &v
}
// GetT returns the T field value if set, zero value otherwise.
func (o *ForexCandles) GetT() []float32 {
if o == nil || o.T == nil {
var ret []float32
return ret
}
return *o.T
}
// GetTOk returns a tuple with the T field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ForexCandles) GetTOk() (*[]float32, bool) {
if o == nil || o.T == nil {
return nil, false
}
return o.T, true
}
// HasT returns a boolean if a field has been set.
func (o *ForexCandles) HasT() bool {
if o != nil && o.T != nil {
return true
}
return false
}
// SetT gets a reference to the given []float32 and assigns it to the T field.
func (o *ForexCandles) SetT(v []float32) {
o.T = &v
}
// GetS returns the S field value if set, zero value otherwise.
func (o *ForexCandles) GetS() string {
if o == nil || o.S == nil {
var ret string
return ret
}
return *o.S
}
// GetSOk returns a tuple with the S field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *ForexCandles) GetSOk() (*string, bool) {
if o == nil || o.S == nil {
return nil, false
}
return o.S, true
}
// HasS returns a boolean if a field has been set.
func (o *ForexCandles) HasS() bool {
if o != nil && o.S != nil {
return true
}
return false
}
// SetS gets a reference to the given string and assigns it to the S field.
func (o *ForexCandles) SetS(v string) {
o.S = &v
}
func (o ForexCandles) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.O != nil {
toSerialize["o"] = o.O
}
if o.H != nil {
toSerialize["h"] = o.H
}
if o.L != nil {
toSerialize["l"] = o.L
}
if o.C != nil {
toSerialize["c"] = o.C
}
if o.V != nil {
toSerialize["v"] = o.V
}
if o.T != nil {
toSerialize["t"] = o.T
}
if o.S != nil {
toSerialize["s"] = o.S
}
return json.Marshal(toSerialize)
}
type NullableForexCandles struct {
value *ForexCandles
isSet bool
}
func (v NullableForexCandles) Get() *ForexCandles {
return v.value
}
func (v *NullableForexCandles) Set(val *ForexCandles) {
v.value = val
v.isSet = true
}
func (v NullableForexCandles) IsSet() bool {
return v.isSet
}
func (v *NullableForexCandles) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableForexCandles(val *ForexCandles) *NullableForexCandles {
return &NullableForexCandles{value: val, isSet: true}
}
func (v NullableForexCandles) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableForexCandles) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | model_forex_candles.go | 0.741112 | 0.500183 | model_forex_candles.go | starcoder |
package robot
import (
"errors"
"math"
)
// Robot contains the configuration and state of the delta robot
type Robot struct {
BaseRadius float64 `json:"BaseRadius"`
BicepLength float64 `json:"BicepLength"`
ForearmLength float64 `json:"ForearmLength"`
EndEffectorRadius float64 `json:"EndEffectorRadius"`
BaseToFloorDistance float64 `json:"BaseToFloorDistance"`
}
// Trigonometric constants
const (
sqrt3 = 1.73205080757
sin120 = sqrt3 / 2.0
cos120 = -0.5
tan60 = sqrt3
sin30 = 0.5
tan30 = 1.0 / sqrt3
dtr = math.Pi / 180.0
)
// Forward kinematics (theta1, theta2, theta3) -> (x, y, z, error)
// returns
func (r *Robot) Forward(theta1, theta2, theta3 float64) (float64, float64, float64, error) {
x0 := 0.0
y0 := 0.0
z0 := 0.0
t := (r.BaseRadius - r.EndEffectorRadius) * tan30 / 2.0
theta1 *= dtr
theta2 *= dtr
theta3 *= dtr
y1 := -(t + r.BicepLength*math.Cos(theta1))
z1 := -r.BicepLength * math.Sin(theta1)
y2 := (t + r.BicepLength*math.Cos(theta2)) * sin30
x2 := y2 * tan60
z2 := -r.BicepLength * math.Sin(theta2)
y3 := (t + r.BicepLength*math.Cos(theta3)) * sin30
x3 := -y3 * tan60
z3 := -r.BicepLength * math.Sin(theta3)
dnm := (y2-y1)*x3 - (y3-y1)*x2
w1 := y1*y1 + z1*z1
w2 := x2*x2 + y2*y2 + z2*z2
w3 := x3*x3 + y3*y3 + z3*z3
// x = (a1*z + b1)/dnm
a1 := (z2-z1)*(y3-y1) - (z3-z1)*(y2-y1)
b1 := -((w2-w1)*(y3-y1) - (w3-w1)*(y2-y1)) / 2.0
// y = (a2*z + b2)/dnm
a2 := -(z2-z1)*x3 + (z3-z1)*x2
b2 := ((w2-w1)*x3 - (w3-w1)*x2) / 2.0
// a*z^2 + b*z + c = 0
a := a1*a1 + a2*a2 + dnm*dnm
b := 2.0 * (a1*b1 + a2*(b2-y1*dnm) - z1*dnm*dnm)
c := (b2-y1*dnm)*(b2-y1*dnm) + b1*b1 + dnm*dnm*(z1*z1-r.ForearmLength*r.ForearmLength)
// discriminant
d := b*b - 4.0*a*c
if d < 0.0 {
return 0.0, 0.0, 0.0, errors.New("Invalid position")
}
z0 = -0.5 * (b + math.Sqrt(d)) / a
x0 = (a1*z0 + b1) / dnm
y0 = (a2*z0 + b2) / dnm
return x0, y0, z0, nil
}
// Inverse kinematics (x,y,z) -> (theta1, theta2, theta3)
func (r *Robot) Inverse(x, y, z float64) (float64, float64, float64, error) {
theta1, err := r.calcAngleYZ(x, y, z)
if err != nil {
return 0.0, 0.0, 0.0, err
}
theta2, err := r.calcAngleYZ((x*cos120)+(y*sin120), (y*cos120)-(x*sin120), z)
if err != nil {
return 0.0, 0.0, 0.0, err
}
theta3, err := r.calcAngleYZ((x*cos120)-(y*sin120), (y*cos120)+(x*sin120), z)
if err != nil {
return 0.0, 0.0, 0.0, err
}
return theta1, theta2, theta3, err
}
// helper function, calculates angle theta1 (for YZ-pane)
func (r *Robot) calcAngleYZ(x0, y0, z0 float64) (float64, error) {
y1 := -0.5 * tan30 * r.BaseRadius
y0 -= 0.5 * tan30 * r.EndEffectorRadius
// z = a + b*y
a := (x0*x0 + y0*y0 + z0*z0 + r.BicepLength*r.BicepLength - r.ForearmLength*r.ForearmLength - y1*y1) / (2.0 * z0)
b := (y1 - y0) / z0
// discriminant
d := -(a+b*y1)*(a+b*y1) + r.BicepLength*(b*b*r.BicepLength+r.BicepLength)
if d < 0 {
return 0.0, errors.New("Invalid position")
}
yj := (y1 - a*b - math.Sqrt(d)) / (b*b + 1)
zj := a + b*yj
theta := math.Atan(-zj/(y1-yj))*180.0/math.Pi + 0.0
if yj > y1 {
theta = math.Atan(-zj/(y1-yj))*180.0/math.Pi + 180.0
}
return theta, nil
} | pkg/robot/robot.go | 0.857171 | 0.527073 | robot.go | starcoder |
package main
// Code based on the Recursive backtracker algorithm.
// https://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_backtracker
// See https://youtu.be/HyK_Q5rrcr4 as an example
// YouTube example ported to Go for the Pixel library.
// Created by <NAME>
import (
"crypto/rand"
"errors"
"flag"
"fmt"
"math/big"
"time"
"src.rocks/redragonx/maze-generator-go/stack"
"github.com/faiface/pixel"
"github.com/faiface/pixel/imdraw"
"github.com/faiface/pixel/pixelgl"
"github.com/pkg/profile"
"golang.org/x/image/colornames"
)
var visitedColor = pixel.RGB(0.5, 0, 1).Mul(pixel.Alpha(0.35))
var hightlightColor = pixel.RGB(0.3, 0, 0).Mul(pixel.Alpha(0.45))
var debug = false
type Cell struct {
// Wall order
// top, right, bottom, left
walls [4]bool
row int
col int
visited bool
}
func (c *Cell) Draw(imd *imdraw.IMDraw, wallSize int) {
drawCol := c.col * wallSize // x
drawRow := c.row * wallSize // y
// fmt.Printf("row: %d, col: %d", c.row, c.col)
imd.Color = colornames.White
if c.walls[0] {
// top line
imd.Push(pixel.V(float64(drawCol), float64(drawRow)), pixel.V(float64(drawCol+wallSize), float64(drawRow)))
imd.Line(3)
}
if c.walls[1] {
// right Line
// imd.Color(colornames.Red)
imd.Push(pixel.V(float64(drawCol+wallSize), float64(drawRow)), pixel.V(float64(drawCol+wallSize), float64(drawRow+wallSize)))
imd.Line(3)
}
if c.walls[2] {
// bottom line
//imd.Color(colornames.Beige)
imd.Push(pixel.V(float64(drawCol+wallSize), float64(drawRow+wallSize)), pixel.V(float64(drawCol), float64(drawRow+wallSize)))
imd.Line(3)
}
if c.walls[3] {
// left line
imd.Push(pixel.V(float64(drawCol), float64(drawRow+wallSize)), pixel.V(float64(drawCol), float64(drawRow)))
imd.Line(3)
}
imd.EndShape = imdraw.SharpEndShape
if c.visited {
imd.Color = visitedColor
imd.Push(pixel.V(float64(drawCol), (float64(drawRow))), pixel.V(float64(drawCol+wallSize), float64(drawRow+wallSize)))
imd.Rectangle(0)
}
}
func (c *Cell) GetNeighbors(grid []*Cell, cols int, rows int) ([]*Cell, error) {
neighbors := []*Cell{}
j := c.row
i := c.col
top, _ := getCellAt(i, j-1, cols, rows, grid)
right, _ := getCellAt(i+1, j, cols, rows, grid)
bottom, _ := getCellAt(i, j+1, cols, rows, grid)
left, _ := getCellAt(i-1, j, cols, rows, grid)
if top != nil && !top.visited {
neighbors = append(neighbors, top)
}
if right != nil && !right.visited {
neighbors = append(neighbors, right)
}
if bottom != nil && !bottom.visited {
neighbors = append(neighbors, bottom)
}
if left != nil && !left.visited {
neighbors = append(neighbors, left)
}
if len(neighbors) > 0 {
return neighbors, nil
} else {
return nil, errors.New("We checked all cells...")
}
}
func (c *Cell) GetRandomNeighbor(grid []*Cell, cols int, rows int) (*Cell, error) {
neighbors, err := c.GetNeighbors(grid, cols, rows)
if neighbors != nil {
nBig, err := rand.Int(rand.Reader, big.NewInt(int64(len(neighbors))))
if err != nil {
panic(err)
}
randomIndex := nBig.Int64()
return neighbors[randomIndex], nil
} else {
return nil, err
}
}
func (c *Cell) hightlight(imd *imdraw.IMDraw, wallSize int) {
x := c.col * wallSize
y := c.row * wallSize
imd.Color = hightlightColor
imd.Push(pixel.V(float64(x), float64(y)), pixel.V(float64(x+wallSize), float64(y+wallSize)))
imd.Rectangle(0)
}
func newCell(col int, row int) *Cell {
newCell := new(Cell)
newCell.row = row
newCell.col = col
for i := range newCell.walls {
newCell.walls[i] = true
}
return newCell
}
// Creates the inital maze slice for use.
func initGrid(cols, rows int) []*Cell {
grid := []*Cell{}
for j := 0; j < rows; j++ {
for i := 0; i < cols; i++ {
newCell := newCell(i, j)
grid = append(grid, newCell)
}
}
return grid
}
func setupMaze(cols, rows int) ([]*Cell, *stack.Stack, *Cell) {
// Make an empty grid
grid := initGrid(cols, rows)
backTrackStack := stack.NewStack(len(grid))
currentCell := grid[0]
return grid, backTrackStack, currentCell
}
func cellIndex(i, j, cols, rows int) int {
if i < 0 || j < 0 || i > cols-1 || j > rows-1 {
return -1
}
return i + j*cols
}
func getCellAt(i int, j int, cols int, rows int, grid []*Cell) (*Cell, error) {
possibleIndex := cellIndex(i, j, cols, rows)
if possibleIndex == -1 {
return nil, fmt.Errorf("cellIndex: CellIndex is a negative number %d", possibleIndex)
}
return grid[possibleIndex], nil
}
func removeWalls(a *Cell, b *Cell) {
x := a.col - b.col
if x == 1 {
a.walls[3] = false
b.walls[1] = false
} else if x == -1 {
a.walls[1] = false
b.walls[3] = false
}
y := a.row - b.row
if y == 1 {
a.walls[0] = false
b.walls[2] = false
} else if y == -1 {
a.walls[2] = false
b.walls[0] = false
}
}
func run() {
// unsiged integers, because easier parsing error checks.
// We must convert these to intergers, as done below...
u_screenWidth, u_screenHeight, u_wallSize := parseArgs()
var (
// In pixels
// Defualt is 800x800x40 = 20x20 wallgrid
screenWidth = int(u_screenWidth)
screenHeight = int(u_screenHeight)
wallSize = int(u_wallSize)
frames = 0
second = time.Tick(time.Second)
grid = []*Cell{}
cols = screenWidth / wallSize
rows = screenHeight / wallSize
currentCell = new(Cell)
backTrackStack = stack.NewStack(1)
)
// Set game FPS manually
fps := time.Tick(time.Second / 60)
cfg := pixelgl.WindowConfig{
Title: "Pixel Rocks! - Maze example",
Bounds: pixel.R(0, 0, float64(screenHeight), float64(screenWidth)),
}
win, err := pixelgl.NewWindow(cfg)
if err != nil {
panic(err)
}
grid, backTrackStack, currentCell = setupMaze(cols, rows)
gridIMDraw := imdraw.New(nil)
for !win.Closed() {
if win.JustReleased(pixelgl.KeyR) {
fmt.Println("R pressed")
grid, backTrackStack, currentCell = setupMaze(cols, rows)
}
win.Clear(colornames.Gray)
gridIMDraw.Clear()
for i := range grid {
grid[i].Draw(gridIMDraw, wallSize)
}
// step 1
// Make the initial cell the current cell and mark it as visited
currentCell.visited = true
currentCell.hightlight(gridIMDraw, wallSize)
// step 2.1
// If the current cell has any neighbours which have not been visited
// Choose a random unvisited cell
nextCell, _ := currentCell.GetRandomNeighbor(grid, cols, rows)
if nextCell != nil && !nextCell.visited {
// step 2.2
// Push the current cell to the stack
backTrackStack.Push(currentCell)
// step 2.3
// Remove the wall between the current cell and the chosen cell
removeWalls(currentCell, nextCell)
// step 2.4
// Make the chosen cell the current cell and mark it as visited
nextCell.visited = true
currentCell = nextCell
} else if backTrackStack.Len() > 0 {
currentCell = backTrackStack.Pop().(*Cell)
}
gridIMDraw.Draw(win)
win.Update()
<-fps
updateFPSDisplay(win, &cfg, &frames, grid, second)
}
}
// Parses the maze arguments, all of them are optional.
// Uses uint as implicit error checking :)
func parseArgs() (uint, uint, uint) {
var mazeWidthPtr = flag.Uint("w", 800, "w sets the maze's width in pixels.")
var mazeHeightPtr = flag.Uint("h", 800, "h sets the maze's height in pixels.")
var wallSizePtr = flag.Uint("c", 40, "c sets the maze cell's size in pixels.")
flag.Parse()
// If these aren't default values AND if they're not the same values.
// We should warn the user that the maze will look funny.
if *mazeWidthPtr != 800 || *mazeHeightPtr != 800 {
if *mazeWidthPtr != *mazeHeightPtr {
fmt.Printf("WARNING: maze width: %d and maze height: %d don't match. \n", *mazeWidthPtr, *mazeHeightPtr)
fmt.Println("Maze will look funny because the maze size is bond to the window size!")
}
}
return *mazeWidthPtr, *mazeHeightPtr, *wallSizePtr
}
func updateFPSDisplay(win *pixelgl.Window, cfg *pixelgl.WindowConfig, frames *int, grid []*Cell, second <-chan time.Time) {
*frames++
select {
case <-second:
win.SetTitle(fmt.Sprintf("%s | FPS: %d with %d Cells", cfg.Title, *frames, len(grid)))
*frames = 0
default:
}
}
func main() {
if debug {
defer profile.Start().Stop()
}
pixelgl.Run(run)
} | maze-generator.go | 0.803444 | 0.413951 | maze-generator.go | starcoder |
package option
import (
m "../measures"
"github.com/phil-mansfield/gotetra/math/interpolate"
"gonum.org/v1/gonum/optimize"
"math"
)
type Pricing func(option Option, spot m.Money, t m.Time) m.Money
type Greek func(option Option, spot m.Money, t m.Time) float64
type Decision interface {
EarlyExcercise(spot m.Money, nonExcercisedValue m.Money) m.Money
}
type Option interface {
Decision
Expiration() m.Time
Payoff(spot m.Money) m.Money
Strike() m.Money // FIXME deprecated ... does not generalize!
}
type PricingParameters struct {
Sigma m.Return
R m.Rate
}
func BinomialPricing(parameters PricingParameters) Pricing {
return func(option Option, spot m.Money, t m.Time) m.Money {
return BinomialModel(
option,
spot,
t,
parameters.Sigma,
parameters.R)
}
}
func GridPricing(parameters PricingParameters) Pricing {
return func(option Option, spot m.Money, t m.Time) m.Money {
if t >= option.Expiration() {
return option.Payoff(spot)
}
SInf := math.Max(2.0*float64(option.Strike()), 1.1*float64(spot))
NAS := 200
S, V := FiniteDifferenceGrid(NAS, SInf)(
option,
t,
parameters.Sigma,
parameters.R)
V0 := make([]float64, len(S))
for i := 0; i < len(S); i++ {
V0[i] = V[i][len(V[0])-1]
}
return m.Money(interpolate.NewLinear(S, V0).Eval(float64(spot)))
}
}
func EuropeanMCPricing(parameters PricingParameters) Pricing {
return func(option Option, spot m.Money, t m.Time) m.Money {
return NoEarlyExcerciseMonteCarloModel(100000, 100, -1)(option, spot, t, parameters.Sigma, parameters.R)
}
}
func diff(f func(x float64) float64, x, d float64) float64 {
return (f(x+d) - f(x-d)) / (2 * d)
}
func diff2nd(f func(x float64) float64, x, d float64) float64 {
return (f(x+d) - 2*f(x) + f(x-d)) / (d * d)
}
func Delta(pricing Pricing) Greek {
return func(option Option, spot m.Money, t m.Time) float64 {
return diff(
func(x float64) float64 { return float64(pricing(option, m.Money(x), t)) },
float64(spot),
0.01*float64(spot))
}
}
func Gamma(pricing Pricing) Greek {
return func(option Option, spot m.Money, t m.Time) float64 {
return diff2nd(
func(x float64) float64 { return float64(pricing(option, m.Money(x), t)) },
float64(spot),
0.05*float64(spot))
}
}
func Theta(pricing Pricing) Greek {
return func(option Option, spot m.Money, t m.Time) float64 {
return diff(
func(x float64) float64 { return float64(pricing(option, spot, m.Time(x))) },
float64(t),
0.001)
}
}
func Rho(pricingFromParameters func(parameters PricingParameters) Pricing, parameters PricingParameters) Greek {
return func(option Option, spot m.Money, t m.Time) float64 {
return diff(
func(r float64) float64 {
tweakedParameters := parameters
tweakedParameters.R = m.Rate(r)
return float64(pricingFromParameters(tweakedParameters)(option, spot, t))
},
float64(parameters.R),
0.0001)
}
}
func ImplyVol(pricingMethod func(PricingParameters) Pricing, R m.Rate) func(option Option, spot m.Money, t m.Time) func(price m.Money) (float64, error) {
return func(option Option, spot m.Money, t m.Time) func(price m.Money) (float64, error) {
return func(price m.Money) (float64, error) {
problem := optimize.Problem{
Func: func(x []float64) float64 {
parameters := PricingParameters{Sigma: m.Return(x[0]), R: R}
pricing := pricingMethod(parameters)
return math.Abs(float64(pricing(option, spot, t) - price))
},
}
result, err := optimize.Minimize(problem, []float64{0.2}, nil, nil)
if err != nil {
return math.NaN(), err
}
return result.X[0], nil
}
}
} | src/option/option.go | 0.600188 | 0.494202 | option.go | starcoder |
package square
// Represents a bank account. For more information about linking a bank account to a Square account, see [Bank Accounts API](/docs/bank-accounts-api).
type BankAccount struct {
// The unique, Square-issued identifier for the bank account.
Id string `json:"id"`
// The last few digits of the account number.
AccountNumberSuffix string `json:"account_number_suffix"`
// The ISO 3166 Alpha-2 country code where the bank account is based. See [Country](#type-country) for possible values
Country string `json:"country"`
// The 3-character ISO 4217 currency code indicating the operating currency of the bank account. For example, the currency code for US dollars is `USD`. See [Currency](#type-currency) for possible values
Currency string `json:"currency"`
// The financial purpose of the associated bank account. See [BankAccountType](#type-bankaccounttype) for possible values
AccountType string `json:"account_type"`
// Name of the account holder. This name must match the name on the targeted bank account record.
HolderName string `json:"holder_name"`
// Primary identifier for the bank. For more information, see [Bank Accounts API](https://developer.squareup.com/docs/docs/bank-accounts-api).
PrimaryBankIdentificationNumber string `json:"primary_bank_identification_number"`
// Secondary identifier for the bank. For more information, see [Bank Accounts API](https://developer.squareup.com/docs/docs/bank-accounts-api).
SecondaryBankIdentificationNumber string `json:"secondary_bank_identification_number,omitempty"`
// Reference identifier that will be displayed to UK bank account owners when collecting direct debit authorization. Only required for UK bank accounts.
DebitMandateReferenceId string `json:"debit_mandate_reference_id,omitempty"`
// Client-provided identifier for linking the banking account to an entity in a third-party system (for example, a bank account number or a user identifier).
ReferenceId string `json:"reference_id,omitempty"`
// The location to which the bank account belongs.
LocationId string `json:"location_id,omitempty"`
// Read-only. The current verification status of this BankAccount object. See [BankAccountStatus](#type-bankaccountstatus) for possible values
Status string `json:"status"`
// Indicates whether it is possible for Square to send money to this bank account.
Creditable bool `json:"creditable"`
// Indicates whether it is possible for Square to take money from this bank account.
Debitable bool `json:"debitable"`
// A Square-assigned, unique identifier for the bank account based on the account information. The account fingerprint can be used to compare account entries and determine if the they represent the same real-world bank account.
Fingerprint string `json:"fingerprint,omitempty"`
// The current version of the `BankAccount`.
Version int32 `json:"version,omitempty"`
// Read only. Name of actual financial institution. For example \"Bank of America\".
BankName string `json:"bank_name,omitempty"`
} | square/model_bank_account.go | 0.834339 | 0.489503 | model_bank_account.go | starcoder |
package forge
import (
"image/color"
"image/color/palette"
)
// Helper function to compare pixel with each other
func (p pixel) isSame(cP pixel) bool {
isTheSameColor := false
fColor := getP9RGBA
var c1 color.RGBA
var c2 color.RGBA
c1.R, c1.G, c1.B, c1.A = fColor(p)
c2.R, c2.G, c2.B, c2.A = fColor(cP)
if c1.R == c2.R && c1.G == c2.G && c1.B == c2.B && c1.A == c2.A {
isTheSameColor = true
}
return isTheSameColor
}
// Return the RGBA values for the WebSafe representation
func getWebSafeRGBA(c color.Color) (uint8, uint8, uint8, uint8) {
p := palette.WebSafe
r, g, b, a := color.Palette.Convert(p, c).RGBA()
return uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)
}
// Return the RGBA values for the P9 representation
func getP9RGBA(c color.Color) (uint8, uint8, uint8, uint8) {
p := palette.Plan9
r, g, b, a := color.Palette.Convert(p, c).RGBA()
return uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8)
}
// Helper function to better understand the complexity of a image's colors
func (img Image) groupPixelOverColor() map[color.Color]int {
col := img.height
row := img.width
m := make(map[color.Color]int)
for i := 0; i < col*row; i++ {
r, g, b, a := getP9RGBA(img.pixels[i])
currentColor := color.RGBA{r, g, b, a}
if _, ok := m[currentColor]; ok {
m[currentColor]++
} else {
m[currentColor] = 0
}
}
return m
}
// Return gImage for a given image
func (img Image) getColorGradient() gImage {
col := img.height
row := img.width
var r, g, b, a uint32
var previousColor pixel
var gImg gImage
gA := make([]bool, col*row)
for i := 0; i < col*row; i++ {
x := i % col
r, g, b, a = img.pixels[i].RGBA()
currentColor := pixel{r, g, b, a}
// Set gradient to false on x = 0 as nothing to compare to
if x == 0 {
gA[i] = false
previousColor = currentColor
continue
}
if currentColor.isSame(previousColor) {
gA[i] = true
}
previousColor = currentColor
}
gImg.sourceImage = &img
gImg.gradMatrix = gA
return gImg
} | forge/colgrad.go | 0.785473 | 0.407392 | colgrad.go | starcoder |
package fp448
import "github.com/cloudflare/circl/internal/conv"
// Size in bytes of an element.
const Size = 56
// Elt is a prime field element.
type Elt [Size]byte
func (e Elt) String() string { return conv.BytesLe2Hex(e[:]) }
// p is the prime modulus 2^448-2^224-1
var p = Elt{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
}
// P returns the prime modulus 2^448-2^224-1.
func P() Elt { return p }
// ToBytes returns the little-endian byte representation of x.
func ToBytes(b []byte, x *Elt) {
if len(b) != Size {
panic("wrong size")
}
Modp(x)
copy(b, x[:])
}
// IsZero returns true if x is equal to 0.
func IsZero(x *Elt) bool { Modp(x); return *x == Elt{} }
// SetOne assigns x=1.
func SetOne(x *Elt) { *x = Elt{}; x[0] = 1 }
// Neg calculates z = -x.
func Neg(z, x *Elt) { Sub(z, &p, x) }
// Modp ensures that z is between [0,p-1].
func Modp(z *Elt) { Sub(z, z, &p) }
// Inv calculates z = 1/x mod p.
func Inv(z, x *Elt) {
x0, x1, x2 := &Elt{}, &Elt{}, &Elt{}
Sqr(x2, x)
Mul(x2, x2, x)
Sqr(x0, x2)
Mul(x0, x0, x)
Sqr(x2, x0)
Sqr(x2, x2)
Sqr(x2, x2)
Mul(x2, x2, x0)
Sqr(x1, x2)
for i := 0; i < 5; i++ {
Sqr(x1, x1)
}
Mul(x1, x1, x2)
Sqr(x2, x1)
for i := 0; i < 11; i++ {
Sqr(x2, x2)
}
Mul(x2, x2, x1)
Sqr(x2, x2)
Sqr(x2, x2)
Sqr(x2, x2)
Mul(x2, x2, x0)
Sqr(x1, x2)
for i := 0; i < 26; i++ {
Sqr(x1, x1)
}
Mul(x1, x1, x2)
Sqr(x2, x1)
for i := 0; i < 53; i++ {
Sqr(x2, x2)
}
Mul(x2, x2, x1)
Sqr(x2, x2)
Sqr(x2, x2)
Sqr(x2, x2)
Mul(x2, x2, x0)
Sqr(x1, x2)
for i := 0; i < 110; i++ {
Sqr(x1, x1)
}
Mul(x1, x1, x2)
Sqr(x2, x1)
Mul(x2, x2, x)
for i := 0; i < 223; i++ {
Sqr(x2, x2)
}
Mul(x2, x2, x1)
Sqr(x2, x2)
Sqr(x2, x2)
Mul(z, x2, x)
}
// Cmov assigns y to x if n is 1.
func Cmov(x, y *Elt, n uint) { cmov(x, y, n) }
// Cswap interchages x and y if n is 1.
func Cswap(x, y *Elt, n uint) { cswap(x, y, n) }
// Add calculates z = x+y mod p.
func Add(z, x, y *Elt) { add(z, x, y) }
// Sub calculates z = x-y mod p
func Sub(z, x, y *Elt) { sub(z, x, y) }
// AddSub calculates (x,y) = (x+y mod p, x-y mod p).
func AddSub(x, y *Elt) { addsub(x, y) }
// Mul calculates z = x*y mod p.
func Mul(z, x, y *Elt) { mul(z, x, y) }
// Sqr calculates z = x^2 mod p.
func Sqr(z, x *Elt) { sqr(z, x) } | math/fp448/fp.go | 0.658857 | 0.516047 | fp.go | starcoder |
package Collection
import (
"fmt"
"reflect"
stream "github.com/wushilin/stream"
)
// Iterator for Collections
type Iterator[T any] interface {
// Iterator must be a stream.Iterator, which defines Next() T, bool
stream.Iterator[T]
// Remove last returned entry (can only be called once for every Next() call)
Remove()
// Set the value of current entry to the new vale, returns the old value
Set(T) T
}
// Defines a function that can test equality of two variable of the same type
// If you don't want to implement, a collection.DefaultEqualizer[T]() is provided, which
// uses reflect.DeepEquals(v1, v2 T) for simplicity
type Equalizer[T any] func(T, T) bool
// Defines common APIs a Collection should support
type Visitor[T any] func(what T) (shouldContinue bool)
type Collection[T any] interface {
// Visit each elements with Visitor. When visitor returns false, it stops
// Returns the number of elements visited.
ForEach(visitor Visitor[T]) int
// Adds a new element to the tail of the list
// Returns whether the add was successful
Add(element T) (added bool)
// Adds all elements in the collection
// Returns the number of elements added
AddAll(elements Collection[T]) (addedCount int)
// Test whether this collection contains the element
// Tests equality with the specified equalizer
// Return true if the element is found
ContainsFunc(what T, equals Equalizer[T]) (exists bool)
// Test whether this collection contains the element
// Tests equality with the default equalizer
// Return true if the element is found
Contains(data T) (exist bool)
// Tests whether if the collection is empty (no elements)
IsEmpty() (isEmpty bool)
// Returns iterator over the list
Iterator() (iterator Iterator[T])
// Remove all with equals tester returns number of elements removed
RemoveAllFunc(collection Collection[T], equals Equalizer[T]) (numberOfItemsRemoved int)
// Remove all with the default equals tester returns number of elements removed
RemoveAll(collection Collection[T]) (numberOfItemsRemoved int)
// Retain all elements in the current collection if it is found in the parameter collection
// Returns number of elements removed
RetainAllFunc(collection Collection[T], equals Equalizer[T]) (numberOfItemsRemoved int)
// Retain all elements in the current collection if it is found in the parameter collection
// Returns number of elements removed
RetainAll(collection Collection[T]) (numberOfItemsRemoved int)
// Get size of the collection
Size() (size int)
// Convert collection to an array
ToArray() (array []T)
// Convert collection to a stream
Stream() (stream stream.Stream[T])
// Removes all elements in the collection, returns the number of items removed
Clear() (numberOfItemsRemoved int)
}
// Reflection.DeepEqual
func EqualsTester[T any](v1, v2 T) bool {
return reflect.DeepEqual(v1, v2)
}
// Default equalizer that uses reflection.DeepEquals
func DefaultEqualizer[T any]() Equalizer[T] {
return EqualsTester[T]
}
// Visit each item in iterator with visitor function.
// Stop when visitor function returns false, or iterator is fully traversed
func ForEach[T any](iter Iterator[T], visitor Visitor[T]) int {
count := 0
for next, ok := iter.Next(); ok; next, ok = iter.Next() {
count++
if !visitor(next) {
break
}
}
return count
}
// Convert iterator to fixed size array
func ToArray[T any](size int, iter Iterator[T]) []T {
result := make([]T, size)
index := 0
for next, ok := iter.Next(); ok; next, ok = iter.Next() {
result[index] = next
index++
}
return result
}
// Prints collection to STDOUT
func PrintCollection[T any](list Collection[T]) {
fmt.Print("[")
count := 0
list.ForEach(func(i T) bool {
if count == list.Size()-1 {
fmt.Printf("%+v", i)
} else {
fmt.Printf("%+v,", i)
}
count++
return true
})
fmt.Println("]")
}
// Add elements to the given collections
func AddElementsTo[T any](what Collection[T], arg ...T) {
for _, obj := range arg {
what.Add(obj)
}
} | Collection/Collection.go | 0.734215 | 0.440289 | Collection.go | starcoder |
package array
import (
"fmt"
)
// Array (Public) - Structure that defines
type Array struct {
size int
collection []interface{}
}
// Init (Public) - initializes the array with whatever size is provided, This is what can be overrided by the user.
func (a *Array) Init(capacity int) *Array {
if capacity < 0 {
return nil
}
a.collection = make([]interface{}, capacity)
a.size = 0
return a
}
// New (Public) - Returns an initialized array with default size of 10.
func New() *Array { return new(Array).Init(10) }
// AddFirst (Public) - ensures the array is big enough for the new item, then
// shifts all the items right one space, then adds the first item to the front,
// lastly it increments the size
func (a *Array) AddFirst(T interface{}) {
a.ensureSpace()
a.shiftRight(0)
a.collection[0] = T
a.size++
}
// AddLast (Public) - ensures the array is big enough for the new item, then
// adds the item to the end of the array list, lastly it increments the size
func (a *Array) AddLast(T interface{}) {
a.ensureSpace()
a.collection[a.size] = T
a.size++
}
// RemoveFirst (Public) - checks if array is empty, then stores the result in a
// variable, then it shifts everything but the first item left, then it decrements
// the size and finally returns the removed item.
func (a *Array) RemoveFirst() interface{} {
if a.size == 0 {
return nil
}
result := a.collection[0]
a.shiftLeft(0)
a.size--
return result
}
// RemoveLast (Public) - Checks for an empty array, then stores the last item in
// the array, then it nils the last value, then decrements the size, finaly
// returns the removed item.
func (a *Array) RemoveLast() interface{} {
if a.size == 0 {
return nil
}
result := a.collection[a.size-1]
a.collection[a.size-1] = nil
a.size--
return result
}
// GetFirst (Public) - Returns nil if array is empty, returns first item
func (a *Array) GetFirst() interface{} {
if a.size == 0 {
return nil
}
return a.collection[0]
}
// GetLast (Public) - Returns nil if array is empty, returns last item
func (a *Array) GetLast() interface{} {
if a.size == 0 {
return nil
}
return a.collection[a.size-1]
}
// Contains (Public) - Checks to see if item is in array, returns true or false
func (a *Array) Contains(T interface{}) bool {
for _, item := range a.collection {
if item == T {
return true
}
}
return false
}
// Size (Public) - returns the size of the Array
func (a *Array) Size() int {
return a.size
}
// String (Public) - formats the array when fmt.Print is called.
func (a *Array) String() string {
if a.size == 0 {
return "[ ]"
}
s := "[ "
for x := 0; x < a.size; x++ {
s += fmt.Sprintf("%v ", a.collection[x])
}
return s + "]"
}
// ensureSpace (Private) - Sees if the size and capacity of the array are the same. If so,
// It creates a new array with double the capacity and overwrites the old array with a new
// array, then clears the new array for the GC.
func (a *Array) ensureSpace() {
if a.size == cap(a.collection) {
new := new(Array).Init(cap(a.collection) * 2)
new.size = a.size
for i := 0; i < a.size; i++ {
new.collection[i] = a.collection[i]
}
*a = *new
new = nil
}
}
// shiftLeft (Private) - Moves all the items left after index (Destructive)
func (a *Array) shiftLeft(index int) {
for i := index; i < a.size-1; i++ {
a.collection[i] = a.collection[i+1]
}
}
// shiftRight (Private) - Moves all the items to the right after the index (non-destructive)
func (a *Array) shiftRight(index int) {
for i := a.size; i > index; i-- {
a.collection[i] = a.collection[i-1]
}
} | array/array.go | 0.741768 | 0.407098 | array.go | starcoder |
package gosmonaut
import (
"bytes"
"encoding/json"
"fmt"
)
// OSMType represents the type of an OSM entity.
type OSMType uint8
// OSM Types: node, way, relation.
const (
NodeType OSMType = 1 << iota
WayType
RelationType
)
// OSMEntity is the common interface of all OSM entities.
type OSMEntity interface {
GetID() int64
GetType() OSMType
GetTags() OSMTags
fmt.Stringer
}
/* Node */
// Node represents an OSM node element.
type Node struct {
ID int64
Lat, Lon float64
Tags OSMTags
}
// GetID returns the ID.
func (n Node) GetID() int64 {
return n.ID
}
// GetType always returns NodeType.
func (n Node) GetType() OSMType {
return NodeType
}
// GetTags returns the tags.
func (n Node) GetTags() OSMTags {
return n.Tags
}
func (n Node) String() string {
return prettyPrintEntity(n)
}
// MarshalJSON prints the JSON representation of the node.
func (n Node) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
ID int64 `json:"id"`
Lat coordFloat `json:"lat"`
Lon coordFloat `json:"lon"`
Tags OSMTags `json:"tags,omitempty"`
}{"node", n.ID, coordFloat(n.Lat), coordFloat(n.Lon), n.Tags})
}
/* Way */
// Way represents an OSM way element.
type Way struct {
ID int64
Tags OSMTags
Nodes []Node
}
// GetID returns the ID.
func (w Way) GetID() int64 {
return w.ID
}
// GetType always returns WayType.
func (w Way) GetType() OSMType {
return WayType
}
// GetTags returns the tags.
func (w Way) GetTags() OSMTags {
return w.Tags
}
func (w Way) String() string {
return prettyPrintEntity(w)
}
// MarshalJSON prints the JSON representation of the way.
func (w Way) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
ID int64 `json:"id"`
Tags OSMTags `json:"tags"`
Nodes []Node `json:"nodes"`
}{"way", w.ID, w.Tags, w.Nodes})
}
/* Relation */
// Relation represents an OSM relation element.
type Relation struct {
ID int64
Tags OSMTags
Members []Member
}
// GetID returns the ID.
func (r Relation) GetID() int64 {
return r.ID
}
// GetType always returns RelationType.
func (r Relation) GetType() OSMType {
return RelationType
}
// GetTags returns the tags.
func (r Relation) GetTags() OSMTags {
return r.Tags
}
func (r Relation) String() string {
return prettyPrintEntity(r)
}
// MarshalJSON prints the JSON representation of the relation.
func (r Relation) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
ID int64 `json:"id"`
Tags OSMTags `json:"tags"`
Members []Member `json:"members"`
}{"relation", r.ID, r.Tags, r.Members})
}
// Member represents a member of a relation.
type Member struct {
Role string `json:"role"`
Entity OSMEntity `json:"entity"`
}
/* OSMTypeSet */
// OSMTypeSet is used to enable/disable OSM types.
type OSMTypeSet uint8
// NewOSMTypeSet returns a new OSMTypeSet with the given types enabled/disabled.
func NewOSMTypeSet(nodes, ways, relations bool) OSMTypeSet {
var s OSMTypeSet
s.Set(NodeType, nodes)
s.Set(WayType, ways)
s.Set(RelationType, relations)
return s
}
// Set enables/disables the given type.
func (s *OSMTypeSet) Set(t OSMType, enabled bool) {
if enabled {
*s = OSMTypeSet(uint8(*s) | uint8(t))
} else {
*s = OSMTypeSet(uint8(*s) & (^uint8(t)))
}
}
// Get returns true if the given type is enabled.
func (s *OSMTypeSet) Get(t OSMType) bool {
return uint8(*s)&uint8(t) != 0
}
/* OSM Tags */
// OSMTags represents a key-value mapping for OSM tags.
type OSMTags []string // Alternating array of keys/values
// NewOSMTags creates new OSMTags and can be used if the number of tags is
// known.
func NewOSMTags(n int) OSMTags {
if n < 0 {
n = 0
}
return make([]string, 0, n*2)
}
// NewOSMTagsFromMap creates new OSMTags that contains the tags from the given
// map.
func NewOSMTagsFromMap(m map[string]string) OSMTags {
t := NewOSMTags(len(m))
for k, v := range m {
t = append(t, k, v)
}
return t
}
// Set adds or updates the value for the given key.
func (t *OSMTags) Set(key, val string) {
if i, ok := t.index(key); ok {
t.set(i+1, val)
} else {
*t = append(*t, key, val)
}
}
// Get returns the value for the given key or false if the key does not exist.
func (t *OSMTags) Get(key string) (string, bool) {
if i, ok := t.index(key); ok {
return t.get(i + 1), true
}
return "", false
}
// Has returns true if the given key exists.
func (t *OSMTags) Has(key string) bool {
_, ok := t.index(key)
return ok
}
// HasValue return true if the given key exists and its value is val.
func (t *OSMTags) HasValue(key, val string) bool {
if i, ok := t.index(key); ok {
return t.get(i+1) == val
}
return false
}
// Map returns the map representation of the tags.
func (t *OSMTags) Map() map[string]string {
m := make(map[string]string, t.Len())
for i := 0; i < len(*t); i += 2 {
m[t.get(i)] = t.get(i + 1)
}
return m
}
func (t OSMTags) String() string {
return prettyPrintEntity(t)
}
// MarshalJSON prints the JSON representation of the tags.
func (t OSMTags) MarshalJSON() ([]byte, error) {
return json.Marshal(t.Map())
}
// Len returns the number of tags.
func (t *OSMTags) Len() int {
return len(*t) / 2
}
func (t *OSMTags) get(i int) string {
return []string(*t)[i]
}
func (t *OSMTags) set(i int, s string) {
[]string(*t)[i] = s
}
func (t *OSMTags) index(key string) (int, bool) {
for i := 0; i < len(*t); i += 2 {
if t.get(i) == key {
return i, true
}
}
return -1, false
}
/* Helpers */
// Print an OSM entity as JSON with indention
func prettyPrintEntity(m json.Marshaler) string {
b := new(bytes.Buffer)
enc := json.NewEncoder(b)
enc.SetIndent("", " ")
enc.Encode(m)
return b.String()
}
// Restrict the JSON decimals to 7 which is the OSM default
type coordFloat float64
func (mf coordFloat) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%.7f", mf)), nil
} | osm_types.go | 0.78968 | 0.431225 | osm_types.go | starcoder |
package binary_search
/*
You are given two non-empty arrays A and B consisting of N integers. These arrays represent N planks. More precisely, A[K] is the start and B[K] the end of the Kβth plank.
Next, you are given a non-empty array C consisting of M integers. This array represents M nails. More precisely, C[I] is the position where you can hammer in the Iβth nail.
We say that a plank (A[K], B[K]) is nailed if there exists a nail C[I] such that A[K] β€ C[I] β€ B[K].
The goal is to find the minimum number of nails that must be used until all the planks are nailed. In other words, you should find a value J such that all planks will be nailed after using only the first J nails. More precisely, for every plank (A[K], B[K]) such that 0 β€ K < N, there should exist a nail C[I] such that I < J and A[K] β€ C[I] β€ B[K].
For example, given arrays A, B such that:
A[0] = 1 B[0] = 4
A[1] = 4 B[1] = 5
A[2] = 5 B[2] = 9
A[3] = 8 B[3] = 10
four planks are represented: [1, 4], [4, 5], [5, 9] and [8, 10].
Given array C such that:
C[0] = 4
C[1] = 6
C[2] = 7
C[3] = 10
C[4] = 2
if we use the following nails:
0, then planks [1, 4] and [4, 5] will both be nailed.
0, 1, then planks [1, 4], [4, 5] and [5, 9] will be nailed.
0, 1, 2, then planks [1, 4], [4, 5] and [5, 9] will be nailed.
0, 1, 2, 3, then all the planks will be nailed.
Thus, four is the minimum number of nails that, used sequentially, allow all the planks to be nailed.
Write a function:
func Solution(A []int, B []int, C []int) int
that, given two non-empty arrays A and B consisting of N integers and a non-empty array C consisting of M integers, returns the minimum number of nails that, used sequentially, allow all the planks to be nailed.
If it is not possible to nail all the planks, the function should return β1.
For example, given arrays A, B, C such that:
A[0] = 1 B[0] = 4
A[1] = 4 B[1] = 5
A[2] = 5 B[2] = 9
A[3] = 8 B[3] = 10
C[0] = 4
C[1] = 6
C[2] = 7
C[3] = 10
C[4] = 2
the function should return 4, as explained above.
Assume that:
N and M are integers within the range [1..30,000];
each element of arrays A, B, C is an integer within the range [1..2*M];
A[K] β€ B[K].
Complexity:
expected worst-case time complexity is O((N+M)*log(M));
expected worst-case space complexity is O(M) (not counting the storage required for input arguments).
*/
func Solution(a []int, b []int, c []int) int {
n := len(a)
m := len(c)
minNails := 1
maxNails := m
var mid int
var missing bool
total := -1
maxCoord := m * 2 + 1
nailed := make([]int, maxCoord)
for ; minNails <= maxNails ; {
missing = false
mid = (maxNails + minNails) / 2
for i := 0 ; i < maxCoord ; i++ {
nailed[i] = 0
}
for i := 0 ; i < mid ; i++ {
nailed[c[i]]++
}
for i := 1 ; i < maxCoord ; i++ {
nailed[i] = nailed[i] + nailed[i - 1]
}
for i := 0 ; i < n ; i++ {
if (nailed[a[i] - 1] == nailed[b[i]]) {
missing = true
}
}
if missing {
minNails = mid + 1
} else {
maxNails = mid - 1
total = mid
}
}
return total
} | binary-search/NailingPlanks.go | 0.840783 | 0.85183 | NailingPlanks.go | starcoder |
package swat
import (
"log"
"math"
)
const (
nsl = 50 // number of soilzone layers
lythick = 10. // layer thickness [mm]
satini = 1. // initial degree of soil saturation relative to fc
minslp = 0.0001 // min CHS: channel slope
secperday = 86400.
hoursperday = 24.
)
/*
go implementaiton of the SWAT model
ref: <NAME>., <NAME>, J.R., <NAME>, 2011. Soil and Water Assessment Tool: Theoretical Documentation Version 2009 (September 2011). 647pp.
specifications:
1. designed for long-term daily simulation
2. currently only applying water balance, i.e., no sediment or water quality
3. SCS CN is adjusted according to soil moisture (ICN=0)
4. snowpack is modelled externally and thus melt is added as an input, so snowpack (sublimation, etc.) is not modelled here
5. assumes a uniform 0.5m soil zone depth, subdivided into 50 1cm layers (see const above)
6. initial conditions starting at 0.25 bankfull
X. Notes:
- Penman-Monteith is not used; therefore transpiration is not modelled (pg.135)
- vertisols are not included, i.e., no bypass flow (pg.152)
- no bypass flow; no partioning to deep aquifer (pg.173)
- perched water table (pg.158)
- lateral flow (pg.160)
- no evaporation or pumping from shallow gw reservoirs (pg.176)
- no percolation to deep aquifers (i.e., no gw sink) (pg.178)
- no shallow aquifer baseflow threshold (GWQMIN/aqt) (pg.174)
- using (HYMO) variable storage routing method (pg.433)
- no in-line transmission losses, evaporation, bank storage Sec7 Ch1
*/
// New SWAT SubBasin constructor
// SUBKM: area of subbasin [km2]
// SLSUBBSN: (L_slp) average slope length [m]
// CHL: (L) longest tributary channel length in subbasin [km]
// CHS: (slp_ch) average slope of tributary channels [m/m]
// CHN: (n) Manning's n value for tributary channels
// CHW: (W_bankfull) width of channel top at bank [m]
// CHD: (depth_bankfull) depth of water wht filled to bank [m]
// SURLAG: surface runoff lag coefficient [0,15]
// GWDELAY: (delta_gw) delay time for aquifer recharge [days]
// GWQMN: (aq_shthr) threshold water level in aquifer for baseflow [mm]
// ALPHABF: (alpha_bf) baseflow recession coeficient (1/k)
func (b *SubBasin) New(HRUs []*HRU, Chn *Channel, SUBKM, SLSUBBSN, CHL, CHS, CHN, SURLAG, GWDELAY, ALPHABF float64) {
b.Ca = SUBKM // subbasin contributing area [kmΒ²]
b.surlag = SURLAG
b.dgw = GWDELAY // the delay of soil zone percolation to aquifer [days]
b.aqt = 0. // GWQMN (no shallow aquifer baseflow threshold (GWQMIN/aqt))
b.agw = ALPHABF // baseflow recession coefficient
b.Outflow = -1 // SubBasin outflow ID
b.slplen = SLSUBBSN
b.tribl = CHL
b.tribs = CHS
b.tribn = CHN
// build HRUs and tconc, add channel element
b.chn = *Chn
ftot, wslp, wovn := 0., 0., 0.
b.hru = make([]HRU, len(HRUs))
for i, u := range HRUs {
ftot += u.f
b.hru[i] = *u
wslp += u.f * u.slp // subsasin weighted average slope
wovn += u.f * u.ovn // subsasin weighted average overland roughness
}
if math.Abs(1.-ftot) > 0.001 {
for _, u := range b.hru {
u.f /= ftot // nomalize hru fractions
}
}
b.tconc = tconc(wslp, SLSUBBSN, wovn, CHL, CHS, CHN, SUBKM)
if math.IsNaN(b.tconc) {
log.Fatalf("SubBasin.New error: tconc is NaN\n")
}
}
// tconc returns the time of concentration to subbasin outlet [hr]
// lengths [m]; slopes [m/m]
func tconc(slp, lslp, ovn, lch, sch, nch, carea float64) float64 {
tov := math.Pow(lslp, 0.6) * math.Pow(ovn, 0.6) / math.Pow(slp, 0.3) / 18. // pg.111
tch := 0.62 * lch * math.Pow(nch, 0.75) / math.Pow(carea, 0.125) / math.Pow(sch, 0.375) // pg.113
return tov + tch // [hr]
}
// New SWAT HRU constructor
// HRUFR: fraction of subbasin area contained in HRU
// HRUSLP: (slp) average slope steepness [m/m]
// OVN: (n) Manning's n value for overland flow
// CN2: moisture condition II curve number
// CV: aboveground biomass and residue [kg/ha]
// ESCO: soil evporation compensation coefficient [0,1] (pg.138)
// IWATABLE: high water table code: set to true when seasonal high water table present
func (m *HRU) New(sz SoilLayer, HRUFR, HRUSLP, OVN, CN2, CV, ESCO float64, IWATABLE bool) {
m.f = HRUFR
m.slp = HRUSLP
m.ovn = OVN
m.cov = math.Exp(-5.0e-5 * CV) // soil cover index (pg.135)
m.esco = ESCO
m.iwt = IWATABLE
m.sz = make([]SoilLayer, nsl)
for i := 0; i < nsl; i++ {
m.sz[i] = sz
}
m.cn.New(CN2, sz.fc*float64(nsl), sz.sat*float64(nsl), HRUSLP) // fc, sat [mm]; SLP as fraction [m/m]
}
// New SWAT soil zone layer constructor
// CLAY: (m_c) percent clay content
// SOLBD: bulk density of soil (Mg/mΒ³=g/cmΒ³)
// SOLAWC: available water capacity as fraction of total soil volume [-]
// SOLK: (ksat) saturated hydraulic conductivity [mm/hr]
func (sl *SoilLayer) New(CLAY, SOLBD, SOLAWC, SOLK float64) {
n := 1. - SOLBD/2.65 // porosity
sl.wp = 0.4 * CLAY * SOLBD / 100. // water content at wilting point as fraction of total soil volume (pg.149)
sl.fc = (sl.wp + SOLAWC) // water content at field capacity as a fraction of total soil volume (pg.150)
sl.frz = false
// converting to [mm]
sl.sat = n * lythick // the amount of water in the soil profile when completely saturated [mm] based on layer thickness
sl.fc *= lythick // the amount of water in the soil profile at field capacity [mm]
sl.sw = sl.fc * satini // initial saturation
sl.wp *= lythick // [mm]
sl.tt = (sl.sat - sl.fc) / SOLK // pg.151 percolation time of travel; Ksat saturated hydraulic conductivity [mm/hr]
}
// New variable storage routing method channel constructor
// CHW: (W_bankfull) width of channel top at bank [m]
// CHD: (depth_bankfull) depth of water filled to bank [m]
// CHL: (L_ch) length of main channel [km]
// CHS: (slp_ch) length of main channel [-]
// CHN: (n) Manning's n value for the main channel
func (c *Channel) New(CHW, CHD, CHL, CHS, CHN float64) {
c.d = CHD // initial flow depth [m]
c.len = CHL * 1000. // converting to [m]
c.zch = zch
c.sqslp = math.Sqrt(math.Max(minslp, CHS)) // square root of channel slope fraction (rise/run)
c.wbf = CHW // channel width at bankfull [m]
c.n = CHN // channel Mannings roughness
c.wfld = 5. * CHW
c.dbf = CHD // bankful depth [m]
c.zch2 = math.Sqrt(1. + c.zch*c.zch)
c.zfld2 = math.Sqrt(1. + zfld*zfld)
c.wbtm = CHW - 2.*zch*CHD // pg.429
if c.wbtm <= 0. {
c.wbtm = CHW / zch
c.zch = (CHW - c.wbtm) / 2. / CHD
}
c.vstr = c.len * (c.wbtm + c.zch*c.d) * c.d // initial volume [mΒ³]
ach := c.vstr / c.len // pg.432
pch := c.wbtm + 2.*c.d*c.zch2 // pg.430
rch := ach / pch // hydraulic radius
q := ach * math.Pow(rch, twothird) * c.sqslp / c.n // pg.431
tt := c.vstr / q
if tt < secperday/2. {
tt = secperday / 2.
}
c.sc = 2. * secperday / (2.*tt + secperday) // pg.434
if c.sc < 0. || c.sc > 1. || (math.IsNaN(c.sc) && c.len > 0.) {
log.Fatalf("Channel.New error: SC = %f\n", c.sc)
}
} | swat/constructors.go | 0.599133 | 0.408808 | constructors.go | starcoder |
package gruff
import (
"fmt"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
)
const ARGUMENT_TYPE_PRO_TRUTH int = 1
const ARGUMENT_TYPE_CON_TRUTH int = 2
const ARGUMENT_TYPE_PRO_STRENGTH int = 3
const ARGUMENT_TYPE_CON_STRENGTH int = 4
/*
An Argument connects a Claim to another Claim or Argument
That is:
a Claim can be used as an ARGUMENT to either prove or disprove the truth of a claim,
or to modify the relevance or impact of another argument.
The TYPE of the argument indicates how the claim (or CLAIM) is being used:
PRO TRUTH: The Claim is a claim that is being used to prove the truth of another claim
Ex: "The defendant was in Cincinatti on the date of the murder"
CON TRUTH: The Claim is used as evidence against another claim
Ex: "The defendant was hospitalized on the date of the murder"
PRO RELEVANCE: The Claim is being used to show that another Argument is relevant
Ex: "The murder occurred in Cincinatti"
CON RELEVANCE: The Claim is being used to show that another Argument is irrelevant
Ex: "The murder occurred in the same hospital in which the defendant was hospitalized"
PRO IMPACT: The Claim is being used to show the importance of another Argument
Ex: "This argument clearly shows that the defendant has no alibi"
CON IMPACT: The Claim is being used to diminish the importance of another argument
Ex: "There is no evidence that the defendant ever left their room"
A quick explanation of the fields:
Claim: The Debate (or claim) that is being used as an argument
Target Claim: The "parent" Claim against which a pro/con truth argument is being made
Target Argument: In the case of a relevance or impact argument, the argument to which it refers
To help understand the difference between relevance and impact arguments, imagine an argument is a bullet:
Impact is the size of your bullet
Relevance is how well you hit your target
Scoring:
Truth: 1.0 = definitely true; 0.5 = equal chance true or false; 0.0 = definitely false. "The world is flat" should have a 0.000000000000000001 truth score.
Impact: 1.0 = This argument is definitely the most important argument for this side - no need to read any others; 0.5 = This is one more argument to consider; 0.01 = Probably not even worth including in the discussion
Relevance: 1.0 = Completely germaine and on-topic; 0.5 = Circumstantial or somewhat relevant; 0.01 = Totally off-point, should be ignored
*
* Topoi for Resolutions of Definition (for scoring Relevance/Impact):
* - Is the interpretation relevant? (relevance)
* - Is the interpretation fair?
* - How should we choose among competing interpretations? (impact)
*
* Topoi for Resolutions of Value (for scoring Relevance/Impact):
* - Is the condition truly good or bad as alleged? (i.e. which values are impacted, and is it positive or negative?)
* - Has the value been properly applied? (relevance)
* - How should we choose among competing values? (impact)
*
* Topoi for Resolutions of Policy (this would look differently in our model - one Issue with multiple claims as solutions?):
* - Is there a problem? (could be represented by a "Do nothing" claim)
* - Where is the credit or blame due?
* - Will the proposal solve the problem?
* - On balance, will things be better off? (trade offs - need to measure each proposal against multiple values)
*
* Types of evidence (Pro/Con-Truth arguments) (not implemented in Gruff):
* - Examples
* - Statistics
* - Tangible objects
* - Testimony
* - Social consensus
* Fallacies: accusations of standard fallacies can be used as arguments against relevance, impact, or truth
* - Fallacies of Inference (con-impact? or con-relevance?):
* - Hasty generalizations
* - Unrepresentative samples
* - Fallacy of composition (if one is, then all are)
* - Fallacy of division (if most are, then this subgroup must be)
* - Errors in inference from sign (correlation vs. causation)
*
* - Fallacies of Relevance:
* - Ad Hominem
* - Appeal to Unreasonable Emotion
* ... more
--> True definition of fallacy: an argument that subverts the purpose of resolving a disagreement
*/
type Argument struct {
Identifier
TargetClaimID *NullableUUID `json:"targetClaimId,omitempty" sql:"type:uuid"`
TargetClaim *Claim `json:"targetClaim,omitempty"`
TargetArgumentID *NullableUUID `json:"targetArgId,omitempty" sql:"type:uuid"`
TargetArgument *Argument `json:"targetArg,omitempty"`
ClaimID uuid.UUID `json:"claimId" sql:"type:uuid;not null"`
Claim *Claim `json:"claim,omitempty"`
Title string `json:"title" sql:"not null" valid:"length(3|1000),required"`
Description string `json:"desc" valid:"length(3|4000)"`
Type int `json:"type" sql:"not null"`
Strength float64 `json:"strength"`
StrengthRU float64 `json:"strengthRU"`
ProStrength []Argument `json:"prostr,omitempty"`
ConStrength []Argument `json:"constr,omitempty"`
}
func (a Argument) ValidateForCreate() GruffError {
err := a.ValidateField("Title")
if err != nil {
return err
}
err = a.ValidateField("Description")
if err != nil {
return err
}
err = a.ValidateField("Type")
if err != nil {
return err
}
err = a.ValidateIDs()
if err != nil {
return err
}
err = a.ValidateType()
if err != nil {
return err
}
return nil
}
func (a Argument) ValidateForUpdate() GruffError {
return a.ValidateForCreate()
}
func (a Argument) ValidateField(f string) GruffError {
err := ValidateStructField(a, f)
return err
}
func (a Argument) ValidateIDs() GruffError {
if a.ClaimID == uuid.Nil {
return NewBusinessError("ClaimID: non zero value required;")
}
if (a.TargetClaimID == nil || a.TargetClaimID.UUID == uuid.Nil) &&
(a.TargetArgumentID == nil || a.TargetArgumentID.UUID == uuid.Nil) {
return NewBusinessError("An Argument must have a target Claim or target Argument ID")
}
if a.TargetClaimID != nil && a.TargetArgumentID != nil {
return NewBusinessError("An Argument can have only one target Claim or target Argument ID")
}
return nil
}
func (a Argument) ValidateType() GruffError {
switch a.Type {
case ARGUMENT_TYPE_PRO_TRUTH, ARGUMENT_TYPE_CON_TRUTH:
if a.TargetClaimID == nil || a.TargetClaimID.UUID == uuid.Nil {
return NewBusinessError("A pro or con truth argument must refer to a target claim")
}
case ARGUMENT_TYPE_PRO_STRENGTH,
ARGUMENT_TYPE_CON_STRENGTH:
if a.TargetArgumentID == nil || a.TargetArgumentID.UUID == uuid.Nil {
return NewBusinessError("An argument for or against argument strength must refer to a target argument")
}
default:
return NewBusinessError("Type: invalid;")
}
return nil
}
// Business methods
func (a Argument) UpdateStrength(ctx *ServerContext) {
ctx.Database.Exec("UPDATE arguments a SET strength = (SELECT AVG(strength) FROM argument_opinions WHERE argument_id = a.id) WHERE id = ?", a.ID)
// TODO: test
if a.StrengthRU == 0.0 {
// There's no roll up score yet, so the strength score itself is affecting related roll ups
a.UpdateAncestorRUs(ctx)
}
}
func (a *Argument) UpdateStrengthRU(ctx *ServerContext) {
// TODO: do it all in SQL?
proArgs, conArgs := a.Arguments(ctx)
if len(proArgs) > 0 || len(conArgs) > 0 {
proScore := 0.0
for _, arg := range proArgs {
remainder := 1.0 - proScore
score := arg.ScoreRU(ctx)
addon := remainder * score
proScore += addon
}
conScore := 0.0
for _, arg := range conArgs {
remainder := 1.0 - conScore
score := arg.ScoreRU(ctx)
addon := remainder * score
conScore += addon
}
netScore := proScore - conScore
netScore = 0.5 + 0.5*netScore
a.StrengthRU = netScore
} else {
a.StrengthRU = 0.0
}
ctx.Database.Set("gorm:save_associations", false).Save(a)
a.UpdateAncestorRUs(ctx)
}
func (a Argument) UpdateAncestorRUs(ctx *ServerContext) {
if a.TargetClaimID != nil {
claim := a.TargetClaim
if claim == nil {
claim = &Claim{}
if err := ctx.Database.Where("id = ?", a.TargetClaimID).First(claim).Error; err != nil {
return
}
}
claim.UpdateTruthRU(ctx)
} else {
arg := a.TargetArgument
if arg == nil {
arg = &Argument{}
if err := ctx.Database.Where("id = ?", a.TargetArgumentID).First(arg).Error; err != nil {
fmt.Println("Error loading argument:", err.Error())
return
}
}
arg.UpdateStrengthRU(ctx)
}
}
func (a *Argument) MoveTo(ctx *ServerContext, newId uuid.UUID, t int) GruffError {
db := ctx.Database
oldArg := Argument{TargetClaimID: a.TargetClaimID, TargetArgumentID: a.TargetArgumentID, Type: a.Type}
oldTargetID := a.TargetArgumentID
oldTargetType := OBJECT_TYPE_ARGUMENT
if oldTargetID == nil {
oldTargetID = a.TargetClaimID
oldTargetType = OBJECT_TYPE_CLAIM
}
switch t {
case ARGUMENT_TYPE_PRO_TRUTH, ARGUMENT_TYPE_CON_TRUTH:
newClaim := Claim{}
if err := db.Where("id = ?", newId).First(&newClaim).Error; err != nil {
return NewNotFoundError(err.Error())
}
newIdN := NullableUUID{newId}
a.TargetClaimID = &newIdN
a.TargetClaim = &newClaim
a.TargetArgumentID = nil
case ARGUMENT_TYPE_PRO_STRENGTH, ARGUMENT_TYPE_CON_STRENGTH:
newArg := Argument{}
if err := db.Where("id = ?", newId).First(&newArg).Error; err != nil {
return NewNotFoundError(err.Error())
}
newIdN := NullableUUID{newId}
a.TargetArgumentID = &newIdN
a.TargetArgument = &newArg
a.TargetClaimID = nil
default:
return NewNotFoundError(fmt.Sprintf("Type unknown: %d", t))
}
a.Type = t
if err := db.Set("gorm:save_associations", false).Save(a).Error; err != nil {
return NewServerError(err.Error())
}
// TODO: Goroutine
// Notify argument voters of move so they can vote again
ops := []ArgumentOpinion{}
if err := db.Where("argument_id = ?", a.ID).Find(&ops).Error; err != nil {
db.Rollback()
return NewServerError(err.Error())
}
for _, op := range ops {
NotifyArgumentMoved(ctx, op.UserID, a.ID, oldTargetID.UUID, oldTargetType)
}
// Notify sub argument voters of move so they can double-check their vote
uids := []uint64{}
rows, dberr := db.Model(ArgumentOpinion{}).
Select("DISTINCT argument_opinions.user_id").
Where("argument_id IN (SELECT id FROM arguments WHERE target_argument_id = ?)", a.ID).
Rows()
defer rows.Close()
if dberr == nil {
for rows.Next() {
var uid uint64
err := rows.Scan(&uid)
if err == nil {
uids = append(uids, uid)
}
}
}
for _, uid := range uids {
NotifyParentArgumentMoved(ctx, uid, a.ID, oldTargetID.UUID, oldTargetType)
}
// Clear opinions on the moved argument
if err := db.Exec("DELETE FROM argument_opinions WHERE argument_id = ?", a.ID).Error; err != nil {
db.Rollback()
return NewServerError(err.Error())
}
a.UpdateAncestorRUs(ctx)
oldArg.UpdateAncestorRUs(ctx)
return nil
}
func (a Argument) Score(ctx *ServerContext) float64 {
c := a.Claim
if c == nil {
c = &Claim{}
ctx.Database.Where("id = ?", a.ClaimID).First(c)
}
return a.Strength * c.Truth
}
func (a Argument) ScoreRU(ctx *ServerContext) float64 {
c := a.Claim
if c == nil {
c = &Claim{}
ctx.Database.Where("id = ?", a.ClaimID).First(c)
}
truth := c.TruthRU
if truth == 0.0 {
truth = c.Truth
}
strength := a.StrengthRU
if strength == 0.0 {
strength = a.Strength
}
return strength * truth
}
func (a Argument) Arguments(ctx *ServerContext) (proArgs []Argument, conArgs []Argument) {
proArgs = a.ProStrength
conArgs = a.ConStrength
if len(proArgs) == 0 {
ctx.Database.
Preload("Claim").
Scopes(OrderByBestArgument).
Where("type = ?", ARGUMENT_TYPE_PRO_STRENGTH).
Where("target_argument_id = ?", a.ID).
Find(&proArgs)
}
if len(conArgs) == 0 {
ctx.Database.
Preload("Claim").
Scopes(OrderByBestArgument).
Where("type = ?", ARGUMENT_TYPE_CON_STRENGTH).
Where("target_argument_id = ?", a.ID).
Find(&conArgs)
}
return
}
// Scopes
func OrderByBestArgument(db *gorm.DB) *gorm.DB {
return db.Joins("LEFT JOIN claims c ON c.id = arguments.claim_id").
Order("(arguments.strength * c.truth) DESC")
} | gruff/argument.go | 0.615203 | 0.564129 | argument.go | starcoder |
package maroto
// Proportion represents a proportion from a rectangle, example: 16x9, 4x3...
type Proportion struct {
// Width from the rectangle: Barcode, image and etc
Width float64
// Height from the rectangle: Barcode, image and etc
Height float64
}
// BarcodeProp represents properties from a barcode inside a cell
type BarcodeProp struct {
// Left is the space between the left cell boundary to the barcode, if center is false
Left float64
// Top is space between the upper cell limit to the barcode, if center is false
Top float64
// Percent is how much the barcode will occupy the cell,
// ex 100%: The barcode will fulfill the entire cell
// ex 50%: The greater side from the barcode will have half the size of the cell
Percent float64
// Proportion is the proportion between size of the barcode
// Ex: 16x9, 4x3...
Proportion Proportion
// Center define that the barcode will be vertically and horizontally centralized
Center bool
}
// RectProp represents properties from a rectangle (Image, QrCode or Barcode) inside a cell
type RectProp struct {
// Left is the space between the left cell boundary to the rectangle, if center is false
Left float64
// Top is space between the upper cell limit to the barcode, if center is false
Top float64
// Percent is how much the rectangle will occupy the cell,
// ex 100%: The rectangle will fulfill the entire cell
// ex 50%: The greater side from the rectangle will have half the size of the cell
Percent float64
// Center define that the barcode will be vertically and horizontally centralized
Center bool
}
// TextProp represents properties from a Text inside a cell
type TextProp struct {
// Top is space between the upper cell limit to the barcode, if align is not center
Top float64
// Family of the text, ex: Arial, helvetica and etc
Family Family
// Style of the text, ex: Normal, bold and etc
Style Style
// Size of the text
Size float64
// Align of the text
Align Align
// Extrapolate define if the text will automatically add a new line when
// text reach the right cell boundary
Extrapolate bool
}
// FontProp represents properties from a text
type FontProp struct {
// Family of the text, ex: Arial, helvetica and etc
Family Family
// Style of the text, ex: Normal, bold and etc
Style Style
// Size of the text
Size float64
}
// TableListProp represents properties from a TableList
type TableListProp struct {
// HeaderHeight is the height of the cell with headers
HeaderHeight float64
// HeaderProp is the custom properties of the text inside
// the headers
HeaderProp FontProp
// ContentHeight is the height of the cells with contents
ContentHeight float64
// ContentProp is the custom properties of the text inside
// the contents
ContentProp FontProp
// Align is the align of the text (header and content) inside the columns
Align Align
// HeaderContentSpace is the space between the header and the contents
HeaderContentSpace float64
}
// MakeValid from RectProp means will make the properties from a rectangle reliable to fit inside a cell
// and define default values for a rectangle
func (r *RectProp) MakeValid() {
if r.Percent <= 0.0 || r.Percent > 100.0 {
r.Percent = 100.0
}
if r.Center {
r.Left = 0
r.Top = 0
}
if r.Left < 0.0 {
r.Left = 0.0
}
if r.Top < 0.0 {
r.Top = 0
}
}
// MakeValid from BarcodeProp means will make the properties from a barcode reliable to fit inside a cell
// and define default values for a barcode
func (r *BarcodeProp) MakeValid() {
if r.Percent <= 0.0 || r.Percent > 100.0 {
r.Percent = 100.0
}
if r.Center {
r.Left = 0
r.Top = 0
}
if r.Left < 0.0 {
r.Left = 0.0
}
if r.Top < 0.0 {
r.Top = 0
}
if r.Proportion.Width <= 0 {
r.Proportion.Width = 1
}
if r.Proportion.Height <= 0 {
r.Proportion.Height = 1
}
if r.Proportion.Height > r.Proportion.Width*0.33 {
r.Proportion.Height = r.Proportion.Width * 0.33
}
}
// MakeValid from TextProp define default values for a Text
func (f *TextProp) MakeValid() {
if f.Family == "" {
f.Family = Arial
}
if f.Style == "" {
f.Style = Normal
}
if f.Align == "" {
f.Align = Left
}
if f.Size == 0.0 {
f.Size = 10.0
}
if f.Top < 0.0 {
f.Top = 0.0
}
}
// MakeValid from FontProp define default values for a Signature
func (f *FontProp) MakeValid() {
if f.Family == "" {
f.Family = Arial
}
if f.Style == "" {
f.Style = Bold
}
if f.Size == 0.0 {
f.Size = 8.0
}
}
// ToTextProp from FontProp return a TextProp based on FontProp
func (f *FontProp) ToTextProp(align Align, top float64) TextProp {
textProp := TextProp{
Family: f.Family,
Style: f.Style,
Size: f.Size,
Align: align,
Top: top,
}
textProp.MakeValid()
return textProp
}
// MakeValid from TableListProp define default values for a TableList
func (t *TableListProp) MakeValid() {
if t.HeaderProp.Size == 0.0 {
t.HeaderProp.Size = 10.0
}
if t.HeaderProp.Family == "" {
t.HeaderProp.Family = Arial
}
if t.HeaderProp.Style == "" {
t.HeaderProp.Style = Bold
}
if t.HeaderHeight == 0.0 {
t.HeaderHeight = 7.0
}
if t.Align == "" {
t.Align = Left
}
if t.ContentProp.Size == 0.0 {
t.ContentProp.Size = 10.0
}
if t.ContentProp.Family == "" {
t.ContentProp.Family = Arial
}
if t.ContentProp.Style == "" {
t.ContentProp.Style = Normal
}
if t.ContentHeight == 0.0 {
t.ContentHeight = 5.0
}
if t.HeaderContentSpace == 0.0 {
t.HeaderContentSpace = 4.0
}
} | properties.go | 0.765856 | 0.72459 | properties.go | starcoder |
package cryptoapis
import (
"encoding/json"
)
// CoinsForwardingSuccessDataItem Defines an `item` as one result.
type CoinsForwardingSuccessDataItem struct {
// Represents the specific blockchain protocol name, e.g. Ethereum, Bitcoin, etc.
Blockchain string `json:"blockchain"`
// Represents the name of the blockchain network used; blockchain networks are usually identical as technology and software, but they differ in data, e.g. - \"mainnet\" is the live network with actual data while networks like \"testnet\", \"ropsten\", \"rinkeby\" are test networks.
Network string `json:"network"`
// Represents the hash of the address that provides the coins.
FromAddress string `json:"fromAddress"`
// Represents the hash of the address to forward the coins to.
ToAddress string `json:"toAddress"`
// Represents the amount of coins that have been forwarded.
ForwardedAmount string `json:"forwardedAmount"`
// Represents the unit of coins that have been forwarded, e.g. BTC.
ForwardedUnit string `json:"forwardedUnit"`
// Represents the amount of the fee spent for the coins to be forwarded.
SpentFeesAmount string `json:"spentFeesAmount"`
// Represents the unit of the fee spent for the coins to be forwarded, e.g. BTC.
SpentFeesUnit string `json:"spentFeesUnit"`
// Defines the unique Transaction ID that triggered the coin forwarding.
TriggerTransactionId string `json:"triggerTransactionId"`
// Defines the unique Transaction ID that forwarded the coins.
ForwardingTransactionId string `json:"forwardingTransactionId"`
}
// NewCoinsForwardingSuccessDataItem instantiates a new CoinsForwardingSuccessDataItem object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewCoinsForwardingSuccessDataItem(blockchain string, network string, fromAddress string, toAddress string, forwardedAmount string, forwardedUnit string, spentFeesAmount string, spentFeesUnit string, triggerTransactionId string, forwardingTransactionId string) *CoinsForwardingSuccessDataItem {
this := CoinsForwardingSuccessDataItem{}
this.Blockchain = blockchain
this.Network = network
this.FromAddress = fromAddress
this.ToAddress = toAddress
this.ForwardedAmount = forwardedAmount
this.ForwardedUnit = forwardedUnit
this.SpentFeesAmount = spentFeesAmount
this.SpentFeesUnit = spentFeesUnit
this.TriggerTransactionId = triggerTransactionId
this.ForwardingTransactionId = forwardingTransactionId
return &this
}
// NewCoinsForwardingSuccessDataItemWithDefaults instantiates a new CoinsForwardingSuccessDataItem object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewCoinsForwardingSuccessDataItemWithDefaults() *CoinsForwardingSuccessDataItem {
this := CoinsForwardingSuccessDataItem{}
return &this
}
// GetBlockchain returns the Blockchain field value
func (o *CoinsForwardingSuccessDataItem) GetBlockchain() string {
if o == nil {
var ret string
return ret
}
return o.Blockchain
}
// GetBlockchainOk returns a tuple with the Blockchain field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetBlockchainOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Blockchain, true
}
// SetBlockchain sets field value
func (o *CoinsForwardingSuccessDataItem) SetBlockchain(v string) {
o.Blockchain = v
}
// GetNetwork returns the Network field value
func (o *CoinsForwardingSuccessDataItem) GetNetwork() string {
if o == nil {
var ret string
return ret
}
return o.Network
}
// GetNetworkOk returns a tuple with the Network field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetNetworkOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Network, true
}
// SetNetwork sets field value
func (o *CoinsForwardingSuccessDataItem) SetNetwork(v string) {
o.Network = v
}
// GetFromAddress returns the FromAddress field value
func (o *CoinsForwardingSuccessDataItem) GetFromAddress() string {
if o == nil {
var ret string
return ret
}
return o.FromAddress
}
// GetFromAddressOk returns a tuple with the FromAddress field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetFromAddressOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.FromAddress, true
}
// SetFromAddress sets field value
func (o *CoinsForwardingSuccessDataItem) SetFromAddress(v string) {
o.FromAddress = v
}
// GetToAddress returns the ToAddress field value
func (o *CoinsForwardingSuccessDataItem) GetToAddress() string {
if o == nil {
var ret string
return ret
}
return o.ToAddress
}
// GetToAddressOk returns a tuple with the ToAddress field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetToAddressOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ToAddress, true
}
// SetToAddress sets field value
func (o *CoinsForwardingSuccessDataItem) SetToAddress(v string) {
o.ToAddress = v
}
// GetForwardedAmount returns the ForwardedAmount field value
func (o *CoinsForwardingSuccessDataItem) GetForwardedAmount() string {
if o == nil {
var ret string
return ret
}
return o.ForwardedAmount
}
// GetForwardedAmountOk returns a tuple with the ForwardedAmount field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetForwardedAmountOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ForwardedAmount, true
}
// SetForwardedAmount sets field value
func (o *CoinsForwardingSuccessDataItem) SetForwardedAmount(v string) {
o.ForwardedAmount = v
}
// GetForwardedUnit returns the ForwardedUnit field value
func (o *CoinsForwardingSuccessDataItem) GetForwardedUnit() string {
if o == nil {
var ret string
return ret
}
return o.ForwardedUnit
}
// GetForwardedUnitOk returns a tuple with the ForwardedUnit field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetForwardedUnitOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ForwardedUnit, true
}
// SetForwardedUnit sets field value
func (o *CoinsForwardingSuccessDataItem) SetForwardedUnit(v string) {
o.ForwardedUnit = v
}
// GetSpentFeesAmount returns the SpentFeesAmount field value
func (o *CoinsForwardingSuccessDataItem) GetSpentFeesAmount() string {
if o == nil {
var ret string
return ret
}
return o.SpentFeesAmount
}
// GetSpentFeesAmountOk returns a tuple with the SpentFeesAmount field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetSpentFeesAmountOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.SpentFeesAmount, true
}
// SetSpentFeesAmount sets field value
func (o *CoinsForwardingSuccessDataItem) SetSpentFeesAmount(v string) {
o.SpentFeesAmount = v
}
// GetSpentFeesUnit returns the SpentFeesUnit field value
func (o *CoinsForwardingSuccessDataItem) GetSpentFeesUnit() string {
if o == nil {
var ret string
return ret
}
return o.SpentFeesUnit
}
// GetSpentFeesUnitOk returns a tuple with the SpentFeesUnit field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetSpentFeesUnitOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.SpentFeesUnit, true
}
// SetSpentFeesUnit sets field value
func (o *CoinsForwardingSuccessDataItem) SetSpentFeesUnit(v string) {
o.SpentFeesUnit = v
}
// GetTriggerTransactionId returns the TriggerTransactionId field value
func (o *CoinsForwardingSuccessDataItem) GetTriggerTransactionId() string {
if o == nil {
var ret string
return ret
}
return o.TriggerTransactionId
}
// GetTriggerTransactionIdOk returns a tuple with the TriggerTransactionId field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetTriggerTransactionIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.TriggerTransactionId, true
}
// SetTriggerTransactionId sets field value
func (o *CoinsForwardingSuccessDataItem) SetTriggerTransactionId(v string) {
o.TriggerTransactionId = v
}
// GetForwardingTransactionId returns the ForwardingTransactionId field value
func (o *CoinsForwardingSuccessDataItem) GetForwardingTransactionId() string {
if o == nil {
var ret string
return ret
}
return o.ForwardingTransactionId
}
// GetForwardingTransactionIdOk returns a tuple with the ForwardingTransactionId field value
// and a boolean to check if the value has been set.
func (o *CoinsForwardingSuccessDataItem) GetForwardingTransactionIdOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.ForwardingTransactionId, true
}
// SetForwardingTransactionId sets field value
func (o *CoinsForwardingSuccessDataItem) SetForwardingTransactionId(v string) {
o.ForwardingTransactionId = v
}
func (o CoinsForwardingSuccessDataItem) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["blockchain"] = o.Blockchain
}
if true {
toSerialize["network"] = o.Network
}
if true {
toSerialize["fromAddress"] = o.FromAddress
}
if true {
toSerialize["toAddress"] = o.ToAddress
}
if true {
toSerialize["forwardedAmount"] = o.ForwardedAmount
}
if true {
toSerialize["forwardedUnit"] = o.ForwardedUnit
}
if true {
toSerialize["spentFeesAmount"] = o.SpentFeesAmount
}
if true {
toSerialize["spentFeesUnit"] = o.SpentFeesUnit
}
if true {
toSerialize["triggerTransactionId"] = o.TriggerTransactionId
}
if true {
toSerialize["forwardingTransactionId"] = o.ForwardingTransactionId
}
return json.Marshal(toSerialize)
}
type NullableCoinsForwardingSuccessDataItem struct {
value *CoinsForwardingSuccessDataItem
isSet bool
}
func (v NullableCoinsForwardingSuccessDataItem) Get() *CoinsForwardingSuccessDataItem {
return v.value
}
func (v *NullableCoinsForwardingSuccessDataItem) Set(val *CoinsForwardingSuccessDataItem) {
v.value = val
v.isSet = true
}
func (v NullableCoinsForwardingSuccessDataItem) IsSet() bool {
return v.isSet
}
func (v *NullableCoinsForwardingSuccessDataItem) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableCoinsForwardingSuccessDataItem(val *CoinsForwardingSuccessDataItem) *NullableCoinsForwardingSuccessDataItem {
return &NullableCoinsForwardingSuccessDataItem{value: val, isSet: true}
}
func (v NullableCoinsForwardingSuccessDataItem) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableCoinsForwardingSuccessDataItem) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | model_coins_forwarding_success_data_item.go | 0.885551 | 0.404802 | model_coins_forwarding_success_data_item.go | starcoder |
package dot
import (
"encoding/json"
"strconv"
"time"
)
// Timestamp represents time as number of milliseconds from 1970.
type Timestamp int64
const e6 = 1e6
const e3 = 1e3
var zeroTime = time.Unix(0, 0)
// ToTimestamp converts from Go time to timestamp (in nanosecond).
func ToTimestamp(t time.Time) Timestamp {
if IsZeroTime(t) {
return 0
}
return Timestamp(t.UnixNano() / e6)
}
// IsZeroTime checks whether given time is zero.
// When transport time using grpc, empty time is marshalled to time.Unix(0, 0).
func IsZeroTime(t time.Time) bool {
return t.IsZero() || t.Equal(zeroTime)
}
// Now returns current time.
func Now() Timestamp {
return ToTimestamp(time.Now())
}
// MarshalJSON implements JSONMarshaler
func (t Timestamp) MarshalJSON() ([]byte, error) {
var b = make([]byte, 0, 16)
b = append(b, '"')
b = strconv.AppendInt(b, int64(t), 10)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON implements JSONUnmarshaler
func (t *Timestamp) UnmarshalJSON(b []byte) error {
// Trim quotes
if len(b) >= 2 && b[0] == '"' {
b = b[1 : len(b)-1]
}
var v int64
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
*t = Timestamp(v)
return nil
}
// ToTime converts from timestamp to Go time.
func (t Timestamp) ToTime() time.Time {
if t == 0 {
return time.Time{}
}
return time.Unix(int64(t)/1e3, int64(t%1e3)*e6).UTC()
}
// Unix converts Timestamp to seconds
func (t Timestamp) Unix() int64 {
return int64(t) / 1e3
}
// UnixNano extracts nanoseconds from Timestamp
func (t Timestamp) UnixNano() int64 {
return int64(t) * e6
}
// After reports whether the time instant t is after u
func (t Timestamp) After(u Timestamp) bool {
return t > u
}
// Before reports whether the time instant t is before u
func (t Timestamp) Before(u Timestamp) bool {
return t < u
}
// Add adds duration to timestamp
func (t Timestamp) Add(d time.Duration) Timestamp {
return t + Timestamp(d/e6)
}
// Sub subs timestamp
func (t Timestamp) Sub(u Timestamp) time.Duration {
return time.Duration((t - u) * e6)
}
// AddDays add a number of days to timestamp
func (t Timestamp) AddDays(days int) Timestamp {
return t + Timestamp(days*24*60*60*1e3)
}
func (t Timestamp) String() string {
return t.ToTime().Format(time.RFC3339)
}
// Millis returns the timestamp as number of milliseconds from 1970
func (t Timestamp) Millis() int64 {
return int64(t)
}
// IsZero reports whether timestamp is zero
func (t Timestamp) IsZero() bool {
return t == 0
}
// Millis converts from Go time to timestamp (in millisecond).
func Millis(t time.Time) int64 {
if IsZeroTime(t) {
return 0
}
return t.UnixNano() / e6
} | be/pkg/dot/time.go | 0.824002 | 0.481698 | time.go | starcoder |
package openweathermap
type ForecastBase struct {
DateEpochS int64 `json:"dt"`
PressureHPa float64 `json:"pressure"` // Atmospheric pressure on the sea level, hPa
HumidityPct float64 `json:"humidity"` // Humidity, %
DewPointK float64 `json:"dew_point"` // Atmospheric temperature (varying according to pressure and humidity) below which water droplets begin to condense and dew can form. Units β default: kelvin, metric: Celsius, imperial: Fahrenheit.
CloudPct float64 `json:"clouds"` // Cloudiness, %
UVIndex float64 `json:"uvi"` // Current UV index
VisibilityM float64 `json:"visibility"` // Average visibility, metres
WindSpeedMPS float64 `json:"wind_speed"` // Wind speed. Wind speed. Units β default: metre/sec, metric: metre/sec, imperial: miles/hour. How to change units used
WindGustMPS float64 `json:"wind_gust"` // (where available) Wind gust. Units β default: metre/sec, metric: metre/sec, imperial: miles/hour. How to change units used
WindDeg float64 `json:"wind_deg"` // Wind direction, degrees (meteorological)
Weather []ObsWeather `json:"weather"`
}
type Current struct {
ForecastBase
SunriseEpochS int64 `json:"sunrise"` // Sunrise time, Unix, UTC
SunsetEpochS int64 `json:"sunset"` // Sunset time, Unix, UTC
TempK float64 `json:"temp"` // Temperature. Units - default: kelvin, metric: Celsius, imperial: Fahrenheit. How to change units used
FeelsLikeK float64 `json:"feels_like"` // Temperature. This temperature parameter accounts for the human perception of weather. Units β default: kelvin, metric: Celsius, imperial: Fahrenheit.
Rain ObsPrecip `json:"rain"`
Snow ObsPrecip `json:"snow"`
}
type MinuteForecast struct {
DateEpochS int64 `json:"dt"`
PrecipitationMM float64 `json:"precipitation"`
}
type DailyTemp struct {
MorningK float64 `json:"morn"`
DayK float64 `json:"day"`
EveningK float64 `json:"eve"`
NightK float64 `json:"night"`
MinK float64 `json:"min"`
MaxK float64 `json:"max"`
}
type DailyForecast struct {
ForecastBase
SunriseEpochS int64 `json:"sunrise"` // Sunrise time, Unix, UTC
SunsetEpochS int64 `json:"sunset"` // Sunset time, Unix, UTC
MoonriseEpochS int64 `json:"moonrise"` // The time of when the moon rises for this day, Unix, UTC
MoonsetEpochS int64 `json:"moonset"` // The time of when the moon sets for this day, Unix, UTC
MoonPhase float64 `json:"moon_phase"` // Moon phase. 0 and 1 are 'new moon', 0.25 is 'first quarter moon', 0.5 is 'full moon' and 0.75 is 'last quarter moon'. The periods in between are called 'waxing crescent', 'waxing gibous', 'waning gibous', and 'waning crescent', respectively.
Temp DailyTemp `json:"temp"` // Units β default: kelvin, metric: Celsius, imperial: Fahrenheit. How to change units used
FeelsLike DailyTemp `json:"feels_like"`
PrecipitationPct float64 `json:"pop"` // Probability of precipitation
RainMM float64 `json:"rain"` // (where available) Precipitation volume, mm
SnowMM float64 `json:"snow"` // (where available) Snow volume, mm
}
type Alert struct {
SenderName string `json:"sender_name"` // Name of the alert source. Please read here the full list of alert sources
Event string `json:"event"` // Alert event name
StartEpochS int64 `json:"start"` // Date and time of the start of the alert, Unix, UTC
EndEpochS int64 `json:"end"` // Date and time of the end of the alert, Unix, UTC
Description string `json:"description"` // Description of the alert
Tags []string `json:"tags"` // Type of severe weather
}
type Forecast struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
TZName string `json:"timezone"`
TZOffsetS int64 `json:"timezone_offset"`
Current Current `json:"current"`
Minutely []MinuteForecast `json:"minutely"`
Hourly []Current `json:"hourly"`
Daily []DailyForecast `json:"daily"`
Alerts []Alert `json:"alerts"`
} | forecast.go | 0.849019 | 0.533397 | forecast.go | starcoder |
package staque
type BoolStaque []bool
func NewBool() BoolStaque {
return BoolStaque{}
}
func (staque BoolStaque) Push(xs ...bool) BoolStaque {
return append(staque, xs...)
}
func (stk BoolStaque) Peekstk() (last bool, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que BoolStaque) Peekque() (first bool, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk BoolStaque) Popstk() (modified BoolStaque, last bool, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]bool, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que BoolStaque) Popque() (modified BoolStaque, first bool, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]bool, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type ByteStaque []byte
func NewByte() ByteStaque {
return ByteStaque{}
}
func (staque ByteStaque) Push(xs ...byte) ByteStaque {
return append(staque, xs...)
}
func (stk ByteStaque) Peekstk() (last byte, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que ByteStaque) Peekque() (first byte, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk ByteStaque) Popstk() (modified ByteStaque, last byte, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]byte, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que ByteStaque) Popque() (modified ByteStaque, first byte, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]byte, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Complex128Staque []complex128
func NewComplex128() Complex128Staque {
return Complex128Staque{}
}
func (staque Complex128Staque) Push(xs ...complex128) Complex128Staque {
return append(staque, xs...)
}
func (stk Complex128Staque) Peekstk() (last complex128, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Complex128Staque) Peekque() (first complex128, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Complex128Staque) Popstk() (modified Complex128Staque, last complex128, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]complex128, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Complex128Staque) Popque() (modified Complex128Staque, first complex128, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]complex128, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Complex64Staque []complex64
func NewComplex64() Complex64Staque {
return Complex64Staque{}
}
func (staque Complex64Staque) Push(xs ...complex64) Complex64Staque {
return append(staque, xs...)
}
func (stk Complex64Staque) Peekstk() (last complex64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Complex64Staque) Peekque() (first complex64, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Complex64Staque) Popstk() (modified Complex64Staque, last complex64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]complex64, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Complex64Staque) Popque() (modified Complex64Staque, first complex64, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]complex64, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type ErrorStaque []error
func NewError() ErrorStaque {
return ErrorStaque{}
}
func (staque ErrorStaque) Push(xs ...error) ErrorStaque {
return append(staque, xs...)
}
func (stk ErrorStaque) Peekstk() (last error, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que ErrorStaque) Peekque() (first error, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk ErrorStaque) Popstk() (modified ErrorStaque, last error, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]error, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que ErrorStaque) Popque() (modified ErrorStaque, first error, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]error, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Float32Staque []float32
func NewFloat32() Float32Staque {
return Float32Staque{}
}
func (staque Float32Staque) Push(xs ...float32) Float32Staque {
return append(staque, xs...)
}
func (stk Float32Staque) Peekstk() (last float32, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Float32Staque) Peekque() (first float32, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Float32Staque) Popstk() (modified Float32Staque, last float32, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]float32, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Float32Staque) Popque() (modified Float32Staque, first float32, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]float32, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Float64Staque []float64
func NewFloat64() Float64Staque {
return Float64Staque{}
}
func (staque Float64Staque) Push(xs ...float64) Float64Staque {
return append(staque, xs...)
}
func (stk Float64Staque) Peekstk() (last float64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Float64Staque) Peekque() (first float64, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Float64Staque) Popstk() (modified Float64Staque, last float64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]float64, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Float64Staque) Popque() (modified Float64Staque, first float64, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]float64, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type IntStaque []int
func NewInt() IntStaque {
return IntStaque{}
}
func (staque IntStaque) Push(xs ...int) IntStaque {
return append(staque, xs...)
}
func (stk IntStaque) Peekstk() (last int, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que IntStaque) Peekque() (first int, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk IntStaque) Popstk() (modified IntStaque, last int, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]int, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que IntStaque) Popque() (modified IntStaque, first int, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]int, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Int16Staque []int16
func NewInt16() Int16Staque {
return Int16Staque{}
}
func (staque Int16Staque) Push(xs ...int16) Int16Staque {
return append(staque, xs...)
}
func (stk Int16Staque) Peekstk() (last int16, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Int16Staque) Peekque() (first int16, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Int16Staque) Popstk() (modified Int16Staque, last int16, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]int16, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Int16Staque) Popque() (modified Int16Staque, first int16, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]int16, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Int32Staque []int32
func NewInt32() Int32Staque {
return Int32Staque{}
}
func (staque Int32Staque) Push(xs ...int32) Int32Staque {
return append(staque, xs...)
}
func (stk Int32Staque) Peekstk() (last int32, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Int32Staque) Peekque() (first int32, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Int32Staque) Popstk() (modified Int32Staque, last int32, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]int32, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Int32Staque) Popque() (modified Int32Staque, first int32, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]int32, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Int64Staque []int64
func NewInt64() Int64Staque {
return Int64Staque{}
}
func (staque Int64Staque) Push(xs ...int64) Int64Staque {
return append(staque, xs...)
}
func (stk Int64Staque) Peekstk() (last int64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Int64Staque) Peekque() (first int64, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Int64Staque) Popstk() (modified Int64Staque, last int64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]int64, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Int64Staque) Popque() (modified Int64Staque, first int64, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]int64, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Int8Staque []int8
func NewInt8() Int8Staque {
return Int8Staque{}
}
func (staque Int8Staque) Push(xs ...int8) Int8Staque {
return append(staque, xs...)
}
func (stk Int8Staque) Peekstk() (last int8, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Int8Staque) Peekque() (first int8, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Int8Staque) Popstk() (modified Int8Staque, last int8, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]int8, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Int8Staque) Popque() (modified Int8Staque, first int8, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]int8, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type RuneStaque []rune
func NewRune() RuneStaque {
return RuneStaque{}
}
func (staque RuneStaque) Push(xs ...rune) RuneStaque {
return append(staque, xs...)
}
func (stk RuneStaque) Peekstk() (last rune, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que RuneStaque) Peekque() (first rune, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk RuneStaque) Popstk() (modified RuneStaque, last rune, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]rune, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que RuneStaque) Popque() (modified RuneStaque, first rune, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]rune, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type StringStaque []string
func NewString() StringStaque {
return StringStaque{}
}
func (staque StringStaque) Push(xs ...string) StringStaque {
return append(staque, xs...)
}
func (stk StringStaque) Peekstk() (last string, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que StringStaque) Peekque() (first string, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk StringStaque) Popstk() (modified StringStaque, last string, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]string, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que StringStaque) Popque() (modified StringStaque, first string, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]string, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type UintStaque []uint
func NewUint() UintStaque {
return UintStaque{}
}
func (staque UintStaque) Push(xs ...uint) UintStaque {
return append(staque, xs...)
}
func (stk UintStaque) Peekstk() (last uint, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que UintStaque) Peekque() (first uint, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk UintStaque) Popstk() (modified UintStaque, last uint, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]uint, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que UintStaque) Popque() (modified UintStaque, first uint, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]uint, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Uint16Staque []uint16
func NewUint16() Uint16Staque {
return Uint16Staque{}
}
func (staque Uint16Staque) Push(xs ...uint16) Uint16Staque {
return append(staque, xs...)
}
func (stk Uint16Staque) Peekstk() (last uint16, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Uint16Staque) Peekque() (first uint16, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Uint16Staque) Popstk() (modified Uint16Staque, last uint16, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]uint16, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Uint16Staque) Popque() (modified Uint16Staque, first uint16, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]uint16, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Uint32Staque []uint32
func NewUint32() Uint32Staque {
return Uint32Staque{}
}
func (staque Uint32Staque) Push(xs ...uint32) Uint32Staque {
return append(staque, xs...)
}
func (stk Uint32Staque) Peekstk() (last uint32, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Uint32Staque) Peekque() (first uint32, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Uint32Staque) Popstk() (modified Uint32Staque, last uint32, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]uint32, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Uint32Staque) Popque() (modified Uint32Staque, first uint32, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]uint32, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Uint64Staque []uint64
func NewUint64() Uint64Staque {
return Uint64Staque{}
}
func (staque Uint64Staque) Push(xs ...uint64) Uint64Staque {
return append(staque, xs...)
}
func (stk Uint64Staque) Peekstk() (last uint64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Uint64Staque) Peekque() (first uint64, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Uint64Staque) Popstk() (modified Uint64Staque, last uint64, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]uint64, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Uint64Staque) Popque() (modified Uint64Staque, first uint64, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]uint64, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type Uint8Staque []uint8
func NewUint8() Uint8Staque {
return Uint8Staque{}
}
func (staque Uint8Staque) Push(xs ...uint8) Uint8Staque {
return append(staque, xs...)
}
func (stk Uint8Staque) Peekstk() (last uint8, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que Uint8Staque) Peekque() (first uint8, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk Uint8Staque) Popstk() (modified Uint8Staque, last uint8, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]uint8, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que Uint8Staque) Popque() (modified Uint8Staque, first uint8, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]uint8, 0, cap(que)/2), que[1:]...), que[0], nil
}
}
type UintptrStaque []uintptr
func NewUintptr() UintptrStaque {
return UintptrStaque{}
}
func (staque UintptrStaque) Push(xs ...uintptr) UintptrStaque {
return append(staque, xs...)
}
func (stk UintptrStaque) Peekstk() (last uintptr, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypeek
} else {
last = stk[ilast]
}
return
}
func (que UintptrStaque) Peekque() (first uintptr, isempty error) {
if len(que) == 0 {
isempty = emptypeek
} else {
first = que[0]
}
return
}
func (stk UintptrStaque) Popstk() (modified UintptrStaque, last uintptr, isempty error) {
if ilast := len(stk) - 1; ilast < 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for last; so, we need named returns to set default values for last
} else if ilast < cap(stk)/4 {
return append(make([]uintptr, 0, cap(stk)/2), stk[:ilast]...), stk[ilast], nil
} else {
return stk[:ilast], stk[ilast], nil
}
}
func (que UintptrStaque) Popque() (modified UintptrStaque, first uintptr, isempty error) {
if len(que) == 0 {
isempty = emptypop // as this generic function will become multi-typed, we have many possible
return // zero values for first; so, we need named returns to set default values for first
} else if len(que) > cap(que)/4 {
return que[1:], que[0], nil
} else {
return append(make([]uintptr, 0, cap(que)/2), que[1:]...), que[0], nil
}
} | staque/staque_specialized.go | 0.680348 | 0.640678 | staque_specialized.go | starcoder |
package roadway
import (
"go-experiments/common/commonmath"
"go-experiments/voxelli/geometry"
"math"
"github.com/go-gl/mathgl/mgl32"
)
// Defines the default road type that is never in bounds
type OutOfBoundsRoad struct {
}
func (oob OutOfBoundsRoad) InBounds(position mgl32.Vec2) bool {
return false
}
func (oob OutOfBoundsRoad) GetBounds(gridPos commonMath.IntVec2) []geometry.Intersectable {
return []geometry.Intersectable{}
}
// Defines a road that is oriented in the X+ direction
type StraightRoad struct {
rotated bool // If true, the road is oriented in the Y+ direction instead
}
func (straightRoad StraightRoad) InBounds(position mgl32.Vec2) bool {
if straightRoad.rotated {
// Limitation is in the Y direction
return position.Y() > 1.0 && position.Y() < float32(GetGridSize()-1)
}
return position.X() > 1.0 && position.X() < float32(GetGridSize()-1)
}
func (straightRoad StraightRoad) GetBounds(gridPos commonMath.IntVec2) []geometry.Intersectable {
gridSize := float32(GetGridSize())
gridOffset := mgl32.Vec2{float32(gridPos.X()) * gridSize, float32(gridPos.Y()) * gridSize}
if straightRoad.rotated {
// Limitation on the top and the bottom
return []geometry.Intersectable{
geometry.NewLineSegment(mgl32.Vec2{0, gridSize}.Add(gridOffset), mgl32.Vec2{gridSize, gridSize}.Add(gridOffset)),
geometry.NewLineSegment(mgl32.Vec2{0, 0}.Add(gridOffset), mgl32.Vec2{gridSize, 0}.Add(gridOffset)),
}
}
return []geometry.Intersectable{
geometry.NewLineSegment(mgl32.Vec2{gridSize, 0}.Add(gridOffset), mgl32.Vec2{gridSize, gridSize}.Add(gridOffset)),
geometry.NewLineSegment(mgl32.Vec2{0, 0}.Add(gridOffset), mgl32.Vec2{0, gridSize}.Add(gridOffset)),
}
}
// Defines a curved road that starts out straight in the X- direction and curves in the Y+ direction
type CurvedRoad struct {
rotation int // Defines the number of times to rotate in the CW direction
}
func (curvedRoad CurvedRoad) InBounds(position mgl32.Vec2) bool {
gridExtent := float32(GetGridSize()) - 0.5
var length float32
switch curvedRoad.rotation % 4 {
case 0:
// Center == (gridExtent, 0) (down-to-right)
length = position.Sub(mgl32.Vec2{gridExtent, 0}).Len()
case 1:
// Center == (gridExtent, gridExtent) (up-to-right)
length = position.Sub(mgl32.Vec2{gridExtent, gridExtent}).Len()
case 2:
// Center == (0, gridExtent) (left-to-up)
length = position.Sub(mgl32.Vec2{0, gridExtent}).Len()
case 3:
// Center == (0, 0) (left-to-down)
length = position.Len()
}
return length < gridExtent
}
func (curvedRoad CurvedRoad) GetBounds(gridPos commonMath.IntVec2) []geometry.Intersectable {
gridSize := float32(GetGridSize())
gridOffset := mgl32.Vec2{float32(gridPos.X()) * gridSize, float32(gridPos.Y()) * gridSize}
var arc geometry.ArcSegment
switch curvedRoad.rotation % 4 {
case 0:
arc = geometry.NewArcSegment(mgl32.Vec2{gridSize, 0}.Add(gridOffset), gridSize, math.Pi/2, math.Pi)
case 1:
arc = geometry.NewArcSegment(mgl32.Vec2{gridSize, gridSize}.Add(gridOffset), gridSize, math.Pi, 3*math.Pi/2)
case 2:
arc = geometry.NewArcSegment(mgl32.Vec2{0, gridSize}.Add(gridOffset), gridSize, 3*math.Pi/2, 2*math.Pi)
case 3:
arc = geometry.NewArcSegment(mgl32.Vec2{0, 0}.Add(gridOffset), gridSize, 0, math.Pi/2)
}
return []geometry.Intersectable{arc}
} | voxelli/roadway/roadTypes.go | 0.82176 | 0.642348 | roadTypes.go | starcoder |
package cluster
import (
"fmt"
"strconv"
)
// NewIndex builds a new empty index for PodInfo.
func NewIndex() *Index {
return &Index{
Containers: make(Set),
DaemonSets: make(Set),
Deployments: make(Set),
Namespaces: make(Set),
Nodes: make(Set),
Pods: make(Set),
Running: make(Set),
StatefulSets: make(Set),
}
}
// Index provides indexes for a number of the cluster entities.
type Index struct {
Containers Set
DaemonSets Set
Deployments Set
Namespaces Set
Nodes Set
Pods Set
Running Set
StatefulSets Set
}
// Summary provides a summary overview of the number of entities in the cluster.
type Summary struct {
Containers int
DaemonSets int
Deployments int
Namespaces int
Nodes int
Pods int
Running int
StatefulSets int
}
// Summary provides a summary count for all of the entities.
func (index *Index) Summary() Summary {
return Summary{
Containers: index.Containers.Len(),
DaemonSets: index.DaemonSets.Len(),
Deployments: index.Deployments.Len(),
Nodes: index.Nodes.Len(),
Namespaces: index.Namespaces.Len(),
Pods: index.Pods.Len(),
Running: index.Running.Len(),
StatefulSets: index.StatefulSets.Len(),
}
}
const (
// DaemonSet is the related owner key for that type of k8s entity.
DaemonSet = "DaemonSet"
// ReplicaSet is the related owner key for that type of k8s entity.
ReplicaSet = "ReplicaSet"
// StatefulSet is the related owner key for that type of k8s entity.
StatefulSet = "StatefulSet"
)
// Each extracts the relevant pod details and integrates it into the index.
func (index *Index) Each(pod PodInfo) {
qualifiedName := fmt.Sprintf("%s/%s", pod.Namespace, pod.Name)
index.Pods.Add(qualifiedName)
if pod.IsRunning {
index.Running.Add(qualifiedName)
}
index.Namespaces.Add(pod.Namespace)
if pod.Host != "" {
index.Nodes.Add(pod.Host)
}
for i, c := range pod.Containers {
var name = c.Name
if name == "" {
name = strconv.Itoa(i)
}
index.Containers.Add(fmt.Sprintf("%s/%s", qualifiedName, name))
}
for n, t := range pod.Owners {
switch t {
case DaemonSet:
index.DaemonSets.Add(n)
break
case ReplicaSet: // hackish way to calculate deployments
index.Deployments.Add(n)
break
case StatefulSet:
index.StatefulSets.Add(n)
}
}
}
// Set provides a set collection for strings.
type Set map[string]bool
// Add integrates the item into the underlying set.
func (s Set) Add(item string) {
s[item] = true
}
// Len lists the number of items in the set.
func (s Set) Len() int {
return len(s)
} | cluster/index.go | 0.692122 | 0.407363 | index.go | starcoder |
package slippy
import "math"
func NewTile(z, x, y uint64, buffer float64, srid uint64) *Tile {
return &Tile{
z: z,
x: x,
y: y,
Buffer: buffer,
SRID: srid,
}
}
type Tile struct {
// zoom
z uint64
// column
x uint64
// row
y uint64
// buffer will add a buffer to the tile bounds. this buffer is expected to use the same units as the SRID
// of the projected tile (i.e. WebMercator = pixels, 3395 = meters)
Buffer float64
// spatial reference id
SRID uint64
}
func (t *Tile) ZXY() (uint64, uint64, uint64) {
return t.z, t.x, t.y
}
// TODO(arolek): return geom.Extent once it has been refactored
// TODO(arolek): support alternative SRIDs. Currently this assumes 3857
// Extent will return the tile extent excluding the tile's buffer and the Extent's SRID
func (t *Tile) Extent() (extent [2][2]float64, srid uint64) {
max := 20037508.34
// resolution
res := (max * 2) / math.Exp2(float64(t.z))
// unbuffered extent
return [2][2]float64{
{
-max + (float64(t.x) * res), // MinX
max - (float64(t.y) * res), // Miny
},
{
-max + (float64(t.x) * res) + res, // MaxX
max - (float64(t.y) * res) - res, // MaxY
},
}, t.SRID
}
// BufferedExtent will return the tile extent including the tile's buffer and the Extent's SRID
func (t *Tile) BufferedExtent() (bufferedExtent [2][2]float64, srid uint64) {
extent, _ := t.Extent()
// TODO(arolek): the following value is hard coded for MVT, but this concept needs to be abstracted to support different projections
mvtTileWidthHeight := 4096.0
// the bounds / extent
mvtTileExtent := [2][2]float64{{0 - t.Buffer, 0 - t.Buffer}, {mvtTileWidthHeight + t.Buffer, mvtTileWidthHeight + t.Buffer}}
xspan := extent[1][0] - extent[0][0]
yspan := extent[1][1] - extent[0][1]
bufferedExtent[0][0] = (mvtTileExtent[0][0] * xspan / mvtTileWidthHeight) + extent[0][0]
bufferedExtent[0][1] = (mvtTileExtent[0][1] * yspan / mvtTileWidthHeight) + extent[0][1]
bufferedExtent[1][0] = (mvtTileExtent[1][0] * xspan / mvtTileWidthHeight) + extent[0][0]
bufferedExtent[1][1] = (mvtTileExtent[1][1] * yspan / mvtTileWidthHeight) + extent[0][1]
return bufferedExtent, t.SRID
} | geom/slippy/tile.go | 0.516595 | 0.436922 | tile.go | starcoder |
package KsanaDB
import(
"math"
"errors"
)
type aggFunc func(float64, float64, ...interface{}) float64
var fnRegistry = map[string] interface{} {
"sum": func(sum float64, val float64, others ...interface{}) float64 {
return sum + val
},
"max": func() func(dummy float64, val float64, others ...interface{}) float64 {
max := (-1)*math.MaxFloat64
return func(dummy float64, val float64, others ...interface{}) float64 {
if max < val {
max = val
return val
} else {
return max
}
}
},
"min": func() func(dummy float64, val float64, others ...interface{}) float64 {
min := math.MaxFloat64
return func(dummy float64, val float64, others ...interface{}) float64 {
if min > val {
min = val
return val
} else {
return min
}
}
},
"count": func(sum float64, val float64, others ...interface{}) float64 {
return sum + 1
},
"avg": func() func(dummy float64, val float64, others ...interface{}) float64 {
i := 0
sum := float64(0)
return func(dummy float64, val float64, others ...interface{}) float64 {
i = i + 1
sum = sum + val
return sum/float64(i)
}
},
"std": func() func(dummy float64, val float64, others ...interface{}) float64 {
i := 0
mean := float64(0)
m2 := float64(0)
// Welford's algorithm
return func(dummy float64, val float64, others ...interface{}) float64 {
i = i + 1
delta := val - mean
mean = mean + delta / float64(i)
m2 = m2 + delta * (val - mean)
if i < 2 {
return math.SmallestNonzeroFloat64
}
return math.Sqrt(m2/float64((i-1)))
}
},
"first": func() func(dummy float64, val float64, others ...interface{}) float64 {
var first *float64
return func(dummy float64, val float64, others ...interface{}) float64 {
if first == nil {
first = &val
}
return *first
}
},
"raw": func(dummy float64, val float64, others ...interface{}) float64 {
return val
},
}
func getFuncMap(funName string) func(float64, float64, ...interface{}) float64 {
var aggf aggFunc
switch funName {
case "sum":
aggf = fnRegistry["sum"].(func(float64, float64, ...interface{}) float64)
case "max":
f := fnRegistry["max"].(func() func(float64, float64, ...interface{}) float64)
aggf = f()
case "min":
f := fnRegistry["min"].(func() func(float64, float64, ...interface{}) float64)
aggf = f()
case "count":
aggf = fnRegistry["count"].(func(float64, float64, ...interface{}) float64)
case "avg":
f := fnRegistry["avg"].(func() func(float64, float64, ...interface{}) float64)
aggf = f()
case "std":
f := fnRegistry["std"].(func() func(float64, float64, ...interface{}) float64)
aggf = f()
case "first":
f := fnRegistry["first"].(func() func(float64, float64, ...interface{}) float64)
aggf = f()
case "raw", "last":
aggf = fnRegistry["raw"].(func(float64, float64, ...interface{}) float64)
}
return aggf
}
func isTimeRangeFunction(f string) (bool, error) {
ret := false
var err error
switch f {
case "sum", "max", "min", "count", "avg", "std", "first", "last":
ret = true
case "raw":
ret = false
default:
err = errors.New("no such aggreate function")
}
return ret, err
} | Core/Aggregator.go | 0.603114 | 0.410343 | Aggregator.go | starcoder |
// Package testonly contains code and data for testing Merkle trees, such as a
// reference implementation of in-memory Merkle tree.
package testonly
import "encoding/hex"
// LeafInputs returns a slice of leaf inputs for testing Merkle trees.
func LeafInputs() [][]byte {
return [][]byte{
hd(""),
hd("00"),
hd("10"),
hd("2021"),
hd("3031"),
hd("40414243"),
hd("5051525354555657"),
hd("606162636465666768696a6b6c6d6e6f"),
}
}
// NodeHashes returns a structured slice of node hashes for all complete
// subtrees of a Merkle tree built from LeafInputs() using the RFC 6962 hashing
// strategy. The first index in the slice is the tree level (zero being the
// leaves level), the second is the horizontal index within a level.
func NodeHashes() [][][]byte {
return [][][]byte{{
hd("6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d"),
hd("96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7"),
hd("<KEY>"),
hd("07506a85fd9dd2f120eb694f86011e5bb4662e5c415a62917033d4a9624487e7"),
hd("bc1a0643b12e4d2d7c77918f44e0f4f79a838b6cf9ec5b5c283e1f4d88599e6b"),
hd("4271a26be0d8a84f0bd54c8c302e7cb3a3b5d1fa6780a40bcce2873477dab658"),
hd("b08693ec2e721597130641e8211e7eedccb4c26413963eee6c1e2ed16ffb1a5f"),
hd("46f6ffadd3d06a09ff3c5860d2755c8b9819db7df44251788c7d8e3180de8eb1"),
}, {
hd("fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125"),
hd("5f083f0a1a33ca076a95279832580db3e0ef4584bdff1f54c8a360f50de3031e"),
hd("0ebc5d3437fbe2db158b9f126a1d118e308181031d0a949f8dededebc558ef6a"),
hd("ca854ea128ed050b41b35ffc1b87b8eb2bde461e9e3b5596ece6b9d5975a0ae0"),
}, {
hd("d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7"),
hd("6b47aaf29ee3c2af9af889bc1fb9254dabd31177f16232dd6aab035ca39bf6e4"),
}, {
hd("5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328"),
}}
}
// RootHashes returns a slice of Merkle tree root hashes for all subsequent
// trees built from LeafInputs() using the RFC 6962 hashing strategy. Hashes
// are indexed by tree size starting from an empty tree.
func RootHashes() [][]byte {
return [][]byte{
EmptyRootHash(),
hd("6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d"),
hd("fac54203e7cc696cf0dfcb42c92a1d9dbaf70ad9e621f4bd8d98662f00e3c125"),
hd("aeb6bcfe274b70a14fb067a5e5578264db0fa9b51af5e0ba159158f329e06e77"),
hd("d37ee418976dd95753c1c73862b9398fa2a2cf9b4ff0fdfe8b30cd95209614b7"),
hd("4e3bbb1f7b478dcfe71fb631631519a3bca12c9aefca1612bfce4c13a86264d4"),
hd("76e67dadbcdf1e10e1b74ddc608abd2f98dfb16fbce75277b5232a127f2087ef"),
hd("ddb89be403809e325750d3d263cd78929c2942b7942a34b77e122c9594a74c8c"),
hd("5dc9da79a70659a9ad559cb701ded9a2ab9d823aad2f4960cfe370eff4604328"),
}
}
// CompactTrees returns a slice of compact.Tree internal hashes for all
// subsequent trees built from LeafInputs() using the RFC 6962 hashing
// strategy.
func CompactTrees() [][][]byte {
nh := NodeHashes()
return [][][]byte{
nil, // Empty tree.
{nh[0][0]},
{nh[1][0]},
{nh[1][0], nh[0][2]},
{nh[2][0]},
{nh[2][0], nh[0][4]},
{nh[2][0], nh[1][2]},
{nh[2][0], nh[1][2], nh[0][6]},
{nh[3][0]},
}
}
// EmptyRootHash returns the root hash for an empty Merkle tree that uses
// SHA256-based strategy from RFC 6962.
func EmptyRootHash() []byte {
return hd("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
}
// hd decodes a hex string or panics.
func hd(b string) []byte {
r, err := hex.DecodeString(b)
if err != nil {
panic(err)
}
return r
} | testonly/constants.go | 0.739328 | 0.449574 | constants.go | starcoder |
package consensus
import "math"
// The Difficulty is defined as the maximum target divided by the block hash.
type Difficulty struct {
num uint64
}
func (p *Difficulty) zero() Difficulty {
return Difficulty{num: 0}
}
// Difficulty of MIN_DIFFICULTY
func (p *Difficulty) min() Difficulty {
return Difficulty{num: MinDifficulty}
}
// Unit is a difficulty unit, which is the graph weight of minimal graph
func (p *Difficulty) Unit(chainType ChainType) Difficulty {
return Difficulty{num: uint64(initialGraphWeight(chainType))}
}
// FromNum converts a `uint64` into a `Difficulty`
func (p *Difficulty) FromNum(num uint64) Difficulty {
// can't have difficulty lower than 1
return Difficulty{num: uint64(math.Max(float64(num), 1))}
}
// saturatingSubUint8 is a saturating uint8 subtraction. Computes a - b, saturating at the numeric bounds instead of overflowing.
func saturatingSubUint8(a, b uint8) uint8 {
if a < b {
return 0
}
return a - b
}
// saturatingSubUint16 is a saturating uint16 subtraction. Computes a - b, saturating at the numeric bounds instead of overflowing.
func saturatingSubUint16(a, b uint16) uint16 {
if a < b {
return 0
}
return a - b
}
// saturatingSubUint32 is a saturating uint32 subtraction. Computes a - b, saturating at the numeric bounds instead of overflowing.
func saturatingSubUint32(a, b uint32) uint32 {
if a < b {
return 0
}
return a - b
}
// saturatingSubUint64 is a saturating uint64 subtraction. Computes a - b, saturating at the numeric bounds instead of overflowing.
func saturatingSubUint64(a, b uint64) uint64 {
if a < b {
return 0
}
return a - b
}
// saturatingAddUint8 is a saturating uint8 addition. Computes a + b, saturating at the numeric bounds instead of overflowing.
func saturatingAddUint8(a, b uint8) uint8 {
c := a + b
if c < a {
return math.MaxUint8
}
return a + b
}
// saturatingAddUint16 is a saturating uint16 addition. Computes a + b, saturating at the numeric bounds instead of overflowing.
func saturatingAddUint16(a, b uint16) uint16 {
c := a + b
if c < a {
return math.MaxUint16
}
return a + b
}
// saturatingAddUint32 is a saturating uint32 addition. Computes a + b, saturating at the numeric bounds instead of overflowing.
func saturatingAddUint32(a, b uint32) uint32 {
c := a + b
if c < a {
return math.MaxUint32
}
return a + b
}
// saturatingAddUint64 is a saturating uint64 addition. Computes a + b, saturating at the numeric bounds instead of overflowing.
func saturatingAddUint64(a, b uint64) uint64 {
c := a + b
if c < a {
return math.MaxUint64
}
return a + b
} | core/consensus/types.go | 0.866373 | 0.447158 | types.go | starcoder |
package lexer
import (
"io"
)
// BufferedReader describes the interface for a buffered reader, that stores
// the read contents in a buffer until it gets reset.
type BufferedReader interface {
// StartPos returns the position of the total input since the last reset.
StartPos() int
// CurrPos returns the current position relative to the total input.
CurrPos() int
// Current returns the byte at the current position.
Current() byte
// All returns the whole content of the buffer.
All() []byte
// Next returns the next byte read from the input. If an error occurred
// during the read process or if the reader is at the end of its input the
// second return value is false.
Next() (byte, bool)
// Backup moves the position of the buffer one to the left.
Backup()
// Reset resets the buffer content.
Reset()
}
// BufferedIOReader implements the BufferedReader with an io.Reader as input.
type BufferedIOReader struct {
reader io.Reader
buf []byte
pos int
start int
}
// NewBufferedReader returns a new buffered reader, that reads from the given
// io.Reader.
func NewBufferedReader(reader io.Reader) *BufferedIOReader {
return &BufferedIOReader{
reader: reader,
buf: make([]byte, 0),
pos: 0,
start: 0,
}
}
// StartPos returns the position of the total input since the last reset.
func (r *BufferedIOReader) StartPos() int {
return r.start
}
// CurrPos returns the current position relative to the total input.
func (r *BufferedIOReader) CurrPos() int {
return r.pos + r.start
}
// Current returns the byte at the current position.
func (r *BufferedIOReader) Current() byte {
return r.buf[r.pos-1]
}
// All returns the whole content of the buffer.
func (r *BufferedIOReader) All() []byte {
return r.buf[0:r.pos]
}
// Next returns the next byte read from the input. If an error occurred
// during the read process or if the reader is at the end of its input the
// second return value is false.
func (r *BufferedIOReader) Next() (byte, bool) {
if r.pos < len(r.buf) {
r.pos++
return r.Current(), true
}
bt := make([]byte, 1, 1)
_, err := r.reader.Read(bt)
if err != nil {
return 0, false
}
r.buf = append(r.buf, bt[0])
r.pos++
return r.Current(), true
}
// Backup moves the position of the buffer one to the left.
func (r *BufferedIOReader) Backup() {
r.pos--
}
// Reset resets the buffer content.
func (r *BufferedIOReader) Reset() {
r.buf = r.buf[r.pos:len(r.buf)]
r.start = r.CurrPos()
r.pos = 0
}
// StaticBufferedReader implements a buffered reader with a string as input.
type StaticBufferedReader struct {
str string
pos int
start int
}
// NewBufferedReaderFromString returns a new buffered reader, with the given
// string as input.
func NewBufferedReaderFromString(str string) *StaticBufferedReader {
return &StaticBufferedReader{
str: str,
pos: 0,
start: 0,
}
}
// StartPos returns the position of the total input since the last reset.
func (r *StaticBufferedReader) StartPos() int {
return r.start
}
// CurrPos returns the current position relative to the total input.
func (r *StaticBufferedReader) CurrPos() int {
return r.pos
}
// Current returns the byte at the current position.
func (r *StaticBufferedReader) Current() byte {
if r.pos == 0 {
return 0
}
return r.str[r.pos-1]
}
// All returns the whole content of the buffer.
func (r *StaticBufferedReader) All() []byte {
return []byte(r.str[r.start:r.pos])
}
// Next returns the next byte read from the input. If an error occurred
// during the read process or if the reader is at the end of its input the
// second return value is false.
func (r *StaticBufferedReader) Next() (byte, bool) {
if r.pos >= len(r.str) {
return 0, false
}
r.pos++
return r.Current(), true
}
// Backup moves the position of the buffer one to the left.
func (r *StaticBufferedReader) Backup() {
r.pos--
}
// Reset resets the buffer content.
func (r *StaticBufferedReader) Reset() {
r.start = r.pos
} | lexer/reader.go | 0.771672 | 0.493409 | reader.go | starcoder |
package callback
import (
"encoding/binary"
"io"
"math"
)
// WriteFn is a function type that writes the provided samples to the
// specified io.Writer. It returns the number of bytes written and a non-nil
// error if an error is encountered during write.
type WriteFn func(out io.Writer, x []int16) (int, error)
// NewWriteFn creates a new WriteFn that writes samples using the provided
// ByteOrder. The function uses an internal persistent buffer to avoid
// allocations. In comparison, calling encoding/binary on a slice will
// allocate a new []byte on each call.
func NewWriteFn(order binary.ByteOrder) WriteFn {
const sizeOfScalar = 2
buf := make([]byte, 4096)
return func(out io.Writer, x []int16) (int, error) {
numBytes := len(x) * sizeOfScalar
if len(buf) < numBytes {
next := len(buf) * sizeOfScalar
if next < numBytes {
next = numBytes
}
buf = make([]byte, next)
}
switch order {
case binary.LittleEndian:
bi := 0
for i := range x {
binary.LittleEndian.PutUint16(buf[bi:], uint16(x[i]))
bi += sizeOfScalar
}
case binary.BigEndian:
bi := 0
for i := range x {
binary.BigEndian.PutUint16(buf[bi:], uint16(x[i]))
bi += sizeOfScalar
}
default:
bi := 0
for i := range x {
order.PutUint16(buf[bi:], uint16(x[i]))
bi += sizeOfScalar
}
}
return out.Write(buf[:numBytes])
}
}
// Float32WriteFn is a function type that writes the provided samples to the
// specified io.Writer. It returns the number of bytes written and a non-nil
// error if an error is encountered during write.
type Float32WriteFn func(out io.Writer, x []float32) (int, error)
// NewFloat32WriteFn creates a new Float32WriteFn that writes samples using
// the provided ByteOrder. The function uses an internal persistent buffer
// to avoid allocations. In comparison, calling encoding/binary on a slice
// will allocate a new []byte on each call.
func NewFloat32WriteFn(order binary.ByteOrder) Float32WriteFn {
const sizeOfScalar = 4
buf := make([]byte, 4096)
return func(out io.Writer, x []float32) (int, error) {
numBytes := len(x) * sizeOfScalar
if len(buf) < numBytes {
next := len(buf) * 2
if next < numBytes {
next = numBytes
}
buf = make([]byte, next)
}
switch order {
case binary.LittleEndian:
bi := 0
for i := range x {
binary.LittleEndian.PutUint32(buf[bi:], math.Float32bits(x[i]))
bi += sizeOfScalar
}
case binary.BigEndian:
bi := 0
for i := range x {
binary.BigEndian.PutUint32(buf[bi:], math.Float32bits(x[i]))
bi += sizeOfScalar
}
default:
bi := 0
for i := range x {
order.PutUint32(buf[bi:], math.Float32bits(x[i]))
bi += sizeOfScalar
}
}
return out.Write(buf[:numBytes])
}
}
// Complex64WriteFn is a function type that writes the provided samples to the
// specified io.Writer. It returns the number of bytes written and a non-nil
// error if an error is encountered during write.
type Complex64WriteFn func(out io.Writer, x []complex64) (int, error)
// NewComplex64WriteFn creates a new Complex64WriteFn that writes samples using
// the provided ByteOrder. The function uses an internal persistent buffer
// to avoid allocations. In comparison, calling encoding/binary on a slice
// will allocate a new []byte on each call.
func NewComplex64WriteFn(order binary.ByteOrder) Complex64WriteFn {
const (
sizeOfScalar = 4
scalarsPerFrame = 2
sizeOfFrame = sizeOfScalar * scalarsPerFrame
)
buf := make([]byte, 4096)
return func(out io.Writer, x []complex64) (int, error) {
numBytes := len(x) * sizeOfFrame
if len(buf) < numBytes {
next := len(buf) * 2
if next < numBytes {
next = numBytes
}
buf = make([]byte, next)
}
switch order {
case binary.BigEndian:
bi := 0
for i := range x {
binary.BigEndian.PutUint32(buf[bi:], math.Float32bits(real(x[i])))
binary.BigEndian.PutUint32(buf[bi+sizeOfScalar:], math.Float32bits(imag(x[i])))
bi += sizeOfFrame
}
case binary.LittleEndian:
bi := 0
for i := range x {
binary.LittleEndian.PutUint32(buf[bi:], math.Float32bits(real(x[i])))
binary.LittleEndian.PutUint32(buf[bi+sizeOfScalar:], math.Float32bits(imag(x[i])))
bi += sizeOfFrame
}
default:
bi := 0
for i := range x {
order.PutUint32(buf[bi:], math.Float32bits(real(x[i])))
order.PutUint32(buf[bi+sizeOfScalar:], math.Float32bits(imag(x[i])))
bi += sizeOfFrame
}
}
return out.Write(buf[:numBytes])
}
} | helpers/callback/write.go | 0.694199 | 0.487124 | write.go | starcoder |
package ast
import (
"fmt"
"strings"
"github.com/genelet/sqlproto/xast"
"github.com/akito0107/xsqlparser/sqlast"
"github.com/akito0107/xsqlparser/sqltoken"
)
func xposTo(pos sqltoken.Pos) *xast.Pos {
return &xast.Pos{
Line:int32(pos.Line),
Col:int32(pos.Col)}
}
func posTo(pos *xast.Pos) sqltoken.Pos {
return sqltoken.Pos{
Line:int(pos.Line),
Col:int(pos.Col)}
}
func xposplusTo(pos sqltoken.Pos) *xast.Pos {
return &xast.Pos{
Line:int32(pos.Line),
Col:int32(pos.Col)+1}
}
func xidentTo(ident *sqlast.Ident) *xast.Ident {
if ident == nil { return nil }
return &xast.Ident{
Value: ident.Value,
From: xposTo(ident.From),
To: xposTo(ident.To)}
}
func xwildcardTo(card *sqlast.Wildcard) *xast.Ident {
if card == nil { return nil }
return &xast.Ident{
Value: "*",
From: xposTo(card.Wildcard),
To: xposplusTo(card.Wildcard)}
}
func identTo(ident *xast.Ident) sqlast.Node {
if ident == nil { return nil }
if ident.Value== "*" {
return &sqlast.Wildcard{Wildcard: posTo(ident.From)}
}
return &sqlast.Ident{
Value: ident.Value,
From: posTo(ident.From),
To: posTo(ident.To)}
}
func xidentsTo(ident *sqlast.Ident) *xast.CompoundIdent {
if ident == nil { return nil }
return &xast.CompoundIdent{Idents:[]*xast.Ident{xidentTo(ident)}}
}
func xwildcardsTo(card *sqlast.Wildcard) *xast.CompoundIdent {
if card == nil { return nil }
return &xast.CompoundIdent{Idents:[]*xast.Ident{xwildcardTo(card)}}
}
func xcompoundTo(idents *sqlast.CompoundIdent) *xast.CompoundIdent {
if idents == nil { return nil }
var xs []*xast.Ident
for _, item := range idents.Idents {
xs = append(xs, xidentTo(item))
}
return &xast.CompoundIdent{Idents:xs}
}
func xwildcarditemTo(t *sqlast.QualifiedWildcardSelectItem) *xast.CompoundIdent {
if t == nil { return nil }
comp := xobjectnameTo(t.Prefix)
comp.Idents = append(comp.Idents, &xast.Ident{
Value: "*",
From: xposTo(t.Pos()),
To: xposplusTo(t.Pos())})
return comp
}
func compoundTo(idents *xast.CompoundIdent) sqlast.Node {
if idents == nil { return nil }
if len(idents.Idents) == 1 {
return identTo(idents.Idents[0])
}
var xs []*sqlast.Ident
for _, item := range idents.Idents {
switch t := identTo(item).(type) {
case *sqlast.Wildcard:
return &sqlast.QualifiedWildcardSelectItem{
Prefix: &sqlast.ObjectName{Idents:xs}}
case *sqlast.Ident:
xs = append(xs, t)
default:
}
}
return &sqlast.CompoundIdent{Idents:xs}
}
func xobjectnameTo(idents *sqlast.ObjectName) *xast.CompoundIdent {
if idents == nil { return nil }
var xs []*xast.Ident
for _, item := range idents.Idents {
xs = append(xs, xidentTo(item))
}
return &xast.CompoundIdent{Idents:xs}
}
func compoundToObjectname(idents *xast.CompoundIdent) *sqlast.ObjectName {
if idents == nil { return nil }
var xs []*sqlast.Ident
for _, item := range idents.Idents {
xs = append(xs, identTo(item).(*sqlast.Ident))
}
return &sqlast.ObjectName{Idents:xs}
}
func xoperatorTo(op *sqlast.Operator) *xast.Operator {
if op == nil { return nil }
return &xast.Operator{
Type: xast.OperatorType(op.Type),
From: xposTo(op.From),
To: xposTo(op.To)}
}
func operatorTo(op *xast.Operator) *sqlast.Operator {
if op == nil { return nil }
return &sqlast.Operator{
Type: sqlast.OperatorType(op.Type),
From: posTo(op.From),
To: posTo(op.To)}
}
func xjointypeTo(t *sqlast.JoinType) *xast.JoinType {
if t == nil { return nil }
return &xast.JoinType{
Condition: xast.JoinTypeCondition(t.Condition),
From: xposTo(t.From),
To: xposTo(t.To)}
}
func jointypeTo(t *xast.JoinType) *sqlast.JoinType {
if t == nil { return nil }
return &sqlast.JoinType{
Condition: sqlast.JoinTypeCondition(t.Condition),
From: posTo(t.From),
To: posTo(t.To)}
}
func xstringTo(t *sqlast.SingleQuotedString) *xast.StringUnit {
if t == nil { return nil }
return &xast.StringUnit{
Value: t.String,
From: xposTo(t.From),
To: xposTo(t.To)}
}
func stringTo(t *xast.StringUnit) *sqlast.SingleQuotedString {
if t == nil { return nil }
return &sqlast.SingleQuotedString{
String: t.Value,
From: posTo(t.From),
To: posTo(t.To)}
}
func xdoubleTo(t *sqlast.DoubleValue) *xast.DoubleUnit {
if t == nil { return nil }
return &xast.DoubleUnit{
Value: t.Double,
From: xposTo(t.From),
To: xposTo(t.To)}
}
func doubleTo(t *xast.DoubleUnit) *sqlast.DoubleValue {
if t == nil { return nil }
return &sqlast.DoubleValue{
Double: t.Value,
From: posTo(t.From),
To: posTo(t.To)}
}
func xlongTo(t *sqlast.LongValue) *xast.LongUnit {
if t == nil { return nil }
return &xast.LongUnit{
Value: t.Long,
From: xposTo(t.From),
To: xposTo(t.To)}
}
func longTo(t *xast.LongUnit) *sqlast.LongValue {
if t == nil { return nil }
return &sqlast.LongValue{
Long: t.Value,
From: posTo(t.From),
To: posTo(t.To)}
}
func xfunctionTo(s *sqlast.Function) (*xast.AggFunction, *xast.CompoundIdent) {
if s == nil { return nil, nil }
name := s.Name.Idents[0]
aggType := xast.AggType(xast.AggType_value[strings.ToUpper(name.Value)])
var args []*xast.CompoundIdent
for _, item := range s.Args {
switch t := item.(type) {
case *sqlast.Ident:
args = append(args, xidentsTo(t))
case *sqlast.CompoundIdent:
args = append(args, xcompoundTo(t))
case *sqlast.Wildcard:
args = append(args, xwildcardsTo(t))
default:
args = append(args, nil)
}
}
return &xast.AggFunction{
TypeName: aggType,
RestArgs: args[1:],
From: xposTo(name.From),
To: xposTo(name.To)}, args[0]
}
func functionTo(f *xast.AggFunction, c *xast.CompoundIdent) *sqlast.Function {
if f == nil { return nil }
aggname := xast.AggType_name[int32(f.TypeName)]
on := &sqlast.ObjectName{Idents:[]*sqlast.Ident{&sqlast.Ident{
Value: aggname,
From: posTo(f.From),
To: posTo(f.To)}}}
if c == nil { return &sqlast.Function{Name: on} }
var args []sqlast.Node
args = append(args, compoundTo(c))
for _, item := range f.RestArgs {
args = append(args, compoundTo(item))
}
return &sqlast.Function{
Name: on,
Args: args}
}
func xsetoperatorTo(op sqlast.SQLSetOperator) (*xast.SetOperator, error) {
xop := &xast.SetOperator{}
switch t := op.(type) {
case *sqlast.UnionOperator:
xop.Type = xast.SetOperatorType_Union
xop.From = xposTo(t.From)
xop.To = xposTo(t.To)
case *sqlast.IntersectOperator:
xop.Type = xast.SetOperatorType_Intersect
xop.From = xposTo(t.From)
xop.To = xposTo(t.To)
case *sqlast.ExceptOperator:
xop.Type = xast.SetOperatorType_Except
xop.From = xposTo(t.From)
xop.To = xposTo(t.To)
default:
return nil, fmt.Errorf("unknow set operation %#v", op)
}
return xop, nil
}
func setoperatorTo(op *xast.SetOperator) sqlast.SQLSetOperator {
switch op.Type {
case xast.SetOperatorType_Union:
return &sqlast.UnionOperator{
From: posTo(op.From),
To: posTo(op.To)}
case xast.SetOperatorType_Intersect:
return &sqlast.IntersectOperator{
From: posTo(op.From),
To: posTo(op.To)}
case xast.SetOperatorType_Except:
return &sqlast.ExceptOperator{
From: posTo(op.From),
To: posTo(op.To)}
default:
}
return nil
} | ast/basic.go | 0.526586 | 0.588771 | basic.go | starcoder |
package scene
import "github.com/mokiat/gomath/dprec"
type Segment struct {
Left VerticalLine
Right VerticalLine
Normal dprec.Vec3
Lines []Line
TextureName string
}
func (s Segment) Middle() VerticalLine {
return VerticalLine{
X: (s.Left.X + s.Right.X) / 2.0,
Z: (s.Left.Z + s.Right.Z) / 2.0,
}
}
func (s Segment) Top() float64 {
if len(s.Lines) == 0 {
return 0.0
}
line := s.Lines[0]
result := dprec.Max(line.P1.Y, line.P2.Y)
for _, line := range s.Lines {
result = dprec.Max(result, line.P1.Y)
result = dprec.Max(result, line.P2.Y)
}
return result
}
func (s Segment) Bottom() float64 {
if len(s.Lines) == 0 {
return 0.0
}
line := s.Lines[0]
result := dprec.Min(line.P1.Y, line.P2.Y)
for _, line := range s.Lines {
result = dprec.Min(result, line.P1.Y)
result = dprec.Min(result, line.P2.Y)
}
return result
}
func (s Segment) ContainsVerticalLine(line VerticalLine, precision float64) bool {
lineOffset := dprec.Vec3Diff(line.FlatPoint(), s.Middle().FlatPoint())
surfaceDistance := dprec.Vec3Dot(
s.Normal,
lineOffset,
)
if dprec.Abs(surfaceDistance) > precision {
return false
}
segmentLength := dprec.Vec3Diff(s.Right.FlatPoint(), s.Left.FlatPoint()).Length()
lineOffsetLength := lineOffset.Length()
return lineOffsetLength-precision < segmentLength/2.0
}
func (s Segment) LeftPartition(verticalLine VerticalLine, precision float64) Segment {
var partitionedLines []Line
for _, line := range s.Lines {
flatDistanceP1 := dprec.Vec3Diff(line.FlatP1(), s.Left.FlatPoint()).Length()
flatDistanceP2 := dprec.Vec3Diff(line.FlatP2(), s.Left.FlatPoint()).Length()
flatDistanceVerticalLine := dprec.Vec3Diff(verticalLine.FlatPoint(), s.Left.FlatPoint()).Length()
switch {
case flatDistanceP1 <= flatDistanceVerticalLine && flatDistanceP2 <= flatDistanceVerticalLine:
partitionedLines = append(partitionedLines, line)
case flatDistanceP1 <= flatDistanceVerticalLine && flatDistanceP2 >= flatDistanceVerticalLine:
partitionedLines = append(partitionedLines, line.P1Partition(verticalLine))
case flatDistanceP2 <= flatDistanceVerticalLine && flatDistanceP1 >= flatDistanceVerticalLine:
partitionedLines = append(partitionedLines, line.P2Partition(verticalLine))
}
}
return Segment{
Left: s.Left,
Right: verticalLine,
Normal: s.Normal,
Lines: partitionedLines,
TextureName: s.TextureName,
}
}
func (s Segment) RightPartition(verticalLine VerticalLine, precision float64) Segment {
var partitionedLines []Line
for _, line := range s.Lines {
flatDistanceP1 := dprec.Vec3Diff(line.FlatP1(), s.Left.FlatPoint()).Length()
flatDistanceP2 := dprec.Vec3Diff(line.FlatP2(), s.Left.FlatPoint()).Length()
flatDistanceVerticalLine := dprec.Vec3Diff(verticalLine.FlatPoint(), s.Left.FlatPoint()).Length()
switch {
case flatDistanceP1 >= flatDistanceVerticalLine && flatDistanceP2 >= flatDistanceVerticalLine:
partitionedLines = append(partitionedLines, line)
case flatDistanceP1 <= flatDistanceVerticalLine && flatDistanceP2 >= flatDistanceVerticalLine:
partitionedLines = append(partitionedLines, line.P2Partition(verticalLine))
case flatDistanceP2 <= flatDistanceVerticalLine && flatDistanceP1 >= flatDistanceVerticalLine:
partitionedLines = append(partitionedLines, line.P1Partition(verticalLine))
}
}
return Segment{
Left: verticalLine,
Right: s.Right,
Normal: s.Normal,
Lines: partitionedLines,
TextureName: s.TextureName,
}
}
type SegmentList []Segment | cmd/softgfx-lvlgen/internal/scene/segment.go | 0.728072 | 0.440168 | segment.go | starcoder |
package vida
import (
"bytes"
"fmt"
"strconv"
)
// Value interface models the inteface for all Vida Values.
type Value interface {
TypeName() string
Description() string
Equals(Value) bool
BinaryOp(byte, Value) (Value, error)
PrefixOp(byte) (Value, error)
IsIterable() bool
MakeIterator() Iterator
IsHashable() bool
MakeHashKey() HashKey
IsValueSemantics() bool
HasMethods() bool
GetMethod(string) (Value, bool, error)
Clone() Value
}
// SelectorOperable interface for Values implementing operator selector (value '.' property)
type SelectorOperable interface {
SelectorGet(string) (Value, error)
SelectorSet(string, Value) error
}
// SubscriptOperable interface for Values implementing operator subscript (value '[expr]')
type SubscriptOperable interface {
SubscriptGet(Value) (Value, error)
SubscriptSet(Value, Value) error
}
// SliceOperable interface for Values implementing slice operator subscript (value '[e:e]' | '[e:]' | '[:e]' | '[:]')
type SliceOperable interface {
SliceGet(UInt32, Value, Value) (Value, error)
SliceSet(UInt32, Value, Value, Value) error
}
// HashKey models a key for a Map and Set collections.
type HashKey struct {
Type string
ValueDescription string
}
// Interface Value
func (hash HashKey) TypeName() string {
return "HashKey"
}
func (hash HashKey) Description() string {
return fmt.Sprintf("hashkey(%v)", hash.ValueDescription)
}
func (hash HashKey) Equals(other Value) bool {
if value, ok := other.(HashKey); ok {
return hash.Type == value.Type && hash.ValueDescription == value.ValueDescription
}
return false
}
func (hash HashKey) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, hash)
}
func (hash HashKey) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, hash)
}
func (hash HashKey) IsIterable() bool {
return false
}
func (hash HashKey) MakeIterator() Iterator {
return nil
}
func (hash HashKey) IsHashable() bool {
return true
}
func (hash HashKey) MakeHashKey() HashKey {
return hash
}
func (hash HashKey) IsValueSemantics() bool {
return false
}
func (hash HashKey) HasMethods() bool {
return false
}
func (hash HashKey) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, hash)
}
func (hash HashKey) Clone() Value {
return HashKey{Type: hash.Type, ValueDescription: hash.ValueDescription}
}
// Type IStop is a type for signaling the exhaustation of iterators.
type IStop byte
// Interface Value
func (istop IStop) TypeName() string {
return "<IStop>"
}
func (eof IStop) Description() string {
return "<IStop>"
}
func (istop IStop) Equals(other Value) bool {
_, ok := other.(IStop)
return ok
}
func (istop IStop) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, istop)
}
func (istop IStop) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, istop)
}
func (istop IStop) IsIterable() bool {
return false
}
func (istop IStop) MakeIterator() Iterator {
return nil
}
func (istop IStop) IsHashable() bool {
return true
}
func (istop IStop) MakeHashKey() HashKey {
return HashKey{
Type: istop.TypeName(),
ValueDescription: istop.Description(),
}
}
func (istop IStop) IsValueSemantics() bool {
return true
}
func (istop IStop) HasMethods() bool {
return false
}
func (istop IStop) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, istop)
}
func (istop IStop) Clone() Value {
return istop
}
// Function models the static representation of callable, executable code.
type Function struct {
Name string // The name of the function.
Arity UInt32 // The arity of the function.
Vararg bool // The function can receive an arbitrary number of args.
FreeVarCount Bytecode // Count of free variables.
Code []Bytecode // The Bytecode of the function.
Lines map[UInt32]UInt32 // A map between Bytecode to number lines.
Constants []Value // The constant list of values of the function.
ModuleName string // The module in this function has been defined.
CanAccessPrivateState bool // The function can access private state of an instance.
}
// Interface Value
func (function Function) TypeName() string {
return "Function"
}
func (function Function) Description() string {
if function.Vararg {
if function.Arity == 0 {
return fmt.Sprintf("function(%v/...)", function.Name)
}
return fmt.Sprintf("function(%v/%v...)", function.Name, function.Arity)
}
return fmt.Sprintf("function(%v/%v)", function.Name, function.Arity)
}
func (function Function) Equals(other Value) bool {
if value, ok := other.(Function); ok {
return fmt.Sprint(function) == fmt.Sprint(value)
}
return false
}
func (function Function) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, function)
}
func (function Function) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, function)
}
func (function Function) IsIterable() bool {
return false
}
func (function Function) MakeIterator() Iterator {
return nil
}
func (function Function) IsHashable() bool {
return true
}
func (function Function) MakeHashKey() HashKey {
return HashKey{
Type: function.TypeName(),
ValueDescription: fmt.Sprint(function),
}
}
func (function Function) IsValueSemantics() bool {
return false
}
func (function Function) HasMethods() bool {
return false
}
func (function Function) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, function)
}
func (function Function) Clone() Value {
return function
}
// Closure is the run time representation of a function with its own captured environment.
type Closure struct {
Function *Function // The function this closure has.
FreeVars []Value // The run time free variables linked to this closure.
StructID UInt // In case the function can access private state, this is the run time structu id linked to.
}
// Interface Value
func (closure Closure) TypeName() string {
return "Function"
}
func (closure Closure) Description() string {
return closure.Function.Description()
}
func (closure Closure) Equals(other Value) bool {
if value, ok := other.(Closure); ok {
return closure.Function == value.Function && fmt.Sprint(closure.FreeVars) == fmt.Sprint(value.FreeVars)
}
return false
}
func (closure Closure) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, closure)
}
func (closure Closure) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, closure)
}
func (closure Closure) IsIterable() bool {
return false
}
func (closure Closure) MakeIterator() Iterator {
return nil
}
func (closure Closure) IsHashable() bool {
return true
}
func (closure Closure) MakeHashKey() HashKey {
return HashKey{
Type: closure.TypeName(),
ValueDescription: fmt.Sprint(closure.Function),
}
}
func (closure Closure) IsValueSemantics() bool {
return false
}
func (closure Closure) HasMethods() bool {
return false
}
func (closure Closure) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, closure)
}
func (closure Closure) Clone() Value {
return closure
}
// GFunction is a Value that represents a function written in Go that can be run for the Vida VM.
type GFunction struct {
Name string
Value func(args ...Value) (Value, error)
}
// Interface Value
func (gf GFunction) TypeName() string {
return "GFunction"
}
func (gf GFunction) Description() string {
return fmt.Sprintf("gfunction%v", gf)
}
func (gf GFunction) Equals(other Value) bool {
if _, ok := other.(GFunction); ok {
return fmt.Sprint(gf) == fmt.Sprint(other)
}
return false
}
func (gf GFunction) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, gf)
}
func (gf GFunction) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, gf)
}
func (gf GFunction) IsIterable() bool {
return false
}
func (gf GFunction) MakeIterator() Iterator {
return nil
}
func (gf GFunction) IsHashable() bool {
return true
}
func (gf GFunction) MakeHashKey() HashKey {
return HashKey{
Type: gf.TypeName(),
ValueDescription: gf.Description(),
}
}
func (gf GFunction) IsValueSemantics() bool {
return false
}
func (gf GFunction) HasMethods() bool {
return false
}
func (gf GFunction) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, gf)
}
func (gf GFunction) Clone() Value {
return gf
}
// Result models the result of computations that could fail.
type Result struct {
Error Value
Value Value
}
// Interface SelectorOperator. Result implements only get becuase it is an immutable Value.
func (result Result) SelectorGet(field string) (Value, error) {
switch field {
case optionValue:
return result.Value, nil
case optionError:
return result.Error, nil
default:
return nil, NameNotDefinedInCompoundDataType(field, result)
}
}
func (result Result) SelectorSet(string, Value) error {
return ValueIsImmutable(result)
}
// Interface Value
func (result Result) TypeName() string {
return "Result"
}
func (result Result) Description() string {
return fmt.Sprintf("Result(value:%v error:%v)", result.Value.Description(), result.Error.Description())
}
func (result Result) Equals(other Value) bool {
if value, ok := other.(Result); ok {
return result.Value.Equals(value.Value) && result.Error.Equals(value.Error)
}
return false
}
func (result Result) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, result)
}
func (result Result) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, result)
}
func (result Result) IsIterable() bool {
return false
}
func (result Result) MakeIterator() Iterator {
return nil
}
func (result Result) IsHashable() bool {
return false
}
func (result Result) MakeHashKey() HashKey {
return HashKey{}
}
func (result Result) IsValueSemantics() bool {
return false
}
func (result Result) HasMethods() bool {
return false
}
func (result Result) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, result)
}
func (result Result) Clone() Value {
return Result{
Error: result.Error.Clone(),
Value: result.Value.Clone(),
}
}
// Struct is the stencil or blueprint of a new user-defined structured data type.
type Struct struct {
Id UInt
Name string
Public Namespace
Private Namespace
Methods Namespace
}
// Interface SelectorOperator. Struct implements only get becuase it is an immutable Value.
func (s Struct) SelectorGet(field string) (Value, error) {
if value, ok := s.Methods[field]; ok {
return value, nil
}
return nil, NameNotDefinedInCompoundDataType(field, s)
}
func (s Struct) SelectorSet(string, Value) error {
return ValueIsImmutable(s)
}
// Interface Value
func (s Struct) TypeName() string {
return "Struct"
}
func (s Struct) Description() string {
return fmt.Sprintf("struct(%v{%v/%v})", s.Name, len(s.Public), len(s.Methods))
}
func (s Struct) Equals(other Value) bool {
if value, ok := other.(Struct); ok {
return s.Name == value.Name
}
return false
}
func (s Struct) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, s)
}
func (s Struct) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, s)
}
func (s Struct) IsIterable() bool {
return false
}
func (s Struct) MakeIterator() Iterator {
return nil
}
func (s Struct) IsHashable() bool {
return true
}
func (s Struct) MakeHashKey() HashKey {
return HashKey{
Type: s.TypeName(),
ValueDescription: s.Description(),
}
}
func (s Struct) IsValueSemantics() bool {
return false
}
func (s Struct) HasMethods() bool {
return false
}
func (s Struct) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, s)
}
func (s Struct) Clone() Value {
return s
}
// Instance models unique objects instances of some structured data types.
type Instance struct {
Id UInt
Struct *Struct
Public Namespace
Private Namespace
}
// Interface SelectorOperator.
func (instance Instance) SelectorGet(field string) (Value, error) {
if value, ok := instance.Public[field]; ok {
return value, nil
}
if value, ok := instance.Private[field]; ok && globalState.currentFiber.frame.closure.Function.CanAccessPrivateState && globalState.currentFiber.frame.closure.StructID == instance.Struct.Id {
return value, nil
}
return nil, NameNotDefinedInCompoundDataType(field, instance)
}
func (instance Instance) SelectorSet(property string, value Value) error {
if _, ok := instance.Public[property]; ok {
instance.Public[property] = value
return nil
}
if _, ok := instance.Private[property]; ok && globalState.currentFiber.frame.closure.Function.CanAccessPrivateState && globalState.currentFiber.frame.closure.StructID == instance.Struct.Id {
instance.Private[property] = value
return nil
}
return NameNotDefinedInCompoundDataType(property, instance)
}
// Interface Value
func (instance Instance) TypeName() string {
return instance.Struct.Name
}
func (instance Instance) Description() string {
var builder bytes.Buffer
builder.WriteString(instance.Struct.Name)
builder.WriteString("( ")
for key, value := range instance.Public {
builder.WriteString(fmt.Sprintf("%v:%v ", key, value.Description()))
}
builder.WriteString(")")
return builder.String()
}
func (instance Instance) Equals(other Value) bool {
if value, ok := other.(Instance); ok && instance.Id == value.Id && instance.Struct.Name == value.Struct.Name {
for k, v := range instance.Public {
if val, okProp := value.Public[k]; !(okProp && v.Equals(val)) {
return false
}
}
return true
}
return false
}
func (instance Instance) BinaryOp(op byte, rhs Value) (Value, error) {
var operator string
switch op {
case TKAdd:
operator = operatorAdd
case TKMinus:
operator = operatorSub
case TKMul:
operator = operatorMul
case TKDiv:
operator = operatorDiv
case TKMod:
operator = operatorMod
case TKPercent:
operator = operatorRem
case TKPower:
operator = operatorPow
case TKGT:
operator = operatorGT
case TKGE:
operator = operatorGE
case TKLT:
operator = operatorLT
case TKLE:
operator = operatorLE
case TKAnd:
operator = operatorAnd
case TKOr:
operator = operatorLOr
default:
return nil, OperatorNotDefined(op, instance)
}
if method, okMethod := instance.Struct.Methods[operator].(Closure); okMethod {
if method.Function.Arity == 2 {
fiber := fiberPool.Get().(*Fiber)
fiber.reset(method)
fiber.parentFiber = globalState.currentFiber
fiber.state = fiberRunning
fiber.parentFiber.state = fiberWaiting
globalState.currentFiber = fiber
globalState.vm.Fiber = fiber
globalState.vm.stack[globalState.vm.top] = instance
globalState.vm.top++
globalState.vm.stack[globalState.vm.top] = rhs
globalState.vm.top++
if err := globalState.vm.runInterpreter(method.Function.Name); err != nil {
fiberPool.Put(fiber)
return NilValue, err
}
value := globalState.vm.stack[globalState.vm.top-1]
globalState.currentFiber = globalState.currentFiber.parentFiber
globalState.vm.Fiber = globalState.currentFiber
globalState.currentFiber.state = fiberRunning
fiberPool.Put(fiber)
return value, nil
} else {
return nil, ArityErrorInBinaryOperatorOverload()
}
} else {
return nil, MethodNotDefined(operator, instance)
}
}
func (instance Instance) PrefixOp(op byte) (Value, error) {
var operator string
switch op {
case TKNot:
operator = operatorNot
case TKMinus:
operator = operatorPrefixNeg
case TKAdd:
operator = operatorPrefixPos
default:
return nil, OperatorNotDefined(op, instance)
}
if method, okMethod := instance.Struct.Methods[operator].(Closure); okMethod {
if method.Function.Arity == 1 {
fiber := fiberPool.Get().(*Fiber)
fiber.reset(method)
fiber.parentFiber = globalState.currentFiber
fiber.state = fiberRunning
fiber.parentFiber.state = fiberWaiting
globalState.currentFiber = fiber
globalState.vm.Fiber = fiber
globalState.vm.stack[globalState.vm.top] = instance
globalState.vm.top++
if err := globalState.vm.runInterpreter(method.Function.Name); err != nil {
fiberPool.Put(fiber)
return NilValue, err
}
value := globalState.vm.stack[globalState.vm.top-1]
globalState.currentFiber = globalState.currentFiber.parentFiber
globalState.vm.Fiber = globalState.currentFiber
globalState.currentFiber.state = fiberRunning
fiberPool.Put(fiber)
return value, nil
} else {
return nil, ArityErrorInUnaryOperatorOverload()
}
} else {
return nil, MethodNotDefined(operator, instance)
}
}
func (instance Instance) IsIterable() bool {
return false
}
func (instance Instance) MakeIterator() Iterator {
return nil
}
func (instance Instance) IsHashable() bool {
return true
}
func (instance Instance) MakeHashKey() HashKey {
return HashKey{
Type: instance.TypeName(),
ValueDescription: strconv.FormatUint(uint64(instance.Id), 16),
}
}
func (instance Instance) IsValueSemantics() bool {
return false
}
func (instance Instance) HasMethods() bool {
return true
}
func (instance Instance) GetMethod(name string) (Value, bool, error) {
if method, ok := instance.Struct.Methods[name]; ok {
return method, true, nil
}
if prop, ok := instance.Public[name]; ok {
return prop, false, nil
}
return nil, false, MethodNotDefined(name, instance)
}
func (instance Instance) Clone() Value {
id := globalInstanceUniqueID
globalInstanceUniqueID++
namespace := make(Namespace)
for k, v := range instance.Public {
namespace[k] = v.Clone()
}
private := make(Namespace)
for k, v := range instance.Private {
private[k] = v.Clone()
}
return Instance{
Struct: instance.Struct,
Id: id,
Public: namespace,
Private: private,
}
}
// Interface subscript operator.
func (instance Instance) SubscriptGet(index Value) (Value, error) {
if method, okMethod := instance.Struct.Methods[operatorSubscriptGet].(Closure); okMethod {
if method.Function.Arity == 2 {
fiber := fiberPool.Get().(*Fiber)
fiber.reset(method)
fiber.parentFiber = globalState.currentFiber
fiber.state = fiberRunning
fiber.parentFiber.state = fiberWaiting
globalState.currentFiber = fiber
globalState.vm.Fiber = fiber
globalState.vm.stack[globalState.vm.top] = instance
globalState.vm.top++
globalState.vm.stack[globalState.vm.top] = index
globalState.vm.top++
if err := globalState.vm.runInterpreter(method.Function.Name); err != nil {
fiberPool.Put(fiber)
return NilValue, err
}
value := globalState.vm.stack[globalState.vm.top-1]
globalState.currentFiber = globalState.currentFiber.parentFiber
globalState.vm.Fiber = globalState.currentFiber
globalState.currentFiber.state = fiberRunning
fiberPool.Put(fiber)
return value, nil
} else {
return nil, ArityErrorInUnaryOperatorOverload()
}
} else {
return nil, MethodNotDefined(operatorSubscriptGet, instance)
}
}
func (instance Instance) SubscriptSet(index, value Value) error {
if method, okMethod := instance.Struct.Methods[operatorSubscriptSet].(Closure); okMethod {
if method.Function.Arity == 3 {
fiber := fiberPool.Get().(*Fiber)
fiber.reset(method)
fiber.parentFiber = globalState.currentFiber
fiber.state = fiberRunning
fiber.parentFiber.state = fiberWaiting
globalState.currentFiber = fiber
globalState.vm.Fiber = fiber
globalState.vm.stack[globalState.vm.top] = instance
globalState.vm.top++
globalState.vm.stack[globalState.vm.top] = index
globalState.vm.top++
globalState.vm.stack[globalState.vm.top] = value
globalState.vm.top++
if err := globalState.vm.runInterpreter(method.Function.Name); err != nil {
fiberPool.Put(fiber)
return err
}
globalState.currentFiber = globalState.currentFiber.parentFiber
globalState.vm.Fiber = globalState.currentFiber
globalState.currentFiber.state = fiberRunning
fiberPool.Put(fiber)
return nil
} else {
return ArityErrorInUnaryOperatorOverload()
}
} else {
return MethodNotDefined(operatorSubscriptGet, instance)
}
}
// Pair is a helper struct to hold keys and values as return value when iterating over maps and records.
type Pair struct {
key Value
value Value
}
// Interface SelectorOperator. Pair implements only get becuase it is an immutable Value.
func (pair Pair) SelectorGet(field string) (Value, error) {
switch field {
case mapPairKey:
return pair.key, nil
case mapPairValue:
return pair.value, nil
default:
return nil, NameNotDefinedInCompoundDataType(field, pair)
}
}
func (pair Pair) SelectorSet(string, Value) error {
return ValueIsImmutable(pair)
}
// Interface Value
func (pair Pair) TypeName() string {
return "Pair"
}
func (pair Pair) Description() string {
return fmt.Sprintf("Pair( key:%v value:%v )", pair.key.Description(), pair.value.Description())
}
func (pair Pair) Equals(other Value) bool {
if value, ok := other.(Pair); ok {
return pair.key.Equals(value.key) && pair.value.Equals(value.value)
}
return false
}
func (pair Pair) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, pair)
}
func (pair Pair) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, pair)
}
func (pair Pair) IsIterable() bool {
return false
}
func (pair Pair) MakeIterator() Iterator {
return nil
}
func (pair Pair) IsHashable() bool {
return false
}
func (pair Pair) MakeHashKey() HashKey {
return HashKey{}
}
func (pair Pair) IsValueSemantics() bool {
return false
}
func (pair Pair) HasMethods() bool {
return false
}
func (pair Pair) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, pair)
}
func (pair Pair) Clone() Value {
return Pair{
key: pair.key.Clone(),
value: pair.value.Clone(),
}
}
// Tuple is a helper struct to hold indexes and values as return value when iterating over lists and strings.
type Tuple struct {
index Value
value Value
}
// Interface SelectorOperator. Tuple implements only get becuase it is an immutable Value.
func (tuple Tuple) SelectorGet(field string) (Value, error) {
switch field {
case tupleIndex:
return tuple.index, nil
case mapPairValue:
return tuple.value, nil
default:
return nil, NameNotDefinedInCompoundDataType(field, tuple)
}
}
func (tuple Tuple) SelectorSet(string, Value) error {
return ValueIsImmutable(tuple)
}
// Interface Value
func (tuple Tuple) TypeName() string {
return "Tuple"
}
func (tuple Tuple) Description() string {
return fmt.Sprintf("Tuple( index:%v value:%v )", tuple.index.Description(), tuple.value.Description())
}
func (tuple Tuple) Equals(other Value) bool {
if value, ok := other.(Tuple); ok {
return tuple.index.Equals(value.index) && tuple.value.Equals(value.value)
}
return false
}
func (tuple Tuple) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, tuple)
}
func (tuple Tuple) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, tuple)
}
func (tuple Tuple) IsIterable() bool {
return false
}
func (tuple Tuple) MakeIterator() Iterator {
return nil
}
func (tuple Tuple) IsHashable() bool {
return false
}
func (tuple Tuple) MakeHashKey() HashKey {
return HashKey{}
}
func (tuple Tuple) IsValueSemantics() bool {
return false
}
func (tuple Tuple) HasMethods() bool {
return false
}
func (tuple Tuple) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, tuple)
}
func (tuple Tuple) Clone() Value {
return Tuple{
index: tuple.index.Clone(),
value: tuple.value.Clone(),
}
}
// NamedConstants models small namespace of constant values. Those values must have value semantics.
type NamedConstants struct {
Name string
Constants Namespace
Indexes map[Bytecode]string
}
// Interface SelectorOperator. NamedConstants implements only get becuase it is an immutable Value.
func (constants NamedConstants) SelectorGet(field string) (Value, error) {
if value, ok := constants.Constants[field]; ok {
return value, nil
}
return nil, NameNotDefinedInCompoundDataType(field, constants)
}
func (constants NamedConstants) SelectorSet(string, Value) error {
return ValueIsImmutable(constants)
}
// Interface Value
func (constants NamedConstants) TypeName() string {
return "GroupedConstants"
}
func (constants NamedConstants) Description() string {
return fmt.Sprintf("NamedConstants(%v/%v)", constants.Name, len(constants.Constants))
}
func (constants NamedConstants) Equals(other Value) bool {
if value, ok := other.(NamedConstants); ok {
return constants.Name == value.Name
}
return false
}
func (constants NamedConstants) BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, constants)
}
func (constants NamedConstants) PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, constants)
}
func (constants NamedConstants) IsIterable() bool {
return false
}
func (constants NamedConstants) MakeIterator() Iterator {
return nil
}
func (constants NamedConstants) IsHashable() bool {
return true
}
func (constants NamedConstants) MakeHashKey() HashKey {
return HashKey{
Type: constants.TypeName(),
ValueDescription: constants.Description(),
}
}
func (constants NamedConstants) IsValueSemantics() bool {
return false
}
func (constants NamedConstants) HasMethods() bool {
return false
}
func (constants NamedConstants) GetMethod(name string) (Value, bool, error) {
return nil, false, MethodNotDefined(name, constants)
}
func (constants NamedConstants) Clone() Value {
return constants
}
// Value Interface Template.
/*
// Value Interface
func () TypeName() string {}
func () Description() string {}
func () Equals(Value) bool {}
func () BinaryOp(op byte, rhs Value) (Value, error) {
return nil, OperatorNotDefined(op, )
}
func () PrefixOp(op byte) (Value, error) {
return nil, OperatorNotDefined(op, )
}
func () IsIterable() bool {
return false
}
func () MakeIterator() Iterator {
return nil
}
func () IsHashable() bool {
return true
}
func () MakeHashKey() HashKey {
return HashKey{
Type: .TypeName(),
ValueDescription: .Description(),
}
}
func () IsValueSemantics() bool {
return false
}
func () HasMethods() bool {
return false
}
func () GetMethod(name string) (vida.Value, bool, error) {
return nil, false, MethodNotDefined(name, )
}
func ( ) Clone() Value {
}
*/ | vida/value.go | 0.774328 | 0.405096 | value.go | starcoder |
package knot
import (
"errors"
"fmt"
)
// Orientation values: East, North, West, South.
const (
E Orientation = iota
N
W
S
// Orientations used for crosses:
EN // E over N
NW // N over W
WS // W over S
SE // S over E
ES // E over S
NE // N over E
WN // W over N
SW // S over W
// Used to clamp values.
MaxOrientation
MaxBaseOrientation = MaxOrientation / 3
)
const (
Forward Direction = iota
TurnLeft
Under
TurnRight
// Used to clamp values.
MaxDirection
)
var IncompleteDirections = errors.New("knot: incomplete directions")
// Orientation encodes an absolute directionality.
type Orientation byte
// Direction encodes a relative directionality.
// It is effectively the same as a orientation but relative to the current value.
type Direction Orientation
// Directions are the minimum information required to reconstruct a knot diagram.
type Directions []Direction
// Cell combines orientation with direction to be stored in the coordinate system.
type Cell struct {
Orientation
Direction
}
// Point encodes a point on the X/Y coordinate system.
type Point struct{ X, Y int }
// Grid is a sparse mapping of poinds (coordinates) to cells.
type Grid map[Point]Cell
// InvalidCrossing indicates an invalid crossing.
type InvalidCrossing Point
// Error implements the error interface.
func (err InvalidCrossing) Error() string {
return fmt.Sprintf("knot: invalid crossing at position %s", Point(err))
}
// Grid decodes directions into a grid containing cells.
// It uses (0, 0) as the starting point, and east as the initial orientation.
func (ds Directions) Grid() (Grid, error) {
g := Grid{}
if len(ds) == 0 {
return nil, IncompleteDirections
}
pos, o := Point{}, E
for _, d := range ds {
c := Cell{o, d}
if old, ok := g[pos]; ok {
// Position already in use, check whether we can make a crossing here.
if d != Forward && d != Under {
return nil, fmt.Errorf("%w: direction must be %s or %s, got %s", InvalidCrossing(pos), Forward, Under, d)
}
if old.IsCross() {
// Technically this should never happen, but still.
return nil, fmt.Errorf("%w: coordinates already contain crossing %s", InvalidCrossing(pos), old)
}
if !old.IsStraight() {
return nil, fmt.Errorf("%w: can only cross at straight line, not %s", InvalidCrossing(pos), old)
}
if !old.IsPerpendicular(o) {
return nil, fmt.Errorf("%w: existing cell %s is not perpendicular to current orientation %s", InvalidCrossing(pos), old, o)
}
g[pos] = Cell{old.Cross(o, d == Forward), Forward}
} else {
// Position not in use.
if d == Under {
return nil, fmt.Errorf("%w: nothing to go under", InvalidCrossing(pos))
}
g[pos] = c
}
o = o.Turn(d)
pos = pos.Step(o)
}
if (pos != Point{}) {
return nil, IncompleteDirections
}
return g, nil
}
// Base clamps the orientation to its base orientation.
func (o Orientation) Base() Orientation {
return o % MaxBaseOrientation
}
// Cross crosses two orientations, with the second one going either over (over = true) or under (over = false).
func (o Orientation) Cross(other Orientation, over bool) Orientation {
if (o == N && other == E && over) || (o == E && other == N && !over) {
return EN
}
if (o == W && other == N && over) || (o == N && other == W && !over) {
return NW
}
if (o == S && other == W && over) || (o == W && other == S && !over) {
return WS
}
if (o == E && other == S && over) || (o == S && other == E && !over) {
return SE
}
if (o == S && other == E && over) || (o == E && other == S && !over) {
return ES
}
if (o == E && other == N && over) || (o == N && other == E && !over) {
return NE
}
if (o == N && other == W && over) || (o == W && other == N && !over) {
return WN
}
if (o == W && other == S && over) || (o == S && other == W && !over) {
return SW
}
panic(fmt.Sprintf("invalid cross: %s.Cross(%s, %v)", o, other, over))
}
// IsCross checks whether the orientation corresponds to a crossing.
func (o Orientation) IsCross() bool {
return o != o.Base()
}
// Clamp returns a copy with all but the two least significant bits cleared.
func (o Orientation) Clamp() Orientation {
return o % MaxOrientation
}
// Turn towards direction.
func (o Orientation) Turn(to Direction) Orientation {
switch to.Clamp() {
case Forward, Under:
return o
case TurnLeft:
return (o + 1).Base()
case TurnRight:
return (o - 1).Base()
}
panic("knot: should not happen")
}
// IsPerpendicular checks whether two orientations are perpendicular.
func (o Orientation) IsPerpendicular(other Orientation) bool {
return (o+other)%2 == 1
}
// String returns a short, human-readable representation.
func (o Orientation) String() string {
switch o.Clamp() {
case E:
return "E"
case N:
return "N"
case W:
return "W"
case S:
return "S"
case EN:
return "EN"
case NW:
return "NW"
case WS:
return "WS"
case SE:
return "SE"
case ES:
return "ES"
case NE:
return "NE"
case WN:
return "WN"
case SW:
return "SW"
}
panic("knot: should not happen")
}
// Clamp returns a copy with all but the two least significant bits cleared.
func (d Direction) Clamp() Direction {
return d % MaxDirection
}
// IsStraight returns true if the direction is forward or under (i.e. do not turn).
func (d Direction) IsStraight() bool {
return d%2 == 0
}
// String returns a short, human-readable representation.
func (d Direction) String() string {
switch d.Clamp() {
case Forward:
return "F"
case TurnLeft:
return "L"
case Under:
return "U"
case TurnRight:
return "R"
}
panic("knot: should not happen")
}
// String returns a short, human-readable representation.
func (c Cell) String() string {
return fmt.Sprintf("%s (%s)", c.Orientation, c.Direction)
}
// Step returns the point one step towards the passed orientation.
func (p Point) Step(towards Orientation) Point {
switch towards.Base() {
case E:
return Point{p.X + 1, p.Y}
case N:
return Point{p.X, p.Y + 1}
case W:
return Point{p.X - 1, p.Y}
case S:
return Point{p.X, p.Y - 1}
}
panic("knot: should not happen")
}
// String returns a short, human-readable representation.
func (p Point) String() string {
return fmt.Sprintf("(%d, %d)", p.X, p.Y)
} | go/knot/coding.go | 0.773045 | 0.559471 | coding.go | starcoder |
package math
import (
nativeMath "math"
)
type Vector3 struct {
Vector2
Z float32
}
func NewDefaultVector3() *Vector3 {
return NewVector3(0, 0, 0)
}
func NewVector3(x float32, y float32, z float32) *Vector3 {
return &Vector3{
Vector2: *NewVector2(x, y),
Z: z,
}
}
func NewVector3Inf(sign int) *Vector3 {
return &Vector3{
Vector2: *NewVector2Inf(sign),
Z: float32(nativeMath.Inf(sign)),
}
}
func NewVector3FromArray(arr []float32, offset int) *Vector3 {
return NewVector3(
arr[offset],
arr[offset+1],
arr[offset+2],
)
}
func (vec *Vector3) Set(x float32, y float32, z float32) {
vec.X = x
vec.Y = y
vec.Z = z
}
func (vec *Vector3) SetZ(z float32) {
vec.Z = z
}
func (vec *Vector3) SetScalar(num float32) {
vec.X = num
vec.Y = num
vec.Z = num
}
func (vec *Vector3) SetFromSpherical(s *Spherical) {
vec.SetFromSphericalCoordinates(s.radius, s.phi, s.theta)
}
func (vec *Vector3) SetFromSphericalCoordinates(radius float32, phi float32, theta float32) {
sinPhiRadius := Sin(phi) * radius
vec.X = sinPhiRadius * Sin(theta)
vec.Y = Cos(phi) * radius
vec.Z = sinPhiRadius * Cos(theta)
}
func (vec *Vector3) SetFromCylindrical(c *Cylindrical) {
vec.SetFromCylindricalCoordinates(c.radius, c.theta, c.y)
}
func (vec *Vector3) SetFromCylindricalCoordinates(radius float32, theta float32, y float32) {
vec.X = radius * Sin(theta)
vec.Y = y
vec.Z = radius * Cos(theta)
}
func (vec *Vector3) SetFromMatrixPosition(m *Matrix4) {
vec.X = m.elements[12]
vec.Y = m.elements[13]
vec.Z = m.elements[14]
}
func (vec *Vector3) SetFromMatrixScale(m *Matrix4) {
vec.SetFromMatrixColumn(m, 0)
sx := vec.GetLength()
vec.SetFromMatrixColumn(m, 1)
sy := vec.GetLength()
vec.SetFromMatrixColumn(m, 2)
sz := vec.GetLength()
vec.X = sx
vec.Y = sy
vec.Z = sz
}
func (vec *Vector3) SetFromMatrixColumn(m *Matrix4, col int) {
offset := col * 4
vec.X = m.elements[offset]
vec.Y = m.elements[offset+1]
vec.Z = m.elements[offset+2]
}
func (vec *Vector3) Copy(source *Vector3) {
vec.X = source.X
vec.Y = source.Y
vec.Z = source.Z
}
func (vec *Vector3) Clone() *Vector3 {
return &Vector3{
Vector2: *vec.Vector2.Clone(),
Z: vec.Z,
}
}
func (vec *Vector3) Add(a *Vector3) {
vec.X += a.X
vec.Y += a.Y
vec.Z += a.Z
}
func (vec *Vector3) AddComponents(x float32, y float32, z float32) {
vec.X += x
vec.Y += y
vec.Z += z
}
func (vec *Vector3) AddScalar(num float32) {
vec.X += num
vec.Y += num
vec.Z += num
}
func (vec *Vector3) SetAddVectors(v1 *Vector3, v2 *Vector3) {
vec.X = v1.X + v2.X
vec.Y = v1.Y + v2.Y
vec.Z = v1.Z + v2.Z
}
func (vec *Vector3) AddScaledVector(v1 *Vector3, scale float32) {
vec.X += v1.X * scale
vec.Y += v1.Y * scale
vec.Z += v1.Z * scale
}
func (vec *Vector3) Sub(v *Vector3) {
vec.X -= v.X
vec.Y -= v.Y
vec.Z -= v.Z
}
func (vec *Vector3) SubScalar(num float32) {
vec.X -= num
vec.Y -= num
vec.Z -= num
}
func (vec *Vector3) SetSubVectors(v1 *Vector3, v2 *Vector3) {
vec.X = v1.X - v2.X
vec.Y = v1.Y - v2.Y
vec.Z = v1.Z - v2.Z
}
func (vec *Vector3) Multiply(v *Vector3) {
vec.X *= v.X
vec.Y *= v.Y
vec.Z *= v.Z
}
func (vec *Vector3) MultiplyScalar(num float32) {
vec.X *= num
vec.Y *= num
vec.Z *= num
}
func (vec *Vector3) Divide(v *Vector3) {
vec.X /= v.X
vec.Y /= v.Y
vec.Z /= v.Z
}
func (vec *Vector3) DivideScalar(num float32) {
vec.MultiplyScalar(1 / num)
}
func (vec *Vector3) ApplyEuler(euler *Euler) {
quaternion := NewDefaultQuaternion()
quaternion.SetFromEuler(euler, false)
vec.ApplyQuaternion(quaternion)
}
func (vec *Vector3) ApplyAxisAngle(axis *Vector3, angle Angle) {
quaternion := NewDefaultQuaternion()
quaternion.SetFromAxisAngle(axis, angle)
vec.ApplyQuaternion(quaternion)
}
func (vec *Vector3) ApplyMatrix3(m *Matrix3) {
x := vec.X
y := vec.Y
z := vec.Z
e := m.GetElements()
vec.X = e[0]*x + e[3]*y + e[6]*z
vec.Y = e[1]*x + e[4]*y + e[7]*z
vec.Z = e[2]*x + e[5]*y + e[8]*z
}
func (vec *Vector3) ApplyMatrix4(m *Matrix4) {
x := vec.X
y := vec.Y
z := vec.Z
e := m.GetElements()
w := 1 / (e[3]*x + e[7]*y + e[11]*z + e[15])
vec.X = (e[0]*x + e[4]*y + e[8]*z + e[12]) * w
vec.Y = (e[1]*x + e[5]*y + e[9]*z + e[13]) * w
vec.Z = (e[2]*x + e[6]*y + e[10]*z + e[14]) * w
}
func (vec *Vector3) ApplyQuaternion(q *Quaternion) {
x := vec.X
y := vec.Y
z := vec.Z
qx := q.GetX()
qy := q.GetY()
qz := q.GetZ()
qw := q.GetW()
// calculate quaternion * vector
ix := qw*x + qy*z - qz*y
iy := qw*y + qz*x - qx*z
iz := qw*z + qx*y - qy*x
iw := - qx*x - qy*y - qz*z
// calculate result * inverse quaternion
vec.X = ix*qw + iw*- qx + iy*- qz - iz*- qy
vec.Y = iy*qw + iw*- qy + iz*- qx - ix*- qz
vec.Z = iz*qw + iw*- qz + ix*- qy - iy*- qx
}
// input: THREE.Matrix4 affine matrix
// vector interpreted as a direction
func (vec *Vector3) TransformDirection(matrix *Matrix4) {
x := vec.X
y := vec.Y
z := vec.Z
vec.X = matrix.elements[0]*x + matrix.elements[4]*y + matrix.elements[8]*z
vec.Y = matrix.elements[1]*x + matrix.elements[5]*y + matrix.elements[9]*z
vec.Z = matrix.elements[2]*x + matrix.elements[6]*y + matrix.elements[10]*z
vec.Normalize()
}
func (vec *Vector3) Min(v *Vector3) {
vec.X = Min(vec.X, v.X)
vec.Y = Min(vec.Y, v.Y)
vec.Z = Min(vec.Z, v.Z)
}
func (vec *Vector3) Max(v *Vector3) {
vec.X = Max(vec.X, v.X)
vec.Y = Max(vec.Y, v.Y)
vec.Z = Max(vec.Z, v.Z)
}
// Clamps the value to be between min and max.
func (vec *Vector3) Clamp(min *Vector3, max *Vector3) {
vec.X = Max(min.X, Min(max.X, vec.X))
vec.Y = Max(min.Y, Min(max.Y, vec.Y))
vec.Z = Max(min.Z, Min(max.Z, vec.Z))
}
func (vec *Vector3) ClampScalar(min float32, max float32) {
minVec := NewVector3(min, min, min)
maxVec := NewVector3(max, max, max)
vec.Clamp(minVec, maxVec)
}
func (vec *Vector3) ClampLength(min float32, max float32) {
length := vec.GetLength()
div := length
if length == 0 {
div = 1
}
vec.DivideScalar(div)
vec.MultiplyScalar(Max(min, Min(max, length)))
}
func (vec *Vector3) Floor() {
vec.X = Floor(vec.X)
vec.Y = Floor(vec.Y)
vec.Z = Floor(vec.Z)
}
func (vec *Vector3) Ceil() {
vec.X = Ceil(vec.X)
vec.Y = Ceil(vec.Y)
vec.Z = Ceil(vec.Z)
}
func (vec *Vector3) Round() {
vec.X = Round(vec.X)
vec.Y = Round(vec.Y)
vec.Z = Round(vec.Z)
}
func (vec *Vector3) RoundToZero() {
if vec.X < 0 {
vec.X = Ceil(vec.X)
} else {
vec.X = Floor(vec.X)
}
if vec.Y < 0 {
vec.Y = Ceil(vec.Y)
} else {
vec.Y = Floor(vec.Y)
}
if vec.Z < 0 {
vec.Z = Ceil(vec.Z)
} else {
vec.Z = Floor(vec.Z)
}
}
func (vec *Vector3) Negate() {
vec.X = -vec.X
vec.Y = -vec.Y
vec.Z = -vec.Z
}
func (vec *Vector3) Dot(v *Vector3) float32 {
return vec.X*v.X + vec.Y*v.Y + vec.Z*v.Z
}
func (vec *Vector3) Cross(v *Vector3) {
ax := vec.X
ay := vec.Y
az := vec.Z
vec.X = ay*v.Z - az*v.Y
vec.Y = az*v.X - ax*v.Z
vec.Z = ax*v.Y - ay*v.X
}
func (vec *Vector3) CrossVectors(a *Vector3, b *Vector3) {
vec.X = a.Y*b.Z - a.Z*b.Y
vec.Y = a.Z*b.X - a.X*b.Z
vec.Z = a.X*b.Y - a.Y*b.X
}
func (vec *Vector3) GetLengthSq() float32 {
return vec.X*vec.X + vec.Y*vec.Y + vec.Z*vec.Z
}
func (vec *Vector3) GetLength() float32 {
return Sqrt(vec.GetLengthSq())
}
func (vec *Vector3) SetLength(length float32) {
vec.Normalize()
vec.MultiplyScalar(length)
}
func (vec *Vector3) GetManhattanLength() float32 {
return Abs(vec.X) + Abs(vec.Y) + Abs(vec.Z)
}
func (vec *Vector3) Normalize() {
div := vec.GetLength()
if div == 0 {
div = 1
}
vec.DivideScalar(div)
}
func (vec *Vector3) ProjectOnVector(v *Vector3) {
scalar := v.Dot(vec) * v.GetLengthSq()
vec.Copy(v)
vec.MultiplyScalar(scalar)
}
func (vec *Vector3) ProjectOnPlane(p *Plane) {
v1 := vec.Clone()
v1.ProjectOnVector(p.GetNormal())
vec.Sub(v1)
}
func (vec *Vector3) Reflect(normal *Vector3) {
v1 := normal.Clone()
v1.MultiplyScalar(2 * vec.Dot(normal))
vec.Sub(v1)
}
func (vec *Vector3) AngleTo(v *Vector3) float32 {
theta := vec.Dot(v) / (Sqrt(vec.GetLengthSq() * v.GetLengthSq()))
return Acos(Clamp(theta, -1, 1))
}
func (vec *Vector3) GetDistanceTo(v *Vector3) float32 {
return Sqrt(vec.GetDistanceToSquared(v))
}
func (vec *Vector3) GetDistanceToSquared(v *Vector3) float32 {
dx := vec.X - v.X
dy := vec.Y - v.Y
dz := vec.Z - v.Z
return dx*dx + dy*dy + dz*dz
}
func (vec *Vector3) GetManhattanDistanceTo(v *Vector3) float32 {
return Abs(vec.X-v.X) + Abs(vec.Y-v.Y) + Abs(vec.Z-v.Z)
}
func (vec *Vector3) Lerp(v *Vector3, alpha float32) {
vec.X += (v.X - vec.X) * alpha
vec.Y += (v.Y - vec.Y) * alpha
vec.Z += (v.Z - vec.Z) * alpha
}
func (vec *Vector3) LerpVectors(v1 *Vector3, v2 *Vector3, alpha float32) {
vec.SetSubVectors(v2, v1)
vec.MultiplyScalar(alpha)
vec.Add(v1)
}
func (vec *Vector3) Equals(v *Vector3) bool {
return vec.X == v.X && vec.Y == v.Y && vec.Z == v.Z
}
func (vec *Vector3) ToArray() [3]float32 {
return [3]float32{vec.X, vec.Y, vec.Z}
}
func (vec *Vector3) CopyToArray(array []float32, offset int) {
va := vec.ToArray()
copy(array[offset:], va[0:])
} | vector3.go | 0.794704 | 0.83622 | vector3.go | starcoder |
package log
import (
"encoding/json"
"fmt"
"strings"
)
var (
_ WatcherHandler = (*assertBaseHandler)(nil)
_ WatcherHandler = (*assertContainsHandler)(nil)
_ WatcherHandler = (*assertJSONContainsHandler)(nil)
_ WatcherHandlerFactory = (*assertBaseFactory)(nil)
_ WatcherHandlerFactory = (*assertContainsFactory)(nil)
_ WatcherHandlerFactory = (*assertJSONContainsFactory)(nil)
)
type assertBase struct {
message string
}
func (a *assertBase) fail() error {
return fmt.Errorf("log assertion failed: %s", a.message)
}
func (a *assertBase) String() string {
return fmt.Sprintf("assertBase{message: %s}", a.message)
}
type assertBaseHandler assertBase
func (h *assertBaseHandler) Line(line string) error {
return nil
}
func (h *assertBaseHandler) Finish() error {
return nil
}
type assertBaseFactory assertBase
func (fac *assertBaseFactory) New() (WatcherHandler, error) {
return &assertBaseHandler{
message: fac.message,
}, nil
}
type assertContains struct {
assertBase
text string
expected bool
}
func (a *assertContains) String() string {
return fmt.Sprintf("assertContains{message: %s text: %s expected: %t}", a.message, a.text, a.expected)
}
type assertContainsHandler struct {
assertContains
seen bool
}
func (h *assertContainsHandler) Line(line string) error {
if strings.Contains(line, h.text) {
h.seen = true
}
return nil
}
func (h *assertContainsHandler) Finish() error {
if h.seen != h.expected {
return h.fail()
}
return nil
}
type assertContainsFactory struct {
assertContains
}
func (fac *assertContainsFactory) New() (WatcherHandler, error) {
return &assertContainsHandler{
assertContains: fac.assertContains,
}, nil
}
// AssertContains returns a factory of log handlers which check that the given
// text is contained in the log output.
func AssertContains(text, message string) WatcherHandlerFactory {
return &assertContainsFactory{
assertContains: assertContains{
assertBase: assertBase{message},
text: text,
expected: true,
},
}
}
// AssertNotContains returns a factory of log handlers which check that the
// given text is not contained in the log output.
func AssertNotContains(text, message string) WatcherHandlerFactory {
return &assertContainsFactory{
assertContains: assertContains{
assertBase: assertBase{message},
text: text,
expected: false,
},
}
}
type assertJSONContains struct {
assertBase
key string
value string
expected bool
}
func (a *assertJSONContains) String() string {
return fmt.Sprintf("assertJSONContains{message: %s key: %s value: %s expected: %t}", a.message, a.key, a.value, a.expected)
}
type assertJSONContainsHandler struct {
assertJSONContains
seen bool
}
func (h *assertJSONContainsHandler) Line(line string) error {
var kvs map[string]interface{}
if err := json.Unmarshal([]byte(line), &kvs); err != nil {
return nil
}
// TODO: Support arbitrary nested paths as keys.
v := kvs[h.key]
if v == nil {
return nil
}
// TODO: Support other types.
switch v.(type) {
case string:
if v == h.value {
h.seen = true
}
}
return nil
}
func (h *assertJSONContainsHandler) Finish() error {
if h.seen != h.expected {
return h.fail()
}
return nil
}
type assertJSONContainsFactory struct {
assertJSONContains
}
func (fac *assertJSONContainsFactory) New() (WatcherHandler, error) {
return &assertJSONContainsHandler{
assertJSONContains: fac.assertJSONContains,
}, nil
}
// AssertJSONContains returns a factory of log handlers which check that the
// given key/value pair is contained encoded as JSON in the log output.
func AssertJSONContains(key, value, message string) WatcherHandlerFactory {
return &assertJSONContainsFactory{
assertJSONContains: assertJSONContains{
assertBase: assertBase{message},
key: key,
value: value,
expected: true,
},
}
}
// AssertNotJSONContains returns a factory of log handlers which check that the
// given key/value pair is not contained encoded as JSON in the log output.
func AssertNotJSONContains(key, value, message string) WatcherHandlerFactory {
return &assertJSONContainsFactory{
assertJSONContains: assertJSONContains{
assertBase: assertBase{message},
key: key,
value: value,
expected: false,
},
}
} | go/oasis-test-runner/log/handlers.go | 0.67694 | 0.425725 | handlers.go | starcoder |
package xdr
// TimeBounds extracts the timebounds (if any) from the transaction's
// Preconditions.
func (tx *Transaction) TimeBounds() *TimeBounds {
switch tx.Cond.Type {
case PreconditionTypePrecondNone:
return nil
case PreconditionTypePrecondTime:
return tx.Cond.TimeBounds
case PreconditionTypePrecondV2:
return tx.Cond.V2.TimeBounds
default:
panic("unsupported precondition type: " + tx.Cond.Type.String())
}
}
// LedgerBounds extracts the ledgerbounds (if any) from the transaction's
// Preconditions.
func (tx *Transaction) LedgerBounds() *LedgerBounds {
switch tx.Cond.Type {
case PreconditionTypePrecondNone, PreconditionTypePrecondTime:
return nil
case PreconditionTypePrecondV2:
return tx.Cond.V2.LedgerBounds
default:
panic("unsupported precondition type: " + tx.Cond.Type.String())
}
}
// MinSeqNum extracts the min seq number (if any) from the transaction's
// Preconditions.
func (tx *Transaction) MinSeqNum() *SequenceNumber {
switch tx.Cond.Type {
case PreconditionTypePrecondNone, PreconditionTypePrecondTime:
return nil
case PreconditionTypePrecondV2:
return tx.Cond.V2.MinSeqNum
default:
panic("unsupported precondition type: " + tx.Cond.Type.String())
}
}
// MinSeqAge extracts the min seq age (if any) from the transaction's
// Preconditions.
func (tx *Transaction) MinSeqAge() *Duration {
switch tx.Cond.Type {
case PreconditionTypePrecondNone, PreconditionTypePrecondTime:
return nil
case PreconditionTypePrecondV2:
return &tx.Cond.V2.MinSeqAge
default:
panic("unsupported precondition type: " + tx.Cond.Type.String())
}
}
// MinSeqLedgerGap extracts the min seq ledger gap (if any) from the transaction's
// Preconditions.
func (tx *Transaction) MinSeqLedgerGap() *Uint32 {
switch tx.Cond.Type {
case PreconditionTypePrecondNone, PreconditionTypePrecondTime:
return nil
case PreconditionTypePrecondV2:
return &tx.Cond.V2.MinSeqLedgerGap
default:
panic("unsupported precondition type: " + tx.Cond.Type.String())
}
}
// ExtraSigners extracts the extra signers (if any) from the transaction's
// Preconditions.
func (tx *Transaction) ExtraSigners() []SignerKey {
switch tx.Cond.Type {
case PreconditionTypePrecondNone, PreconditionTypePrecondTime:
return nil
case PreconditionTypePrecondV2:
return tx.Cond.V2.ExtraSigners
default:
panic("unsupported precondition type: " + tx.Cond.Type.String())
}
} | xdr/transaction.go | 0.761006 | 0.521532 | transaction.go | starcoder |
package main
import (
"fmt"
"math/rand"
"os"
"time"
)
var commandsDescription = map[string]string{
"partition": "split a dataset file into more smaller files",
"heatmap": "creates a heatmap of the datasets according to their accuracy",
"similarities": "calculates and stores the similarity matrix of the specified datasets",
"train": "exhaustively trains the specified ML job with the datasets and creates a scores matrix",
"clustering": "clusters the datasets based on the similarity matrix and prints their accuracy vs their cluster",
"simcomparison": "compares a list of similarity matrices",
"mds": "executes Multidimensional Scaling to a similarity matrix",
}
var expDescription = map[string]string{
"exp-accuracy": "trains an ML model and prints the error",
"exp-ordering": "compares the ordering of the datasets to the original ordering",
"exp-online-indexer": "executes the online indexer experiment",
}
var utilsDescription = map[string]string{
"print-utils": "utilility to print objects in binary form",
"help": "prints this help message",
}
var commandsToFunctions = map[string]func(){
"partition": partitionerRun,
"heatmap": heatmapRun,
"similarities": similaritiesRun,
"train": trainRun,
"clustering": clusteringRun,
"simcomparison": simcomparisonRun,
"mds": mdsRun,
"indexing": indexingRun,
"exp-accuracy": expAccuracyRun,
"exp-ordering": expOrderingRun,
"exp-online-indexer": expOnlineIndexerRun,
"print-utils": printUtilsRun,
"help": helpRun,
}
func main() {
rand.Seed(int64(time.Now().Nanosecond()))
if len(os.Args) < 2 {
helpRun()
}
// consume the first command
command := os.Args[1]
os.Args = os.Args[1:]
if fun, ok := commandsToFunctions[command]; ok {
fun()
} else {
fmt.Fprintln(os.Stderr, "Command not identified")
}
}
func helpRun() {
fmt.Fprintf(os.Stderr, "Usage: %s [command]\n", "data-profiler-utils")
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintln(os.Stderr, "List of utils:")
for name, description := range utilsDescription {
fmt.Fprintf(os.Stderr, "\t%s - %s\n", name, description)
}
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintln(os.Stderr, "List of commands:")
for name, description := range commandsDescription {
fmt.Fprintf(os.Stderr, "\t%s - %s\n", name, description)
}
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintln(os.Stderr, "List of experiments:")
for name, description := range expDescription {
fmt.Fprintf(os.Stderr, "\t%s - %s\n", name, description)
}
os.Exit(1)
} | data-profiler-utils/main.go | 0.523908 | 0.561395 | main.go | starcoder |
package transform
import (
"fmt"
"math"
"github.com/pzduniak/unipdf/common"
)
// Matrix is a linear transform matrix in homogenous coordinates.
// PDF coordinate transforms are always affine so we only need 6 of these. See newMatrix.
type Matrix [9]float64
// IdentityMatrix returns the identity transform.
func IdentityMatrix() Matrix {
return NewMatrix(1, 0, 0, 1, 0, 0)
}
// TranslationMatrix returns a matrix that translates by `tx`,`ty`.
func TranslationMatrix(tx, ty float64) Matrix {
return NewMatrix(1, 0, 0, 1, tx, ty)
}
// ScaleMatrix returns a matrix that scales by `x`,`y`.
func ScaleMatrix(x, y float64) Matrix {
return NewMatrix(x, 0, 0, y, 0, 0)
}
// RotationMatrix returns a matrix that rotates by angle `angle`, specified in radians.
func RotationMatrix(angle float64) Matrix {
c := math.Cos(angle)
s := math.Sin(angle)
return NewMatrix(c, s, -s, c, 0, 0)
}
// ShearMatrix returns a matrix that shears `x`,`y`.
func ShearMatrix(x, y float64) Matrix {
return NewMatrix(1, y, x, 1, 0, 0)
}
// NewMatrix returns an affine transform matrix laid out in homogenous coordinates as
// a b 0
// c d 0
// tx ty 1
func NewMatrix(a, b, c, d, tx, ty float64) Matrix {
m := Matrix{
a, b, 0,
c, d, 0,
tx, ty, 1,
}
m.clampRange()
return m
}
// String returns a string describing `m`.
func (m Matrix) String() string {
a, b, c, d, tx, ty := m[0], m[1], m[3], m[4], m[6], m[7]
return fmt.Sprintf("[%7.4f,%7.4f,%7.4f,%7.4f:%7.4f,%7.4f]", a, b, c, d, tx, ty)
}
// Set sets `m` to affine transform a,b,c,d,tx,ty.
func (m *Matrix) Set(a, b, c, d, tx, ty float64) {
m[0], m[1] = a, b
m[3], m[4] = c, d
m[6], m[7] = tx, ty
m.clampRange()
}
// Concat sets `m` to `b` Γ `m`.
// `b` needs to be created by newMatrix. i.e. It must be an affine transform.
// b00 b01 0 m00 m01 0 b00*m00 + b01*m01 b00*m10 + b01*m11 0
// b10 b11 0 Γ m10 m11 0 β b10*m00 + b11*m01 b10*m10 + b11*m11 0
// b20 b21 1 m20 m21 1 b20*m00 + b21*m10 + m20 b20*m01 + b21*m11 + m21 1
func (m *Matrix) Concat(b Matrix) {
*m = Matrix{
b[0]*m[0] + b[1]*m[3], b[0]*m[1] + b[1]*m[4], 0,
b[3]*m[0] + b[4]*m[3], b[3]*m[1] + b[4]*m[4], 0,
b[6]*m[0] + b[7]*m[3] + m[6], b[6]*m[1] + b[7]*m[4] + m[7], 1,
}
m.clampRange()
}
// Mult returns `b` Γ `m`.
func (m Matrix) Mult(b Matrix) Matrix {
m.Concat(b)
return m
}
// Translate appends a translation of `x`,`y` to `m`.
// m.Translate(dx, dy) is equivalent to m.Concat(NewMatrix(1, 0, 0, 1, dx, dy))
func (m *Matrix) Translate(x, y float64) {
m.Concat(TranslationMatrix(x, y))
}
// Translation returns the translation part of `m`.
func (m *Matrix) Translation() (float64, float64) {
return m[6], m[7]
}
// Scale scales the current matrix by `x`,`y`.
func (m *Matrix) Scale(x, y float64) {
m.Concat(ScaleMatrix(x, y))
}
// Rotate rotates the current matrix by angle `angle`, specified in radians.
func (m *Matrix) Rotate(angle float64) {
m.Concat(RotationMatrix(angle))
}
// Shear shears the current matrix by `x',`y`.
func (m *Matrix) Shear(x, y float64) {
m.Concat(ShearMatrix(x, y))
}
// Clone returns a copy of the current matrix.
func (m *Matrix) Clone() Matrix {
return NewMatrix(m[0], m[1], m[3], m[4], m[6], m[7])
}
// Transform returns coordinates `x`,`y` transformed by `m`.
func (m *Matrix) Transform(x, y float64) (float64, float64) {
xp := x*m[0] + y*m[1] + m[6]
yp := x*m[3] + y*m[4] + m[7]
return xp, yp
}
// ScalingFactorX returns the X scaling of the affine transform.
func (m *Matrix) ScalingFactorX() float64 {
return math.Hypot(m[0], m[1])
}
// ScalingFactorY returns the Y scaling of the affine transform.
func (m *Matrix) ScalingFactorY() float64 {
return math.Hypot(m[3], m[4])
}
// Angle returns the angle of the affine transform in `m` in degrees.
func (m *Matrix) Angle() float64 {
theta := math.Atan2(-m[1], m[0])
if theta < 0.0 {
theta += 2 * math.Pi
}
return theta / math.Pi * 180.0
}
// clampRange forces `m` to have reasonable values. It is a guard against crazy values in corrupt PDF files.
// Currently it clamps elements to [-maxAbsNumber, -maxAbsNumber] to avoid floating point exceptions.
func (m *Matrix) clampRange() {
for i, x := range m {
if x > maxAbsNumber {
common.Log.Debug("CLAMP: %g -> %g", x, maxAbsNumber)
m[i] = maxAbsNumber
} else if x < -maxAbsNumber {
common.Log.Debug("CLAMP: %g -> %g", x, -maxAbsNumber)
m[i] = -maxAbsNumber
}
}
}
// Unrealistic returns true if `m` is too small to have been created intentionally.
// If it returns true then `m` probably contains junk values, due to some processing error in the
// PDF generator or our code.
func (m *Matrix) Unrealistic() bool {
xx, xy, yx, yy := math.Abs(m[0]), math.Abs(m[1]), math.Abs(m[3]), math.Abs(m[4])
goodXxYy := xx > minSafeScale && yy > minSafeScale
goodXyYx := xy > minSafeScale && yx > minSafeScale
return !(goodXxYy || goodXyYx)
}
// minSafeScale is the minimum matrix scale that is expected to occur in a valid PDF file.
const minSafeScale = 1e-6
// maxAbsNumber defines the maximum absolute value of allowed practical matrix element values as needed
// to avoid floating point exceptions.
// TODO(gunnsth): Add reference or point to a specific example PDF that validates this.
const maxAbsNumber = 1e9
// minDeterminant is the smallest matrix determinant we are prepared to deal with.
// Smaller determinants may lead to rounding errors.
const minDeterminant = 1.0e-6 | bot/vendor/github.com/pzduniak/unipdf/internal/transform/matrix.go | 0.930742 | 0.711706 | matrix.go | starcoder |
package scanner
import (
"bufio"
"bytes"
"io"
"os"
"strconv"
"github.com/lukasmalkmus/spl/internal/app/spl/token"
)
var eof = rune(0)
// Scanner represents a lexical scanner which tokenizes source code.
type Scanner struct {
r *bufio.Reader
pos token.Position
resetColumnCount bool
}
// New returns a new Scanner instance which reads from the given reader.
func New(r io.Reader) *Scanner {
return &Scanner{
r: bufio.NewReader(r),
pos: token.Position{Filename: "", Line: 1, Column: 0},
}
}
// NewFileScanner returns a new Scanner instance, but will exclusively take an
// *os.File as argument instead of the more general io.Reader interface.
// Therefore it will enhance token positions with the filename.
func NewFileScanner(f *os.File) *Scanner {
return &Scanner{
r: bufio.NewReader(f),
pos: token.Position{Filename: f.Name(), Line: 1, Column: 0},
}
}
// Scan scans the next token and returns the token itself, its literal and its
// position in the source code. The source end is indicated by token.EOF.
func (s *Scanner) Scan() (token.Token, string, token.Position) {
s.skipWhitespace()
ch, pos := s.read()
// If we see a letter consume as an ident or reserved word.
// If we see a digit consume as an integer.
// If we see a "'" consume as an integer as well, but us a specialized
// scanning method.
if isLetter(ch) {
s.unread()
return s.scanIdent()
} else if isDigit(ch) {
s.unread()
return s.scanInteger()
} else if ch == '\'' {
s.unread()
return s.scanSpecialInteger()
}
// Otherwise tokenize the individual characters. No match results in an
// illegal token.
switch ch {
case eof:
pos.Column--
return token.EOF, "", pos
case '+':
return token.ADD, string(ch), pos
case '-':
return token.SUB, string(ch), pos
case '*':
return token.MUL, string(ch), pos
case '/':
if pch := s.peek(); pch == '/' {
return s.scanComment()
}
return token.QUO, string(ch), pos
case '=':
return token.EQL, string(ch), pos
case '<':
if pch := s.peek(); pch == '=' {
_, _ = s.read()
return token.LEQ, string(ch) + string(pch), pos
}
return token.LSS, string(ch), pos
case '>':
if pch := s.peek(); pch == '=' {
_, _ = s.read()
return token.GEQ, string(ch) + string(pch), pos
}
return token.GTR, string(ch), pos
case '#':
return token.NOT, string(ch), pos
case ':':
if pch := s.peek(); pch == '=' {
_, _ = s.read()
return token.ASSIGN, string(ch) + string(pch), pos
}
return token.COLON, string(ch), pos
case '(':
return token.LPAREN, string(ch), pos
case '[':
return token.LBRACK, string(ch), pos
case '{':
return token.LBRACE, string(ch), pos
case ')':
return token.RPAREN, string(ch), pos
case ']':
return token.RBRACK, string(ch), pos
case '}':
return token.RBRACE, string(ch), pos
case ',':
return token.COMMA, string(ch), pos
case ';':
return token.SEMICOLON, string(ch), pos
}
return token.ILLEGAL, string(ch), pos
}
// scanComment consumes the current rune and all contiguous comment runes.
func (s *Scanner) scanComment() (token.Token, string, token.Position) {
// Create a buffer for the comments text. It is initially populated with a
// slash which is the first slash of the comment token.
var buf bytes.Buffer
_ = buf.WriteByte('/')
ch, pos := s.read()
_, _ = buf.WriteRune(ch)
// Read every subsequent character into the buffer. Newline or EOF will
// cause the loop to exit.
for {
if ch, _ := s.read(); isNewline(ch) {
s.unread()
break
} else if ch == eof {
break
} else {
_, _ = buf.WriteRune(ch)
}
}
return token.COMMENT, buf.String(), pos
}
// scanIdent consumes the current rune and all contiguous ident runes.
func (s *Scanner) scanIdent() (token.Token, string, token.Position) {
var buf bytes.Buffer
ch, pos := s.read()
_, _ = buf.WriteRune(ch)
// Read every subsequent ident character into the buffer. Non-ident
// characters and EOF will cause the loop to exit.
for {
if ch, _ := s.read(); ch == eof {
break
} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {
s.unread()
break
} else {
_, _ = buf.WriteRune(ch)
}
}
// Make sure the last character is not an underscore, which is illegal.
if ch := buf.Bytes()[buf.Len()-1]; ch == '_' {
return token.ILLEGAL, buf.String(), pos
}
return token.Lookup(buf.String()), buf.String(), pos
}
// scanInteger consumes the current rune and all contiguous integer runes.
func (s *Scanner) scanInteger() (token.Token, string, token.Position) {
var buf bytes.Buffer
ch, pos := s.read()
_, _ = buf.WriteRune(ch)
// Read every subsequent character into the buffer. Non-integer characters
// and EOF will cause the loop to exit.
for {
if ch, _ := s.read(); ch == eof {
break
} else if !isLetter(ch) && !isDigit(ch) {
s.unread()
break
} else {
_, _ = buf.WriteRune(ch)
}
}
// Uppercase 'X' not allowed in hexadecimal representation.
if bytes.ContainsRune(buf.Bytes(), 'X') {
return token.ILLEGAL, buf.String(), pos
} else if _, err := strconv.ParseInt(buf.String(), 0, 32); err != nil {
return token.ILLEGAL, buf.String(), pos
}
return token.INT, buf.String(), pos
}
// scanSpecialInteger consumes the current rune and all contiguous special
// integer runes.
func (s *Scanner) scanSpecialInteger() (token.Token, string, token.Position) {
var buf bytes.Buffer
ch, pos := s.read()
_, _ = buf.WriteRune(ch)
// Read every subsequent character into the buffer. Non-integer characters,
// multiple whitespaces and EOF will cause the loop to exit.
var (
charCount uint8 = 1 // We already saw one.
sqmCount uint8 = 1 // We already saw one.
wsCount uint8
)
for {
if ch, _ := s.read(); ch == eof {
break
} else if (sqmCount == 2 && charCount >= 3) || sqmCount > 2 || wsCount > 2 {
s.unread()
break
} else {
charCount++
if ch == '\'' {
sqmCount++
} else if ch == ' ' {
wsCount++
}
_, _ = buf.WriteRune(ch)
}
}
b := buf.Bytes()
// The first character is a tick so the last one must be one, too.
if l := len(b); l < 3 || b[l-1] != '\'' {
return token.ILLEGAL, buf.String(), pos
}
// If the length of the input is three, the character encapsuled by the
// single quotation marks must be a printable ASCII character.
// If the length of the input is four, the characters encapsuled by the
// single quotation marks must form an ASCII escape sequence by the first
// character being a backslash and the second character being a letter.
if len(b) == 3 && b[1] > 31 && b[1] < 127 {
return token.INT, buf.String(), pos
} else if len(b) == 4 && b[1] == '\\' && isLetter(rune(b[2])) {
return token.INT, buf.String(), pos
}
return token.ILLEGAL, buf.String(), pos
}
// skipWhitespace consumes the current rune and all contiguous newline and
// whitespace. It keeps track of the token position.
func (s *Scanner) skipWhitespace() {
var buf bytes.Buffer
for ch, _ := s.read(); isNewline(ch) || isWhitespace(ch); ch, _ = s.read() {
if isNewline(ch) {
_, _ = buf.WriteRune(ch)
s.resetColumnCount = true
}
}
clean := stripCR(buf.Bytes())
s.pos.Line += len(clean)
s.unread()
}
// read reads the next rune from the buffered reader. Returns rune(0) if an
// error occurs (which can also be io.EOF returned from the underlying reader).
func (s *Scanner) read() (rune, token.Position) {
if s.resetColumnCount {
s.pos.Column = 0
s.resetColumnCount = false
}
s.pos.Column++
s.pos.Char++
// Read from the underlying reader.
ch, _, err := s.r.ReadRune()
if err != nil {
return eof, s.pos
}
return ch, s.pos
}
// unread places the previously read rune back on the reader.
func (s *Scanner) unread() {
_ = s.r.UnreadRune()
s.pos.Column--
s.pos.Char--
}
// unread peeks for the next rune from the buffered reader.
func (s *Scanner) peek() rune {
ch, _ := s.read()
s.unread()
return ch
}
// isWhitespace returns true if the rune is a space or tab.
func isWhitespace(ch rune) bool { return ch == ' ' || ch == '\t' }
// isNewline returns true if the rune is a newline.
func isNewline(ch rune) bool { return ch == '\n' || ch == '\r' }
// isLetter returns true if the rune is a letter.
func isLetter(ch rune) bool { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') }
// isDigit returns true if the rune is a digit.
func isDigit(ch rune) bool { return (ch >= '0' && ch <= '9') }
// stripCR removes every carriage-return from a slice of bytes, effectively
// turning a CRLF into a LF.
func stripCR(b []byte) []byte {
c := make([]byte, 0)
for _, ch := range b {
if ch == '\n' {
c = append(c, ch)
}
}
return c
} | internal/app/spl/scanner/scanner.go | 0.675444 | 0.401043 | scanner.go | starcoder |
package audio
import "syscall/js"
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam
type AudioParam struct {
value js.Value
}
func (param AudioParam) Default() float64 {
return param.value.Get("defaultValue").Float()
}
func (param AudioParam) Max() float64 {
return param.value.Get("maxValue").Float()
}
func (param AudioParam) Min() float64 {
return param.value.Get("minValue").Float()
}
func (param AudioParam) Get() float64 {
return param.value.Get("value").Float()
}
func (param AudioParam) Set(value float64) {
param.value.Set("value", value)
}
// AtTime returns a namespace of operations on AudioParam
// that are scheduled at specified time.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam#Methods
func (param AudioParam) AtTime(time float64) AtTime {
return AtTime{value: param.value, time: time}
}
// AtTime is a namespace of operations on AudioParam
// that are scheduled at specified time.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam#Methods
type AtTime struct {
value js.Value
time float64
}
// Set schedules an instant change to the AudioParam value at a precise time,
// as measured against AudioContext.CurrentTime.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setValueAtTime
func (param AtTime) Set(value float64) {
param.value.Call("setValueAtTime", value, param.time)
}
// LinearRampTo schedules a gradual linear change in the value of the AudioParam.
// The change starts at the time specified for the previous event,
// follows a linear ramp to the new value given in the value parameter,
// and reaches the new value at the time given in the `time` parameter.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/linearRampToValueAtTime
func (param AtTime) LinearRampTo(value float64) {
param.value.Call("linearRampToValueAtTime", value, param.time)
}
// ExponentialRampTo schedules a gradual exponential change in the value of the AudioParam.
// The change starts at the time specified for the previous event,
// follows an exponential ramp to the new value given in the value parameter,
// and reaches the new value at the time given in the `time` parameter.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/exponentialRampToValueAtTime
func (param AtTime) ExponentialRampTo(value float64) {
param.value.Call("exponentialRampToValueAtTime", value, param.time)
}
// SetTarget schedules the start of a gradual change to the AudioParam value.
// This is useful for decay or release portions of ADSR envelopes.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setTargetAtTime
func (param AtTime) SetTarget(target, timeConstant float64) {
param.value.Call("setTargetAtTime", target, param.time, timeConstant)
}
// SetCurve schedules the parameter's value to change following a curve
// defined by a list of values. The curve is a linear interpolation between
// the sequence of values defined in an array of floating-point values,
// which are scaled to fit into the given interval starting at `time` and a specific `duration`.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setValueCurveAtTime
func (param AtTime) SetCurve(values []float64, duration float64) {
param.value.Call("setValueCurveAtTime", values, param.time, duration)
}
// Cancel cancels all scheduled future changes to the AudioParam.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/cancelScheduledValues
func (param AtTime) Cancel(values []float64, duration float64) {
param.value.Call("cancelScheduledValues", param.time)
}
// CancelAndHold cancels all scheduled future changes to the AudioParam
// but holds its value at a given time until further changes are made using other methods.
// https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/cancelAndHoldAtTime
func (param AtTime) CancelAndHold() {
param.value.Call("cancelAndHoldAtTime", param.time)
} | audio/audio_param.go | 0.877299 | 0.421492 | audio_param.go | starcoder |
package termui
import "strings"
/* Table is like:
βAwesome Table βββββββββββββββββββββββββββββββββββββββββββββββββ
β Col0 | Col1 | Col2 | Col3 | Col4 | Col5 | Col6 |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Some Item #1 | AAA | 123 | CCCCC | EEEEE | GGGGG | IIIII |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Some Item #2 | BBB | 456 | DDDDD | FFFFF | HHHHH | JJJJJ |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Datapoints are a two dimensional array of strings: [][]string
Example:
data := [][]string{
{"Col0", "Col1", "Col3", "Col4", "Col5", "Col6"},
{"Some Item #1", "AAA", "123", "CCCCC", "EEEEE", "GGGGG", "IIIII"},
{"Some Item #2", "BBB", "456", "DDDDD", "FFFFF", "HHHHH", "JJJJJ"},
}
table := termui.NewTable()
table.Rows = data // type [][]string
table.FgColor = termui.ColorWhite
table.BgColor = termui.ColorDefault
table.Height = 7
table.Width = 62
table.Y = 0
table.X = 0
table.Border = true
*/
// Table tracks all the attributes of a Table instance
type Table struct {
Block
Rows [][]string
CellWidth []int
FgColor Attribute
BgColor Attribute
FgColors []Attribute
BgColors []Attribute
Separator bool
TextAlign Align
}
// NewTable returns a new Table instance
func NewTable() *Table {
table := &Table{Block: *NewBlock()}
table.FgColor = ColorWhite
table.BgColor = ColorDefault
table.Separator = true
return table
}
// CellsWidth calculates the width of a cell array and returns an int
func cellsWidth(cells []Cell) int {
width := 0
for _, c := range cells {
width += c.Width()
}
return width
}
// Analysis generates and returns an array of []Cell that represent all columns in the Table
func (table *Table) Analysis() [][]Cell {
var rowCells [][]Cell
length := len(table.Rows)
if length < 1 {
return rowCells
}
if len(table.FgColors) == 0 {
table.FgColors = make([]Attribute, len(table.Rows))
}
if len(table.BgColors) == 0 {
table.BgColors = make([]Attribute, len(table.Rows))
}
cellWidths := make([]int, len(table.Rows[0]))
for y, row := range table.Rows {
if table.FgColors[y] == 0 {
table.FgColors[y] = table.FgColor
}
if table.BgColors[y] == 0 {
table.BgColors[y] = table.BgColor
}
for x, str := range row {
cells := DefaultTxBuilder.Build(str, table.FgColors[y], table.BgColors[y])
cw := cellsWidth(cells)
if cellWidths[x] < cw {
cellWidths[x] = cw
}
rowCells = append(rowCells, cells)
}
}
table.CellWidth = cellWidths
return rowCells
}
// SetSize calculates the table size and sets the internal value
func (table *Table) SetSize() {
length := len(table.Rows)
if table.Separator {
table.Height = length*2 + 1
} else {
table.Height = length + 2
}
table.Width = 2
if length != 0 {
for _, cellWidth := range table.CellWidth {
table.Width += cellWidth + 3
}
}
}
// CalculatePosition ...
func (table *Table) CalculatePosition(x int, y int, coordinateX *int, coordinateY *int, cellStart *int) {
if table.Separator {
*coordinateY = table.innerArea.Min.Y + y*2
} else {
*coordinateY = table.innerArea.Min.Y + y
}
if x == 0 {
*cellStart = table.innerArea.Min.X
} else {
*cellStart += table.CellWidth[x-1] + 3
}
switch table.TextAlign {
case AlignRight:
*coordinateX = *cellStart + (table.CellWidth[x] - len(table.Rows[y][x])) + 2
case AlignCenter:
*coordinateX = *cellStart + (table.CellWidth[x]-len(table.Rows[y][x]))/2 + 2
default:
*coordinateX = *cellStart + 2
}
}
// Buffer ...
func (table *Table) Buffer() Buffer {
buffer := table.Block.Buffer()
rowCells := table.Analysis()
pointerX := table.innerArea.Min.X + 2
pointerY := table.innerArea.Min.Y
borderPointerX := table.innerArea.Min.X
for y, row := range table.Rows {
for x := range row {
table.CalculatePosition(x, y, &pointerX, &pointerY, &borderPointerX)
background := DefaultTxBuilder.Build(strings.Repeat(" ", table.CellWidth[x]+3), table.BgColors[y], table.BgColors[y])
cells := rowCells[y*len(row)+x]
for i, back := range background {
buffer.Set(borderPointerX+i, pointerY, back)
}
coordinateX := pointerX
for _, printer := range cells {
buffer.Set(coordinateX, pointerY, printer)
coordinateX += printer.Width()
}
if x != 0 {
dividors := DefaultTxBuilder.Build("|", table.FgColors[y], table.BgColors[y])
for _, dividor := range dividors {
buffer.Set(borderPointerX, pointerY, dividor)
}
}
}
if table.Separator {
border := DefaultTxBuilder.Build(strings.Repeat("β", table.Width-2), table.FgColor, table.BgColor)
for i, cell := range border {
buffer.Set(i+1, pointerY+1, cell)
}
}
}
return buffer
} | vendor/github.com/gizak/termui/table.go | 0.708918 | 0.486027 | table.go | starcoder |
package main
import (
"fmt"
"os"
"strings"
"text/template"
"github.com/aquasecurity/cfsec/internal/app/cfsec/rules"
)
const (
baseWebPageTemplate = `---
title: {{$.Summary}}
shortcode: {{$.ShortCode}}
summary: {{$.Summary}}
permalink: /docs/{{$.Service}}/{{$.ShortCode}}/
---
### Explanation
{{$.Explanation}}
### Possible Impact
{{$.Impact}}
### Suggested Resolution
{{$.Resolution}}
{{if $.BadExample }}
### Insecure Example
The following example will fail the {{$.ID}} check.
` + "```yaml" + `
{{ (index $.BadExample 0) }}
` + "```" + `
{{end}}
{{if $.GoodExample }}
### Secure Example
The following example will pass the {{$.ID}} check.
` + "```yaml" + `
{{ (index $.GoodExample 0) }}
` + "```" + `
{{end}}
{{if $.Links}}
### Related Links
{{range $link := $.Links}}
- [{{.}}]({{.}})
{{end}}
{{end}}
`
)
type docEntry struct {
Summary string
ID string
ShortCode string
Service string
Explanation string
Impact string
Resolution string
BadExample []string
GoodExample []string
Links []string
}
func newEntry(check rules.Rule) docEntry {
var links []string
for _, link := range check.Base.Rule().Links {
if strings.HasPrefix(link, "https://cfsec.dev") {
continue
}
links = append(links, link)
}
return docEntry{
Summary: check.Base.Rule().Summary,
ID: check.ID(),
ShortCode: check.Base.Rule().ShortCode,
Explanation: check.Base.Rule().Explanation,
Impact: check.Base.Rule().Impact,
Resolution: check.Base.Rule().Resolution,
BadExample: check.BadExample,
GoodExample: check.GoodExample,
Service: check.Base.Rule().Service,
Links: links,
}
}
func generateWebPages(fileContents []rules.Rule) error {
for _, check := range fileContents {
webProviderPath := fmt.Sprintf("docs/checks/%s", strings.ToLower(check.Base.Rule().Service))
entry := newEntry(check)
if err := generateWebPage(webProviderPath, entry); err != nil {
return err
}
}
return nil
}
var funcMap = template.FuncMap{
"ToUpper": strings.ToUpper,
"Join": join,
}
func join(s []string) string {
if s == nil {
return ""
}
return strings.Join(s[1:], s[0])
}
func generateWebPage(webProviderPath string, r docEntry) error {
if err := os.MkdirAll(webProviderPath, os.ModePerm); err != nil {
return err
}
filePath := fmt.Sprintf("%s/%s.md", webProviderPath, r.ShortCode)
fmt.Printf("Generating page for %s at %s\n", r.ID, filePath)
webTmpl := template.Must(template.New("web").Funcs(funcMap).Parse(baseWebPageTemplate))
return writeTemplate(r, filePath, webTmpl)
}
func writeTemplate(contents interface{}, path string, tmpl *template.Template) error {
outputFile, err := os.Create(path)
if err != nil {
return err
}
defer func() { _ = outputFile.Close() }()
return tmpl.Execute(outputFile, contents)
} | cmd/cfsec-docs/webpage.go | 0.661923 | 0.617657 | webpage.go | starcoder |
package manuals
// Gif is the man page for `<prefix>man gif`
const gif string = `
Gif(1) User Commands Gif(1)
NAME
gif - Selects a random gif to display based off the user's input.
SYNOPSIS
<prefix>gif [tag]
DESCRIPTION
Gif returns to the requester a single giy based off the input tag
provided. The gif is sent to the same channel that the user executed
the command within.
EXAMPLE
<prefix>gif laugh
`
// Man is the man page for `<prefix>man man`
const man string = `
Man(1) User Commands Man(1)
NAME
man - Used to get information about a bot command.
SYNOPSIS
<prefix>man [command]
DESCRIPTION
Man returns to the requester the information about a command and how
that command is to be used. The message is sent as a DM to the user
requesting the information.
EXAMPLE
<prefix>man pong
`
// Meme is the man page for `<prefix>man man`
const meme string = `
MEME(1) User Commands MEME(1)
NAME
meme - Create a meme on the fly.
SYNOPSIS
<prefix>meme [meme name] [top text] [bottom text]
DESCRIPTION
Meme sends back a new meme created with the text the user provides
by calling the memegen.link api. Text with spaces must be formatted
as this_is_top or this-is-top.
COMMAND SYNOPSIS
This is just a brief synopsis of <prefix>meme commands to serve as a
reminder to those who already know the memegen.link api; for more
information please refer to https://memegen.link/api/
<prefix>meme list
Returns the template url on memegen.link with all available images.
<prefix>meme spongebob why_are_you here
Returns the url to the newly created mocking spongebob meme with
the top text "why are you" and the bottom text "here".
<prefix>meme spongebob why_are_you
Returns the url to the newly created mocking spongebob meme with
the top text "why are you" and no bottom text.
`
// Ping is the man page for `<prefix>man rule34`
const ping string = `
PING(1) User Commands PING(1)
NAME
ping - Used to check the bots responce.
SYNOPSIS
<prefix>ping
DESCRIPTION
Ping will return "pong" when the bot is online.
EXAMPLE
<prefix>ping
`
// Rule34 is the man page for `<prefix>man rule34`
const rule34 string = `
RULE34(1) User Commands RULE34(1)
NAME
rule34 - NSFW command to grab a random image from rule34.xxx
SYNOPSIS
<prefix>rule34 [tag]
DESCRIPTION
Rule34 states that "if it exists there is porn for it." This command
will only trigger in a channel marked as NFSW.
EXAMPLE
<prefix>rule34 boobs
` | manuals/manpages.go | 0.560734 | 0.502686 | manpages.go | starcoder |
package check
import (
"fmt"
"time"
)
// Duration is the type of a check function which takes a time.Duration
// parameter and returns an error or nil if the check passes
type Duration func(d time.Duration) error
// DurationGT returns a function that will check that the value is
// greater than the limit
func DurationGT(limit time.Duration) Duration {
return func(d time.Duration) error {
if d > limit {
return nil
}
return fmt.Errorf("the value (%s) must be greater than %s", d, limit)
}
}
// DurationGE returns a function that will check that the value is
// greater than or equal to the limit
func DurationGE(limit time.Duration) Duration {
return func(d time.Duration) error {
if d >= limit {
return nil
}
return fmt.Errorf("the value (%s) must be greater than or equal to %s",
d, limit)
}
}
// DurationLT returns a function that will check that the value is
// less than the limit
func DurationLT(limit time.Duration) Duration {
return func(d time.Duration) error {
if d < limit {
return nil
}
return fmt.Errorf("the value (%s) must be less than %s", d, limit)
}
}
// DurationLE returns a function that will check that the value is
// less than or equal to the limit
func DurationLE(limit time.Duration) Duration {
return func(d time.Duration) error {
if d <= limit {
return nil
}
return fmt.Errorf("the value (%s) must be less than or equal to %s",
d, limit)
}
}
// DurationBetween returns a function that will check that the
// value lies between the upper and lower limits (inclusive)
func DurationBetween(low, high time.Duration) Duration {
if low >= high {
panic(fmt.Sprintf(
"Impossible checks passed to DurationBetween: "+
"the lower limit (%s) should be less than the upper limit (%s)",
low, high))
}
return func(d time.Duration) error {
if d < low {
return fmt.Errorf(
"the value (%s) must be between %s and %s - too short",
d, low, high)
}
if d > high {
return fmt.Errorf(
"the value (%s) must be between %s and %s - too long",
d, low, high)
}
return nil
}
}
// DurationOr returns a function that will check that the value, when
// passed to each of the check funcs in turn, passes at least one of them
func DurationOr(chkFuncs ...Duration) Duration {
return func(d time.Duration) error {
compositeErr := ""
sep := "("
for _, cf := range chkFuncs {
err := cf(d)
if err == nil {
return nil
}
compositeErr += sep + err.Error()
sep = _Or
}
return fmt.Errorf("%s)", compositeErr)
}
}
// DurationAnd returns a function that will check that the value, when
// passed to each of the check funcs in turn, passes all of them
func DurationAnd(chkFuncs ...Duration) Duration {
return func(d time.Duration) error {
for _, cf := range chkFuncs {
err := cf(d)
if err != nil {
return err
}
}
return nil
}
}
// DurationNot returns a function that will check that the value, when passed
// to the check func, does not pass it. You must also supply the error text
// to appear after the duration that fails. This error text should be a string
// that describes the quality that the duration should not have. So, for
// instance, if the function being Not'ed was
// check.DurationGE(5)
// then the errMsg parameter should be
// "a duration greater than or equal to 5".
func DurationNot(c Duration, errMsg string) Duration {
return func(d time.Duration) error {
err := c(d)
if err != nil {
return nil
}
return fmt.Errorf("'%s' should not be %s", d, errMsg)
}
} | check/duration.go | 0.766206 | 0.566738 | duration.go | starcoder |
package output
import (
"context"
"errors"
"fmt"
"time"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/types"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeResource] = TypeSpec{
constructor: NewResource,
Summary: `
Resource is an output type that runs a resource output by its name. This output
allows you to run the same configured output resource in multiple places.`,
Description: `
Resource outputs also have the advantage of name based metrics and logging. For
example, the config:
` + "``` yaml" + `
output:
broker:
pattern: fan_out
outputs:
- kafka:
addresses: [ TODO ]
topic: foo
- gcp_pubsub:
project: bar
topic: baz
` + "```" + `
Is equivalent to:
` + "``` yaml" + `
output:
broker:
pattern: fan_out
outputs:
- resource: foo
- resource: bar
resources:
outputs:
foo:
kafka_balanced:
addresses: [ TODO ]
topic: foo
bar:
gcp_pubsub:
project: bar
topic: baz
` + "```" + `
But now the metrics path of Kafka output will be
` + "`resources.outputs.foo`" + `, this way of flattening observability
labels becomes more useful as configs get larger and more nested.`,
}
}
//------------------------------------------------------------------------------
type outputProvider interface {
GetOutput(name string) (types.OutputWriter, error)
}
//------------------------------------------------------------------------------
// Resource is a processor that returns the result of a output resource.
type Resource struct {
mgr outputProvider
name string
log log.Modular
stats metrics.Type
transactions <-chan types.Transaction
ctx context.Context
done func()
mErrNotFound metrics.StatCounter
}
// NewResource returns a resource output.
func NewResource(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
// TODO: V4 Remove this
outputProvider, ok := mgr.(outputProvider)
if !ok {
return nil, errors.New("manager does not support output resources")
}
if _, err := outputProvider.GetOutput(conf.Resource); err != nil {
return nil, fmt.Errorf("failed to obtain output resource '%v': %v", conf.Resource, err)
}
ctx, done := context.WithCancel(context.Background())
return &Resource{
mgr: outputProvider,
name: conf.Resource,
log: log,
stats: stats,
ctx: ctx,
done: done,
mErrNotFound: stats.GetCounter("error_not_found"),
}, nil
}
//------------------------------------------------------------------------------
func (r *Resource) loop() {
// Metrics paths
var (
mCount = r.stats.GetCounter("count")
)
var ts *types.Transaction
for {
if ts == nil {
select {
case t, open := <-r.transactions:
if !open {
r.done()
return
}
ts = &t
case <-r.ctx.Done():
return
}
}
mCount.Incr(1)
out, err := r.mgr.GetOutput(r.name)
if err != nil {
r.log.Debugf("Failed to obtain output resource '%v': %v", r.name, err)
r.mErrNotFound.Incr(1)
select {
case <-time.After(time.Second):
case <-r.ctx.Done():
return
}
} else {
out.WriteTransaction(r.ctx, *ts)
ts = nil
}
}
}
//------------------------------------------------------------------------------
// Consume assigns a messages channel for the output to read.
func (r *Resource) Consume(ts <-chan types.Transaction) error {
if r.transactions != nil {
return types.ErrAlreadyStarted
}
r.transactions = ts
go r.loop()
return nil
}
// Connected returns a boolean indicating whether this output is currently
// connected to its target.
func (r *Resource) Connected() bool {
out, err := r.mgr.GetOutput(r.name)
if err != nil {
r.log.Debugf("Failed to obtain output resource '%v': %v", r.name, err)
r.mErrNotFound.Incr(1)
return false
}
return out.Connected()
}
// CloseAsync shuts down the output and stops processing requests.
func (r *Resource) CloseAsync() {
r.done()
}
// WaitForClose blocks until the output has closed down.
func (r *Resource) WaitForClose(timeout time.Duration) error {
select {
case <-r.ctx.Done():
case <-time.After(timeout):
return types.ErrTimeout
}
return nil
}
//------------------------------------------------------------------------------ | lib/output/resource.go | 0.591841 | 0.704697 | resource.go | starcoder |
package server
import (
"errors"
"github.com/influxdata/influxdb-client-go/v2/api/query"
)
func MeasurementFromRecord(r *query.FluxRecord) (Measurement, error) {
if r == nil {
return nil, errors.New("nil record")
}
switch r.Field() {
case "pressure":
return pressureMeasurementFromRecord(r)
case "humidity":
return humidityMeasurementFromRecord(r)
case "temperature":
return temperatureMeasurementFromRecord(r)
case "batteryvoltage":
return batteryVoltageMeasurementFromRecord(r)
case "":
return nil, errors.New("empty field")
default:
return nil, errors.New("unknown field: " + r.Field())
}
}
func pressureMeasurementFromRecord(r *query.FluxRecord) (Measurement, error) {
if r == nil || r.Field() != "pressure" {
return nil, errors.New("not a pressure record")
}
mac, ok := r.ValueByKey("sensormac").(string)
if !ok || mac == "" {
return nil, errors.New("pressure: missing sensormac field")
}
recordTime := r.Time()
switch pressure := r.Value().(type) {
case int64:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case int32:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case int16:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case int8:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case int:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case uint8:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case uint16:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case uint32:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case uint64:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case float32:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
case float64:
return &PressureMeasurement{
SensorID_: mac,
Pressure_: int(pressure),
Time_: recordTime,
}, nil
}
return nil, errors.New("pressure: cannot cast value int")
}
func humidityMeasurementFromRecord(r *query.FluxRecord) (Measurement, error) {
if r == nil || r.Field() != "humidity" {
return nil, errors.New("not a humidity record")
}
mac, ok := r.ValueByKey("sensormac").(string)
if !ok || mac == "" {
return nil, errors.New("humidity: missing sensormac field")
}
humidity, ok := r.Value().(float64)
if !ok {
return nil, errors.New("humidity: cannot cast value to float64")
}
recordTime := r.Time()
return &HumidityMeasurement{
SensorID_: mac,
Humidity_: humidity,
Time_: recordTime,
}, nil
}
func temperatureMeasurementFromRecord(r *query.FluxRecord) (Measurement, error) {
if r == nil || r.Field() != "temperature" {
return nil, errors.New("not a temperature record")
}
mac, ok := r.ValueByKey("sensormac").(string)
if !ok || mac == "" {
return nil, errors.New("temperature: missing sensormac field")
}
temperature, ok := r.Value().(float64)
if !ok {
return nil, errors.New("temperature: cannot cast value to float64")
}
recordTime := r.Time()
return &TemperatureMeasurement{
SensorID_: mac,
Temperature_: temperature,
Time_: recordTime,
}, nil
}
func batteryVoltageMeasurementFromRecord(r *query.FluxRecord) (Measurement, error) {
if r == nil || r.Field() != "batteryvoltage" {
return nil, errors.New("not a batteryvoltage record")
}
mac, ok := r.ValueByKey("sensormac").(string)
if !ok || mac == "" {
return nil, errors.New("batteryvoltage: missing sensormac field")
}
voltage, ok := r.Value().(float64)
if !ok {
return nil, errors.New("batteryvoltage: cannot cast value to float64")
}
recordTime := r.Time()
return &BatteryVoltageMeasurement{
SensorID_: mac,
Voltage_: voltage,
Time_: recordTime,
}, nil
} | server/record_processing.go | 0.742515 | 0.46478 | record_processing.go | starcoder |
package gm
import (
"github.com/cpmech/gosl/la"
"github.com/cpmech/gosl/utl"
)
// Metrics holds data related to a position in a space represented by curvilinear coordinates
type Metrics struct {
U la.Vector // reference coordinates {r,s,t}
X la.Vector // physical coordinates {x,y,z}
CovG0 la.Vector // covariant basis g_0 = d{x}/dr
CovG1 la.Vector // covariant basis g_1 = d{x}/ds
CovG2 la.Vector // covariant basis g_2 = d{x}/dt
CntG0 la.Vector // contravariant basis g_0 = dr/d{x} (gradients)
CntG1 la.Vector // contravariant basis g_1 = ds/d{x} (gradients)
CntG2 la.Vector // contravariant basis g_2 = dt/d{x} (gradients)
CovGmat *la.Matrix // covariant metrics g_ij = g_i β
g_j
CntGmat *la.Matrix // contravariant metrics g^ij = g^i β
g^j
DetCovGmat float64 // determinant of covariant g matrix = det(CovGmat)
Homogeneous bool // homogeneous grid => nil second order derivatives and Christoffel symbols
GammaS [][][]float64 // [k][i][j] Christoffel coefficients of second kind (non-homogeneous)
L []float64 // [3] L-coefficients = sum(Ξ_ij^k β
g^ij) (non-homogeneous)
}
// NewMetrics2d allocate new 2D metrics structure
// NOTE: the second order derivatives (from ddxdrr) may be nil => homogeneous grid
func NewMetrics2d(u, x, dxdr, dxds, ddxdrr, ddxdss, ddxdrs la.Vector) (o *Metrics) {
// input
o = new(Metrics)
o.U = u.GetCopy()
o.X = x.GetCopy()
o.CovG0 = dxdr.GetCopy()
o.CovG1 = dxds.GetCopy()
// covariant metrics
o.CovGmat = la.NewMatrix(2, 2)
o.CovGmat.Set(0, 0, la.VecDot(o.CovG0, o.CovG0))
o.CovGmat.Set(1, 1, la.VecDot(o.CovG1, o.CovG1))
o.CovGmat.Set(0, 1, la.VecDot(o.CovG0, o.CovG1))
o.CovGmat.Set(1, 0, o.CovGmat.Get(0, 1))
// contravariant metrics
o.CntGmat = la.NewMatrix(2, 2)
o.DetCovGmat = la.MatInvSmall(o.CntGmat, o.CovGmat, 1e-13)
// contravariant vectors
o.CntG0 = la.NewVector(2)
o.CntG1 = la.NewVector(2)
for i := 0; i < 2; i++ {
o.CntG0[i] += o.CntGmat.Get(0, 0)*o.CovG0[i] + o.CntGmat.Get(0, 1)*o.CovG1[i]
o.CntG1[i] += o.CntGmat.Get(1, 0)*o.CovG0[i] + o.CntGmat.Get(1, 1)*o.CovG1[i]
}
// check if homogeneous grid
o.Homogeneous = ddxdrr == nil
if o.Homogeneous {
return
}
// Christoffel vectors
Ξ00, Ξ11, Ξ01 := ddxdrr, ddxdss, ddxdrs
// Christoffel symbols of second kind
o.GammaS = utl.Deep3alloc(2, 2, 2)
o.GammaS[0][0][0] = la.VecDot(Ξ00, o.CntG0)
o.GammaS[0][1][1] = la.VecDot(Ξ11, o.CntG0)
o.GammaS[0][0][1] = la.VecDot(Ξ01, o.CntG0)
o.GammaS[0][1][0] = o.GammaS[0][0][1]
o.GammaS[1][0][0] = la.VecDot(Ξ00, o.CntG1)
o.GammaS[1][1][1] = la.VecDot(Ξ11, o.CntG1)
o.GammaS[1][0][1] = la.VecDot(Ξ01, o.CntG1)
o.GammaS[1][1][0] = o.GammaS[1][0][1]
// L-coefficients
o.L = make([]float64, 2)
o.L[0] = o.GammaS[0][0][0]*o.CntGmat.Get(0, 0) + o.GammaS[0][1][1]*o.CntGmat.Get(1, 1) + 2.0*o.GammaS[0][0][1]*o.CntGmat.Get(0, 1)
o.L[1] = o.GammaS[1][0][0]*o.CntGmat.Get(0, 0) + o.GammaS[1][1][1]*o.CntGmat.Get(1, 1) + 2.0*o.GammaS[1][0][1]*o.CntGmat.Get(0, 1)
return
}
// NewMetrics3d allocate new 3D metrics structure
// NOTE: the second order derivatives (from ddxdrr) may be nil => homogeneous grid
func NewMetrics3d(u, x, dxdr, dxds, dxdt, ddxdrr, ddxdss, ddxdtt, ddxdrs, ddxdrt, ddxdst la.Vector) (o *Metrics) {
// input
o = new(Metrics)
o.U = u.GetCopy()
o.X = x.GetCopy()
o.CovG0 = dxdr.GetCopy()
o.CovG1 = dxds.GetCopy()
o.CovG2 = dxdt.GetCopy()
// covariant metrics
o.CovGmat = la.NewMatrix(3, 3)
o.CovGmat.Set(0, 0, la.VecDot(o.CovG0, o.CovG0))
o.CovGmat.Set(1, 1, la.VecDot(o.CovG1, o.CovG1))
o.CovGmat.Set(2, 2, la.VecDot(o.CovG2, o.CovG2))
o.CovGmat.Set(0, 1, la.VecDot(o.CovG0, o.CovG1))
o.CovGmat.Set(1, 2, la.VecDot(o.CovG1, o.CovG2))
o.CovGmat.Set(2, 0, la.VecDot(o.CovG2, o.CovG0))
o.CovGmat.Set(1, 0, o.CovGmat.Get(0, 1))
o.CovGmat.Set(2, 1, o.CovGmat.Get(1, 2))
o.CovGmat.Set(0, 2, o.CovGmat.Get(2, 0))
// contravariant metrics
o.CntGmat = la.NewMatrix(3, 3)
o.DetCovGmat = la.MatInvSmall(o.CntGmat, o.CovGmat, 1e-13)
// contravariant vectors
o.CntG0 = la.NewVector(3)
o.CntG1 = la.NewVector(3)
o.CntG2 = la.NewVector(3)
for i := 0; i < 3; i++ {
o.CntG0[i] += o.CntGmat.Get(0, 0)*o.CovG0[i] + o.CntGmat.Get(0, 1)*o.CovG1[i] + o.CntGmat.Get(0, 2)*o.CovG2[i]
o.CntG1[i] += o.CntGmat.Get(1, 0)*o.CovG0[i] + o.CntGmat.Get(1, 1)*o.CovG1[i] + o.CntGmat.Get(1, 2)*o.CovG2[i]
o.CntG2[i] += o.CntGmat.Get(2, 0)*o.CovG0[i] + o.CntGmat.Get(2, 1)*o.CovG1[i] + o.CntGmat.Get(2, 2)*o.CovG2[i]
}
// check if homogeneous grid
o.Homogeneous = ddxdrr == nil
if o.Homogeneous {
return
}
// Christoffel vectors
Ξ00, Ξ11, Ξ22, Ξ01, Ξ02, Ξ12 := ddxdrr, ddxdss, ddxdtt, ddxdrs, ddxdrt, ddxdst
// Christoffel symbols of second kind
o.GammaS = utl.Deep3alloc(3, 3, 3)
o.GammaS[0][0][0] = la.VecDot(Ξ00, o.CntG0)
o.GammaS[0][1][1] = la.VecDot(Ξ11, o.CntG0)
o.GammaS[0][2][2] = la.VecDot(Ξ22, o.CntG0)
o.GammaS[0][0][1] = la.VecDot(Ξ01, o.CntG0)
o.GammaS[0][0][2] = la.VecDot(Ξ02, o.CntG0)
o.GammaS[0][1][2] = la.VecDot(Ξ12, o.CntG0)
o.GammaS[0][1][0] = o.GammaS[0][0][1]
o.GammaS[0][2][0] = o.GammaS[0][0][2]
o.GammaS[0][2][1] = o.GammaS[0][1][2]
o.GammaS[1][0][0] = la.VecDot(Ξ00, o.CntG1)
o.GammaS[1][1][1] = la.VecDot(Ξ11, o.CntG1)
o.GammaS[1][2][2] = la.VecDot(Ξ22, o.CntG1)
o.GammaS[1][0][1] = la.VecDot(Ξ01, o.CntG1)
o.GammaS[1][0][2] = la.VecDot(Ξ02, o.CntG1)
o.GammaS[1][1][2] = la.VecDot(Ξ12, o.CntG1)
o.GammaS[1][1][0] = o.GammaS[1][0][1]
o.GammaS[1][2][0] = o.GammaS[1][0][2]
o.GammaS[1][2][1] = o.GammaS[1][1][2]
o.GammaS[2][0][0] = la.VecDot(Ξ00, o.CntG2)
o.GammaS[2][1][1] = la.VecDot(Ξ11, o.CntG2)
o.GammaS[2][2][2] = la.VecDot(Ξ22, o.CntG2)
o.GammaS[2][0][1] = la.VecDot(Ξ01, o.CntG2)
o.GammaS[2][0][2] = la.VecDot(Ξ02, o.CntG2)
o.GammaS[2][1][2] = la.VecDot(Ξ12, o.CntG2)
o.GammaS[2][1][0] = o.GammaS[2][0][1]
o.GammaS[2][2][0] = o.GammaS[2][0][2]
o.GammaS[2][2][1] = o.GammaS[2][1][2]
// L-coefficients
o.L = make([]float64, 3)
o.L[0] = o.GammaS[0][0][0]*o.CntGmat.Get(0, 0) + o.GammaS[0][1][1]*o.CntGmat.Get(1, 1) + o.GammaS[0][2][2]*o.CntGmat.Get(2, 2) + 2.0*o.GammaS[0][0][1]*o.CntGmat.Get(0, 1) + 2.0*o.GammaS[0][0][2]*o.CntGmat.Get(0, 2) + 2.0*o.GammaS[0][1][2]*o.CntGmat.Get(1, 2)
o.L[1] = o.GammaS[1][0][0]*o.CntGmat.Get(0, 0) + o.GammaS[1][1][1]*o.CntGmat.Get(1, 1) + o.GammaS[1][2][2]*o.CntGmat.Get(2, 2) + 2.0*o.GammaS[1][0][1]*o.CntGmat.Get(0, 1) + 2.0*o.GammaS[1][0][2]*o.CntGmat.Get(0, 2) + 2.0*o.GammaS[1][1][2]*o.CntGmat.Get(1, 2)
o.L[2] = o.GammaS[2][0][0]*o.CntGmat.Get(0, 0) + o.GammaS[2][1][1]*o.CntGmat.Get(1, 1) + o.GammaS[2][2][2]*o.CntGmat.Get(2, 2) + 2.0*o.GammaS[2][0][1]*o.CntGmat.Get(0, 1) + 2.0*o.GammaS[2][0][2]*o.CntGmat.Get(0, 2) + 2.0*o.GammaS[2][1][2]*o.CntGmat.Get(1, 2)
return
} | gm/metrics.go | 0.506103 | 0.543772 | metrics.go | starcoder |
package floats
import (
"github.com/chewxy/math32"
)
// MatZero fills zeros in a matrix of 32-bit floats.
func MatZero(x [][]float32) {
for i := range x {
for j := range x[i] {
x[i][j] = 0
}
}
}
// Zero fills zeros in a slice of 32-bit floats.
func Zero(a []float32) {
for i := range a {
a[i] = 0
}
}
// SubTo subtracts one vector by another and saves the result in dst: dst = a - b
func SubTo(a, b, dst []float32) {
if len(dst) != len(b) || len(a) != len(b) {
panic("floats: slice lengths do not match")
}
for i := range dst {
dst[i] = a[i] - b[i]
}
}
// Add two vectors: dst = dst + s
func Add(dst, s []float32) {
if len(dst) != len(s) {
panic("floats: slice lengths do not match")
}
for i := range dst {
dst[i] += s[i]
}
}
// MulConst multiplies a vector with a const: dst = dst * c
func MulConst(dst []float32, c float32) {
for i := range dst {
dst[i] *= c
}
}
// Div one vectors by another: dst = dst / s
func Div(dst, s []float32) {
if len(dst) != len(s) {
panic("floats: slice lengths do not match")
}
for i := range dst {
dst[i] /= s[i]
}
}
// Mul two vectors: dst = dst * s
func Mul(dst, s []float32) {
if len(dst) != len(s) {
panic("floats: slice lengths do not match")
}
for i := range dst {
dst[i] *= s[i]
}
}
// Sub one vector by another: dst = dst - s
func Sub(dst, s []float32) {
if len(dst) != len(s) {
panic("floats: slice lengths do not match")
}
for i := range dst {
dst[i] -= s[i]
}
}
// MulConstTo multiplies a vector and a const, then saves the result in dst: dst = a * c
func MulConstTo(a []float32, c float32, dst []float32) {
if len(a) != len(dst) {
panic("floats: slice lengths do not match")
}
for i := range a {
dst[i] = a[i] * c
}
}
// MulConstAddTo multiplies a vector and a const, then adds to dst: dst = dst + a * c
func MulConstAddTo(a []float32, c float32, dst []float32) {
if len(a) != len(dst) {
panic("floats: slice lengths do not match")
}
for i := range a {
dst[i] += a[i] * c
}
}
// MulAddTo multiplies a vector and a vector, then adds to a vector: c += a * b
func MulAddTo(a, b, c []float32) {
if len(a) != len(b) || len(a) != len(c) {
panic("floats: slice lengths do not match")
}
for i := range a {
c[i] += a[i] * b[i]
}
}
// AddTo adds two vectors and saves the result in dst: dst = a + b
func AddTo(a, b, dst []float32) {
if len(a) != len(b) || len(a) != len(dst) {
panic("floats: slice lengths do not match")
}
for i := range a {
dst[i] = a[i] + b[i]
}
}
// Dot two vectors.
func Dot(a, b []float32) (ret float32) {
if len(a) != len(b) {
panic("floats: slice lengths do not match")
}
for i := range a {
ret += a[i] * b[i]
}
return
}
// Min element of a slice of 32-bit floats.
func Min(x []float32) float32 {
if len(x) == 0 {
panic("floats: zero slice length")
}
min := x[0]
for _, v := range x[1:] {
if v < min {
min = v
}
}
return min
}
// Max element of a slice of 32-bit floats.
func Max(x []float32) float32 {
if len(x) == 0 {
panic("floats: zero slice length")
}
max := x[0]
for _, v := range x[1:] {
if v > max {
max = v
}
}
return max
}
// Sum of a slice of 32-bit floats.
func Sum(x []float32) float32 {
sum := float32(0)
for _, v := range x {
sum += v
}
return sum
}
// Mean of a slice of 32-bit floats.
func Mean(x []float32) float32 {
return Sum(x) / float32(len(x))
}
// StdDev returns the sample standard deviation.
func StdDev(x []float32) float32 {
_, variance := MeanVariance(x)
return math32.Sqrt(variance)
}
// MeanVariance computes the sample mean and unbiased variance, where the mean and variance are
// \sum_i w_i * x_i / (sum_i w_i)
// \sum_i w_i (x_i - mean)^2 / (sum_i w_i - 1)
// respectively.
// If weights is nil then all of the weights are 1. If weights is not nil, then
// len(x) must equal len(weights).
// When weights sum to 1 or less, a biased variance estimator should be used.
func MeanVariance(x []float32) (mean, variance float32) {
// This uses the corrected two-pass algorithm (1.7), from "Algorithms for computing
// the sample variance: Analysis and recommendations" by Chan, <NAME>., <NAME>,
// and <NAME>.
// note that this will panic if the slice lengths do not match
mean = Mean(x)
var (
ss float32
compensation float32
)
for _, v := range x {
d := v - mean
ss += d * d
compensation += d
}
variance = (ss - compensation*compensation/float32(len(x))) / float32(len(x)-1)
return
} | floats/floats.go | 0.775477 | 0.518241 | floats.go | starcoder |
package bin
import (
"encoding/binary"
"io"
"reflect"
"strconv"
"strings"
)
type tag string
func (t tag) nonEmpty() bool {
return len(t) > 0
}
type tags reflect.StructTag
func (t tags) hex() tag {
return tag(reflect.StructTag(t).Get("hex"))
}
func (t tags) cond() tag {
return tag(reflect.StructTag(t).Get("cond"))
}
func (t tags) endianness() tag {
return tag(reflect.StructTag(t).Get("endianness"))
}
func (t tags) size() tag {
return tag(reflect.StructTag(t).Get("size"))
}
func (t tags) bitmask() tag {
return tag(reflect.StructTag(t).Get("bitmask"))
}
func (t tags) bits() tag {
return tag(reflect.StructTag(t).Get("bits"))
}
func (t tags) bound() tag {
return tag(reflect.StructTag(t).Get("bound"))
}
func (t tags) transient() tag {
return tag(reflect.StructTag(t).Get("transient"))
}
func bitmaskBits(value tag) (bitmaskBits uint64) {
prefix := string(value[:2])
bitmask := string(value[2:])
if prefix == "0x" {
bitmaskBits, _ = strconv.ParseUint(bitmask, 16, len(bitmask)*4)
return
} else if prefix == "0b" {
bitmaskBits, _ = strconv.ParseUint(bitmask, 2, len(bitmask))
return
}
panic("Unsupported prefix: " + prefix)
}
func order(endianness tag) binary.ByteOrder {
if endianness == "be" {
return binary.BigEndian
}
return binary.LittleEndian
}
func checkConditions(cond tag, parent reflect.Value) bool {
if cond.nonEmpty() {
conditions := strings.Split(string(cond), ";")
for _, c := range conditions {
if !checkCondition(c, parent) {
return false
}
}
}
return true
}
func checkCondition(cond string, parent reflect.Value) bool {
v := strings.Split(cond, ":")
t := v[0]
c := v[1]
var op string
switch {
case strings.Contains(c, "=="):
op = "=="
case strings.Contains(c, "!="):
op = "!="
}
v = strings.Split(c, op)
l := v[0]
r := v[1]
getField := func() reflect.Value {
v := parent
pathElements := strings.Split(l, ".")
for _, e := range pathElements {
v = unpoint(v.FieldByName(e))
}
return v
}
switch t {
case "uint":
lv := uint64(getField().Uint())
n, _ := strconv.Atoi(r)
rv := uint64(n)
switch op {
case "==":
return lv == rv
case "!=":
return lv != rv
}
default:
panic("Unknown condition type: " + t)
}
return true
}
func unpoint(p reflect.Value) reflect.Value {
if p.Kind() == reflect.Ptr {
return unpoint(p.Elem())
} else {
return p
}
}
type Serializable interface {
Serialize(w io.Writer)
Deserialize(r io.Reader)
}
var serializable = reflect.TypeOf((*Serializable)(nil)).Elem() | bin.go | 0.539954 | 0.45175 | bin.go | starcoder |
package LeetCode
type MyCircularDeque struct {
f, r *node
len, cap int
}
type node struct {
value int
pre, next *node
}
/** Initialize your data structure here. Set the size of the deque to be k. */
func Constructor(k int) MyCircularDeque {
return MyCircularDeque{cap: k}
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
func (this *MyCircularDeque) InsertFront(value int) bool {
if this.len == this.cap {
return false
}
n := &node{value: value}
if this.len == 0 {
this.f = n
this.r = n
} else {
n.next = this.f
this.f.pre = n
this.f = n
}
this.len++
return true
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
func (this *MyCircularDeque) InsertLast(value int) bool {
if this.len == this.cap {
return false
}
n := &node{value: value}
if this.len == 0 {
this.f = n
this.r = n
} else {
n.pre = this.r
this.r.next = n
this.r = n
}
this.len++
return true
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
func (this *MyCircularDeque) DeleteFront() bool {
if this.len == 0 {
return false
}
if this.len == 1 {
this.f, this.r = nil, nil
} else {
this.f = this.f.next
this.f.pre = nil
}
this.len--
return true
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
func (this *MyCircularDeque) DeleteLast() bool {
if this.len == 0 {
return false
}
if this.len == 1 {
this.f, this.r = nil, nil
} else {
this.r = this.r.pre
this.r.next = nil
}
this.len--
return true
}
/** Get the front item from the deque. */
func (this *MyCircularDeque) GetFront() int {
if this.len == 0 {
return -1
}
return this.f.value
}
/** Get the last item from the deque. */
func (this *MyCircularDeque) GetRear() int {
if this.len == 0 {
return -1
}
return this.r.value
}
/** Checks whether the circular deque is empty or not. */
func (this *MyCircularDeque) IsEmpty() bool {
return this.len == 0
}
/** Checks whether the circular deque is full or not. */
func (this *MyCircularDeque) IsFull() bool {
return this.len == this.cap
}
/**
* Your MyCircularDeque object will be instantiated and called as such:
* obj := Constructor(k);
* param_1 := obj.InsertFront(value);
* param_2 := obj.InsertLast(value);
* param_3 := obj.DeleteFront();
* param_4 := obj.DeleteLast();
* param_5 := obj.GetFront();
* param_6 := obj.GetRear();
* param_7 := obj.IsEmpty();
* param_8 := obj.IsFull();
*/ | 06.algorithm004-02/week01/04homework/Leetcode_641_052.go | 0.685739 | 0.478651 | Leetcode_641_052.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.