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 main
import (
"github.com/gen2brain/raylib-go/physics"
"github.com/gen2brain/raylib-go/raylib"
)
func main() {
screenWidth := int32(800)
screenHeight := int32(450)
raylib.SetConfigFlags(raylib.FlagMsaa4xHint)
raylib.InitWindow(screenWidth, screenHeight, "Physac [raylib] - physics friction")
// Physac logo drawing position
logoX := screenWidth - raylib.MeasureText("Physac", 30) - 10
logoY := int32(15)
// Initialize physics and default physics bodies
physics.Init()
// Create floor rectangle physics body
floor := physics.NewBodyRectangle(raylib.NewVector2(float32(screenWidth)/2, float32(screenHeight)), float32(screenHeight), 100, 10)
floor.Enabled = false // Disable body state to convert it to static (no dynamics, but collisions)
wall := physics.NewBodyRectangle(raylib.NewVector2(float32(screenWidth)/2, float32(screenHeight)*0.8), 10, 80, 10)
wall.Enabled = false // Disable body state to convert it to static (no dynamics, but collisions)
// Create left ramp physics body
rectLeft := physics.NewBodyRectangle(raylib.NewVector2(25, float32(screenHeight)-5), 250, 250, 10)
rectLeft.Enabled = false // Disable body state to convert it to static (no dynamics, but collisions)
rectLeft.SetRotation(30 * raylib.Deg2rad)
// Create right ramp physics body
rectRight := physics.NewBodyRectangle(raylib.NewVector2(float32(screenWidth)-25, float32(screenHeight)-5), 250, 250, 10)
rectRight.Enabled = false // Disable body state to convert it to static (no dynamics, but collisions)
rectRight.SetRotation(330 * raylib.Deg2rad)
// Create dynamic physics bodies
bodyA := physics.NewBodyRectangle(raylib.NewVector2(35, float32(screenHeight)*0.6), 40, 40, 10)
bodyA.StaticFriction = 0.1
bodyA.DynamicFriction = 0.1
bodyA.SetRotation(30 * raylib.Deg2rad)
bodyB := physics.NewBodyRectangle(raylib.NewVector2(float32(screenWidth)-35, float32(screenHeight)*0.6), 40, 40, 10)
bodyB.StaticFriction = 1
bodyB.DynamicFriction = 1
bodyB.SetRotation(330 * raylib.Deg2rad)
raylib.SetTargetFPS(60)
for !raylib.WindowShouldClose() {
// Physics steps calculations
physics.Update()
if raylib.IsKeyPressed(raylib.KeyR) { // Reset physics input
// Reset dynamic physics bodies position, velocity and rotation
bodyA.Position = raylib.NewVector2(35, float32(screenHeight)*0.6)
bodyA.Velocity = raylib.NewVector2(0, 0)
bodyA.AngularVelocity = 0
bodyA.SetRotation(30 * raylib.Deg2rad)
bodyB.Position = raylib.NewVector2(float32(screenWidth)-35, float32(screenHeight)*0.6)
bodyB.Velocity = raylib.NewVector2(0, 0)
bodyB.AngularVelocity = 0
bodyB.SetRotation(330 * raylib.Deg2rad)
}
raylib.BeginDrawing()
raylib.ClearBackground(raylib.Black)
raylib.DrawFPS(screenWidth-90, screenHeight-30)
// Draw created physics bodies
bodiesCount := physics.GetBodiesCount()
for i := 0; i < bodiesCount; i++ {
body := physics.GetBody(i)
vertexCount := physics.GetShapeVerticesCount(i)
for j := 0; j < vertexCount; j++ {
// Get physics bodies shape vertices to draw lines
// NOTE: GetShapeVertex() already calculates rotation transformations
vertexA := body.GetShapeVertex(j)
jj := 0
if j+1 < vertexCount { // Get next vertex or first to close the shape
jj = j + 1
}
vertexB := body.GetShapeVertex(jj)
raylib.DrawLineV(vertexA, vertexB, raylib.Green) // Draw a line between two vertex positions
}
}
raylib.DrawRectangle(0, screenHeight-49, screenWidth, 49, raylib.Black)
raylib.DrawText("Friction amount", (screenWidth-raylib.MeasureText("Friction amount", 30))/2, 75, 30, raylib.White)
raylib.DrawText("0.1", int32(bodyA.Position.X)-raylib.MeasureText("0.1", 20)/2, int32(bodyA.Position.Y)-7, 20, raylib.White)
raylib.DrawText("1", int32(bodyB.Position.X)-raylib.MeasureText("1", 20)/2, int32(bodyB.Position.Y)-7, 20, raylib.White)
raylib.DrawText("Press 'R' to reset example", 10, 10, 10, raylib.White)
raylib.DrawText("Physac", logoX, logoY, 30, raylib.White)
raylib.DrawText("Powered by", logoX+50, logoY-7, 10, raylib.White)
raylib.EndDrawing()
}
physics.Close() // Unitialize physics
raylib.CloseWindow()
} | examples/physics/physac/friction/main.go | 0.684159 | 0.535281 | main.go | starcoder |
package data
import (
"encoding/binary"
"fmt"
"math"
"reflect"
"time"
"github.com/zeroshade/go-drill/internal/rpc/proto/exec/shared"
)
type TimestampVector struct {
*Int64Vector
}
func (TimestampVector) Type() reflect.Type {
return reflect.TypeOf(time.Time{})
}
func NewTimestampVector(data []byte, meta *shared.SerializedField) *TimestampVector {
return &TimestampVector{
NewInt64Vector(data, meta),
}
}
func (v *TimestampVector) Get(index uint) time.Time {
ts := v.Int64Vector.Get(index)
return time.Unix(ts/1000, ts%1000)
}
func (v *TimestampVector) Value(index uint) interface{} {
return v.Get(index)
}
type DateVector struct {
*TimestampVector
}
func (dv *DateVector) Get(index uint) time.Time {
return dv.TimestampVector.Get(index).UTC()
}
func (dv *DateVector) Value(index uint) interface{} {
return dv.Get(index)
}
func NewDateVector(data []byte, meta *shared.SerializedField) *DateVector {
return &DateVector{NewTimestampVector(data, meta)}
}
type TimeVector struct {
*Int32Vector
}
func (TimeVector) Type() reflect.Type {
return reflect.TypeOf(time.Time{})
}
func (t *TimeVector) Get(index uint) time.Time {
ts := t.Int32Vector.Get(index)
h, m, s := time.Unix(int64(ts/1000), int64(ts%1000)).UTC().Clock()
return time.Date(0, 1, 1, h, m, s, 0, time.UTC)
}
func (t *TimeVector) Value(index uint) interface{} {
return t.Get(index)
}
func NewTimeVector(date []byte, meta *shared.SerializedField) *TimeVector {
return &TimeVector{NewInt32Vector(date, meta)}
}
type NullableTimestampVector struct {
*NullableInt64Vector
}
func (NullableTimestampVector) Type() reflect.Type {
return reflect.TypeOf(time.Time{})
}
func (v *NullableTimestampVector) Get(index uint) *time.Time {
ts := v.NullableInt64Vector.Get(index)
if ts == nil {
return nil
}
ret := time.Unix(*ts/1000, *ts%1000)
return &ret
}
func (v *NullableTimestampVector) Value(index uint) interface{} {
val := v.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableTimestampVector(data []byte, meta *shared.SerializedField) *NullableTimestampVector {
return &NullableTimestampVector{
NewNullableInt64Vector(data, meta),
}
}
type NullableDateVector struct {
*NullableTimestampVector
}
func (nv *NullableDateVector) Get(index uint) *time.Time {
ret := nv.NullableTimestampVector.Get(index)
if ret != nil {
*ret = ret.UTC()
}
return ret
}
func (nv *NullableDateVector) Value(index uint) interface{} {
ret := nv.Get(index)
if ret != nil {
return *ret
}
return nil
}
func NewNullableDateVector(data []byte, meta *shared.SerializedField) *NullableDateVector {
return &NullableDateVector{NewNullableTimestampVector(data, meta)}
}
type NullableTimeVector struct {
*NullableInt32Vector
}
func (NullableTimeVector) Type() reflect.Type {
return reflect.TypeOf(time.Time{})
}
func (v *NullableTimeVector) Get(index uint) *time.Time {
ts := v.NullableInt32Vector.Get(index)
if ts == nil {
return nil
}
h, m, s := time.Unix(int64(*ts/1000), int64(*ts%1000)).UTC().Clock()
ret := time.Date(0, 1, 1, h, m, s, 0, time.UTC)
return &ret
}
func (v *NullableTimeVector) Value(index uint) interface{} {
val := v.Get(index)
if val != nil {
return *val
}
return val
}
func NewNullableTimeVector(data []byte, meta *shared.SerializedField) *NullableTimeVector {
return &NullableTimeVector{NewNullableInt32Vector(data, meta)}
}
type intervalBase interface {
Type() reflect.Type
TypeLen() (int64, bool)
Len() int
GetRawBytes() []byte
getval(index int) []byte
}
type fixedWidthVec struct {
data []byte
valsz int
meta *shared.SerializedField
}
func (fixedWidthVec) Type() reflect.Type {
return reflect.TypeOf(string(""))
}
func (fixedWidthVec) TypeLen() (int64, bool) {
return 0, false
}
func (v *fixedWidthVec) GetRawBytes() []byte {
return v.data
}
func (v *fixedWidthVec) Len() int {
return int(v.meta.GetValueCount())
}
func (v *fixedWidthVec) getval(index int) []byte {
start := index * v.valsz
return v.data[start : start+v.valsz]
}
type nullableIntervalBase interface {
intervalBase
IsNull(index uint) bool
GetNullBytemap() []byte
}
type nullableFixedWidthVec struct {
*fixedWidthVec
nullByteMap
}
func (nv *nullableFixedWidthVec) GetNullBytemap() []byte {
return nv.byteMap
}
func (nv *nullableFixedWidthVec) getval(index int) []byte {
if nv.IsNull(uint(index)) {
return nil
}
return nv.fixedWidthVec.getval(index)
}
func newNullableFixedWidth(data []byte, meta *shared.SerializedField, valsz int) *nullableFixedWidthVec {
byteMap := data[:meta.GetValueCount()]
remaining := data[meta.GetValueCount():]
return &nullableFixedWidthVec{
&fixedWidthVec{remaining, valsz, meta},
nullByteMap{byteMap},
}
}
type intervalVector struct {
intervalBase
process func([]byte) string
}
func (iv *intervalVector) Get(index uint) string {
return iv.process(iv.getval(int(index)))
}
func (iv *intervalVector) Value(index uint) interface{} {
return iv.Get(index)
}
type nullableIntervalVector struct {
nullableIntervalBase
process func([]byte) string
}
func (iv *nullableIntervalVector) Get(index uint) *string {
data := iv.getval(int(index))
if data == nil {
return nil
}
ret := iv.process(data)
return &ret
}
func (iv *nullableIntervalVector) Value(index uint) interface{} {
val := iv.Get(index)
if val != nil {
return *val
}
return val
}
func processYear(val []byte) string {
m := int32(binary.LittleEndian.Uint32(val))
var prefix string
if m < 0 {
m = -m
prefix = "-"
}
years := m / 12
months := m % 12
return fmt.Sprintf("%s%d-%d", prefix, years, months)
}
const daysToMillis = 24 * 60 * 60 * 1000
func processDay(val []byte) string {
days := int32(binary.LittleEndian.Uint32(val))
millis := int32(binary.LittleEndian.Uint32(val[4:]))
isneg := (days < 0) || (days == 0 && millis < 0)
if days < 0 {
days = -days
}
if millis < 0 {
millis = -millis
}
days += millis / daysToMillis
millis = millis % daysToMillis
dur := time.Duration(millis) * time.Millisecond
var prefix string
if isneg {
prefix = "-"
}
return fmt.Sprintf("%s%d days %s", prefix, days, dur.String())
}
func processInterval(val []byte) string {
m := int32(binary.LittleEndian.Uint32(val))
days := int32(binary.LittleEndian.Uint32(val[4:]))
millis := int32(binary.LittleEndian.Uint32(val[8:]))
isneg := (m < 0) || (m == 0 && days < 0) || (m == 0 && days == 0 && millis < 0)
m = int32(math.Abs(float64(m)))
days = int32(math.Abs(float64(days)))
millis = int32(math.Abs(float64(millis)))
years := m / 12
months := m % 12
days += millis / daysToMillis
millis = millis % daysToMillis
dur := time.Duration(millis) * time.Millisecond
var prefix string
if isneg {
prefix = "-"
}
return fmt.Sprintf("%s%d-%d-%d %s", prefix, years, months, days, dur.String())
}
func NewIntervalYearVector(data []byte, meta *shared.SerializedField) *intervalVector {
return &intervalVector{
intervalBase: &fixedWidthVec{data, 4, meta},
process: processYear,
}
}
func NewNullableIntervalYearVector(data []byte, meta *shared.SerializedField) *nullableIntervalVector {
return &nullableIntervalVector{
newNullableFixedWidth(data, meta, 4),
processYear,
}
}
func NewIntervalDayVector(data []byte, meta *shared.SerializedField) *intervalVector {
return &intervalVector{
intervalBase: &fixedWidthVec{data, 8, meta},
process: processDay,
}
}
func NewNullableIntervalDayVector(data []byte, meta *shared.SerializedField) *nullableIntervalVector {
return &nullableIntervalVector{
newNullableFixedWidth(data, meta, 8),
processDay,
}
}
func NewIntervalVector(data []byte, meta *shared.SerializedField) *intervalVector {
return &intervalVector{
intervalBase: &fixedWidthVec{data, 12, meta},
process: processInterval,
}
}
func NewNullableIntervalVector(data []byte, meta *shared.SerializedField) *nullableIntervalVector {
return &nullableIntervalVector{
newNullableFixedWidth(data, meta, 12),
processInterval,
}
} | internal/data/date_time_vectors.go | 0.679179 | 0.706316 | date_time_vectors.go | starcoder |
package physics
import (
"errors"
"github.com/strangedev/vroom/algebra"
"github.com/strangedev/vroom/gfx"
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
"github.com/faiface/pixel/imdraw"
)
const (
splitThreshold = 2
minBoxWidth = 5
maxItems = 1000
)
type QuadKey struct {
Pnt interface{}
Bounds algebra.Rectangle
}
type QuadNode struct {
bounds algebra.Rectangle
keys []*QuadKey
Children []*QuadNode
}
type QuadTree interface {
insert(k *QuadKey)
InsertAt(pnt interface{}, bounds algebra.Rectangle) *QuadKey
Remove(k *QuadKey) error
ClippingCandidates(k *QuadKey) <-chan *QuadKey
ClippingCandidatesAt(bounds algebra.Rectangle) <-chan *QuadKey
gfx.Drawable
}
func NewQuadTree(width, height float64) QuadTree {
root := newQuadNode(
algebra.Rectangle{
Ul: algebra.Vector2{0, height},
Ur: algebra.Vector2{width, height},
Dl: algebra.Vector2{0, 0},
Dr: algebra.Vector2{width, 0},
},
)
return &root
}
func newQuadNode(bounds algebra.Rectangle) QuadNode {
return QuadNode{
bounds,
make([]*QuadKey, 0, splitThreshold),
make([]*QuadNode, 0, 4),
}
}
func (n *QuadNode) isLeaf() bool {
return len(n.Children) == 0
}
func (k *QuadKey) pickNode(ul, ur, dl, dr *QuadNode) (n *QuadNode, e error) {
clipCount := 0
if ul.bounds.Clips(k.Bounds) && clipCount <= 1 {
n = ul
clipCount++
}
if ur.bounds.Clips(k.Bounds) && clipCount <= 1 {
n = ur
clipCount++
}
if dl.bounds.Clips(k.Bounds) && clipCount <= 1 {
n = dl
clipCount++
}
if dr.bounds.Clips(k.Bounds) && clipCount <= 1 {
n = dr
clipCount++
}
if clipCount == 0 {
panic("Key did not clip any quadrant! If this happens, beat up the programmer ... gosh that's me")
} else if clipCount > 1 {
e = errors.New("More than one candidate")
}
return
}
func (n *QuadNode) split() {
width := 0.5 * (n.bounds.Ur[0] - n.bounds.Ul[0])
height := 0.5 * (n.bounds.Ul[1] - n.bounds.Dl[1])
boundsUl := algebra.Rectangle{
Ul: n.bounds.Ul,
Ur: algebra.Vector2{n.bounds.Ul[0] + width, n.bounds.Ul[1]},
Dl: algebra.Vector2{n.bounds.Ul[0], n.bounds.Ul[1] - height},
Dr: algebra.Vector2{n.bounds.Ul[0] + width, n.bounds.Ul[1] - height},
}
boundsUr := algebra.Rectangle{
Ul: boundsUl.Ur,
Ur: n.bounds.Ur,
Dl: boundsUl.Dr,
Dr: algebra.Vector2{n.bounds.Ur[0], n.bounds.Ur[1] - height},
}
boundsDl := algebra.Rectangle{
Ul: boundsUl.Dl,
Ur: boundsUl.Dr,
Dl: n.bounds.Dl,
Dr: algebra.Vector2{n.bounds.Dl[0] + width, n.bounds.Dl[1]},
}
boundsDr := algebra.Rectangle{
Ul: boundsUl.Dr,
Ur: boundsUr.Dr,
Dl: boundsDl.Dr,
Dr: n.bounds.Dr,
}
childUl := newQuadNode(boundsUl)
childUr := newQuadNode(boundsUr)
childDl := newQuadNode(boundsDl)
childDr := newQuadNode(boundsDr)
parentKeys := make([]*QuadKey, 0, len(n.keys))
for _, key := range n.keys {
node, err := key.pickNode(&childUl, &childUr, &childDl, &childDr)
if err != nil {
parentKeys = append(parentKeys, key)
} else {
node.keys = append(node.keys, key)
}
}
if len(parentKeys) != len(n.keys) {
n.keys = parentKeys
n.Children = []*QuadNode{&childUl, &childUr, &childDl, &childDr}
}
// otherwise, no keys could be placed in children
// do not modify QuadNode n and let the new nodes
// be garbage collected
}
func (root *QuadNode) insert(k *QuadKey) {
current := root
for !current.isLeaf() {
node, err := k.pickNode(
current.Children[0],
current.Children[1],
current.Children[2],
current.Children[3],
)
if err != nil {
current.keys = append(current.keys, k)
return
}
current = node
}
current.keys = append(current.keys, k)
boxWidth, _ := current.bounds.Size()
if boxWidth >= minBoxWidth && len(current.keys) > splitThreshold {
current.split()
}
}
func (root *QuadNode) InsertAt(pnt interface{}, bounds algebra.Rectangle) (k *QuadKey) {
k = &QuadKey{pnt, bounds}
root.insert(k)
return
}
func (root *QuadNode) Remove(k *QuadKey) error {
return nil
}
func (root *QuadNode) Draw(win *pixelgl.Window) {
imd := imdraw.New(nil)
imd.Color = pixel.RGB(1, 0, 0)
queue := make(chan *QuadNode, 100)
queue <- root
for node := range queue{
for _, child := range node.Children {
queue <- child
}
if len(queue) == 0 {
close(queue)
}
imd.Push(
node.bounds.Ul.ToPixelVec(),
node.bounds.Ur.ToPixelVec(),
)
imd.Line(2)
imd.Push(
node.bounds.Ul.ToPixelVec(),
node.bounds.Dl.ToPixelVec(),
)
imd.Line(2)
imd.Push(
node.bounds.Ur.ToPixelVec(),
node.bounds.Dr.ToPixelVec(),
)
imd.Line(2)
imd.Push(
node.bounds.Dl.ToPixelVec(),
node.bounds.Dr.ToPixelVec(),
)
imd.Line(2)
}
imd.Draw(win)
}
func (root *QuadNode) ClippingCandidates(k *QuadKey) <-chan *QuadKey {
ch := root.ClippingCandidatesAt((*k).Bounds)
candidates := make(chan *QuadKey, maxItems)
go func () {
for c := range ch {
if c.Pnt != k.Pnt {
candidates <- c
}
}
close(candidates)
}()
return candidates
}
func (root *QuadNode) ClippingCandidatesAt(bounds algebra.Rectangle) <-chan *QuadKey {
candidates := make(chan *QuadKey)
go func() {
queue := make(chan *QuadNode, maxItems)
queue <- root
for node := range queue{
for _, key := range node.keys {
if key.Bounds.Clips(bounds) {
candidates <- key
}
}
for _, child := range node.Children {
if child.bounds.Clips(bounds) {
queue <- child
}
}
if len(queue) == 0 {
close(queue)
}
}
close(candidates)
}()
return candidates
} | physics/quadtree.go | 0.627495 | 0.453867 | quadtree.go | starcoder |
package storage
import (
"github.com/janelia-flyem/dvid/dvid"
)
// GraphSetter defines operations that modify a graph
type GraphSetter interface {
// CreateGraph creates a graph with the given context.
CreateGraph(ctx Context) error
// AddVertex inserts an id of a given weight into the graph
AddVertex(ctx Context, id dvid.VertexID, weight float64) error
// AddEdge adds an edge between vertex id1 and id2 with the provided weight
AddEdge(ctx Context, id1 dvid.VertexID, id2 dvid.VertexID, weight float64) error
// SetVertexWeight modifies the weight of vertex id
SetVertexWeight(ctx Context, id dvid.VertexID, weight float64) error
// SetEdgeWeight modifies the weight of the edge defined by id1 and id2
SetEdgeWeight(ctx Context, id1 dvid.VertexID, id2 dvid.VertexID, weight float64) error
// SetVertexProperty adds arbitrary data to a vertex using a string key
SetVertexProperty(ctx Context, id dvid.VertexID, key string, value []byte) error
// SetEdgeProperty adds arbitrary data to an edge using a string key
SetEdgeProperty(ctx Context, id1 dvid.VertexID, id2 dvid.VertexID, key string, value []byte) error
// RemoveVertex removes the vertex and its properties and edges
RemoveVertex(ctx Context, id dvid.VertexID) error
// RemoveEdge removes the edge defined by id1 and id2 and its properties
RemoveEdge(ctx Context, id1 dvid.VertexID, id2 dvid.VertexID) error
// RemoveGraph removes the entire graph including all vertices, edges, and properties
RemoveGraph(ctx Context) error
// RemoveVertexProperty removes the property data for vertex id at the key
RemoveVertexProperty(ctx Context, id dvid.VertexID, key string) error
// RemoveEdgeProperty removes the property data for edge at the key
RemoveEdgeProperty(ctx Context, id1 dvid.VertexID, id2 dvid.VertexID, key string) error
}
// GraphGetter defines operations that retrieve information from a graph
type GraphGetter interface {
// GetVertices retrieves a list of all vertices in the graph
GetVertices(ctx Context) ([]dvid.GraphVertex, error)
// GetEdges retrieves a list of all edges in the graph
GetEdges(ctx Context) ([]dvid.GraphEdge, error)
// GetVertex retrieves a vertex given a vertex id
GetVertex(ctx Context, id dvid.VertexID) (dvid.GraphVertex, error)
// GetVertex retrieves an edges between two vertex IDs
GetEdge(ctx Context, id1 dvid.VertexID, id2 dvid.VertexID) (dvid.GraphEdge, error)
// GetVertexProperty retrieves a property as a byte array given a vertex id
GetVertexProperty(ctx Context, id dvid.VertexID, key string) ([]byte, error)
// GetEdgeProperty retrieves a property as a byte array given an edge defined by id1 and id2
GetEdgeProperty(ctx Context, id1 dvid.VertexID, id2 dvid.VertexID, key string) ([]byte, error)
}
// GraphDB defines the entire interface that a graph database should support
type GraphDB interface {
GraphSetter
GraphGetter
Close()
} | storage/graphdb.go | 0.626581 | 0.660946 | graphdb.go | starcoder |
package blockchain
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
"log"
"math"
"math/big"
)
// take the data from the block
// create a counter (nonce) which starts at 0
// create a hash of the data plus the counter
// check the hash to see if it meets a set of requirements. These requirements represent the difficulty
// of the proof of work. If the hash meets the requirements then we use it to sign the block otherwise we go back
// generate another hash and repeat the process
// Requirements:
// the first few bytes must contain 0s
// generally speaking with a real blockchain the difficulty would increase over a large period of time. You want to do this
// to account for the:
// - increase in miners
// - increase in computational power
// Generally:
// we want the time to mine a block stay the same
// we want the block rate to stay the same
const Difficulty = 12
type ProofOfWork struct {
Block *Block
Target *big.Int
}
// Here we create a new big integer of 1
// we bit shift the integer to the left by 256 - 12 (244)
// resulting in 100000...
// we then create a new proof of work with the block and the target hash of 1000000000...
func NewProof(b *Block) *ProofOfWork {
target := big.NewInt(1)
target.Lsh(target, uint(256-Difficulty))
pow := &ProofOfWork{b, target}
return pow
}
func (pow *ProofOfWork) InitData(nonce int) []byte {
data := bytes.Join(
[][]byte{
pow.Block.PrevHash,
pow.Block.HashTransactions(),
ToHex(int64(nonce)),
ToHex(int64(Difficulty)),
},
[]byte{},
)
return data
}
func (pow *ProofOfWork) run() (int, []byte) {
var initHash big.Int
var hash [32]byte
nonce := 0
for nonce < math.MaxInt64 {
data := pow.InitData(nonce)
hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
initHash.SetBytes(hash[:])
if initHash.Cmp(pow.Target) == -1 {
break
} else {
nonce++
}
}
fmt.Println()
return nonce, hash[:]
}
func (pow *ProofOfWork) Validate() bool {
var intHash big.Int
data := pow.InitData(pow.Block.Nonce)
hash := sha256.Sum256(data)
intHash.SetBytes(hash[:])
return intHash.Cmp(pow.Target) == -1
}
func ToHex(num int64) []byte {
buff := new(bytes.Buffer)
err := binary.Write(buff, binary.BigEndian, num)
if err != nil {
log.Panic(err)
}
return buff.Bytes()
} | blockchain/proof.go | 0.676834 | 0.495422 | proof.go | starcoder |
package ogdate
import "time"
const (
FmtY = "2006"
FmtM = "01"
FmtD = "02"
FmtYMD = "2006-01-02"
)
func Today() Date {
return NewDate(time.Now().In(time.Local))
}
func Yesterday() Date {
return Today().DayAgo(1)
}
func Tomorrow() Date {
return Today().DayLater(1)
}
func On(y int, m time.Month, d int) Date {
return NewDate(time.Date(y, m, d, 0, 0, 0, 0, time.Local))
}
func LastDay(y int, m time.Month) Date {
return On(y, m+1, 0)
}
func Weekday(y int, m time.Month, d int) time.Weekday {
return On(y, m, d).Weekday()
}
func FirstSunday(y int, m time.Month) Date {
return NthSunday(y, m, 1)
}
func SecondSunday(y int, m time.Month) Date {
return NthSunday(y, m, 2)
}
func ThirdSunday(y int, m time.Month) Date {
return NthSunday(y, m, 3)
}
func FourthSunday(y int, m time.Month) Date {
return NthSunday(y, m, 4)
}
func NthSunday(y int, m time.Month, nth int) Date {
d := On(y, m, 1+((nth-1)*7))
switch {
case d.IsSunday():
return d
case d.IsMonday():
return d.DayLater(6)
case d.IsTuesday():
return d.DayLater(5)
case d.IsWednesday():
return d.DayLater(4)
case d.IsThursday():
return d.DayLater(3)
case d.IsFriday():
return d.DayLater(2)
case d.IsSaturday():
return d.DayLater(1)
default:
return d
}
}
func FirstMonday(y int, m time.Month) Date {
return NthMonday(y, m, 1)
}
func SecondMonday(y int, m time.Month) Date {
return NthMonday(y, m, 2)
}
func ThirdMonday(y int, m time.Month) Date {
return NthMonday(y, m, 3)
}
func FourthMonday(y int, m time.Month) Date {
return NthMonday(y, m, 4)
}
func NthMonday(y int, m time.Month, nth int) Date {
d := On(y, m, 1+((nth-1)*7))
switch {
case d.IsSunday():
return d.DayLater(1)
case d.IsMonday():
return d
case d.IsTuesday():
return d.DayLater(6)
case d.IsWednesday():
return d.DayLater(5)
case d.IsThursday():
return d.DayLater(4)
case d.IsFriday():
return d.DayLater(3)
case d.IsSaturday():
return d.DayLater(2)
default:
return d
}
}
func FirstTuesday(y int, m time.Month) Date {
return NthTuesday(y, m, 1)
}
func SecondTuesday(y int, m time.Month) Date {
return NthTuesday(y, m, 2)
}
func ThirdTuesday(y int, m time.Month) Date {
return NthTuesday(y, m, 3)
}
func FourthTuesday(y int, m time.Month) Date {
return NthTuesday(y, m, 4)
}
func NthTuesday(y int, m time.Month, nth int) Date {
d := On(y, m, 1+((nth-1)*7))
switch {
case d.IsSunday():
return d.DayLater(2)
case d.IsMonday():
return d.DayLater(1)
case d.IsTuesday():
return d
case d.IsWednesday():
return d.DayLater(6)
case d.IsThursday():
return d.DayLater(5)
case d.IsFriday():
return d.DayLater(4)
case d.IsSaturday():
return d.DayLater(3)
default:
return d
}
}
func FirstWednesday(y int, m time.Month) Date {
return NthWednesday(y, m, 1)
}
func SecondWednesday(y int, m time.Month) Date {
return NthWednesday(y, m, 2)
}
func ThirdWednesday(y int, m time.Month) Date {
return NthWednesday(y, m, 3)
}
func FourthWednesday(y int, m time.Month) Date {
return NthWednesday(y, m, 4)
}
func NthWednesday(y int, m time.Month, nth int) Date {
d := On(y, m, 1+((nth-1)*7))
switch {
case d.IsSunday():
return d.DayLater(3)
case d.IsMonday():
return d.DayLater(2)
case d.IsTuesday():
return d.DayLater(1)
case d.IsWednesday():
return d
case d.IsThursday():
return d.DayLater(6)
case d.IsFriday():
return d.DayLater(5)
case d.IsSaturday():
return d.DayLater(4)
default:
return d
}
}
func FirstThrusday(y int, m time.Month) Date {
return NthThrusday(y, m, 1)
}
func SecondThrusday(y int, m time.Month) Date {
return NthThrusday(y, m, 2)
}
func ThirdThrusday(y int, m time.Month) Date {
return NthThrusday(y, m, 3)
}
func FourthThrusday(y int, m time.Month) Date {
return NthThrusday(y, m, 4)
}
func NthThrusday(y int, m time.Month, nth int) Date {
d := On(y, m, 1+((nth-1)*7))
switch {
case d.IsSunday():
return d.DayLater(4)
case d.IsMonday():
return d.DayLater(3)
case d.IsTuesday():
return d.DayLater(2)
case d.IsWednesday():
return d.DayLater(1)
case d.IsThursday():
return d
case d.IsFriday():
return d.DayLater(6)
case d.IsSaturday():
return d.DayLater(5)
default:
return d
}
}
func FirstFriday(y int, m time.Month) Date {
return NthFriday(y, m, 1)
}
func SecondFriday(y int, m time.Month) Date {
return NthFriday(y, m, 2)
}
func ThirdFriday(y int, m time.Month) Date {
return NthFriday(y, m, 3)
}
func FourthFriday(y int, m time.Month) Date {
return NthFriday(y, m, 4)
}
func NthFriday(y int, m time.Month, nth int) Date {
d := On(y, m, 1+((nth-1)*7))
switch {
case d.IsSunday():
return d.DayLater(5)
case d.IsMonday():
return d.DayLater(4)
case d.IsTuesday():
return d.DayLater(3)
case d.IsWednesday():
return d.DayLater(2)
case d.IsThursday():
return d.DayLater(1)
case d.IsFriday():
return d
case d.IsSaturday():
return d.DayLater(6)
default:
return d
}
}
func FirstSaturday(y int, m time.Month) Date {
return NthSaturday(y, m, 1)
}
func SecondSaturday(y int, m time.Month) Date {
return NthSaturday(y, m, 2)
}
func ThirdSaturday(y int, m time.Month) Date {
return NthSaturday(y, m, 3)
}
func FourthSaturday(y int, m time.Month) Date {
return NthSaturday(y, m, 4)
}
func NthSaturday(y int, m time.Month, nth int) Date {
d := On(y, m, 1+((nth-1)*7))
switch {
case d.IsSunday():
return d.DayLater(6)
case d.IsMonday():
return d.DayLater(5)
case d.IsTuesday():
return d.DayLater(4)
case d.IsWednesday():
return d.DayLater(3)
case d.IsThursday():
return d.DayLater(2)
case d.IsFriday():
return d.DayLater(1)
case d.IsSaturday():
return d
default:
return d
}
}
func NewDate(t time.Time) Date {
return Date{t: t}
}
type Date struct {
t time.Time
}
func (d Date) String() string {
return d.t.String()
}
func (d Date) Y() int {
return d.t.Year()
}
func (d Date) M() time.Month {
return d.t.Month()
}
func (d Date) D() int {
return d.t.Day()
}
// calc
func (d Date) Eq(u Date) bool {
return d.EqY(u) && d.EqM(u) && d.EqD(u)
}
func (d Date) EqY(u Date) bool {
return d.Y() == u.Y()
}
func (d Date) EqM(u Date) bool {
return d.M() == u.M()
}
func (d Date) EqD(u Date) bool {
return d.D() == u.D()
}
func (d Date) Add(dur time.Duration) Date {
return NewDate(d.t.Add(dur))
}
func (d Date) Sub(dur time.Duration) Date {
return d.Add(dur * -1)
}
func (d Date) DayLater(n int) Date {
return d.Add(time.Hour * 24 * time.Duration(n))
}
func (d Date) WeekLater(n int) Date {
return d.DayLater(n * 7)
}
func (d Date) MonthLater(n int) Date {
return d.DayLater(n * 30)
}
func (d Date) YearLater(n int) Date {
return d.DayLater(n * 365)
}
func (d Date) DayAgo(n int) Date {
return d.Sub(time.Hour * 24 * time.Duration(n))
}
func (d Date) WeekAgo(n int) Date {
return d.DayAgo(n * 7)
}
func (d Date) MonthAgo(n int) Date {
return d.DayAgo(n * 30)
}
func (d Date) YearAgo(n int) Date {
return d.DayAgo(n * 365)
}
// Weekday
func (d Date) Weekday() time.Weekday {
return d.t.Weekday()
}
func (d Date) IsSunday() bool {
return d.t.Weekday() == time.Sunday
}
func (d Date) IsMonday() bool {
return d.t.Weekday() == time.Monday
}
func (d Date) IsFirstMonday() bool {
return d.Eq(FirstMonday(d.Y(), d.M()))
}
func (d Date) IsSecondMonday() bool {
return d.Eq(SecondMonday(d.Y(), d.M()))
}
func (d Date) IsThirdMonday() bool {
return d.Eq(ThirdMonday(d.Y(), d.M()))
}
func (d Date) IsFourthMonday() bool {
return d.Eq(FourthMonday(d.Y(), d.M()))
}
func (d Date) IsTuesday() bool {
return d.t.Weekday() == time.Tuesday
}
func (d Date) IsWednesday() bool {
return d.t.Weekday() == time.Wednesday
}
func (d Date) IsThursday() bool {
return d.t.Weekday() == time.Thursday
}
func (d Date) IsFriday() bool {
return d.t.Weekday() == time.Friday
}
func (d Date) IsSaturday() bool {
return d.t.Weekday() == time.Saturday
}
func (d Date) IsJanuary() bool {
return d.t.Month() == time.January
}
func (d Date) NextSunday() Date {
switch {
case d.IsSunday():
return d.DayLater(7)
case d.IsMonday():
return d.DayLater(6)
case d.IsTuesday():
return d.DayLater(5)
case d.IsWednesday():
return d.DayLater(4)
case d.IsThursday():
return d.DayLater(3)
case d.IsFriday():
return d.DayLater(2)
case d.IsSaturday():
return d.DayLater(1)
default:
return d
}
}
func (d Date) NextMonday() Date {
switch {
case d.IsSunday():
return d.DayLater(1)
case d.IsMonday():
return d.DayLater(7)
case d.IsTuesday():
return d.DayLater(6)
case d.IsWednesday():
return d.DayLater(5)
case d.IsThursday():
return d.DayLater(4)
case d.IsFriday():
return d.DayLater(3)
case d.IsSaturday():
return d.DayLater(2)
default:
return d
}
}
func (d Date) NextTuesday() Date {
switch {
case d.IsSunday():
return d.DayLater(2)
case d.IsMonday():
return d.DayLater(1)
case d.IsTuesday():
return d.DayLater(7)
case d.IsWednesday():
return d.DayLater(6)
case d.IsThursday():
return d.DayLater(5)
case d.IsFriday():
return d.DayLater(4)
case d.IsSaturday():
return d.DayLater(3)
default:
return d
}
}
func (d Date) NextWednesday() Date {
switch {
case d.IsSunday():
return d.DayLater(3)
case d.IsMonday():
return d.DayLater(2)
case d.IsTuesday():
return d.DayLater(1)
case d.IsWednesday():
return d.DayLater(7)
case d.IsThursday():
return d.DayLater(6)
case d.IsFriday():
return d.DayLater(5)
case d.IsSaturday():
return d.DayLater(4)
default:
return d
}
}
func (d Date) NextThursday() Date {
switch {
case d.IsSunday():
return d.DayLater(4)
case d.IsMonday():
return d.DayLater(3)
case d.IsTuesday():
return d.DayLater(2)
case d.IsWednesday():
return d.DayLater(1)
case d.IsThursday():
return d.DayLater(7)
case d.IsFriday():
return d.DayLater(6)
case d.IsSaturday():
return d.DayLater(5)
default:
return d
}
}
func (d Date) NextFriday() Date {
switch {
case d.IsSunday():
return d.DayLater(5)
case d.IsMonday():
return d.DayLater(4)
case d.IsTuesday():
return d.DayLater(3)
case d.IsWednesday():
return d.DayLater(2)
case d.IsThursday():
return d.DayLater(1)
case d.IsFriday():
return d.DayLater(7)
case d.IsSaturday():
return d.DayLater(6)
default:
return d
}
}
func (d Date) NextSaturday() Date {
switch {
case d.IsSunday():
return d.DayLater(6)
case d.IsMonday():
return d.DayLater(5)
case d.IsTuesday():
return d.DayLater(4)
case d.IsWednesday():
return d.DayLater(3)
case d.IsThursday():
return d.DayLater(2)
case d.IsFriday():
return d.DayLater(1)
case d.IsSaturday():
return d.DayLater(7)
default:
return d
}
}
func (d Date) LastSunday() Date {
switch {
case d.IsSunday():
return d.DayAgo(7)
case d.IsMonday():
return d.DayAgo(6)
case d.IsTuesday():
return d.DayAgo(5)
case d.IsWednesday():
return d.DayAgo(4)
case d.IsThursday():
return d.DayAgo(3)
case d.IsFriday():
return d.DayAgo(2)
case d.IsSaturday():
return d.DayAgo(1)
default:
return d
}
}
func (d Date) LastMonday() Date {
switch {
case d.IsSunday():
return d.DayAgo(1)
case d.IsMonday():
return d.DayAgo(7)
case d.IsTuesday():
return d.DayAgo(6)
case d.IsWednesday():
return d.DayAgo(5)
case d.IsThursday():
return d.DayAgo(4)
case d.IsFriday():
return d.DayAgo(3)
case d.IsSaturday():
return d.DayAgo(2)
default:
return d
}
}
func (d Date) LastTuesday() Date {
switch {
case d.IsSunday():
return d.DayAgo(2)
case d.IsMonday():
return d.DayAgo(1)
case d.IsTuesday():
return d.DayAgo(7)
case d.IsWednesday():
return d.DayAgo(6)
case d.IsThursday():
return d.DayAgo(5)
case d.IsFriday():
return d.DayAgo(4)
case d.IsSaturday():
return d.DayAgo(3)
default:
return d
}
}
func (d Date) LastWednesday() Date {
switch {
case d.IsSunday():
return d.DayAgo(3)
case d.IsMonday():
return d.DayAgo(2)
case d.IsTuesday():
return d.DayAgo(1)
case d.IsWednesday():
return d.DayAgo(7)
case d.IsThursday():
return d.DayAgo(6)
case d.IsFriday():
return d.DayAgo(5)
case d.IsSaturday():
return d.DayAgo(4)
default:
return d
}
}
func (d Date) LastThursday() Date {
switch {
case d.IsSunday():
return d.DayAgo(4)
case d.IsMonday():
return d.DayAgo(3)
case d.IsTuesday():
return d.DayAgo(2)
case d.IsWednesday():
return d.DayAgo(1)
case d.IsThursday():
return d.DayAgo(7)
case d.IsFriday():
return d.DayAgo(6)
case d.IsSaturday():
return d.DayAgo(5)
default:
return d
}
}
func (d Date) LastFriday() Date {
switch {
case d.IsSunday():
return d.DayAgo(5)
case d.IsMonday():
return d.DayAgo(4)
case d.IsTuesday():
return d.DayAgo(3)
case d.IsWednesday():
return d.DayAgo(2)
case d.IsThursday():
return d.DayAgo(1)
case d.IsFriday():
return d.DayAgo(7)
case d.IsSaturday():
return d.DayAgo(6)
default:
return d
}
}
func (d Date) LastSaturday() Date {
switch {
case d.IsSunday():
return d.DayAgo(6)
case d.IsMonday():
return d.DayAgo(5)
case d.IsTuesday():
return d.DayAgo(4)
case d.IsWednesday():
return d.DayAgo(3)
case d.IsThursday():
return d.DayAgo(2)
case d.IsFriday():
return d.DayAgo(1)
case d.IsSaturday():
return d.DayAgo(7)
default:
return d
}
}
// Fmt
func (d Date) FmtY() string {
return d.t.Format(FmtY)
}
func (d Date) FmtM() string {
return d.t.Format(FmtM)
}
func (d Date) FmtD() string {
return d.t.Format(FmtD)
}
func (d Date) FmtYMD() string {
return d.t.Format(FmtYMD)
} | ogdate.go | 0.574037 | 0.531331 | ogdate.go | starcoder |
package osc
import (
"encoding/json"
)
// QuotaTypes One or more quotas.
type QuotaTypes struct {
// The resource ID if it is a resource-specific quota, `global` if it is not.
QuotaType *string `json:"QuotaType,omitempty"`
// One or more quotas associated with the user.
Quotas *[]Quota `json:"Quotas,omitempty"`
}
// NewQuotaTypes instantiates a new QuotaTypes 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 NewQuotaTypes() *QuotaTypes {
this := QuotaTypes{}
return &this
}
// NewQuotaTypesWithDefaults instantiates a new QuotaTypes 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 NewQuotaTypesWithDefaults() *QuotaTypes {
this := QuotaTypes{}
return &this
}
// GetQuotaType returns the QuotaType field value if set, zero value otherwise.
func (o *QuotaTypes) GetQuotaType() string {
if o == nil || o.QuotaType == nil {
var ret string
return ret
}
return *o.QuotaType
}
// GetQuotaTypeOk returns a tuple with the QuotaType field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *QuotaTypes) GetQuotaTypeOk() (*string, bool) {
if o == nil || o.QuotaType == nil {
return nil, false
}
return o.QuotaType, true
}
// HasQuotaType returns a boolean if a field has been set.
func (o *QuotaTypes) HasQuotaType() bool {
if o != nil && o.QuotaType != nil {
return true
}
return false
}
// SetQuotaType gets a reference to the given string and assigns it to the QuotaType field.
func (o *QuotaTypes) SetQuotaType(v string) {
o.QuotaType = &v
}
// GetQuotas returns the Quotas field value if set, zero value otherwise.
func (o *QuotaTypes) GetQuotas() []Quota {
if o == nil || o.Quotas == nil {
var ret []Quota
return ret
}
return *o.Quotas
}
// GetQuotasOk returns a tuple with the Quotas field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *QuotaTypes) GetQuotasOk() (*[]Quota, bool) {
if o == nil || o.Quotas == nil {
return nil, false
}
return o.Quotas, true
}
// HasQuotas returns a boolean if a field has been set.
func (o *QuotaTypes) HasQuotas() bool {
if o != nil && o.Quotas != nil {
return true
}
return false
}
// SetQuotas gets a reference to the given []Quota and assigns it to the Quotas field.
func (o *QuotaTypes) SetQuotas(v []Quota) {
o.Quotas = &v
}
func (o QuotaTypes) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.QuotaType != nil {
toSerialize["QuotaType"] = o.QuotaType
}
if o.Quotas != nil {
toSerialize["Quotas"] = o.Quotas
}
return json.Marshal(toSerialize)
}
type NullableQuotaTypes struct {
value *QuotaTypes
isSet bool
}
func (v NullableQuotaTypes) Get() *QuotaTypes {
return v.value
}
func (v *NullableQuotaTypes) Set(val *QuotaTypes) {
v.value = val
v.isSet = true
}
func (v NullableQuotaTypes) IsSet() bool {
return v.isSet
}
func (v *NullableQuotaTypes) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableQuotaTypes(val *QuotaTypes) *NullableQuotaTypes {
return &NullableQuotaTypes{value: val, isSet: true}
}
func (v NullableQuotaTypes) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableQuotaTypes) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | v2/model_quota_types.go | 0.717111 | 0.448064 | model_quota_types.go | starcoder |
package day3
import (
"ryepup/advent2021/utils"
)
/*
--- Day 3: Binary Diagnostic ---
The submarine has been making some odd creaking noises, so you ask it to produce
a diagnostic report just in case.
The diagnostic report (your puzzle input) consists of a list of binary numbers
which, when decoded properly, can tell you many useful things about the
conditions of the submarine. The first parameter to check is the power
consumption.
You need to use the binary numbers in the diagnostic report to generate two new
binary numbers (called the gamma rate and the epsilon rate). The power
consumption can then be found by multiplying the gamma rate by the epsilon rate.
Each bit in the gamma rate can be determined by finding the most common bit in
the corresponding position of all numbers in the diagnostic report. For example,
given the following diagnostic report:
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
Considering only the first bit of each number, there are five 0 bits and seven 1
bits. Since the most common bit is 1, the first bit of the gamma rate is 1.
The most common second bit of the numbers in the diagnostic report is 0, so the
second bit of the gamma rate is 0.
The most common value of the third, fourth, and fifth bits are 1, 1, and 0,
respectively, and so the final three bits of the gamma rate are 110.
So, the gamma rate is the binary number 10110, or 22 in decimal.
The epsilon rate is calculated in a similar way; rather than use the most common
bit, the least common bit from each position is used. So, the epsilon rate is
01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9)
produces the power consumption, 198.
Use the binary numbers in your diagnostic report to calculate the gamma rate and
epsilon rate, then multiply them together. What is the power consumption of the
submarine? (Be sure to represent your answer in decimal, not binary.)
*/
func Part1(path string) (int, error) {
lines, err := utils.ReadLines(path)
if err != nil {
return 0, err
}
width := len(lines[0])
columnSums := make([]int, width)
for _, line := range lines {
for i := 0; i < width; i++ {
if line[i] == '1' {
columnSums[i]++
}
}
}
majority := len(lines) / 2
gamma := 0
epsilon := 0
for i := 0; i < width; i++ {
factor := 1 << i
if columnSums[width-i-1] > majority {
gamma += factor
} else {
epsilon += factor
}
}
return gamma * epsilon, nil
} | day3/part1.go | 0.761627 | 0.627495 | part1.go | starcoder |
package section
import (
"bytes"
"crypto/sha256"
"crypto/sha512"
"encoding/binary"
"errors"
"fmt"
"hash/fnv"
cbor "github.com/britram/borat"
log "github.com/inconshreveable/log15"
"github.com/netsec-ethz/rains/internal/pkg/algorithmTypes"
"github.com/netsec-ethz/rains/internal/pkg/datastructures/bitarray"
"github.com/spaolacci/murmur3"
)
//DataStructure contains information about a datastructure. The Type defines the object in Data.
type DataStructure struct {
Type DataStructureType
Data interface{}
}
// UnmarshalArray takes in a CBOR decoded array and populates the object.
func (d *DataStructure) UnmarshalArray(in []interface{}) error {
switch DataStructureType(in[0].(int)) {
case BloomFilterType:
bf := BloomFilter{
NofHashFunctions: int(in[2].(int)),
ModeOfOperation: ModeOfOperationType(in[3].(int)),
Filter: bitarray.BitArray(in[4].([]byte)),
}
for _, hash := range in[1].([]interface{}) {
bf.HashFamily = append(bf.HashFamily, algorithmTypes.Hash(hash.(int)))
}
d.Type = BloomFilterType
d.Data = bf
default:
return fmt.Errorf("unknown datastructure type: %v", d.Type)
}
return nil
}
// MarshalCBOR implements a CBORMarshaler.
func (d DataStructure) MarshalCBOR(w *cbor.CBORWriter) error {
var res []interface{}
switch d.Type {
case BloomFilterType:
bf := d.Data.(BloomFilter)
family := make([]int, len(bf.HashFamily))
for i, hash := range bf.HashFamily {
family[i] = int(hash)
}
res = []interface{}{BloomFilterType, family, bf.NofHashFunctions, bf.ModeOfOperation, []byte(bf.Filter)}
default:
return fmt.Errorf("unknown datastructure type: %v", d.Type)
}
return w.WriteArray(res)
}
//CompareTo compares two DS and returns 0 if they are equal, 1 if s is greater than
//dataStructure and -1 if d is smaller than dataStructure
func (d DataStructure) CompareTo(ds DataStructure) int {
if d.Type < ds.Type {
return -1
} else if d.Type > ds.Type {
return 1
}
switch d.Type {
case BloomFilterType:
return d.Data.(BloomFilter).CompareTo(ds.Data.(BloomFilter))
default:
log.Warn("Data structure type does not exist")
}
return 0
}
//DataStructureType enumerates data structure connection for pshards
type DataStructureType int
const (
BloomFilterType DataStructureType = iota + 1
)
//ModeOfOperationType enumerates mode of operation connection for pshards
type ModeOfOperationType int
const (
StandardOpType ModeOfOperationType = iota
KirschMitzenmacher1
KirschMitzenmacher2
)
//BloomFilter is a probabilistic datastructure for membership queries.
type BloomFilter struct {
HashFamily []algorithmTypes.Hash
NofHashFunctions int
ModeOfOperation ModeOfOperationType
Filter bitarray.BitArray
}
//HasAssertion returns true if a might be part of the set represented by the bloom filter. It
//returns false if a is certainly not part of the set.
func (b BloomFilter) HasAssertion(a *Assertion) (bool, error) {
switch b.ModeOfOperation {
case StandardOpType:
return b.hasAssertionStandard(a.BloomFilterEncoding())
case KirschMitzenmacher1, KirschMitzenmacher2:
return b.hasAssertionKM(a.BloomFilterEncoding())
default:
return false, errors.New("Unsupported mode of operation for a bloom filter")
}
}
func (b BloomFilter) hasAssertionStandard(assertionEncoding string) (bool, error) {
if len(b.HashFamily) != b.NofHashFunctions {
log.Error("len(HashFamily) != nofHashFunctions", "len(HashFamily)", len(b.HashFamily),
"NofHashFunctions", b.NofHashFunctions)
return false, errors.New("len(HashFamily) != nofHashFunctions")
}
for _, id := range b.HashFamily {
if val, err := b.Filter.GetBit(int(calcHash(id, assertionEncoding) % uint64(8*len(b.Filter)))); err != nil {
return false, err
} else if !val {
return false, nil
}
}
return true, nil
}
func (b BloomFilter) hasAssertionKM(assertionEncoding string) (bool, error) {
hash1, hash2, err := b.getKMHashes(assertionEncoding)
if err != nil {
return false, err
}
for i := 0; i < b.NofHashFunctions; i++ {
if val, err := b.Filter.GetBit(int((hash1 + uint64(i)*hash2) % uint64(8*len(b.Filter)))); err != nil {
return false, err
} else if !val {
return false, nil
}
}
return true, nil
}
//AddAssertion sets the corresponding bits to 1 in the bloom filter based on the hash family,
//number of hash functions used and mode of operation.
func (b BloomFilter) AddAssertion(a *Assertion) error {
switch b.ModeOfOperation {
case StandardOpType:
return b.addAssertionStandard(a.BloomFilterEncoding())
case KirschMitzenmacher1, KirschMitzenmacher2:
return b.addAssertionKM(a.BloomFilterEncoding())
default:
return errors.New("Unsupported mode of operation for a bloom filter")
}
}
func (b BloomFilter) addAssertionStandard(assertionEncoding string) error {
if len(b.HashFamily) != b.NofHashFunctions {
log.Error("len(HashFamily) != nofHashFunctions", "len(HashFamily)", len(b.HashFamily),
"NofHashFunctions", b.NofHashFunctions)
return errors.New("len(HashFamily) != nofHashFunctions")
}
for _, id := range b.HashFamily {
if err := b.Filter.SetBit(int(calcHash(id, assertionEncoding) % uint64(8*len(b.Filter)))); err != nil {
return err
}
}
return nil
}
func (b BloomFilter) addAssertionKM(assertionEncoding string) error {
hash1, hash2, err := b.getKMHashes(assertionEncoding)
if err != nil {
return err
}
for i := 0; i < b.NofHashFunctions; i++ {
if err := b.Filter.SetBit(int((hash1 + uint64(i)*hash2) % uint64(8*len(b.Filter)))); err != nil {
return err
}
}
return nil
}
func (b BloomFilter) getKMHashes(assertionEncoding string) (uint64, uint64, error) {
if len(b.HashFamily) == 1 {
//FIXME CFE currently only works for hash functions returning 64 bit value
hash := calcHash(b.HashFamily[0], assertionEncoding)
return uint64(int(hash)), uint64(int(hash >> 32)), nil //int64(int()) truncate upper 32 bits
} else if len(b.HashFamily) != 2 {
return calcHash(b.HashFamily[0], assertionEncoding), calcHash(b.HashFamily[1], assertionEncoding), nil
} else {
log.Error("len(HashFamily) should be 1 or 2", "len(HashFamily)", len(b.HashFamily),
"NofHashFunctions", b.NofHashFunctions)
return 0, 0, errors.New("len(HashFamily) should be 1 or 2")
}
}
func calcHash(hashType algorithmTypes.Hash, encoding string) uint64 {
switch hashType {
case algorithmTypes.Sha256:
hash := sha256.Sum256([]byte(encoding))
return binary.BigEndian.Uint64(hash[:])
case algorithmTypes.Sha384:
hash := sha512.Sum384([]byte(encoding))
return binary.BigEndian.Uint64(hash[:])
case algorithmTypes.Sha512:
hash := sha512.Sum512([]byte(encoding))
return binary.BigEndian.Uint64(hash[:])
case algorithmTypes.Fnv64:
hash := fnv.New64()
return hash.Sum64()
case algorithmTypes.Murmur364:
return murmur3.Sum64([]byte(encoding))
default:
log.Error("Unsupported hash algorithm type")
return 0
}
}
//CompareTo compares two BloomFilters and returns 0 if they are equal, 1 if b is greater than
//bloomFilter and -1 if b is smaller than bloomFilter
func (b BloomFilter) CompareTo(bloomFilter BloomFilter) int {
//FIXME CFE remove this function and use cbor encoded string to compare
if b.NofHashFunctions < bloomFilter.NofHashFunctions {
return -1
} else if b.NofHashFunctions > bloomFilter.NofHashFunctions {
return 1
} else if b.ModeOfOperation < bloomFilter.ModeOfOperation {
return -1
} else if b.ModeOfOperation > bloomFilter.ModeOfOperation {
return 1
} else if len(b.Filter) < len(bloomFilter.Filter) {
return -1
} else if len(b.Filter) < len(bloomFilter.Filter) {
return 1
}
return bytes.Compare(b.Filter, bloomFilter.Filter)
} | internal/pkg/section/datastructure.go | 0.604165 | 0.413684 | datastructure.go | starcoder |
package reflect
import (
"reflect"
)
const EQUALMETHOD = "Equal"
func Equal(v1, v2 interface{}) bool {
return EqualValue(reflect.ValueOf(v1), reflect.ValueOf(v2))
}
func EqualValue(v1, v2 reflect.Value) bool {
if v1.Kind() != v2.Kind() {
return false
}
switch v1.Kind() {
case reflect.Bool:
return v1.Bool() == v2.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v1.Int() == v2.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v1.Uint() == v2.Uint()
case reflect.Float32, reflect.Float64:
return v1.Float() == v2.Float()
case reflect.Complex64, reflect.Complex128:
return v1.Complex() == v2.Complex()
case reflect.Array, reflect.Slice: //集合类型,首先进行程度和集合类型检测,一致进行后续判断
if v1.Len() != v2.Len() || v1.Type().Elem() != v2.Type().Elem() {
return false
}
if checkEqualFunc(v1, v2) {
return true
}
for i := 0; i < v1.Len(); i++ {
if !EqualValue(v1.Index(i), v2.Index(i)) {
return false
}
}
return true
case reflect.Chan:
panic(Err_Equal_UnsupportType)
case reflect.Func:
return v1.Type() == v2.Type()
case reflect.Interface:
v := v2.Convert(v1.Type())
if v.IsNil() {
return false
}
return true
case reflect.Map:
if v1.Len() != v2.Len() || v1.Type().Key() != v2.Type().Key() || v1.Type().Elem() != v2.Type().Elem() {
return false
}
if checkEqualFunc(v1, v2) {
return true
}
keys := v1.MapKeys()
for _, key := range keys {
v1item := v1.MapIndex(key)
v2item := v2.MapIndex(key)
if !v2item.IsValid() {
return false
}
if !EqualValue(v1item, v2item) {
return false
}
}
return true
case reflect.Ptr:
if v1.Pointer() == v2.Pointer() {
return true
} else if v1.Elem().Type() == v2.Elem().Type() {
if checkEqualFunc(v1, v2) {
return true
} else {
return EqualValue(v1.Elem(), v2.Elem())
}
}
case reflect.String:
return v1.String() == v2.String()
case reflect.Struct:
if v1.Type() != v2.Type() {
return false
}
if checkEqualFunc(v1, v2) {
return true
}
numfile := v1.NumField()
for i := 0; i < numfile; i++ {
if !EqualValue(v1.Field(i), v2.Field(i)) {
return false
}
}
return true
case reflect.UnsafePointer:
panic(Err_Equal_UnsupportType)
}
return false
}
func checkEqualFunc(v1, v2 reflect.Value) (outputresult bool) {
defer func() {
if err := recover(); err != nil {
outputresult = false
}
}()
if f, has := v1.Type().MethodByName(EQUALMETHOD); has {
inlen := f.Type.NumIn()
outlen := f.Type.NumOut()
if inlen != 2 || outlen != 1 {
return false
}
if f.Type.In(1) != v1.Type() || f.Type.Out(0).Kind() != reflect.Bool {
return false
}
result := f.Func.Call([]reflect.Value{v1, v2})
return result[0].Bool()
} else {
return false
}
}
func EqualValueMust(v1, v2 reflect.Value) bool {
defer func() {}()
return EqualValue(v1, v2)
}
func EqualMust(v1, v2 interface{}) bool {
defer func() {}()
return Equal(v1, v2)
} | reflect/equal.go | 0.517815 | 0.470858 | equal.go | starcoder |
package slice
import "errors"
// DeleteBool removes an element at a specific index of a bool slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteBool(a []bool, i int) ([]bool, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteByte removes an element at a specific index of a byte slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteByte(a []byte, i int) ([]byte, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteComplex128 removes an element at a specific index of a complex128 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteComplex128(a []complex128, i int) ([]complex128, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteComplex64 removes an element at a specific index of a complex64 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteComplex64(a []complex64, i int) ([]complex64, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteFloat32 removes an element at a specific index of a float32 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteFloat32(a []float32, i int) ([]float32, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteFloat64 removes an element at a specific index of a float64 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteFloat64(a []float64, i int) ([]float64, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteInt removes an element at a specific index of an int slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteInt(a []int, i int) ([]int, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteInt16 removes an element at a specific index of an int16 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteInt16(a []int16, i int) ([]int16, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteInt32 removes an element at a specific index of an int32 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteInt32(a []int32, i int) ([]int32, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteInt64 removes an element at a specific index of an int64 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteInt64(a []int64, i int) ([]int64, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteInt8 removes an element at a specific index of an int8 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteInt8(a []int8, i int) ([]int8, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteRune removes an element at a specific index of a rune slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteRune(a []rune, i int) ([]rune, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteString removes an element at a specific index of a string slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteString(a []string, i int) ([]string, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteUint removes an element at a specific index of a uint slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteUint(a []uint, i int) ([]uint, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteUint16 removes an element at a specific index of a uint16 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteUint16(a []uint16, i int) ([]uint16, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteUint32 removes an element at a specific index of a uint32 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteUint32(a []uint32, i int) ([]uint32, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteUint64 removes an element at a specific index of a uint64 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteUint64(a []uint64, i int) ([]uint64, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteUint8 removes an element at a specific index of a uint8 slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteUint8(a []uint8, i int) ([]uint8, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
}
// DeleteUintptr removes an element at a specific index of a uintptr slice.
// An error is return in case the index is out of bounds or if the slice is nil or empty.
func DeleteUintptr(a []uintptr, i int) ([]uintptr, error) {
if len(a) == 0 {
return nil, errors.New("Cannot delete an element from a nil or empty slice")
}
if i < 0 || i > len(a)-1 {
return nil, errors.New("Index out of bounds")
}
return append(a[:i], a[i+1:]...), nil
} | delete.go | 0.830353 | 0.535766 | delete.go | starcoder |
package arr
import (
"reflect"
"github.com/yaoapp/yao/lib/exception"
"github.com/yaoapp/yao/lib/t"
)
// Pluck pluck a list of the given key / value pairs from the array/slice.
func Pluck(array interface{}, find interface{}, v interface{}) {
values := reflect.ValueOf(array)
if values.Kind() != reflect.Array && values.Kind() != reflect.Slice {
exception.New("Argument 1 must be an Array or Slice", 500).
Ctx(t.M{"array": array, "kind": values.Kind()}).
Throw()
}
method := reflect.ValueOf(find)
if method.Kind() != reflect.Func {
exception.New("Argument 2 must be a Function", 500).
Ctx(t.M{"kind": method.Kind()}).
Throw()
}
methodType := reflect.TypeOf(find)
if methodType.NumIn() != 1 {
exception.New("the Function must have one return value", 500).
Ctx(t.M{"numIn": methodType.NumIn()}).
Throw()
}
if methodType.NumOut() != 1 {
exception.New("the Function must have one return value", 500).
Ctx(t.M{"numIn": methodType.NumOut()}).
Throw()
}
result := reflect.ValueOf(v)
if result.Kind() != reflect.Ptr {
exception.New("Argument 3 must be an Pointer", 500).
Ctx(t.M{"v": v, "kind": values.Kind()}).
Throw()
}
length := values.Len()
typ := methodType.Out(0)
slice := reflect.MakeSlice(reflect.SliceOf(typ), 0, length)
for i := 0; i < length; i++ {
elm := values.Index(i)
vals := method.Call([]reflect.Value{elm})
slice = reflect.Append(slice, vals[0])
}
result.Elem().Set(slice)
}
// Have Check element exists in a array/slice
func Have(array interface{}, item interface{}) bool {
MustBeArray(array)
values := reflect.ValueOf(array)
length := values.Len()
for i := 0; i < length; i++ {
elm := values.Index(i)
if elm.Interface() == item {
return true
}
}
return false
}
// HaveAny Check each element exists in a array/slice
func HaveAny(array interface{}, items interface{}) bool {
MustBeArray(items)
values := reflect.ValueOf(items)
length := values.Len()
for i := 0; i < length; i++ {
item := values.Index(i)
if Have(array, item.Interface()) {
return true
}
}
return false
}
// HaveMany Check each element exists in a array/slice
func HaveMany(array interface{}, items interface{}) bool {
MustBeArray(items)
values := reflect.ValueOf(items)
length := values.Len()
for i := 0; i < length; i++ {
item := values.Index(i)
if !Have(array, item.Interface()) {
return false
}
}
return true
}
// MustBeArray the given variable must be array or slice
func MustBeArray(array interface{}) {
values := reflect.ValueOf(array)
if values.Kind() != reflect.Array && values.Kind() != reflect.Slice {
exception.New("the variable type is not Array or Slice", 500).
Ctx(t.M{"array": array, "kind": values.Kind()}).
Throw()
}
} | lib/arr/arr.go | 0.609873 | 0.47384 | arr.go | starcoder |
package main
/* This virtual component makes possible the use of configuration file. Its interfaces can be used to fetch configuration data from a configuration file. The interface to use among the three, depends on the kind of data you're trying to fetch.
BACKUPS: The following are some actual components capable of backing up this virtual component:
Actual component aaaaag (Configuration Data Provider)
*/
var (
iScalarData_AAAAAF func (string) (string, error) /* To fetch a scalar configuration data (number or string) use this interface.
INPUT
input 0: The name of the data to be fetched.
OUTPT
outpt 0: The value of the data asked to be fetched. Value would be an empty string if any error should occur during the fetch.
outpt 1: Any error that occurs during the fetch. On successful fetch, value would be nil. On failed fetch, value would the error that occured. If the data is not set, value would be an error. */
iSliceData_AAAAAF func (string) ([]string, error) /* To fetch an array configuration data use this interface. The interface requires one parametre which should be the name of the data to be fetched.
INPUT
input 0: The name of the data to be fetched.
OUTPT
outpt 0: The value of the data asked to be fetched. Value would be an empty slice if any error should occur during the fetch.
outpt 1: Any error that occurs during the fetch. On successful fetch, value would be nil. On failed fetch, value would the error that occured. If the data is not set, value would be an error. */
iMapData_AAAAAF func (string) (map[string]string, error) /* To fetch a map configuration data use this interface. The interface requires one parametre which should be the name of the data to be fetched.
INPUT
input 0: The name of the data to be fetched.
OUTPT
outpt 0: The value of the data asked to be fetched. Note indeces of map would all be in lowercase. Value would be an empty map if any error should occur during the fetch.
outpt 1: Any error that occurs during the fetch. On successful fetch, value would be nil. On failed fetch, value would the error that occured. If the data is not set, value would be an error. */
) | aaaaaf.vcConfDataProvider.go | 0.60964 | 0.614654 | aaaaaf.vcConfDataProvider.go | starcoder |
package godig
import (
"github.com/tidwall/gjson"
)
//OneMap retrieves a single record using the provided primary key. The
//returned record is a map of names and values. Everything is a string.
func (t *Table) OneMap(key string) (map[string]string, error) {
var b map[string]string
body, err := t.OneRaw(key)
if err != nil {
return b, err
}
r := gjson.ParseBytes(body)
b = unpackGJsonMap(r)
return b, err
}
//ManyMap returns an array of records. Each record is a map of field names
// and values. An empty array indicates end of data.
func (t *Table) ManyMap(offset int32, count int, crit string) ([]map[string]string, error) {
var a []map[string]string
body, err := t.ManyRaw(offset, count, crit)
if err != nil {
return a, err
}
a = unpackGJsonArray(body)
return a, nil
}
//ManyMapTagged returns an array of records that have a common tag. Each
// record is a map of field names and values. An empty array indicates end of data.
func (t *Table) ManyMapTagged(offset int32, count int, crit string, tag string) ([]map[string]string, error) {
var a []map[string]string
body, err := t.ManyRawTagged(offset, count, crit, tag)
if err != nil {
return a, err
}
a = unpackGJsonArray(body)
return a, nil
}
//LeftJoinMap reads from Salsa and returns an array of maps. The results are
//unmarshalled using gjson. Each map containsa single record.
func (t *Table) LeftJoinMap(offset int32, count int, crit string) ([]map[string]string, error) {
var a []map[string]string
body, err := t.LeftJoinRaw(offset, count, crit)
a = unpackGJsonArray(body)
return a, err
}
func unpackGJsonMap(r gjson.Result) map[string]string {
b := make(map[string]string, 0)
r.ForEach(func(key, value gjson.Result) bool {
b[key.String()] = value.String()
return true
})
return b
}
func unpackGJsonArray(body []byte) []map[string]string {
a := make([]map[string]string, 0)
f := gjson.ParseBytes(body).Array()
for _, r := range f {
b := unpackGJsonMap(r)
a = append(a, b)
}
return a
} | pkg/mapped.go | 0.793586 | 0.416085 | mapped.go | starcoder |
package main
import (
"fmt"
"io/ioutil"
"os"
"time"
)
// To compute x^y under modulo m
func power(x uint64, y uint64, m uint64) uint64 {
if y == 0 {
return 1
}
p := power(x, y/2, m) % m
p = (p * p) % m
if y%2 == 0 {
return p
}
return (x * p) % m
}
// Function to find modular inverse of a under modulo m
// Assumption: m is prime
func modInverse(a uint64, m uint64) uint64 {
return power(a, m-2, m)
}
// k is size of num[] and rem[]. Returns the smallest
// number x such that:
// x % num[0] = rem[0],
// x % num[1] = rem[1],
// ..................
// x % num[k-2] = rem[k-1]
// Assumption: Numbers in num[] are pairwise coprime
// (gcd for every pair is 1)
func findMinX(num []uint64, rem []uint64) uint64 {
// Compute product of all numbers
var prod uint64 = 1
for i := 0; i < len(num); i++ {
prod *= num[i]
}
// Initialize result
var result uint64
// Apply above formula
for i := 0; i < len(num); i++ {
var pp uint64 = prod / num[i]
result += rem[i] * modInverse(pp, num[i]) * pp
}
return result % prod
}
func sanitizeModulo(x, y uint64) uint64 {
return (y - (x % y)) % y
}
func run(s []byte) uint64 {
var currP uint64
f := make([]uint64, 0, 100)
p := make([]uint64, 0, 100)
i := 0
for s[i] != byte('\n') {
i++
}
i++
for i < len(s) && s[i] != byte('\n') {
if s[i] == 'x' {
i++
if s[i] == ',' {
i++
}
currP++
continue
}
if i == len(s) {
break
}
n := len(f)
p = append(p, currP)
currP++
f = append(f, 0)
for i < len(s) && s[i] >= byte('0') && s[i] <= byte('9') {
f[n] = f[n]*10 + uint64(s[i]-'0')
i++
}
if i < len(s) && s[i] == ',' {
i++
}
p[n] = sanitizeModulo(p[n], f[n])
}
return findMinX(f, p)
}
func main() {
// Uncomment this line to disable garbage collection
// debug.SetGCPercent(-1)
// Read input from stdin
input, err := ioutil.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
// Start resolution
start := time.Now()
result := run(input)
// Print result
fmt.Printf("_duration:%f\n", time.Now().Sub(start).Seconds()*1000)
fmt.Println(result)
} | day-13/part-2/ayoub.go | 0.554953 | 0.442275 | ayoub.go | starcoder |
package v1
import (
"context"
"reflect"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
type StatusResponse struct {
// The status code, which should be an enum value of google.rpc.Code.
Code int `pulumi:"code"`
// A list of messages that carry the error details. There is a common set of message types for APIs to use.
Details []map[string]string `pulumi:"details"`
// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
Message string `pulumi:"message"`
}
// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
type StatusResponseOutput struct{ *pulumi.OutputState }
func (StatusResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*StatusResponse)(nil)).Elem()
}
func (o StatusResponseOutput) ToStatusResponseOutput() StatusResponseOutput {
return o
}
func (o StatusResponseOutput) ToStatusResponseOutputWithContext(ctx context.Context) StatusResponseOutput {
return o
}
// The status code, which should be an enum value of google.rpc.Code.
func (o StatusResponseOutput) Code() pulumi.IntOutput {
return o.ApplyT(func(v StatusResponse) int { return v.Code }).(pulumi.IntOutput)
}
// A list of messages that carry the error details. There is a common set of message types for APIs to use.
func (o StatusResponseOutput) Details() pulumi.StringMapArrayOutput {
return o.ApplyT(func(v StatusResponse) []map[string]string { return v.Details }).(pulumi.StringMapArrayOutput)
}
// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.
func (o StatusResponseOutput) Message() pulumi.StringOutput {
return o.ApplyT(func(v StatusResponse) string { return v.Message }).(pulumi.StringOutput)
}
func init() {
pulumi.RegisterOutputType(StatusResponseOutput{})
} | sdk/go/google/bigqueryreservation/v1/pulumiTypes.go | 0.674908 | 0.409634 | pulumiTypes.go | starcoder |
package act
import (
"math"
"strings"
)
// Activation functions implemented
// Linear 2
// Sigmoid 3
// ReLU 4
// SoftSign 1
//ActivationFactory takes the 'name' of the function to be used and returns the corresponding struct
//Linear
//sigmoid
//ReLU
//SoftSign
//default is ReLU
func ActivationFactory(method string) Activation {
switch strings.ToLower(method) {
case "linear":
return Linear{}
case "sigmoid":
return Sigmoid{}
case "relu":
return ReLU{}
case "softsign":
return SoftSign{}
default:
return ReLU{}
}
}
// Activation provides an interface to follow for making
// different versions of activation methods
// Act([]float64) gets y in terms of x
// Derivative([]float64) gets y' in terms of y
// ToString() return struct name
type Activation interface {
// y in terms of x
Act([]float64) []float64
// y' in terms of y
Derivative([]float64) []float64
ToString() string
}
// SoftSign implements the activation interface
// using f(x) = x/(1 + |x|)
// It is tanh like (~-1.0?, ~+1.0?)
type SoftSign struct{}
func (s SoftSign) ToString() string {
return "SoftSign"
}
// Act of SoftSign makes a smooth transition (-1, 1)
func (s SoftSign) Act(x []float64) []float64 {
guess := make([]float64, len(x))
for i, x := range x {
guess[i] = x / (1.0 + math.Abs(x))
}
return guess
}
// Derivative of SoftSign in terms of y
func (s SoftSign) Derivative(y []float64) []float64 {
v := make([]float64, len(y))
for i, y := range y {
var a float64
if y <= 0 {
a = -(y / (y - 1))
} else {
a = y / (y + 1)
}
v[i] = math.Pow(1.0/(1.0+math.Abs(a)), 2.0)
}
return v
}
// Linear implements the activation interface
// using a linear function y = x
// could technically use a coefficient
type Linear struct{}
func (l Linear) ToString() string {
return "Linear"
}
// Act of Linear technically doesn't change the input data, but does return it.
func (l Linear) Act(x []float64) []float64 {
guess := make([]float64, len(x))
copy(guess, x)
return guess
}
// Derivative of Linear returns the scalar of the linear function. 1.0
func (l Linear) Derivative(y []float64) []float64 {
v := make([]float64, len(y))
for i := range y {
v[i] = 1.0
}
return v
}
// Sigmoid implments the activation interface
// using a smooth transition (0, 1)
type Sigmoid struct{}
func (S Sigmoid) ToString() string {
return "Sigmoid"
}
// Act on x suchthat y = 1/(1+e^-x))
func (S Sigmoid) Act(x []float64) []float64 {
guess := make([]float64, len(x))
for i, v := range x {
guess[i] = (1. / (1. + math.Pow(math.E, -v)))
}
return guess
}
// Derivative on y suchthat y` = y(1. - y)
func (S Sigmoid) Derivative(y []float64) []float64 {
v := make([]float64, len(y))
for i, y := range y {
v[i] = y * (1. - y)
}
return v
}
// ReLU implments the activation interface
// using a hard transition y = {0; x < 0, x; x >= 0}
type ReLU struct{}
func (r ReLU) ToString() string {
return "ReLU"
}
// Act of Rectified Linear Unit gives max of (0, x)
func (r ReLU) Act(x []float64) []float64 {
guess := make([]float64, len(x))
for i, y := range x {
if y >= 0 {
guess[i] = y
} else {
guess[i] = 0.0
}
}
return guess
}
// Derivative of Rectified Linear Unit give slope of (max(0, x)) == 0. || 1.
func (r ReLU) Derivative(y []float64) []float64 {
v := make([]float64, len(y))
for i, y := range y {
if y > 0 {
v[i] = 1.0
} else {
v[i] = 0.0
}
}
return v
} | act/activation.go | 0.641085 | 0.410874 | activation.go | starcoder |
package obj
import (
"github.com/deadsy/sdfx/sdf"
"github.com/ivanpointer/pterosphera/render"
)
// MXSwitchSocket defines the socket for a MX switch.
type MXSwitchSocket struct {
// SocketWH defines the width and height of the "hole" part of a MX switch socket.
SocketWH float64
// SideTabW defines the width of the cutouts for the tabs for opening a MX switch.
SideTabW float64
// SideTabsDist defines the distance from the edge that the opening tabs begin.
SideTabsDist float64
// SocketDepth defines the total depth of the socket - important as the leads on the bottom of the switch need to connect with the hot-swap socket.
SocketDepth float64
// TopPlateDepth defines the depth of the top plate for the switch.
TopPlateDepth float64
// ClipHoleW defines the width of the hole for the clip of the MX switch.
ClipHoleW float64
// ClipHoleH defines the height of the hole for the clip of the MX switch.
ClipHoleH float64
// ClipHoleD defines the depth of the hole for the clip of the MX switch.
ClipHoleD float64
}
// MXSwitchSocketRender defines the render settings for a MX switch socket
type MXSwitchSocketRender struct {
Settings render.RenderSettings
}
// Render renders the MX switch socket.
func (s MXSwitchSocket) Render(r MXSwitchSocketRender) (sdf.SDF3, error) {
return s.renderSocketHole(r)
}
func (s MXSwitchSocket) renderSocketHole(r MXSwitchSocketRender) (sdf.SDF3, error) {
// Render the socket hole
socketD := s.SocketDepth - s.TopPlateDepth
socketW := s.SocketWH + (s.SideTabsDist * 2)
socket, err := sdf.Box3D(sdf.V3{X: s.SocketWH, Y: socketW, Z: socketD}, 0)
if err != nil {
return nil, err
}
// Render the plate hole
plateH := s.TopPlateDepth + r.Settings.WeldShift
plate, err := sdf.Box3D(sdf.V3{X: s.SocketWH, Y: s.SocketWH, Z: plateH}, 0)
if err != nil {
return nil, err
}
plateZ := (socketD / 2) + (s.TopPlateDepth / 2)
plate = sdf.Transform3D(plate, sdf.Translate3d(sdf.V3{Z: plateZ}))
// Add the cutout for the switch clips
clipHole, err := sdf.Box3D(sdf.V3{X: s.SocketWH + s.ClipHoleD, Y: s.ClipHoleW, Z: s.ClipHoleH}, 0)
if err != nil {
return nil, err
}
clipHole = sdf.Transform3D(clipHole, sdf.Translate3d(sdf.V3{Z: (socketD / 2) - (s.ClipHoleH / 2)}))
plate = sdf.Union3D(plate, clipHole)
// Cut out the tab holes for opening the switch
tabW := (s.SocketWH - (s.SideTabsDist * 2) - s.SideTabW) / 2
tabH1, err := sdf.Box3D(sdf.V3{X: tabW, Y: socketW, Z: plateH}, 0)
if err != nil {
return nil, err
}
tabOffsetX := ((s.SocketWH / 2) - 1) - (tabW / 2)
tabH1 = sdf.Transform3D(tabH1, sdf.Translate3d(sdf.V3{X: tabOffsetX, Z: plateZ}))
plate = sdf.Union3D(plate, tabH1)
tabH2, err := sdf.Box3D(sdf.V3{X: tabW, Y: socketW, Z: plateH}, 0)
tabH2 = sdf.Transform3D(tabH2, sdf.Translate3d(sdf.V3{X: tabOffsetX * -1, Z: plateZ}))
plate = sdf.Union3D(plate, tabH2)
socket = sdf.Union3D(socket, plate)
// Move the whole model down to align with the plane
socket = sdf.Transform3D(socket, sdf.Translate3d(sdf.V3{Z: ((s.SocketDepth / 2) + s.TopPlateDepth) * -1}))
// Send it!
return socket, nil
} | go_sdx/obj/switches.go | 0.652131 | 0.552057 | switches.go | starcoder |
package main
import "fmt"
func main() {
fmt.Println("Slice types")
// Empty slice declaration. The value of an uninitialized slice is nil.
var emptySlice []int
fmt.Printf("Empty slice %v, is nil %t, len %d, cap %d\n", emptySlice, emptySlice == nil,
len(emptySlice), cap(emptySlice))
// A slice literal describes the entire underlying array literal.
// Thus the length and capacity of a slice literal are the maximum
// element index plus one. A slice literal has the form
var literalSlice = []int{1, 2, 3}
fmt.Printf("Literal slice %v, is nil %t, len %d, cap %d\n", literalSlice, literalSlice == nil,
len(literalSlice), cap(literalSlice))
// A new, initialized slice value for a given element type T is made
// using the built-in function make([]T, length, capacity), which takes
// a slice type and parameters specifying the length and optionally the
// capacity.
// A slice created with make always allocates a new, hidden array to which
// the returned slice value refers. That is, executing
var makeSlice = make([]int, 3, 3)
fmt.Printf("Make slice %v, is nil %t, len %d, cap %d\n", makeSlice, makeSlice == nil,
len(makeSlice), cap(makeSlice))
// Produces the same slice as allocating an array and slicing it, so these
// two expressions are equivalent:
var newSlice = new([3]int)[0:3]
fmt.Printf("New slice %v, is nil %t, len %d, cap %d\n", newSlice, newSlice == nil,
len(newSlice), cap(newSlice))
// https://github.com/golang/go/blob/master/src/runtime/slice.go#L15
//type Slice struct {
// Array [Cap]interface{} // C++ void* Array
// Len int
// Cap int
//}
// A little brain fuck.
fmt.Println("\nA little brain fuck.")
parentSlice := make([]int, 0, 3)
parentSlice = append(parentSlice, 1, 2, 3)
childSliceA := parentSlice
childSliceB := parentSlice
childSliceB = append(childSliceB, 4)
childSliceC := parentSlice
childSliceC = append(childSliceC, 5)
fmt.Printf("Parent slice %v, len %d, cap %d\n", parentSlice, len(parentSlice), cap(parentSlice))
fmt.Printf("Child slice A %v\n", childSliceA)
fmt.Printf("Child slice B %v\n", childSliceB)
fmt.Printf("Child slice C %v\n", childSliceC)
//type Slice struct {
// Array [Cap]interface{} // C++ void* Array
// Len int
// Cap int
//}
// And more
fmt.Println("\nAnd more")
parentSlice = make([]int, 0, 6)
parentSlice = append(parentSlice, 1, 2, 3)
childSliceA = parentSlice
childSliceB = parentSlice
childSliceB = append(childSliceB, 4)
childSliceC = parentSlice
childSliceC = append(childSliceC, 5)
fmt.Printf("Parent slice %v, len %d, cap %d\n", parentSlice, len(parentSlice), cap(parentSlice))
fmt.Printf("Child slice A %v\n", childSliceA)
fmt.Printf("Child slice B %v\n", childSliceB)
fmt.Printf("Child slice C %v\n", childSliceC)
//type Slice struct {
// Array [Cap]interface{} // C++ void* Array
// Len int
// Cap int
//}
// And more
fmt.Println("\nAnd more")
parentSlice = make([]int, 0, 6)
parentSlice = append(parentSlice, 1, 2, 3, 4, 5, 6)
childSliceA = parentSlice[2:4] // change 4 to 6
childSliceA[0] = -1
childSliceA[1] = -2
childSliceA = append(childSliceA, -3, -4)
fmt.Printf("Parent slice %v, len %d, cap %d\n", parentSlice, len(parentSlice), cap(parentSlice))
fmt.Printf("Parent slice[0:2] %v\n", parentSlice[0:2])
fmt.Printf("Parent slice[2:4] %v\n", parentSlice[2:4])
fmt.Printf("Parent slice[4:6] %v\n", parentSlice[4:6])
fmt.Printf("Child slice A %v\n", childSliceA)
//type Slice struct {
// Array [Cap]interface{} // C++ void* Array
// Len int
// Cap int
//}
// And more
fmt.Println("\nAnd more")
type Bag struct {
Things []int
}
bags := []Bag{
{Things: []int{1, 2}}, // Bag 1
{Things: []int{}}, // Bag 2
{Things: []int{10, 20}}, // Bag 3
}
fmt.Printf("Bags: %+v\n", bags)
for i, bag := range bags {
fmt.Printf("Bag %d before append: %+v\n", i+1, bag)
bag.Things = append(bag.Things, 3, 4, 5)
fmt.Printf("Bag %d after append: %+v\n\n", i+1, bag)
}
fmt.Printf("Bags after first loop: %+v\n", bags)
for i := range bags {
fmt.Printf("Bag %d before append: %+v\n", i+1, bags[i])
bags[i].Things = append(bags[i].Things, 3, 4, 5)
fmt.Printf("Bag %d after append: %+v\n\n", i+1, bags[i])
}
fmt.Printf("Bags: %+v\n", bags)
// HOMEWORK: Create the same list of bags, but keep pointers to the Bag
// object in it and do the same append operations yourself.
} | lessons/types/slice.go | 0.573678 | 0.414543 | slice.go | starcoder |
package builtins
import (
"fmt"
"github.com/eandre/sqlparse/pkg/util/pgerror"
"github.com/eandre/sqlparse/sem/tree"
"github.com/eandre/sqlparse/sem/types"
)
func initWindowBuiltins() {
// Add all windows to the Builtins map after a few sanity checks.
for k, v := range windows {
if !v.props.Impure {
panic(fmt.Sprintf("%s: window functions should all be impure, found %v", k, v))
}
if v.props.Class != tree.WindowClass {
panic(fmt.Sprintf("%s: window functions should be marked with the tree.WindowClass "+
"function class, found %v", k, v))
}
builtins[k] = v
}
}
func winProps() tree.FunctionProperties {
return tree.FunctionProperties{
Impure: true,
Class: tree.WindowClass,
}
}
// windows are a special class of builtin functions that can only be applied
// as window functions using an OVER clause.
// See `windowFuncHolder` in the sql package.
var windows = map[string]builtinDefinition{
"row_number": makeBuiltin(winProps(),
makeWindowOverload(tree.ArgTypes{}, types.Int,
"Calculates the number of the current row within its partition, counting from 1."),
),
"rank": makeBuiltin(winProps(),
makeWindowOverload(tree.ArgTypes{}, types.Int,
"Calculates the rank of the current row with gaps; same as row_number of its first peer."),
),
"dense_rank": makeBuiltin(winProps(),
makeWindowOverload(tree.ArgTypes{}, types.Int,
"Calculates the rank of the current row without gaps; this function counts peer groups."),
),
"percent_rank": makeBuiltin(winProps(),
makeWindowOverload(tree.ArgTypes{}, types.Float,
"Calculates the relative rank of the current row: (rank - 1) / (total rows - 1)."),
),
"cume_dist": makeBuiltin(winProps(),
makeWindowOverload(tree.ArgTypes{}, types.Float,
"Calculates the relative rank of the current row: "+
"(number of rows preceding or peer with current row) / (total rows)."),
),
"ntile": makeBuiltin(winProps(),
makeWindowOverload(tree.ArgTypes{{"n", types.Int}}, types.Int,
"Calculates an integer ranging from 1 to `n`, dividing the partition as equally as possible."),
),
"lag": collectOverloads(
winProps(),
types.AnyNonArray,
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{{"val", t}}, t,
"Returns `val` evaluated at the previous row within current row's partition; "+
"if there is no such row, instead returns null.")
},
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{{"val", t}, {"n", types.Int}}, t,
"Returns `val` evaluated at the row that is `n` rows before the current row within its partition; "+
"if there is no such row, instead returns null. `n` is evaluated with respect to the current row.")
},
// TODO(nvanbenschoten): We still have no good way to represent two parameters that
// can be any types but must be the same (eg. lag(T, Int, T)).
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{
{"val", t}, {"n", types.Int}, {"default", t},
}, t,
"Returns `val` evaluated at the row that is `n` rows before the current row within its partition; "+
"if there is no such, row, instead returns `default` (which must be of the same type as `val`). "+
"Both `n` and `default` are evaluated with respect to the current row.")
},
),
"lead": collectOverloads(winProps(), types.AnyNonArray,
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{{"val", t}}, t,
"Returns `val` evaluated at the following row within current row's partition; "+""+
"if there is no such row, instead returns null.")
},
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{{"val", t}, {"n", types.Int}}, t,
"Returns `val` evaluated at the row that is `n` rows after the current row within its partition; "+
"if there is no such row, instead returns null. `n` is evaluated with respect to the current row.")
},
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{
{"val", t}, {"n", types.Int}, {"default", t},
}, t,
"Returns `val` evaluated at the row that is `n` rows after the current row within its partition; "+
"if there is no such, row, instead returns `default` (which must be of the same type as `val`). "+
"Both `n` and `default` are evaluated with respect to the current row.")
},
),
"first_value": collectOverloads(winProps(), types.AnyNonArray,
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{{"val", t}}, t,
"Returns `val` evaluated at the row that is the first row of the window frame.")
}),
"last_value": collectOverloads(winProps(), types.AnyNonArray,
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{{"val", t}}, t,
"Returns `val` evaluated at the row that is the last row of the window frame.")
}),
"nth_value": collectOverloads(winProps(), types.AnyNonArray,
func(t types.T) tree.Overload {
return makeWindowOverload(tree.ArgTypes{
{"val", t}, {"n", types.Int}}, t,
"Returns `val` evaluated at the row that is the `n`th row of the window frame (counting from 1); "+
"null if no such row.")
}),
}
func makeWindowOverload(
in tree.ArgTypes, ret types.T, info string,
) tree.Overload {
return tree.Overload{
Types: in,
ReturnType: tree.FixedReturnType(ret),
Info: info,
}
}
const noFilterIdx = -1
// aggregateWindowFunc aggregates over the the current row's window frame, using
// the internal tree.AggregateFunc to perform the aggregation.
type aggregateWindowFunc struct {
agg tree.AggregateFunc
peerRes tree.Datum
}
// framableAggregateWindowFunc is a wrapper around aggregateWindowFunc that allows
// to reset the aggregate by creating a new instance via a provided constructor.
// shouldReset indicates whether the resetting behavior is desired.
type framableAggregateWindowFunc struct {
shouldReset bool
}
// rowNumberWindow computes the number of the current row within its partition,
// counting from 1.
type rowNumberWindow struct{}
// rankWindow computes the rank of the current row with gaps.
type rankWindow struct {
peerRes *tree.DInt
}
// denseRankWindow computes the rank of the current row without gaps (it counts peer groups).
type denseRankWindow struct {
denseRank int
peerRes *tree.DInt
}
// percentRankWindow computes the relative rank of the current row using:
// (rank - 1) / (total rows - 1)
type percentRankWindow struct {
peerRes *tree.DFloat
}
var dfloatZero = tree.NewDFloat(0)
// cumulativeDistWindow computes the relative rank of the current row using:
// (number of rows preceding or peer with current row) / (total rows)
type cumulativeDistWindow struct {
peerRes *tree.DFloat
}
// ntileWindow computes an integer ranging from 1 to the argument value, dividing
// the partition as equally as possible.
type ntileWindow struct {
ntile *tree.DInt // current result
curBucketCount int // row number of current bucket
boundary int // how many rows should be in the bucket
remainder int // (total rows) % (bucket num)
}
var errInvalidArgumentForNtile = pgerror.NewErrorf(
pgerror.CodeInvalidParameterValueError, "argument of ntile() must be greater than zero")
type leadLagWindow struct {
forward bool
withOffset bool
withDefault bool
}
// firstValueWindow returns value evaluated at the row that is the first row of the window frame.
type firstValueWindow struct{}
// lastValueWindow returns value evaluated at the row that is the last row of the window frame.
type lastValueWindow struct{}
// nthValueWindow returns value evaluated at the row that is the nth row of the window frame
// (counting from 1). Returns null if no such row.
type nthValueWindow struct{}
var errInvalidArgumentForNthValue = pgerror.NewErrorf(
pgerror.CodeInvalidParameterValueError, "argument of nth_value() must be greater than zero") | sem/builtins/window_builtins.go | 0.619471 | 0.465934 | window_builtins.go | starcoder |
package binheap
import (
"golang.org/x/exp/constraints"
)
// ComparableHeap provides additional Search and Delete methods.
// Could be used for comparable types.
type ComparableHeap[T comparable] struct {
Heap[T]
}
// EmptyComparableHeap creates heap for comparable types.
func EmptyComparableHeap[T comparable](comparator func(x, y T) bool) ComparableHeap[T] {
return ComparableHeap[T]{
Heap: EmptyHeap(comparator),
}
}
// ComparableFromSlice creates heap, based on provided slice.
// Slice could be reordered.
func ComparableFromSlice[T comparable](data []T, comparator func(x, y T) bool) ComparableHeap[T] {
return ComparableHeap[T]{
Heap: FromSlice(data, comparator),
}
}
// Search returns if element presents in heap.
func (h *ComparableHeap[T]) Search(x T) bool {
return h.search(x) != -1
}
// Delete removes element from heap, and returns true if x presents in heap.
func (h *ComparableHeap[T]) Delete(x T) bool {
pos := h.search(x)
if pos == -1 {
return false
}
newLen := h.Len() - 1
h.swap(pos, newLen)
h.data = h.data[:newLen]
return true
}
func (h *ComparableHeap[T]) search(x T) int {
for i := range h.data {
if h.data[i] == x {
return i
}
}
return -1
}
// EmptyMinHeap creates empty Min-Heap for ordered types.
func EmptyMinHeap[T constraints.Ordered]() ComparableHeap[T] {
return EmptyComparableHeap(func(x, y T) bool {
return x < y
})
}
// EmptyMaxHeap creates empty Max-Heap for ordered types.
func EmptyMaxHeap[T constraints.Ordered]() ComparableHeap[T] {
return EmptyComparableHeap(func(x, y T) bool {
return x > y
})
}
// EmptyMinHeap creates Min-Heap, based on provided slice.
// Slice could be reordered.
func MinHeapFromSlice[T constraints.Ordered](data []T) ComparableHeap[T] {
return ComparableFromSlice(data, func(x, y T) bool {
return x < y
})
}
// EmptyMaxHeap creates Max-Heap, based on provided slice.
// Slice could be reordered.
func MaxHeapFromSlice[T constraints.Ordered](data []T) ComparableHeap[T] {
return ComparableFromSlice(data, func(x, y T) bool {
return x > y
})
} | binheap/ordered.go | 0.790166 | 0.467028 | ordered.go | starcoder |
package iso20022
// Set of elements identifying the dates related to the underlying transactions.
type TransactionDates1 struct {
// Point in time when the payment order from the initiating party meets the processing conditions of the account servicing agent (debtor's agent in case of a credit transfer, creditor's agent in case of a direct debit). This means - amongst others - that the account servicing agent has received the payment order and has applied checks as eg, authorisation, availability of funds.
AcceptanceDateTime *ISODateTime `xml:"AccptncDtTm,omitempty"`
// Date on which the trade was executed.
TradeDate *ISODate `xml:"TradDt,omitempty"`
// Date on which the amount of money ceases to be available to the agent that owes it and when the amount of money becomes available to the agent to which it is due.
InterbankSettlementDate *ISODate `xml:"IntrBkSttlmDt,omitempty"`
// Start date of the underlying transaction, such as a treasury transaction, an investment plan.
StartDate *ISODate `xml:"StartDt,omitempty"`
// End date of the underlying transaction, such as a treasury transaction, an investment plan.
EndDate *ISODate `xml:"EndDt,omitempty"`
// Date and time of the underlying transaction.
TransactionDateTime *ISODateTime `xml:"TxDtTm,omitempty"`
// Proprietary date related to the underlying transaction.
Proprietary []*ProprietaryDate1 `xml:"Prtry,omitempty"`
}
func (t *TransactionDates1) SetAcceptanceDateTime(value string) {
t.AcceptanceDateTime = (*ISODateTime)(&value)
}
func (t *TransactionDates1) SetTradeDate(value string) {
t.TradeDate = (*ISODate)(&value)
}
func (t *TransactionDates1) SetInterbankSettlementDate(value string) {
t.InterbankSettlementDate = (*ISODate)(&value)
}
func (t *TransactionDates1) SetStartDate(value string) {
t.StartDate = (*ISODate)(&value)
}
func (t *TransactionDates1) SetEndDate(value string) {
t.EndDate = (*ISODate)(&value)
}
func (t *TransactionDates1) SetTransactionDateTime(value string) {
t.TransactionDateTime = (*ISODateTime)(&value)
}
func (t *TransactionDates1) AddProprietary() *ProprietaryDate1 {
newValue := new (ProprietaryDate1)
t.Proprietary = append(t.Proprietary, newValue)
return newValue
} | TransactionDates1.go | 0.795738 | 0.699511 | TransactionDates1.go | starcoder |
package types
import (
"encoding/json"
"fmt"
"regexp"
log "github.com/sirupsen/logrus"
"github.com/smartystreets/assertions"
"github.com/stretchr/objx"
"gopkg.in/yaml.v3"
)
const (
DefaultMatcher = "ShouldEqual"
)
type Assertion func(actual interface{}, expected ...interface{}) string
var asserts = map[string]Assertion{
"ShouldResemble": assertions.ShouldResemble,
"ShouldAlmostEqual": assertions.ShouldAlmostEqual,
"ShouldContainSubstring": assertions.ShouldContainSubstring,
"ShouldEndWith": assertions.ShouldEndWith,
"ShouldEqual": assertions.ShouldEqual,
"ShouldEqualJSON": assertions.ShouldEqualJSON,
"ShouldStartWith": assertions.ShouldStartWith,
"ShouldBeEmpty": ShouldBeEmpty,
"ShouldMatch": ShouldMatch,
"ShouldNotResemble": assertions.ShouldNotResemble,
"ShouldNotAlmostEqual": assertions.ShouldNotAlmostEqual,
"ShouldNotContainSubstring": assertions.ShouldNotContainSubstring,
"ShouldNotEndWith": assertions.ShouldNotEndWith,
"ShouldNotEqual": assertions.ShouldNotEqual,
"ShouldNotStartWith": assertions.ShouldNotStartWith,
"ShouldNotBeEmpty": ShouldNotBeEmpty,
"ShouldNotMatch": ShouldNotMatch,
}
func ShouldMatch(value interface{}, patterns ...interface{}) string {
valueString, ok := value.(string)
if !ok {
return "ShouldMatch works only with strings"
}
for _, pattern := range patterns {
patternString, ok := pattern.(string)
if !ok {
return "ShouldMatch works only with strings"
}
if match, err := regexp.MatchString(patternString, valueString); !match || err != nil {
return fmt.Sprintf("Expected %q to match %q (but it didn't)!", valueString, patternString)
}
}
return ""
}
func ShouldBeEmpty(value interface{}, patterns ...interface{}) string {
return assertions.ShouldBeEmpty(value)
}
func ShouldNotBeEmpty(value interface{}, patterns ...interface{}) string {
return assertions.ShouldNotBeEmpty(value)
}
func ShouldNotMatch(value interface{}, patterns ...interface{}) string {
valueString, ok := value.(string)
if !ok {
return "ShouldNotMatch works only with strings"
}
for _, pattern := range patterns {
patternString, ok := pattern.(string)
if !ok {
return "ShouldNotMatch works only with strings"
}
if match, err := regexp.MatchString(patternString, valueString); match && err == nil {
return fmt.Sprintf("Expected %q to not match %q (but it did)!", valueString, patternString)
}
}
return ""
}
type StringMatcher struct {
Matcher string `json:"matcher" yaml:"matcher,flow"`
Value string `json:"value" yaml:"value,flow"`
}
func (sm StringMatcher) Validate() error {
if _, ok := asserts[sm.Matcher]; !ok {
return fmt.Errorf("invalid matcher %q", sm.Matcher)
}
// Try to compile ShouldMatch regular expressions
if sm.Matcher == "ShouldMatch" || sm.Matcher == "ShouldNotMatch" {
if _, err := regexp.Compile(sm.Value); err != nil {
return fmt.Errorf("invalid regular expression provided to %q operator: %v", sm.Matcher, sm.Value)
}
}
return nil
}
func (sm StringMatcher) Match(value string) bool {
matcher := asserts[sm.Matcher]
if matcher == nil {
log.WithField("matcher", sm.Matcher).Error("Invalid matcher")
return false
}
if res := matcher(value, sm.Value); res != "" {
log.Tracef("Value doesn't match:\n%s", res)
return false
}
return true
}
func (sm *StringMatcher) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err == nil {
sm.Matcher = DefaultMatcher
sm.Value = s
return nil
}
var res struct {
Matcher string `json:"matcher"`
Value string `json:"value"`
}
if err := json.Unmarshal(data, &res); err != nil {
return err
}
sm.Matcher = res.Matcher
sm.Value = res.Value
return sm.Validate()
}
func (sm *StringMatcher) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err == nil {
sm.Matcher = DefaultMatcher
sm.Value = s
return nil
}
var res struct {
Matcher string `yaml:"matcher,flow"`
Value string `yaml:"value,flow"`
}
if err := unmarshal(&res); err != nil {
return err
}
sm.Matcher = res.Matcher
sm.Value = res.Value
return sm.Validate()
}
type StringMatcherSlice []StringMatcher
func (sms StringMatcherSlice) Match(values []string) bool {
if len(sms) > len(values) {
return false
}
for _, matcher := range sms {
matched := false
for _, v := range values {
if matcher.Match(v) {
matched = true
break
}
}
if !matched {
return false
}
}
return true
}
func (sms *StringMatcherSlice) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err == nil {
*sms = []StringMatcher{{
Matcher: DefaultMatcher,
Value: s,
}}
return nil
}
var sm StringMatcher
if err := json.Unmarshal(data, &sm); err == nil {
*sms = []StringMatcher{sm}
return nil
}
var res []StringMatcher
if err := json.Unmarshal(data, &res); err != nil {
return err
}
*sms = res
return nil
}
func (sms *StringMatcherSlice) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err == nil {
*sms = []StringMatcher{{
Matcher: DefaultMatcher,
Value: s,
}}
return nil
}
var sm StringMatcher
if err := unmarshal(&sm); err == nil {
*sms = []StringMatcher{sm}
return nil
}
var res []StringMatcher
if err := unmarshal(&res); err != nil {
return err
}
*sms = res
return nil
}
type MultiMapMatcher map[string]StringMatcherSlice
func (mmm MultiMapMatcher) Match(values map[string][]string) bool {
if len(mmm) > len(values) {
return false
}
for key, matcherValue := range mmm {
value, ok := values[key]
if !ok || !matcherValue.Match(value) {
return false
}
}
return true
}
type BodyMatcher struct {
bodyString *StringMatcher
bodyJson map[string]StringMatcher
}
func (bm BodyMatcher) Match(value string) bool {
if bm.bodyString != nil {
return bm.bodyString.Match(value)
}
j, err := objx.FromJSON(value)
if err != nil {
return false
}
for path, matcher := range bm.bodyJson {
value := j.Get(path)
if value == nil {
return false
}
if ok := matcher.Match(value.String()); !ok {
return false
}
}
return true
}
func (bm BodyMatcher) MarshalJSON() ([]byte, error) {
if bm.bodyString != nil {
return json.Marshal(bm.bodyString)
}
return json.Marshal(bm.bodyJson)
}
func (bm *BodyMatcher) UnmarshalJSON(data []byte) error {
var s StringMatcher
if err := json.Unmarshal(data, &s); err == nil {
if _, ok := asserts[s.Matcher]; ok {
bm.bodyString = &s
return nil
}
}
var res map[string]StringMatcher
if err := json.Unmarshal(data, &res); err != nil {
return err
}
bm.bodyJson = res
return nil
}
func (bm BodyMatcher) MarshalYAML() (interface{}, error) {
if bm.bodyString != nil {
value, err := yaml.Marshal(bm.bodyString)
return string(value), err
}
value, err := yaml.Marshal(bm.bodyJson)
return string(value), err
}
func (bm *BodyMatcher) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s StringMatcher
if err := unmarshal(&s); err == nil {
if _, ok := asserts[s.Matcher]; ok {
bm.bodyString = &s
return nil
}
}
var res map[string]StringMatcher
if err := unmarshal(&res); err != nil {
return err
}
bm.bodyJson = res
return nil
} | server/types/matchers.go | 0.659734 | 0.528229 | matchers.go | starcoder |
package exporters
import (
"github.com/learnitall/gobench/define"
)
// ChainExporter is used to allow for multiple exporters to function through one Expoerterable interface.
// It's important to initiate Exporters and marshalled appropriately
type ChainExporter struct {
Exporters []define.Exporterable
Marshalled [][]byte
}
// doLoop loops through each Exporterable the ChainExporter is configured with and passes it to the given function.
// If an error is returned by the function, then the loop breaks and the error is returned.
func (ce *ChainExporter) doLoop(
loopFunc func(define.Exporterable, int) error,
) error {
for i, exporter := range ce.Exporters {
err := loopFunc(exporter, i)
if err != nil {
return err
}
}
return nil
}
// Setup calls the Setup method on each Exporterable the ChainExporter is configured with.
func (ce *ChainExporter) Setup(cfg *define.Config) error {
return ce.doLoop(
func(e define.Exporterable, i int) error {
return e.Setup(cfg)
},
)
}
// Healthcheck calls the Healthcheck method on each Exporterable the ChainExporter is configured with.
func (ce *ChainExporter) Healthcheck() error {
return ce.doLoop(
func(e define.Exporterable, i int) error {
return e.Healthcheck()
},
)
}
// Teardown calls the Teardown method on each Exporterable the ChainExporter is configured with.
func (ce *ChainExporter) Teardown() error {
return ce.doLoop(
func(e define.Exporterable, i int) error {
return e.Teardown()
},
)
}
// Marshal calls the Marshal method on each Exporterable the ChainExporter is configured with.
// Rather than returning the results of each marshal, they are saved in a slice within the ChainExporter.
// An empty byte array is returned.
// The Exporter function will use these results while exporting payloads.
// This function is ripe for a runtime panic if the `marshalled` field is not
// preallocated to match the length of the number of configured exporters.
func (ce *ChainExporter) Marshal(payload interface{}) ([]byte, error) {
err := ce.doLoop(
func(e define.Exporterable, i int) error {
marshalled, _err := e.Marshal(payload)
if _err != nil {
return _err
}
ce.Marshalled[i] = marshalled
return nil
},
)
return []byte{}, err
}
// Export calls the Export method on each Exporterable the ChainExporter is configured with, using the saved payloads from Marshal.
// This assumes that the ChainExporter's Marshal method has already been called.
// Otherwise, an out-of-bound slice error might be raised.
func (ce *ChainExporter) Export(payload []byte) error {
return ce.doLoop(
func(e define.Exporterable, i int) error {
return e.Export(ce.Marshalled[i])
},
)
} | exporters/chain.go | 0.580114 | 0.471649 | chain.go | starcoder |
package dmc
type DefColor struct {
ColorName string
Floss string
Hex string
R string
G string
B string
}
type DmcColors struct {
ColorBank []DefColor
HexMap map[string]string
}
var colorBank []DefColor
func fillColorBank() *DmcColors {
// v2 will implement a webscraper to scrape these values from threadcolors.com instead
colorBank = []DefColor{
{ColorName: "Salmon Very Light", Floss: "3713", Hex: "#ffe2e2", R: "255", G: "226", B: "226"},
{ColorName: "Salmon Light", Floss: "761", Hex: "#ffc9c9", R: "255", G: "201", B: "201"},
{ColorName: "Salmon", Floss: "760", Hex: "#f5adad", R: "245", G: "173", B: "173"},
{ColorName: "Salmon Medium", Floss: "3712", Hex: "#f18787", R: "241", G: "135", B: "135"},
{ColorName: "Salmon Dark", Floss: "3328", Hex: "#e36d6d", R: "227", G: "109", B: "109"},
{ColorName: "Salmon Very Dark", Floss: "347", Hex: "#bf2d2d", R: "191", G: "45", B: "45"},
{ColorName: "Peach", Floss: "353", Hex: "#fed7cc", R: "254", G: "215", B: "204"},
{ColorName: "Coral Light", Floss: "352", Hex: "#fd9c97", R: "253", G: "156", B: "151"},
{ColorName: "Coral", Floss: "351", Hex: "#e96a67", R: "233", G: "106", B: "103"},
{ColorName: "Coral Medium", Floss: "350", Hex: "#e04848", R: "224", G: "72", B: "72"},
{ColorName: "Coral Dark", Floss: "349", Hex: "#d21035", R: "210", G: "16", B: "53"},
{ColorName: "Coral Red Very Dark", Floss: "817", Hex: "#bb051f", R: "187", G: "5", B: "31"},
{ColorName: "Melon Light", Floss: "3708", Hex: "#ffcbd5", R: "255", G: "203", B: "213"},
{ColorName: "Melon Medium", Floss: "3706", Hex: "#ffadbc", R: "255", G: "173", B: "188"},
{ColorName: "Melon Dark", Floss: "3705", Hex: "#ff7992", R: "255", G: "121", B: "146"},
{ColorName: "Melon Very Dark", Floss: "3801", Hex: "#e74967", R: "231", G: "73", B: "103"},
{ColorName: "Bright Red", Floss: "666", Hex: "#e31d42", R: "227", G: "29", B: "66"},
{ColorName: "Red", Floss: "321", Hex: "#c72b3b", R: "199", G: "43", B: "59"},
{ColorName: "Red Medium", Floss: "304", Hex: "#b71f33", R: "183", G: "31", B: "51"},
{ColorName: "Red Dark", Floss: "498", Hex: "#a7132b", R: "167", G: "19", B: "43"},
{ColorName: "Garnet", Floss: "816", Hex: "#970b23", R: "151", G: "11", B: "35"},
{ColorName: "Garnet Medium", Floss: "815", Hex: "#87071f", R: "135", G: "7", B: "31"},
{ColorName: "Garnet Dark", Floss: "814", Hex: "#7b001b", R: "123", G: "0", B: "27"},
{ColorName: "Carnation Very Light", Floss: "894", Hex: "#ffb2bb", R: "255", G: "178", B: "187"},
{ColorName: "Carnation Light", Floss: "893", Hex: "#fc90a2", R: "252", G: "144", B: "162"},
{ColorName: "Carnation Medium", Floss: "892", Hex: "#ff798c", R: "255", G: "121", B: "140"},
{ColorName: "Carnation Dark", Floss: "891", Hex: "#ff5773", R: "255", G: "87", B: "115"},
{ColorName: "Baby Pink", Floss: "818", Hex: "#ffdfd9", R: "255", G: "223", B: "217"},
{ColorName: "Geranium Pale", Floss: "957", Hex: "#fdb5b5", R: "253", G: "181", B: "181"},
{ColorName: "Geranium", Floss: "956", Hex: "#ff9191", R: "255", G: "145", B: "145"},
{ColorName: "Rose Dark", Floss: "309", Hex: "#d62b5b", R: "214", G: "43", B: "91"},
{ColorName: "Dusty Rose Ult Vy Lt", Floss: "963", Hex: "#ffd7d7", R: "255", G: "215", B: "215"},
{ColorName: "Dusty Rose Med Vy Lt", Floss: "3716", Hex: "#ffbdbd", R: "255", G: "189", B: "189"},
{ColorName: "Dusty Rose Medium", Floss: "962", Hex: "#e68a8a", R: "230", G: "138", B: "138"},
{ColorName: "Dusty Rose Dark", Floss: "961", Hex: "#cf7373", R: "207", G: "115", B: "115"},
{ColorName: "Raspberry Light", Floss: "3833", Hex: "#ea8699", R: "234", G: "134", B: "153"},
{ColorName: "Raspberry Medium", Floss: "3832", Hex: "#db556e", R: "219", G: "85", B: "110"},
{ColorName: "Raspberry Dark", Floss: "3831", Hex: "#b32f48", R: "179", G: "47", B: "72"},
{ColorName: "Raspberry Very Dark", Floss: "777", Hex: "#913546", R: "145", G: "53", B: "70"},
{ColorName: "Baby Pink Light", Floss: "819", Hex: "#ffeeeb", R: "255", G: "238", B: "235"},
{ColorName: "Rose Light", Floss: "3326", Hex: "#fbadb4", R: "251", G: "173", B: "180"},
{ColorName: "Pink Medium", Floss: "776", Hex: "#fcb0b9", R: "252", G: "176", B: "185"},
{ColorName: "Rose Medium", Floss: "899", Hex: "#f27688", R: "242", G: "118", B: "136"},
{ColorName: "Rose", Floss: "335", Hex: "#ee546e", R: "238", G: "84", B: "110"},
{ColorName: "Rose Very Dark", Floss: "326", Hex: "#b33b4b", R: "179", G: "59", B: "75"},
{ColorName: "<NAME>", Floss: "151", Hex: "#f0ced4", R: "240", G: "206", B: "212"},
{ColorName: "<NAME>", Floss: "3354", Hex: "#e4a6ac", R: "228", G: "166", B: "172"},
{ColorName: "<NAME>", Floss: "3733", Hex: "#e8879b", R: "232", G: "135", B: "155"},
{ColorName: "Dusty Rose Very Dark", Floss: "3731", Hex: "#da6783", R: "218", G: "103", B: "131"},
{ColorName: "Dusty Rose Ultra Dark", Floss: "3350", Hex: "#bc4365", R: "188", G: "67", B: "101"},
{ColorName: "Dusty Rose Ult Vy Dk", Floss: "150", Hex: "#ab0249", R: "171", G: "2", B: "73"},
{ColorName: "Mauve Light", Floss: "3689", Hex: "#fbbfc2", R: "251", G: "191", B: "194"},
{ColorName: "Mauve Medium", Floss: "3688", Hex: "#e7a9ac", R: "231", G: "169", B: "172"},
{ColorName: "Mauve", Floss: "3687", Hex: "#c96b70", R: "201", G: "107", B: "112"},
{ColorName: "Mauve Dark", Floss: "3803", Hex: "#ab3357", R: "171", G: "51", B: "87"},
{ColorName: "Mauve Very Dark", Floss: "3685", Hex: "#881531", R: "136", G: "21", B: "49"},
{ColorName: "Cranberry Very Light", Floss: "605", Hex: "#ffc0cd", R: "255", G: "192", B: "205"},
{ColorName: "Cranberry Light", Floss: "604", Hex: "#ffb0be", R: "255", G: "176", B: "190"},
{ColorName: "Cranberry", Floss: "603", Hex: "#ffa4be", R: "255", G: "164", B: "190"},
{ColorName: "Cranberry Medium", Floss: "602", Hex: "#e24874", R: "226", G: "72", B: "116"},
{ColorName: "Cranberry Dark", Floss: "601", Hex: "#d1286a", R: "209", G: "40", B: "106"},
{ColorName: "Cranberry Very Dark", Floss: "600", Hex: "#cd2f63", R: "205", G: "47", B: "99"},
{ColorName: "Cyclamen Pink Light", Floss: "3806", Hex: "#ff8cae", R: "255", G: "140", B: "174"},
{ColorName: "Cyclamen Pink", Floss: "3805", Hex: "#f3478b", R: "243", G: "71", B: "139"},
{ColorName: "Cyclamen Pink Dark", Floss: "3804", Hex: "#e02876", R: "224", G: "40", B: "118"},
{ColorName: "Plum Ultra Light", Floss: "3609", Hex: "#f4aed5", R: "244", G: "174", B: "213"},
{ColorName: "Plum Very Light", Floss: "3608", Hex: "#ea9cc4", R: "234", G: "156", B: "196"},
{ColorName: "Plum Light", Floss: "3607", Hex: "#c54989", R: "197", G: "73", B: "137"},
{ColorName: "Plum", Floss: "718", Hex: "#9c2462", R: "156", G: "36", B: "98"},
{ColorName: "Plum Medium", Floss: "917", Hex: "#9b1359", R: "155", G: "19", B: "89"},
{ColorName: "Plum Dark", Floss: "915", Hex: "#820043", R: "130", G: "0", B: "67"},
{ColorName: "Shell Pink Ult Vy Lt", Floss: "225", Hex: "#ffdfd5", R: "255", G: "223", B: "213"},
{ColorName: "Shell Pink Very Light", Floss: "224", Hex: "#ebb7af", R: "235", G: "183", B: "175"},
{ColorName: "Shell Pink Med Light", Floss: "152", Hex: "#e2a099", R: "226", G: "160", B: "153"},
{ColorName: "Shell Pink Light", Floss: "223", Hex: "#cc847c", R: "204", G: "132", B: "124"},
{ColorName: "Shell Pink Med", Floss: "3722", Hex: "#bc6c64", R: "188", G: "108", B: "100"},
{ColorName: "Shell Pink Dark", Floss: "3721", Hex: "#a14b51", R: "161", G: "75", B: "81"},
{ColorName: "Shell Pink Vy Dk", Floss: "221", Hex: "#883e43", R: "136", G: "62", B: "67"},
{ColorName: "Antique Mauve Vy Lt", Floss: "778", Hex: "#dfb3bb", R: "223", G: "179", B: "187"},
{ColorName: "Antique Mauve Light", Floss: "3727", Hex: "#dba9b2", R: "219", G: "169", B: "178"},
{ColorName: "Antique Mauve Med", Floss: "316", Hex: "#b7737f", R: "183", G: "115", B: "127"},
{ColorName: "Antique Mauve Dark", Floss: "3726", Hex: "#9b5b66", R: "155", G: "91", B: "102"},
{ColorName: "Antique Mauve Md Dk", Floss: "315", Hex: "#814952", R: "129", G: "73", B: "82"},
{ColorName: "Antique Mauve Vy Dk", Floss: "3802", Hex: "#714149", R: "113", G: "65", B: "73"},
{ColorName: "Garnet Very Dark", Floss: "902", Hex: "#822637", R: "130", G: "38", B: "55"},
{ColorName: "Antique Violet Vy Lt", Floss: "3743", Hex: "#d7cbd3", R: "215", G: "203", B: "211"},
{ColorName: "Antique Violet Light", Floss: "3042", Hex: "#b79da7", R: "183", G: "157", B: "167"},
{ColorName: "Antique Violet Medium", Floss: "3041", Hex: "#956f7c", R: "149", G: "111", B: "124"},
{ColorName: "Antique Violet Dark", Floss: "3740", Hex: "#785762", R: "120", G: "87", B: "98"},
{ColorName: "Grape Light", Floss: "3836", Hex: "#ba91aa", R: "186", G: "145", B: "170"},
{ColorName: "Grape Medium", Floss: "3835", Hex: "#946083", R: "148", G: "96", B: "131"},
{ColorName: "Grape Dark", Floss: "3834", Hex: "#72375d", R: "114", G: "55", B: "93"},
{ColorName: "Grape Very Dark", Floss: "154", Hex: "#572433", R: "87", G: "36", B: "51"},
{ColorName: "Lavender Light", Floss: "211", Hex: "#e3cbe3", R: "227", G: "203", B: "227"},
{ColorName: "Lavender Medium", Floss: "210", Hex: "#c39fc3", R: "195", G: "159", B: "195"},
{ColorName: "Lavender Dark", Floss: "209", Hex: "#a37ba7", R: "163", G: "123", B: "167"},
{ColorName: "Lavender Very Dark", Floss: "208", Hex: "#835b8b", R: "131", G: "91", B: "139"},
{ColorName: "Lavender Ultra Dark", Floss: "3837", Hex: "#6c3a6e", R: "108", G: "58", B: "110"},
{ColorName: "Violet Dark", Floss: "327", Hex: "#633666", R: "99", G: "54", B: "102"},
{ColorName: "Violet Very Light", Floss: "153", Hex: "#e6ccd9", R: "230", G: "204", B: "217"},
{ColorName: "Violet Light", Floss: "554", Hex: "#dbb3cb", R: "219", G: "179", B: "203"},
{ColorName: "Violet", Floss: "553", Hex: "#a3638b", R: "163", G: "99", B: "139"},
{ColorName: "Violet Medium", Floss: "552", Hex: "#803a6b", R: "128", G: "58", B: "107"},
{ColorName: "Violet Very Dark", Floss: "550", Hex: "#5c184e", R: "92", G: "24", B: "78"},
{ColorName: "Blue Violet Vy Lt", Floss: "3747", Hex: "#d3d7ed", R: "211", G: "215", B: "237"},
{ColorName: "Blue Violet Light", Floss: "341", Hex: "#b7bfdd", R: "183", G: "191", B: "221"},
{ColorName: "Blue Violet Med Lt", Floss: "156", Hex: "#a3aed1", R: "163", G: "174", B: "209"},
{ColorName: "Blue Violet Medium", Floss: "340", Hex: "#ada7c7", R: "173", G: "167", B: "199"},
{ColorName: "Blue Violet Med Dark", Floss: "155", Hex: "#9891b6", R: "152", G: "145", B: "182"},
{ColorName: "Blue Violet Dark", Floss: "3746", Hex: "#776b98", R: "119", G: "107", B: "152"},
{ColorName: "Blue Violet Very Dark", Floss: "333", Hex: "#5c5478", R: "92", G: "84", B: "120"},
{ColorName: "Cornflower Blue Vy Lt", Floss: "157", Hex: "#bbc3d9", R: "187", G: "195", B: "217"},
{ColorName: "Cornflower Blue Light", Floss: "794", Hex: "#8f9cc1", R: "143", G: "156", B: "193"},
{ColorName: "Cornflower Blue Med", Floss: "793", Hex: "#707da2", R: "112", G: "125", B: "162"},
{ColorName: "Cornflower Blue", Floss: "3807", Hex: "#60678c", R: "96", G: "103", B: "140"},
{ColorName: "Cornflower Blue Dark", Floss: "792", Hex: "#555b7b", R: "85", G: "91", B: "123"},
{ColorName: "Cornflower Blu M V D", Floss: "158", Hex: "#4c526e", R: "76", G: "82", B: "110"},
{ColorName: "Cornflower Blue V D", Floss: "791", Hex: "#464563", R: "70", G: "69", B: "99"},
{ColorName: "Lavender Blue Light", Floss: "3840", Hex: "#b0c0da", R: "176", G: "192", B: "218"},
{ColorName: "Lavender Blue Med", Floss: "3839", Hex: "#7b8eab", R: "123", G: "142", B: "171"},
{ColorName: "Lavender Blue Dark", Floss: "3838", Hex: "#5c7294", R: "92", G: "114", B: "148"},
{ColorName: "Delft Blue Pale", Floss: "800", Hex: "#c0ccde", R: "192", G: "204", B: "222"},
{ColorName: "Delft Blue", Floss: "809", Hex: "#94a8c6", R: "148", G: "168", B: "198"},
{ColorName: "Delft Blue Medium", Floss: "799", Hex: "#748eb6", R: "116", G: "142", B: "182"},
{ColorName: "Delft Blue Dark", Floss: "798", Hex: "#466a8e", R: "70", G: "106", B: "142"},
{ColorName: "Royal Blue", Floss: "797", Hex: "#13477d", R: "19", G: "71", B: "125"},
{ColorName: "Royal Blue Dark", Floss: "796", Hex: "#11416d", R: "17", G: "65", B: "109"},
{ColorName: "Royal Blue Very Dark", Floss: "820", Hex: "#0e365c", R: "14", G: "54", B: "92"},
{ColorName: "Blue Ultra Very Light", Floss: "162", Hex: "#dbecf5", R: "219", G: "236", B: "245"},
{ColorName: "Blue Very Light", Floss: "827", Hex: "#bddded", R: "189", G: "221", B: "237"},
{ColorName: "Blue Light", Floss: "813", Hex: "#a1c2d7", R: "161", G: "194", B: "215"},
{ColorName: "Blue Medium", Floss: "826", Hex: "#6b9ebf", R: "107", G: "158", B: "191"},
{ColorName: "Blue Dark", Floss: "825", Hex: "#4781a5", R: "71", G: "129", B: "165"},
{ColorName: "Blue Very Dark", Floss: "824", Hex: "#396987", R: "57", G: "105", B: "135"},
{ColorName: "Electric Blue Medium", Floss: "996", Hex: "#30c2ec", R: "48", G: "194", B: "236"},
{ColorName: "Electric Blue", Floss: "3843", Hex: "#14aad0", R: "20", G: "170", B: "208"},
{ColorName: "Electric Blue Dark", Floss: "995", Hex: "#2696b6", R: "38", G: "150", B: "182"},
{ColorName: "Turquoise Bright Light", Floss: "3846", Hex: "#06e3e6", R: "6", G: "227", B: "230"},
{ColorName: "Turquoise Bright Med", Floss: "3845", Hex: "#04c4ca", R: "4", G: "196", B: "202"},
{ColorName: "Turquoise Bright Dark", Floss: "3844", Hex: "#12aeba", R: "18", G: "174", B: "186"},
{ColorName: "Blue Gray Light", Floss: "159", Hex: "#c7cad7", R: "199", G: "202", B: "215"},
{ColorName: "Blue Gray Medium", Floss: "160", Hex: "#999fb7", R: "153", G: "159", B: "183"},
{ColorName: "Blue Gray", Floss: "161", Hex: "#7880a4", R: "120", G: "128", B: "164"},
{ColorName: "Baby Blue Ult Vy Lt", Floss: "3756", Hex: "#eefcfc", R: "238", G: "252", B: "252"},
{ColorName: "Baby Blue Very Light", Floss: "775", Hex: "#d9ebf1", R: "217", G: "235", B: "241"},
{ColorName: "Baby Blue Pale", Floss: "3841", Hex: "#cddfed", R: "205", G: "223", B: "237"},
{ColorName: "Baby Blue Light", Floss: "3325", Hex: "#b8d2e6", R: "184", G: "210", B: "230"},
{ColorName: "Baby Blue", Floss: "3755", Hex: "#93b4ce", R: "147", G: "180", B: "206"},
{ColorName: "Baby Blue Medium", Floss: "334", Hex: "#739fc1", R: "115", G: "159", B: "193"},
{ColorName: "Baby Blue Dark", Floss: "322", Hex: "#5a8fb8", R: "90", G: "143", B: "184"},
{ColorName: "Baby Blue Very Dark", Floss: "312", Hex: "#35668b", R: "53", G: "102", B: "139"},
{ColorName: "Baby Blue Ult Vy Dk", Floss: "803", Hex: "#2c597c", R: "44", G: "89", B: "124"},
{ColorName: "Navy Blue", Floss: "336", Hex: "#253b73", R: "37", G: "59", B: "115"},
{ColorName: "Navy Blue Dark", Floss: "823", Hex: "#213063", R: "33", G: "48", B: "99"},
{ColorName: "Navy Blue Very Dark", Floss: "939", Hex: "#1b2853", R: "27", G: "40", B: "83"},
{ColorName: "Antique Blue Ult Vy Lt", Floss: "3753", Hex: "#dbe2e9", R: "219", G: "226", B: "233"},
{ColorName: "Antique Blue Very Lt", Floss: "3752", Hex: "#c7d1db", R: "199", G: "209", B: "219"},
{ColorName: "Antique Blue Light", Floss: "932", Hex: "#a2b5c6", R: "162", G: "181", B: "198"},
{ColorName: "Antique Blue Medium", Floss: "931", Hex: "#6a859e", R: "106", G: "133", B: "158"},
{ColorName: "Antique Blue Dark", Floss: "930", Hex: "#455c71", R: "69", G: "92", B: "113"},
{ColorName: "Antique Blue Very Dk", Floss: "3750", Hex: "#384c5e", R: "56", G: "76", B: "94"},
{ColorName: "Sky Blue Vy Lt", Floss: "828", Hex: "#c5e8ed", R: "197", G: "232", B: "237"},
{ColorName: "Sky Blue Light", Floss: "3761", Hex: "#acd8e2", R: "172", G: "216", B: "226"},
{ColorName: "Sky Blue", Floss: "519", Hex: "#7eb1c8", R: "126", G: "177", B: "200"},
{ColorName: "Wedgewood Light", Floss: "518", Hex: "#4f93a7", R: "79", G: "147", B: "167"},
{ColorName: "Wedgewood Med", Floss: "3760", Hex: "#3e85a2", R: "62", G: "133", B: "162"},
{ColorName: "Wedgewood Dark", Floss: "517", Hex: "#3b768f", R: "59", G: "118", B: "143"},
{ColorName: "Wedgewood Vry Dk", Floss: "3842", Hex: "#32667c", R: "50", G: "102", B: "124"},
{ColorName: "Wedgewood Ult VyDk", Floss: "311", Hex: "#1c5066", R: "28", G: "80", B: "102"},
{ColorName: "Peacock Blue Vy Lt", Floss: "747", Hex: "#e5fcfd", R: "229", G: "252", B: "253"},
{ColorName: "Peacock Blue Light", Floss: "3766", Hex: "#99cfd9", R: "153", G: "207", B: "217"},
{ColorName: "Peacock Blue", Floss: "807", Hex: "#64abba", R: "100", G: "171", B: "186"},
{ColorName: "Peacock Blue Dark", Floss: "806", Hex: "#3d95a5", R: "61", G: "149", B: "165"},
{ColorName: "Peacock Blue Vy Dk", Floss: "3765", Hex: "#347f8c", R: "52", G: "127", B: "140"},
{ColorName: "Turquoise Very Light", Floss: "3811", Hex: "#bce3e6", R: "188", G: "227", B: "230"},
{ColorName: "Turquoise Light", Floss: "598", Hex: "#90c3cc", R: "144", G: "195", B: "204"},
{ColorName: "Turquoise", Floss: "597", Hex: "#5ba3b3", R: "91", G: "163", B: "179"},
{ColorName: "Turquoise Dark", Floss: "3810", Hex: "#488e9a", R: "72", G: "142", B: "154"},
{ColorName: "Turquoise Vy Dark", Floss: "3809", Hex: "#3f7c85", R: "63", G: "124", B: "133"},
{ColorName: "Turquoise Ult Vy Dk", Floss: "3808", Hex: "#366970", R: "54", G: "105", B: "112"},
{ColorName: "Gray Green Vy Lt", Floss: "928", Hex: "#dde3e3", R: "221", G: "227", B: "227"},
{ColorName: "Gray Green Light", Floss: "927", Hex: "#bdcbcb", R: "189", G: "203", B: "203"},
{ColorName: "Gray Green Med", Floss: "926", Hex: "#98aeae", R: "152", G: "174", B: "174"},
{ColorName: "Gray Green Dark", Floss: "3768", Hex: "#657f7f", R: "101", G: "127", B: "127"},
{ColorName: "Gray Green Vy Dark", Floss: "924", Hex: "#566a6a", R: "86", G: "106", B: "106"},
{ColorName: "Teal Green Light", Floss: "3849", Hex: "#52b3a4", R: "82", G: "179", B: "164"},
{ColorName: "Teal Green Med", Floss: "3848", Hex: "#559392", R: "85", G: "147", B: "146"},
{ColorName: "Teal Green Dark", Floss: "3847", Hex: "#347d75", R: "52", G: "125", B: "117"},
{ColorName: "Sea Green Light", Floss: "964", Hex: "#a9e2d8", R: "169", G: "226", B: "216"},
{ColorName: "Sea Green Med", Floss: "959", Hex: "#59c7b4", R: "89", G: "199", B: "180"},
{ColorName: "Sea Green Dark", Floss: "958", Hex: "#3eb6a1", R: "62", G: "182", B: "161"},
{ColorName: "Sea Green Vy Dk", Floss: "3812", Hex: "#2f8c84", R: "47", G: "140", B: "132"},
{ColorName: "Green Bright Lt", Floss: "3851", Hex: "#49b3a1", R: "73", G: "179", B: "161"},
{ColorName: "Green Bright Md", Floss: "943", Hex: "#3d9384", R: "61", G: "147", B: "132"},
{ColorName: "Green Bright Dk", Floss: "3850", Hex: "#378477", R: "55", G: "132", B: "119"},
{ColorName: "Aquamarine Vy Lt", Floss: "993", Hex: "#90c0b4", R: "144", G: "192", B: "180"},
{ColorName: "Aquamarine Lt", Floss: "992", Hex: "#6fae9f", R: "111", G: "174", B: "159"},
{ColorName: "Aquamarine", Floss: "3814", Hex: "#508b7d", R: "80", G: "139", B: "125"},
{ColorName: "Aquamarine Dk", Floss: "991", Hex: "#477b6e", R: "71", G: "123", B: "110"},
{ColorName: "Jade Ultra Vy Lt", Floss: "966", Hex: "#b9d7c0", R: "185", G: "215", B: "192"},
{ColorName: "Jade Very Light", Floss: "564", Hex: "#a7cdaf", R: "167", G: "205", B: "175"},
{ColorName: "Jade Light", Floss: "563", Hex: "#8fc098", R: "143", G: "192", B: "152"},
{ColorName: "Jade Medium", Floss: "562", Hex: "#53976a", R: "83", G: "151", B: "106"},
{ColorName: "Jade Green", Floss: "505", Hex: "#338362", R: "51", G: "131", B: "98"},
{ColorName: "Celadon Green Lt", Floss: "3817", Hex: "#99c3aa", R: "153", G: "195", B: "170"},
{ColorName: "Celadon Green", Floss: "3816", Hex: "#65a57d", R: "101", G: "165", B: "125"},
{ColorName: "Celadon Green Md", Floss: "163", Hex: "#4d8361", R: "77", G: "131", B: "97"},
{ColorName: "Celadon Green Dk", Floss: "3815", Hex: "#477759", R: "71", G: "119", B: "89"},
{ColorName: "Celadon Green VD", Floss: "561", Hex: "#2c6a45", R: "44", G: "106", B: "69"},
{ColorName: "Blue Green Vy Lt", Floss: "504", Hex: "#c4decc", R: "196", G: "222", B: "204"},
{ColorName: "Blue Green Lt", Floss: "3813", Hex: "#b2d4bd", R: "178", G: "212", B: "189"},
{ColorName: "Blue Green Med", Floss: "503", Hex: "#7bac94", R: "123", G: "172", B: "148"},
{ColorName: "Blue Green", Floss: "502", Hex: "#5b9071", R: "91", G: "144", B: "113"},
{ColorName: "Blue Green Dark", Floss: "501", Hex: "#396f52", R: "57", G: "111", B: "82"},
{ColorName: "Blue Green Vy Dk", Floss: "500", Hex: "#044d33", R: "4", G: "77", B: "51"},
{ColorName: "Nile Green Light", Floss: "955", Hex: "#a2d6ad", R: "162", G: "214", B: "173"},
{ColorName: "Nile Green", Floss: "954", Hex: "#88ba91", R: "136", G: "186", B: "145"},
{ColorName: "Nile Green Med", Floss: "913", Hex: "#6dab77", R: "109", G: "171", B: "119"},
{ColorName: "Emerald Green Lt", Floss: "912", Hex: "#1b9d6b", R: "27", G: "157", B: "107"},
{ColorName: "Emerald Green Med", Floss: "911", Hex: "#189065", R: "24", G: "144", B: "101"},
{ColorName: "Emerald Green Dark", Floss: "910", Hex: "#187e56", R: "24", G: "126", B: "86"},
{ColorName: "Emerald Green Vy Dk", Floss: "909", Hex: "#156f49", R: "21", G: "111", B: "73"},
{ColorName: "Emerald Grn Ult V Dk", Floss: "3818", Hex: "#115a3b", R: "17", G: "90", B: "59"},
{ColorName: "Pistachio Green Vy Lt", Floss: "369", Hex: "#d7edcc", R: "215", G: "237", B: "204"},
{ColorName: "Pistachio Green Lt", Floss: "368", Hex: "#a6c298", R: "166", G: "194", B: "152"},
{ColorName: "Pistachio Green Med", Floss: "320", Hex: "#69885a", R: "105", G: "136", B: "90"},
{ColorName: "Pistachio Green Dk", Floss: "367", Hex: "#617a52", R: "97", G: "122", B: "82"},
{ColorName: "Pistachio Grn Vy Dk", Floss: "319", Hex: "#205f2e", R: "32", G: "95", B: "46"},
{ColorName: "Pistachio Grn Ult V D", Floss: "890", Hex: "#174923", R: "23", G: "73", B: "35"},
{ColorName: "Forest Green Lt", Floss: "164", Hex: "#c8d8b8", R: "200", G: "216", B: "184"},
{ColorName: "Forest Green", Floss: "989", Hex: "#8da675", R: "141", G: "166", B: "117"},
{ColorName: "Forest Green Med", Floss: "988", Hex: "#738b5b", R: "115", G: "139", B: "91"},
{ColorName: "Forest Green Dk", Floss: "987", Hex: "#587141", R: "88", G: "113", B: "65"},
{ColorName: "Forest Green Vy Dk", Floss: "986", Hex: "#405230", R: "64", G: "82", B: "48"},
{ColorName: "Yellow Green Vy Lt", Floss: "772", Hex: "#e4ecd4", R: "228", G: "236", B: "212"},
{ColorName: "Yellow Green Lt", Floss: "3348", Hex: "#ccd9b1", R: "204", G: "217", B: "177"},
{ColorName: "Yellow Green Med", Floss: "3347", Hex: "#71935c", R: "113", G: "147", B: "92"},
{ColorName: "Hunter Green", Floss: "3346", Hex: "#406a3a", R: "64", G: "106", B: "58"},
{ColorName: "Hunter Green Dk", Floss: "3345", Hex: "#1b5915", R: "27", G: "89", B: "21"},
{ColorName: "Hunter Green Vy Dk", Floss: "895", Hex: "#1b5300", R: "27", G: "83", B: "0"},
{ColorName: "<NAME>", Floss: "704", Hex: "#9ecf34", R: "158", G: "207", B: "52"},
{ColorName: "Chartreuse", Floss: "703", Hex: "#7bb547", R: "123", G: "181", B: "71"},
{ColorName: "<NAME>", Floss: "702", Hex: "#47a72f", R: "71", G: "167", B: "47"},
{ColorName: "Green Light", Floss: "701", Hex: "#3f8f29", R: "63", G: "143", B: "41"},
{ColorName: "Green Bright", Floss: "700", Hex: "#07731b", R: "7", G: "115", B: "27"},
{ColorName: "Green", Floss: "699", Hex: "#056517", R: "5", G: "101", B: "23"},
{ColorName: "Parrot Green Lt", Floss: "907", Hex: "#c7e666", R: "199", G: "230", B: "102"},
{ColorName: "Parrot Green Md", Floss: "906", Hex: "#7fb335", R: "127", G: "179", B: "53"},
{ColorName: "Parrot Green Dk", Floss: "905", Hex: "#628a28", R: "98", G: "138", B: "40"},
{ColorName: "Parrot Green V Dk", Floss: "904", Hex: "#557822", R: "85", G: "120", B: "34"},
{ColorName: "Avocado Grn U Lt", Floss: "472", Hex: "#d8e498", R: "216", G: "228", B: "152"},
{ColorName: "Avocado Grn V Lt", Floss: "471", Hex: "#aebf79", R: "174", G: "191", B: "121"},
{ColorName: "Avocado Grn Lt", Floss: "470", Hex: "#94ab4f", R: "148", G: "171", B: "79"},
{ColorName: "Avocado Green", Floss: "469", Hex: "#72843c", R: "114", G: "132", B: "60"},
{ColorName: "Avocado Green Md", Floss: "937", Hex: "#627133", R: "98", G: "113", B: "51"},
{ColorName: "Avocado Grn V Dk", Floss: "936", Hex: "#4c5826", R: "76", G: "88", B: "38"},
{ColorName: "Avocado Green Dk", Floss: "935", Hex: "#424d21", R: "66", G: "77", B: "33"},
{ColorName: "Avocado Grn Black", Floss: "934", Hex: "#313919", R: "49", G: "57", B: "25"},
{ColorName: "Fern Green Lt", Floss: "523", Hex: "#abb197", R: "171", G: "177", B: "151"},
{ColorName: "Green Gray", Floss: "3053", Hex: "#9ca482", R: "156", G: "164", B: "130"},
{ColorName: "Green Gray Md", Floss: "3052", Hex: "#889268", R: "136", G: "146", B: "104"},
{ColorName: "Green Gray Dk", Floss: "3051", Hex: "#5f6648", R: "95", G: "102", B: "72"},
{ColorName: "Fern Green Vy Lt", Floss: "524", Hex: "#c4cdac", R: "196", G: "205", B: "172"},
{ColorName: "Fern Green", Floss: "522", Hex: "#969e7e", R: "150", G: "158", B: "126"},
{ColorName: "Fern Green Dark", Floss: "520", Hex: "#666d4f", R: "102", G: "109", B: "79"},
{ColorName: "Pine Green", Floss: "3364", Hex: "#83975f", R: "131", G: "151", B: "95"},
{ColorName: "Pine Green Md", Floss: "3363", Hex: "#728256", R: "114", G: "130", B: "86"},
{ColorName: "Pine Green Dk", Floss: "3362", Hex: "#5e6b47", R: "94", G: "107", B: "71"},
{ColorName: "Moss Green Vy Lt", Floss: "165", Hex: "#eff4a4", R: "239", G: "244", B: "164"},
{ColorName: "Moss Green Lt", Floss: "3819", Hex: "#e0e868", R: "224", G: "232", B: "104"},
{ColorName: "Moss Green Md Lt", Floss: "166", Hex: "#c0c840", R: "192", G: "200", B: "64"},
{ColorName: "Moss Green", Floss: "581", Hex: "#a7ae38", R: "167", G: "174", B: "56"},
{ColorName: "Moss Green Dk", Floss: "580", Hex: "#888d33", R: "136", G: "141", B: "51"},
{ColorName: "Olive Green Lt", Floss: "734", Hex: "#c7c077", R: "199", G: "192", B: "119"},
{ColorName: "Olive Green Md", Floss: "733", Hex: "#bcb34c", R: "188", G: "179", B: "76"},
{ColorName: "Olive Green", Floss: "732", Hex: "#948c36", R: "148", G: "140", B: "54"},
{ColorName: "Olive Green Dk", Floss: "731", Hex: "#938b37", R: "147", G: "139", B: "55"},
{ColorName: "Olive Green V Dk", Floss: "730", Hex: "#827b30", R: "130", G: "123", B: "48"},
{ColorName: "Khaki Green Lt", Floss: "3013", Hex: "#b9b982", R: "185", G: "185", B: "130"},
{ColorName: "Khaki Green Md", Floss: "3012", Hex: "#a6a75d", R: "166", G: "167", B: "93"},
{ColorName: "Khaki Green Dk", Floss: "3011", Hex: "#898a58", R: "137", G: "138", B: "88"},
{ColorName: "Mustard Lt", Floss: "372", Hex: "#ccb784", R: "204", G: "183", B: "132"},
{ColorName: "Mustard", Floss: "371", Hex: "#bfa671", R: "191", G: "166", B: "113"},
{ColorName: "<NAME>", Floss: "370", Hex: "#b89d64", R: "184", G: "157", B: "100"},
{ColorName: "Golden Olive Vy Lt", Floss: "834", Hex: "#dbbe7f", R: "219", G: "190", B: "127"},
{ColorName: "Golden Olive Lt", Floss: "833", Hex: "#c8ab6c", R: "200", G: "171", B: "108"},
{ColorName: "Golden Olive", Floss: "832", Hex: "#bd9b51", R: "189", G: "155", B: "81"},
{ColorName: "Golden Olive Md", Floss: "831", Hex: "#aa8f56", R: "170", G: "143", B: "86"},
{ColorName: "Golden Olive Dk", Floss: "830", Hex: "#8d784b", R: "141", G: "120", B: "75"},
{ColorName: "Golden Olive Vy Dk", Floss: "829", Hex: "#7e6b42", R: "126", G: "107", B: "66"},
{ColorName: "Drab Brown V Lt", Floss: "613", Hex: "#dcc4aa", R: "220", G: "196", B: "170"},
{ColorName: "Drab Brown Lt", Floss: "612", Hex: "#bc9a78", R: "188", G: "154", B: "120"},
{ColorName: "<NAME>", Floss: "611", Hex: "#967656", R: "150", G: "118", B: "86"},
{ColorName: "<NAME> Dk", Floss: "610", Hex: "#796047", R: "121", G: "96", B: "71"},
{ColorName: "Yellow Beige Lt", Floss: "3047", Hex: "#e7d6c1", R: "231", G: "214", B: "193"},
{ColorName: "Yellow Beige Md", Floss: "3046", Hex: "#d8bc9a", R: "216", G: "188", B: "154"},
{ColorName: "Yellow Beige Dk", Floss: "3045", Hex: "#bc966a", R: "188", G: "150", B: "106"},
{ColorName: "Yellow Beige V Dk", Floss: "167", Hex: "#a77c49", R: "167", G: "124", B: "73"},
{ColorName: "Off White", Floss: "746", Hex: "#fcfcee", R: "252", G: "252", B: "238"},
{ColorName: "Old Gold Vy Lt", Floss: "677", Hex: "#f5eccb", R: "245", G: "236", B: "203"},
{ColorName: "Hazelnut Brown Lt", Floss: "422", Hex: "#c69f7b", R: "198", G: "159", B: "123"},
{ColorName: "Hazelnut Brown", Floss: "3828", Hex: "#b78b61", R: "183", G: "139", B: "97"},
{ColorName: "Hazelnut Brown Dk", Floss: "420", Hex: "#a07042", R: "160", G: "112", B: "66"},
{ColorName: "Hazelnut Brown V Dk", Floss: "869", Hex: "#835e39", R: "131", G: "94", B: "57"},
{ColorName: "Topaz", Floss: "728", Hex: "#e4b468", R: "228", G: "180", B: "104"},
{ColorName: "Topaz Medium", Floss: "783", Hex: "#ce9124", R: "206", G: "145", B: "36"},
{ColorName: "Topaz Dark", Floss: "782", Hex: "#ae7720", R: "174", G: "119", B: "32"},
{ColorName: "Topaz Very Dark", Floss: "781", Hex: "#a26d20", R: "162", G: "109", B: "32"},
{ColorName: "Topaz Ultra Vy Dk", Floss: "780", Hex: "#94631a", R: "148", G: "99", B: "26"},
{ColorName: "Old Gold Lt", Floss: "676", Hex: "#e5ce97", R: "229", G: "206", B: "151"},
{ColorName: "Old Gold Medium", Floss: "729", Hex: "#d0a53e", R: "208", G: "165", B: "62"},
{ColorName: "Old Gold Dark", Floss: "680", Hex: "#bc8d0e", R: "188", G: "141", B: "14"},
{ColorName: "Old Gold Vy Dark", Floss: "3829", Hex: "#a98204", R: "169", G: "130", B: "4"},
{ColorName: "Straw Light", Floss: "3822", Hex: "#f6dc98", R: "246", G: "220", B: "152"},
{ColorName: "Straw", Floss: "3821", Hex: "#f3ce75", R: "243", G: "206", B: "117"},
{ColorName: "Straw Dark", Floss: "3820", Hex: "#dfb65f", R: "223", G: "182", B: "95"},
{ColorName: "Straw Very Dark", Floss: "3852", Hex: "#cd9d37", R: "205", G: "157", B: "55"},
{ColorName: "Lemon Light", Floss: "445", Hex: "#fffb8b", R: "255", G: "251", B: "139"},
{ColorName: "Lemon", Floss: "307", Hex: "#fded54", R: "253", G: "237", B: "84"},
{ColorName: "Canary Bright", Floss: "973", Hex: "#ffe300", R: "255", G: "227", B: "0"},
{ColorName: "Lemon Dark", Floss: "444", Hex: "#ffd600", R: "255", G: "214", B: "0"},
{ColorName: "Golden Yellow Vy Lt", Floss: "3078", Hex: "#fdf9cd", R: "253", G: "249", B: "205"},
{ColorName: "Topaz Vy Lt", Floss: "727", Hex: "#fff1af", R: "255", G: "241", B: "175"},
{ColorName: "Topaz Light", Floss: "726", Hex: "#fdd755", R: "253", G: "215", B: "85"},
{ColorName: "Topaz Med Lt", Floss: "725", Hex: "#ffc840", R: "255", G: "200", B: "64"},
{ColorName: "Canary Deep", Floss: "972", Hex: "#ffb515", R: "255", G: "181", B: "21"},
{ColorName: "Yellow Pale Light", Floss: "745", Hex: "#ffe9ad", R: "255", G: "233", B: "173"},
{ColorName: "Yellow Pale", Floss: "744", Hex: "#ffe793", R: "255", G: "231", B: "147"},
{ColorName: "Yellow Med", Floss: "743", Hex: "#fed376", R: "254", G: "211", B: "118"},
{ColorName: "Tangerine Light", Floss: "742", Hex: "#ffbf57", R: "255", G: "191", B: "87"},
{ColorName: "Tangerine Med", Floss: "741", Hex: "#ffa32b", R: "255", G: "163", B: "43"},
{ColorName: "Tangerine", Floss: "740", Hex: "#ff8b00", R: "255", G: "139", B: "0"},
{ColorName: "Pumpkin Light", Floss: "970", Hex: "#f78b13", R: "247", G: "139", B: "19"},
{ColorName: "Pumpkin", Floss: "971", Hex: "#f67f00", R: "246", G: "127", B: "0"},
{ColorName: "Burnt Orange", Floss: "947", Hex: "#ff7b4d", R: "255", G: "123", B: "77"},
{ColorName: "Burnt Orange Med", Floss: "946", Hex: "#eb6307", R: "235", G: "99", B: "7"},
{ColorName: "Burnt Orange Dark", Floss: "900", Hex: "#d15807", R: "209", G: "88", B: "7"},
{ColorName: "Apricot Very Light", Floss: "967", Hex: "#ffded5", R: "255", G: "222", B: "213"},
{ColorName: "Apricot Light", Floss: "3824", Hex: "#fecdc2", R: "254", G: "205", B: "194"},
{ColorName: "Apricot", Floss: "3341", Hex: "#fcab98", R: "252", G: "171", B: "152"},
{ColorName: "Apricot Med", Floss: "3340", Hex: "#ff836f", R: "255", G: "131", B: "111"},
{ColorName: "Burnt Orange Bright", Floss: "608", Hex: "#fd5d35", R: "253", G: "93", B: "53"},
{ColorName: "Orange?Red Bright", Floss: "606", Hex: "#fa3203", R: "250", G: "50", B: "3"},
{ColorName: "Tawny Light", Floss: "951", Hex: "#ffe2cf", R: "255", G: "226", B: "207"},
{ColorName: "Mahogany Ult Vy Lt", Floss: "3856", Hex: "#ffd3b5", R: "255", G: "211", B: "181"},
{ColorName: "Orange Spice Light", Floss: "722", Hex: "#f7976f", R: "247", G: "151", B: "111"},
{ColorName: "Orange Spice Med", Floss: "721", Hex: "#f27842", R: "242", G: "120", B: "66"},
{ColorName: "Orange Spice Dark", Floss: "720", Hex: "#e55c1f", R: "229", G: "92", B: "31"},
{ColorName: "Pumpkin Pale", Floss: "3825", Hex: "#fdbd96", R: "253", G: "189", B: "150"},
{ColorName: "Copper Light", Floss: "922", Hex: "#e27323", R: "226", G: "115", B: "35"},
{ColorName: "Copper", Floss: "921", Hex: "#c66218", R: "198", G: "98", B: "24"},
{ColorName: "Copper Med", Floss: "920", Hex: "#ac5414", R: "172", G: "84", B: "20"},
{ColorName: "Red Copper", Floss: "919", Hex: "#a64510", R: "166", G: "69", B: "16"},
{ColorName: "Red Copper Dark", Floss: "918", Hex: "#82340a", R: "130", G: "52", B: "10"},
{ColorName: "<NAME>", Floss: "3770", Hex: "#ffeee3", R: "255", G: "238", B: "227"},
{ColorName: "Tawny", Floss: "945", Hex: "#fbd5bb", R: "251", G: "213", B: "187"},
{ColorName: "<NAME>", Floss: "402", Hex: "#f7a777", R: "247", G: "167", B: "119"},
{ColorName: "<NAME>", Floss: "3776", Hex: "#cf7939", R: "207", G: "121", B: "57"},
{ColorName: "<NAME>", Floss: "301", Hex: "#b35f2b", R: "179", G: "95", B: "43"},
{ColorName: "<NAME>", Floss: "400", Hex: "#8f430f", R: "143", G: "67", B: "15"},
{ColorName: "<NAME>", Floss: "300", Hex: "#6f2f00", R: "111", G: "47", B: "0"},
{ColorName: "Yellow Ultra Pale", Floss: "3823", Hex: "#fffde3", R: "255", G: "253", B: "227"},
{ColorName: "Autumn Gold Lt", Floss: "3855", Hex: "#fad396", R: "250", G: "211", B: "150"},
{ColorName: "Autumn Gold Med", Floss: "3854", Hex: "#f2af68", R: "242", G: "175", B: "104"},
{ColorName: "Autumn Gold Dk", Floss: "3853", Hex: "#f29746", R: "242", G: "151", B: "70"},
{ColorName: "<NAME> Pale", Floss: "3827", Hex: "#f7bb77", R: "247", G: "187", B: "119"},
{ColorName: "Golden Brown Light", Floss: "977", Hex: "#dc9c56", R: "220", G: "156", B: "86"},
{ColorName: "Golden Brown Med", Floss: "976", Hex: "#c28142", R: "194", G: "129", B: "66"},
{ColorName: "<NAME>", Floss: "3826", Hex: "#ad7239", R: "173", G: "114", B: "57"},
{ColorName: "Golden Brown Dk", Floss: "975", Hex: "#914f12", R: "145", G: "79", B: "18"},
{ColorName: "Peach Very Light", Floss: "948", Hex: "#fee7da", R: "254", G: "231", B: "218"},
{ColorName: "Peach Light", Floss: "754", Hex: "#f7cbbf", R: "247", G: "203", B: "191"},
{ColorName: "Terra Cotta Ult Vy Lt", Floss: "3771", Hex: "#f4bba9", R: "244", G: "187", B: "169"},
{ColorName: "Terra Cotta Vy Lt", Floss: "758", Hex: "#eeaa9b", R: "238", G: "170", B: "155"},
{ColorName: "Terra Cotta Light", Floss: "3778", Hex: "#d98978", R: "217", G: "137", B: "120"},
{ColorName: "Terra Cotta Med", Floss: "356", Hex: "#c56a5b", R: "197", G: "106", B: "91"},
{ColorName: "Terra Cotta", Floss: "3830", Hex: "#b95544", R: "185", G: "85", B: "68"},
{ColorName: "Terra Cotta Dark", Floss: "355", Hex: "#984436", R: "152", G: "68", B: "54"},
{ColorName: "Terra Cotta Vy Dk", Floss: "3777", Hex: "#863022", R: "134", G: "48", B: "34"},
{ColorName: "Rosewood Ult Vy Lt", Floss: "3779", Hex: "#f8cac8", R: "248", G: "202", B: "200"},
{ColorName: "Rosewood Light", Floss: "3859", Hex: "#ba8b7c", R: "186", G: "139", B: "124"},
{ColorName: "Rosewood Med", Floss: "3858", Hex: "#964a3f", R: "150", G: "74", B: "63"},
{ColorName: "Rosewood Dark", Floss: "3857", Hex: "#68251a", R: "104", G: "37", B: "26"},
{ColorName: "Desert Sand Vy Lt", Floss: "3774", Hex: "#f3e1d7", R: "243", G: "225", B: "215"},
{ColorName: "Desert Sand Light", Floss: "950", Hex: "#eed3c4", R: "238", G: "211", B: "196"},
{ColorName: "Desert Sand", Floss: "3064", Hex: "#c48e70", R: "196", G: "142", B: "112"},
{ColorName: "Desert Sand Med", Floss: "407", Hex: "#bb8161", R: "187", G: "129", B: "97"},
{ColorName: "Desert Sand Dark", Floss: "3773", Hex: "#b67552", R: "182", G: "117", B: "82"},
{ColorName: "Desert Sand Vy Dk", Floss: "3772", Hex: "#a06c50", R: "160", G: "108", B: "80"},
{ColorName: "Desert Sand Ult Vy Dk", Floss: "632", Hex: "#875539", R: "135", G: "85", B: "57"},
{ColorName: "Shell Gray Light", Floss: "453", Hex: "#d7cecb", R: "215", G: "206", B: "203"},
{ColorName: "Shell Gray Med", Floss: "452", Hex: "#c0b3ae", R: "192", G: "179", B: "174"},
{ColorName: "Shell Gray Dark", Floss: "451", Hex: "#917b73", R: "145", G: "123", B: "115"},
{ColorName: "Cocoa Light", Floss: "3861", Hex: "#a68881", R: "166", G: "136", B: "129"},
{ColorName: "Cocoa", Floss: "3860", Hex: "#7d5d57", R: "125", G: "93", B: "87"},
{ColorName: "Cocoa Dark", Floss: "779", Hex: "#624b45", R: "98", G: "75", B: "69"},
{ColorName: "Cream", Floss: "712", Hex: "#fffbef", R: "255", G: "251", B: "239"},
{ColorName: "Tan Ult Vy Lt", Floss: "739", Hex: "#f8e4c8", R: "248", G: "228", B: "200"},
{ColorName: "Tan Very Light", Floss: "738", Hex: "#eccc9e", R: "236", G: "204", B: "158"},
{ColorName: "Tan Light", Floss: "437", Hex: "#e4bb8e", R: "228", G: "187", B: "142"},
{ColorName: "Tan", Floss: "436", Hex: "#cb9051", R: "203", G: "144", B: "81"},
{ColorName: "Brown Very Light", Floss: "435", Hex: "#b87748", R: "184", G: "119", B: "72"},
{ColorName: "Brown Light", Floss: "434", Hex: "#985e33", R: "152", G: "94", B: "51"},
{ColorName: "Brown Med", Floss: "433", Hex: "#7a451f", R: "122", G: "69", B: "31"},
{ColorName: "Coffee Brown Dk", Floss: "801", Hex: "#653919", R: "101", G: "57", B: "25"},
{ColorName: "Coffee Brown Vy Dk", Floss: "898", Hex: "#492a13", R: "73", G: "42", B: "19"},
{ColorName: "Coffee Brown Ult Dk", Floss: "938", Hex: "#361f0e", R: "54", G: "31", B: "14"},
{ColorName: "Black Brown", Floss: "3371", Hex: "#1e1108", R: "30", G: "17", B: "8"},
{ColorName: "Beige Brown Ult Vy Lt", Floss: "543", Hex: "#f2e3ce", R: "242", G: "227", B: "206"},
{ColorName: "Mocha Beige Light", Floss: "3864", Hex: "#cbb69c", R: "203", G: "182", B: "156"},
{ColorName: "Mocha Beige Med", Floss: "3863", Hex: "#a4835c", R: "164", G: "131", B: "92"},
{ColorName: "Mocha Beige Dark", Floss: "3862", Hex: "#8a6e4e", R: "138", G: "110", B: "78"},
{ColorName: "Mocha Brown Vy Dk", Floss: "3031", Hex: "#4b3c2a", R: "75", G: "60", B: "42"},
{ColorName: "Snow White", Floss: "B5200", Hex: "#ffffff", R: "255", G: "255", B: "255"},
{ColorName: "White", Floss: "White", Hex: "#fcfbf8", R: "252", G: "251", B: "248"},
{ColorName: "Winter White", Floss: "3865", Hex: "#f9f7f1", R: "249", G: "247", B: "241"},
{ColorName: "Ecru", Floss: "Ecru", Hex: "#f0eada", R: "240", G: "234", B: "218"},
{ColorName: "Beige Gray Light", Floss: "822", Hex: "#e7e2d3", R: "231", G: "226", B: "211"},
{ColorName: "Beige Gray Med", Floss: "644", Hex: "#ddd8cb", R: "221", G: "216", B: "203"},
{ColorName: "Beige Gray Dark", Floss: "642", Hex: "#a49878", R: "164", G: "152", B: "120"},
{ColorName: "Beige Gray Vy Dk", Floss: "640", Hex: "#857b61", R: "133", G: "123", B: "97"},
{ColorName: "Brown Gray Dark", Floss: "3787", Hex: "#625d50", R: "98", G: "93", B: "80"},
{ColorName: "Brown Gray Vy Dk", Floss: "3021", Hex: "#4f4b41", R: "79", G: "75", B: "65"},
{ColorName: "Brown Gray Vy Lt", Floss: "3024", Hex: "#ebeae7", R: "235", G: "234", B: "231"},
{ColorName: "Brown Gray Light", Floss: "3023", Hex: "#b1aa97", R: "177", G: "170", B: "151"},
{ColorName: "Brown Gray Med", Floss: "3022", Hex: "#8e9078", R: "142", G: "144", B: "120"},
{ColorName: "Ash Gray Vy Lt", Floss: "535", Hex: "#636458", R: "99", G: "100", B: "88"},
{ColorName: "Mocha Brown Vy Lt", Floss: "3033", Hex: "#e3d8cc", R: "227", G: "216", B: "204"},
{ColorName: "Mocha Brown Lt", Floss: "3782", Hex: "#d2bca6", R: "210", G: "188", B: "166"},
{ColorName: "Mocha Brown Med", Floss: "3032", Hex: "#b39f8b", R: "179", G: "159", B: "139"},
{ColorName: "Beige Gray Ult Dk", Floss: "3790", Hex: "#7f6a55", R: "127", G: "106", B: "85"},
{ColorName: "Mocha Brown Dk", Floss: "3781", Hex: "#6b5743", R: "107", G: "87", B: "67"},
{ColorName: "Mocha Brn Ult Vy Lt", Floss: "3866", Hex: "#faf6f0", R: "250", G: "246", B: "240"},
{ColorName: "Beige Brown Vy Lt", Floss: "842", Hex: "#d1baa1", R: "209", G: "186", B: "161"},
{ColorName: "Beige Brown Lt", Floss: "841", Hex: "#b69b7e", R: "182", G: "155", B: "126"},
{ColorName: "Beige Brown Med", Floss: "840", Hex: "#9a7c5c", R: "154", G: "124", B: "92"},
{ColorName: "Beige Brown Dk", Floss: "839", Hex: "#675541", R: "103", G: "85", B: "65"},
{ColorName: "Beige Brown Vy Dk", Floss: "838", Hex: "#594937", R: "89", G: "73", B: "55"},
{ColorName: "Beaver Gray Vy Lt", Floss: "3072", Hex: "#e6e8e8", R: "230", G: "232", B: "232"},
{ColorName: "Beaver Gray Lt", Floss: "648", Hex: "#bcb4ac", R: "188", G: "180", B: "172"},
{ColorName: "Beaver Gray Med", Floss: "647", Hex: "#b0a69c", R: "176", G: "166", B: "156"},
{ColorName: "Beaver Gray Dk", Floss: "646", Hex: "#877d73", R: "135", G: "125", B: "115"},
{ColorName: "Beaver Gray Vy Dk", Floss: "645", Hex: "#6e655c", R: "110", G: "101", B: "92"},
{ColorName: "Beaver Gray Ult Dk", Floss: "844", Hex: "#484848", R: "72", G: "72", B: "72"},
{ColorName: "Pearl Gray Vy Lt", Floss: "762", Hex: "#ececec", R: "236", G: "236", B: "236"},
{ColorName: "Pearl Gray", Floss: "415", Hex: "#d3d3d6", R: "211", G: "211", B: "214"},
{ColorName: "Steel Gray Lt", Floss: "318", Hex: "#ababab", R: "171", G: "171", B: "171"},
{ColorName: "Steel Gray Dk", Floss: "414", Hex: "#8c8c8c", R: "140", G: "140", B: "140"},
{ColorName: "Pewter Very Light", Floss: "168", Hex: "#d1d1d1", R: "209", G: "209", B: "209"},
{ColorName: "Pewter Light", Floss: "169", Hex: "#848484", R: "132", G: "132", B: "132"},
{ColorName: "Pewter Gray", Floss: "317", Hex: "#6c6c6c", R: "108", G: "108", B: "108"},
{ColorName: "Pewter Gray Dark", Floss: "413", Hex: "#565656", R: "86", G: "86", B: "86"},
{ColorName: "Pewter Gray Vy Dk", Floss: "3799", Hex: "#424242", R: "66", G: "66", B: "66"},
{ColorName: "Black", Floss: "310", Hex: "#000000", R: "0", G: "0", B: "0"},
}
colorMap := make(map[string]string)
for _, c := range colorBank {
colorMap[c.Hex] = c.ColorName
}
return &DmcColors{
ColorBank: colorBank,
HexMap: colorMap,
}
} | colorBank.go | 0.507568 | 0.666062 | colorBank.go | starcoder |
package math
import (
"errors"
"fmt"
"log"
)
type Matrix3 struct {
elements [9]float32
}
func NewDefaultMatrix3() *Matrix3 {
matrix := &Matrix3{
elements: [9]float32{0, 0, 0, 0, 0, 0, 0, 0, 0},
}
matrix.SetIdentity()
return matrix
}
func NewMatrix3(n11, n12, n13, n21, n22, n23, n31, n32, n33 float32) *Matrix3 {
matrix := &Matrix3{
elements: [9]float32{n11, n12, n13, n21, n22, n23, n31, n32, n33},
}
return matrix
}
func (matrix *Matrix3) GetElements() [9]float32 {
return matrix.elements
}
func (matrix *Matrix3) Set(n11, n12, n13, n21, n22, n23, n31, n32, n33 float32) {
matrix.elements[0] = n11
matrix.elements[1] = n12
matrix.elements[2] = n13
matrix.elements[3] = n21
matrix.elements[4] = n22
matrix.elements[5] = n23
matrix.elements[6] = n31
matrix.elements[7] = n32
matrix.elements[8] = n33
}
func (matrix *Matrix3) SetFromMatrix4(m *Matrix4) {
me := m.GetElements()
matrix.Set(
me[0], me[4], me[8],
me[1], me[5], me[9],
me[2], me[6], me[10],
)
}
func (matrix *Matrix3) SetIdentity() {
matrix.elements = [9]float32{
1, 0, 0,
0, 1, 0,
0, 0, 1,
}
}
func (matrix *Matrix3) Clone() *Matrix3 {
m := Matrix3{
elements: [9]float32{},
}
copy(m.elements[0:], matrix.elements[0:])
return &m
}
func (matrix *Matrix3) Copy(source *Matrix3) {
copy(matrix.elements[0:], source.elements[0:])
}
func (matrix *Matrix3) Multiply(m *Matrix3) {
matrix.MultiplyMatrices(matrix, m)
}
func (matrix *Matrix3) PreMultiply(m *Matrix3) {
matrix.MultiplyMatrices(m, matrix)
}
func (matrix *Matrix3) MultiplyMatrices(ma *Matrix3, mb *Matrix3) {
mae := ma.GetElements()
mbe := mb.GetElements()
matrix.elements[0] = mae[0]*mbe[0] + mae[3]*mbe[1] + mae[6]*mbe[2]
matrix.elements[3] = mae[0]*mbe[3] + mae[3]*mbe[4] + mae[6]*mbe[5]
matrix.elements[6] = mae[0]*mbe[6] + mae[3]*mbe[7] + mae[6]*mbe[8]
matrix.elements[1] = mae[1]*mbe[0] + mae[4]*mbe[1] + mae[7]*mbe[2]
matrix.elements[4] = mae[1]*mbe[3] + mae[4]*mbe[4] + mae[7]*mbe[5]
matrix.elements[7] = mae[1]*mbe[6] + mae[4]*mbe[7] + mae[7]*mbe[8]
matrix.elements[2] = mae[2]*mbe[0] + mae[5]*mbe[1] + mae[8]*mbe[2]
matrix.elements[5] = mae[2]*mbe[3] + mae[5]*mbe[4] + mae[8]*mbe[5]
matrix.elements[8] = mae[2]*mbe[6] + mae[5]*mbe[7] + mae[8]*mbe[8]
}
func (matrix *Matrix3) MultiplyScalar(scalar float32) {
matrix.elements[0] *= scalar
matrix.elements[1] *= scalar
matrix.elements[2] *= scalar
matrix.elements[3] *= scalar
matrix.elements[4] *= scalar
matrix.elements[5] *= scalar
matrix.elements[6] *= scalar
matrix.elements[7] *= scalar
matrix.elements[8] *= scalar
}
func (matrix *Matrix3) Determinant() float32 {
return matrix.elements[0]*matrix.elements[4]*matrix.elements[8] -
matrix.elements[0]*matrix.elements[5]*matrix.elements[7] -
matrix.elements[1]*matrix.elements[3]*matrix.elements[8] +
matrix.elements[1]*matrix.elements[5]*matrix.elements[6] +
matrix.elements[2]*matrix.elements[3]*matrix.elements[7] -
matrix.elements[2]*matrix.elements[4]*matrix.elements[6]
}
func (matrix *Matrix3) Inverse() error {
return matrix.SetInverse(matrix.Clone(), true)
}
// Set the inverse of [ma] in the current [matrix]
func (matrix *Matrix3) SetInverse(ma *Matrix3, errorOnDegenerate bool) error {
t11 := ma.elements[8]*ma.elements[4] - ma.elements[5]*ma.elements[7]
t12 := ma.elements[5]*ma.elements[6] - ma.elements[8]*ma.elements[3]
t13 := ma.elements[7]*ma.elements[3] - ma.elements[4]*ma.elements[6]
det := ma.elements[0]*t11 + ma.elements[1]*t12 + ma.elements[2]*t13
if det == 0 {
if errorOnDegenerate == true {
return errors.New(".SetInverse() can't invert matrix, determinant is 0")
} else {
log.Println(".SetInverse() can't invert matrix, determinant is 0")
matrix.SetIdentity()
return nil
}
}
detInv := 1 / det
matrix.elements[0] = t11 * detInv
matrix.elements[1] = (ma.elements[2]*ma.elements[7] - ma.elements[8]*ma.elements[1]) * detInv
matrix.elements[2] = (ma.elements[5]*ma.elements[1] - ma.elements[2]*ma.elements[4]) * detInv
matrix.elements[3] = t12 * detInv
matrix.elements[4] = (ma.elements[8]*ma.elements[0] - ma.elements[2]*ma.elements[7]) * detInv
matrix.elements[5] = (ma.elements[2]*ma.elements[3] - ma.elements[5]*ma.elements[0]) * detInv
matrix.elements[6] = t13 * detInv
matrix.elements[7] = (ma.elements[1]*ma.elements[6] - ma.elements[7]*ma.elements[0]) * detInv
matrix.elements[8] = (ma.elements[4]*ma.elements[0] - ma.elements[1]*ma.elements[3]) * detInv
return nil
}
func (matrix *Matrix3) Transpose() {
tmp := matrix.elements[1]
matrix.elements[1] = matrix.elements[3]
matrix.elements[3] = tmp
tmp = matrix.elements[2]
matrix.elements[2] = matrix.elements[6]
matrix.elements[6] = tmp
tmp = matrix.elements[5]
matrix.elements[5] = matrix.elements[7]
matrix.elements[7] = tmp
}
// Set the transpose of [ma] in the current [matrix]
func (matrix *Matrix3) SetTranspose(ma *Matrix3) {
matrix.elements[0] = ma.elements[0]
matrix.elements[1] = ma.elements[3]
matrix.elements[2] = ma.elements[6]
matrix.elements[3] = ma.elements[1]
matrix.elements[4] = ma.elements[4]
matrix.elements[5] = ma.elements[7]
matrix.elements[6] = ma.elements[2]
matrix.elements[7] = ma.elements[5]
matrix.elements[8] = ma.elements[8]
}
// Set the normal matrix of [ma] in the current matrix
func (matrix *Matrix3) SetNormalMatrix(ma *Matrix4) {
matrix.SetFromMatrix4(ma)
matrix.SetInverse(matrix, false)
matrix.Transpose()
}
func (matrix *Matrix3) SetUvTransform(tx, ty, sx, sy, rotation, cx, cy float32) {
cos := Cos(rotation)
sin := Sin(rotation)
matrix.Set(
sx*cos, sx*sin, -sx*(cos*cx+sin*cy)+cx+tx,
-sy*sin, sy*cos, -sy*(-sin*cx+cos*cy)+cy+ty,
0, 0, 1,
)
}
func (matrix *Matrix3) Scale(sx float32, sy float32) {
matrix.elements[0] *= sx
matrix.elements[1] *= sy
matrix.elements[3] *= sx
matrix.elements[4] *= sy
matrix.elements[6] *= sx
matrix.elements[7] *= sy
}
func (matrix *Matrix3) Rotate(rotation float32) {
cos := Cos(rotation)
sin := Sin(rotation)
cpMatrix := matrix.Clone()
matrix.elements[0] = cos*cpMatrix.elements[0] + sin*cpMatrix.elements[1]
matrix.elements[3] = cos*cpMatrix.elements[3] + sin*cpMatrix.elements[4]
matrix.elements[6] = cos*cpMatrix.elements[6] + sin*cpMatrix.elements[7]
matrix.elements[1] = cos*cpMatrix.elements[0] + sin*cpMatrix.elements[1]
matrix.elements[4] = cos*cpMatrix.elements[3] + sin*cpMatrix.elements[4]
matrix.elements[7] = cos*cpMatrix.elements[6] + sin*cpMatrix.elements[7]
}
func (matrix *Matrix3) Translate(tx float32, ty float32) {
matrix.elements[0] += tx * matrix.elements[2]
matrix.elements[3] += tx * matrix.elements[5]
matrix.elements[6] += tx * matrix.elements[8]
matrix.elements[1] += ty * matrix.elements[2]
matrix.elements[4] += ty * matrix.elements[5]
matrix.elements[7] += ty * matrix.elements[8]
}
func (matrix *Matrix3) TranslateVector2(v *Vector2) {
matrix.Translate(v.X, v.Y)
}
func (matrix *Matrix3) Equals(ma *Matrix3) bool {
for ind := range matrix.elements {
if matrix.elements[ind] != ma.elements[ind] {
return false
}
}
return true
}
func (matrix *Matrix3) EqualsRound(ma *Matrix3, decimals float32) bool {
mul := Pow(10, decimals)
for ind := range matrix.elements {
if Round(mul * matrix.elements[ind]) / mul != Round(mul * ma.elements[ind]) / mul {
return false
}
}
return true
}
func (matrix *Matrix3) ToArray() [9]float32 {
mc := matrix.Clone()
return mc.elements
}
func (matrix *Matrix3) CopyToArray(array []float32, offset int) {
va := matrix.ToArray()
copy(array[offset:], va[0:])
}
func (matrix *Matrix3) ToString() string {
return fmt.Sprintf("%9.2f %9.2f %9.2f\n%9.2f %9.2f %9.2f\n%9.2f %9.2f %9.2f",
matrix.elements[0], matrix.elements[1], matrix.elements[2],
matrix.elements[3], matrix.elements[4], matrix.elements[5],
matrix.elements[6], matrix.elements[7], matrix.elements[8])
} | matrix3.go | 0.736116 | 0.617541 | matrix3.go | starcoder |
package tonality
import (
"errors"
"strings"
)
// KeyNotation is the type representing a type of key notation.
type KeyNotation int
// Key notatations are the available notations for converting to and from.
const (
CamelotKeys KeyNotation = iota
OpenKey
Musical
MusicalAlt
Beatport
)
var (
// NotationCamelotKeys are the keys in camelot key notation.
NotationCamelotKeys = []string{
"1A", "1B",
"2A", "2B",
"3A", "3B",
"4A", "4B",
"5A", "5B",
"6A", "6B",
"7A", "7B",
"8A", "8B",
"9A", "9B",
"10A", "10B",
"11A", "11B",
"12A", "12B",
}
// NotationOpenKey are the keys in open key notation.
NotationOpenKey = []string{
"6M", "6D",
"7M", "7D",
"8M", "8D",
"9M", "9D",
"10M", "10D",
"11M", "11D",
"12M", "12D",
"1M", "1D",
"2M", "2D",
"3M", "3D",
"4M", "4D",
"5M", "5D",
}
// NotationMusical are the keys in musical notation.
NotationMusical = []string{
"Abm", "B",
"Ebm", "Gb",
"Bbm", "Db",
"Fm", "Ab",
"Cm", "Eb",
"Gm", "Bb",
"Dm", "F",
"Am", "C",
"Em", "G",
"Bm", "D",
"Gbm", "A",
"Dbm", "E",
}
// NotationMusicalAlt are the keys in alternate musical notation.
NotationMusicalAlt = []string{
"G#m", "B",
"Ebm", "F#",
"A#m", "Db",
"Fm", "G#",
"Cm", "D#",
"Gm", "Bb",
"Dm", "F",
"Am", "C",
"Em", "G",
"Bm", "D",
"F#m", "A",
"C#m", "E",
}
// NotationBeatport are the keys in beatport notation.
NotationBeatport = []string{
"G#m", "Bmaj",
"Ebm", "Gb",
"Bbm", "Db",
"Fmin", "Ab",
"Cmin", "Eb",
"Gmin", "Bb",
"Dmin", "Fmaj",
"Amin", "Cmaj",
"Emin", "Gmaj",
"Bmin", "Dmaj",
"F#m", "Amaj",
"C#m", "Emaj",
}
)
var (
notationToKeys = map[KeyNotation][]string{
CamelotKeys: NotationCamelotKeys,
OpenKey: NotationOpenKey,
Musical: NotationMusical,
MusicalAlt: NotationMusicalAlt,
Beatport: NotationBeatport,
}
keyToNotationMap = map[string]KeyNotation{}
notationToKeysMap = map[KeyNotation][]string{}
)
func init() {
for notation, keys := range notationToKeys {
if _, ok := notationToKeysMap[notation]; !ok {
notationToKeysMap[notation] = make([]string, 0)
}
for _, key := range keys {
normalizedKey := normalizeKey(key)
notationToKeysMap[notation] = append(notationToKeysMap[notation], normalizedKey)
if _, ok := keyToNotationMap[normalizedKey]; !ok {
keyToNotationMap[normalizedKey] = notation
}
}
}
}
// ConvertKeyToNotation converts a key from its detected key notation to the
// specified key notation.
func ConvertKeyToNotation(key string, notation KeyNotation) (string, error) {
idx := getKeyIndex(key)
if idx == -1 {
return "", errors.New("invalid key")
}
return notationToKeys[notation][idx], nil
}
func normalizeKey(key string) string {
return strings.TrimLeft(strings.ToLower(key), "0")
}
func getKeyIndex(key string) int {
normalizedKey := normalizeKey(key)
if _, ok := keyToNotationMap[normalizedKey]; !ok {
return -1
}
notation := getNotation(key)
keys := notationToKeysMap[notation]
found := -1
for idx, k := range keys {
if normalizedKey == k {
found = idx
break
}
}
return found
}
func getNotation(key string) KeyNotation {
normalizedKey := normalizeKey(key)
return keyToNotationMap[normalizedKey]
} | vendor/github.com/tombell/tonality/tonality.go | 0.517571 | 0.451327 | tonality.go | starcoder |
package dsp
import "math"
// http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
type BiQuadFilter struct {
B0, B1, B2 float64
A0, A1, A2 float64
prevIn, prevOut [2]float64
}
func (f *BiQuadFilter) Filter(input, output []float64) {
b0a0 := f.B0 / f.A0
b1a0 := f.B1 / f.A0
b2a0 := f.B2 / f.A0
a1a0 := f.A1 / f.A0
a2a0 := f.A2 / f.A0
for i, s := range input {
newSample := b0a0*s + b1a0*f.prevIn[0] + b2a0*f.prevIn[1] - a1a0*f.prevOut[0] - a2a0*f.prevOut[1]
f.prevOut[1] = f.prevOut[0]
f.prevOut[0] = newSample
f.prevIn[1] = f.prevIn[0]
f.prevIn[0] = s
output[i] = newSample
}
}
func (f *BiQuadFilter) FilterF32(input, output []float32) {
b0a0 := f.B0 / f.A0
b1a0 := f.B1 / f.A0
b2a0 := f.B2 / f.A0
a1a0 := f.A1 / f.A0
a2a0 := f.A2 / f.A0
for i, s := range input {
newSample := b0a0*float64(s) + b1a0*f.prevIn[0] + b2a0*f.prevIn[1] - a1a0*f.prevOut[0] - a2a0*f.prevOut[1]
f.prevOut[1] = f.prevOut[0]
f.prevOut[0] = newSample
f.prevIn[1] = f.prevIn[0]
f.prevIn[0] = float64(s)
output[i] = float32(newSample)
}
}
// H(s) = 1 / (s^2 + s/Q + 1)
func NewLowPassBiQuadFilter(sampleRate, cutoffFreq, q float64) *BiQuadFilter {
w0 := 2 * math.Pi * cutoffFreq / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
alpha := sinW0 / (2 * q)
return &BiQuadFilter{
B0: (1 - cosW0) / 2,
B1: 1 - cosW0,
B2: (1 - cosW0) / 2,
A0: 1 + alpha,
A1: -2 * cosW0,
A2: 1 - alpha,
}
}
// H(s) = s^2 / (s^2 + s/Q + 1)
func NewHighPassBiQuadFilter(sampleRate, cutoffFreq, q float64) *BiQuadFilter {
w0 := 2 * math.Pi * cutoffFreq / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
alpha := sinW0 / (2 * q)
return &BiQuadFilter{
B0: (1 + cosW0) / 2,
B1: -(1 + cosW0),
B2: (1 + cosW0) / 2,
A0: 1 + alpha,
A1: -2 * cosW0,
A2: 1 - alpha,
}
}
// H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q)
func NewBandPassConstantSkirtGainBiQuadFilter(sampleRate, centreFrequency, q float64) *BiQuadFilter {
w0 := 2 * math.Pi * centreFrequency / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
alpha := sinW0 / (2 * q)
return &BiQuadFilter{
B0: sinW0 / 2, // = Q*alpha
B1: 0,
B2: -sinW0 / 2, // = -Q*alpha
A0: 1 + alpha,
A1: -2 * cosW0,
A2: 1 - alpha,
}
}
// H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain)
func NewBandPassConstantPeakGainBiQuadFilter(sampleRate, centreFrequency, q float64) *BiQuadFilter {
w0 := 2 * math.Pi * centreFrequency / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
alpha := sinW0 / (2 * q)
return &BiQuadFilter{
B0: alpha,
B1: 0,
B2: -alpha,
A0: 1 + alpha,
A1: -2 * cosW0,
A2: 1 - alpha,
}
}
// H(s) = (s^2 + 1) / (s^2 + s/Q + 1)
func NotchBiQuadFilter(sampleRate, centreFrequency, q float64) *BiQuadFilter {
w0 := 2 * math.Pi * centreFrequency / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
alpha := sinW0 / (2 * q)
return &BiQuadFilter{
B0: 1,
B1: -2 * cosW0,
B2: 1,
A0: 1 + alpha,
A1: -2 * cosW0,
A2: 1 - alpha,
}
}
// H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1)
func AllPassBiQuadFilter(sampleRate, centreFrequency, q float64) *BiQuadFilter {
w0 := 2 * math.Pi * centreFrequency / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
alpha := sinW0 / (2 * q)
return &BiQuadFilter{
B0: 1 - alpha,
B1: -2 * cosW0,
B2: 1 + alpha,
A0: 1 + alpha,
A1: -2 * cosW0,
A2: 1 - alpha,
}
}
// H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1)
func PeakingEQBiQuadFilter(sampleRate, centreFrequency, q, dbGain float64) *BiQuadFilter {
w0 := 2 * math.Pi * centreFrequency / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
alpha := sinW0 / (2 * q)
a := math.Pow(10, dbGain/40) // TODO: should we square root this value?
return &BiQuadFilter{
B0: 1 + alpha*a,
B1: -2 * cosW0,
B2: 1 - alpha*a,
A0: 1 + alpha/a,
A1: -2 * cosW0,
A2: 1 - alpha/a,
}
}
// H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1)
// shelfSlope: a "shelf slope" parameter (for shelving EQ only).
// When S = 1, the shelf slope is as steep as it can be and remain monotonically
// increasing or decreasing gain with frequency. The shelf slope, in dB/octave,
// remains proportional to S for all other values for a fixed f0/Fs and dBgain.</param>
// dbGain: Gain in decibels
func LowShelfBiQuadFilter(sampleRate, cutoffFrequency, shelfSlope, dbGain float64) *BiQuadFilter {
w0 := 2 * math.Pi * cutoffFrequency / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
a := math.Pow(10, dbGain/40.0) // TODO: should we square root this value?
alpha := sinW0 / 2 * math.Sqrt((a+1/a)*(1/shelfSlope-1)+2)
temp := 2 * math.Sqrt(a) * alpha
return &BiQuadFilter{
B0: a * ((a + 1) - (a-1)*cosW0 + temp),
B1: 2 * a * ((a - 1) - (a+1)*cosW0),
B2: a * ((a + 1) - (a-1)*cosW0 - temp),
A0: (a + 1) + (a-1)*cosW0 + temp,
A1: -2 * ((a - 1) + (a+1)*cosW0),
A2: (a + 1) + (a-1)*cosW0 - temp,
}
}
// H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A)
func HighShelfBiQuadFilter(sampleRate, cutoffFrequency, shelfSlope, dbGain float64) *BiQuadFilter {
w0 := 2 * math.Pi * cutoffFrequency / sampleRate
sinW0 := math.Sin(w0)
cosW0 := math.Cos(w0)
a := math.Pow(10, dbGain/40) // TODO: should we square root this value?
alpha := sinW0 / 2 * math.Sqrt((a+1/a)*(1/shelfSlope-1)+2)
temp := 2 * math.Sqrt(a) * alpha
return &BiQuadFilter{
B0: a * ((a + 1) + (a-1)*cosW0 + temp),
B1: -2 * a * ((a - 1) + (a+1)*cosW0),
B2: a * ((a + 1) + (a-1)*cosW0 - temp),
A0: (a + 1) - (a-1)*cosW0 + temp,
A1: 2 * ((a - 1) - (a+1)*cosW0),
A2: (a + 1) - (a-1)*cosW0 - temp,
}
} | dsp/biquad.go | 0.591487 | 0.471588 | biquad.go | starcoder |
package geocube
import (
"encoding/binary"
"fmt"
"image"
"unsafe"
"github.com/airbusgeo/geocube/internal/utils"
"github.com/airbusgeo/godal"
)
// Bitmap decribes any image as a bitmap of bytes
type Bitmap struct {
// Bytes is the []byte representation of the image
Bytes []byte
// Bands is the number of interlaced bands
Bands int
// Rect is the image's bounds.
Rect image.Rectangle
// Datatype of the pixel
DType DType
// For conversion between dtype and byte
ByteOrder binary.ByteOrder
}
// NewBitmapHeader creates a new empty image (pixels are not allocated)
func NewBitmapHeader(r image.Rectangle, dtype DType, bands int) *Bitmap {
return &Bitmap{
Bands: bands,
Rect: r,
DType: dtype,
ByteOrder: nativeEndianness(),
}
}
// NewBitmapFromDataset creates a new bitmap from the dataset, copying the memory
func NewBitmapFromDataset(ds *godal.Dataset) (*Bitmap, error) {
xSize := ds.Structure().SizeX
ySize := ds.Structure().SizeY
bands := ds.Structure().NBands
dtype := DTypeFromGDal(ds.Structure().DataType)
if bands < 1 {
return nil, fmt.Errorf("unsupported band count %d", bands)
}
r := image.Rect(0, 0, xSize, ySize)
image := NewBitmapHeader(r, dtype, bands)
image.Bytes = make([]byte, dtype.Size()*bands*r.Dx()*r.Dy())
if bands == 1 {
// Read one band
band := ds.Bands()[0]
if err := band.Read(0, 0, image.getPix(), xSize, ySize); err != nil {
return nil, fmt.Errorf("band.IO: %w", err)
}
} else {
bandmap := make([]int, bands)
for i := 0; i < bands; i++ {
bandmap[i] = i + 1
}
// Read severals bands
if err := ds.Read(0, 0, image.getPix(), xSize, ySize); err != nil {
return nil, fmt.Errorf("dataset.IO: %w", err)
}
}
return image, nil
}
// SizeX returns the x size of the image
func (i *Bitmap) SizeX() int {
return i.Rect.Dx()
}
// SizeY returns the y size of the image
func (i *Bitmap) SizeY() int {
return i.Rect.Dy()
}
func (i *Bitmap) getPix() interface{} {
// Convert up to a slice of the right type
var pix interface{}
switch i.DType {
case DTypeUINT8:
pix = i.Bytes
case DTypeUINT16:
pix = utils.SliceByteToUInt16(i.Bytes)
case DTypeUINT32:
pix = utils.SliceByteToUInt32(i.Bytes)
case DTypeINT8:
pix = utils.SliceByteToInt8(i.Bytes)
case DTypeINT16:
pix = utils.SliceByteToInt16(i.Bytes)
case DTypeINT32:
pix = utils.SliceByteToInt32(i.Bytes)
case DTypeFLOAT32:
pix = utils.SliceByteToFloat32(i.Bytes)
case DTypeFLOAT64:
pix = utils.SliceByteToFloat64(i.Bytes)
case DTypeCOMPLEX64:
pix = utils.SliceByteToComplex64(i.Bytes)
}
return pix
}
func nativeEndianness() binary.ByteOrder {
var i int32 = 0x01020304
u := unsafe.Pointer(&i)
pb := (*byte)(u)
b := *pb
if b == 0x04 {
return binary.LittleEndian
}
return binary.BigEndian
} | internal/geocube/image.go | 0.758421 | 0.560674 | image.go | starcoder |
package types
import (
"io"
"math"
"github.com/lyraproj/puppet-evaluator/eval"
)
type TupleType struct {
size *IntegerType
givenOrActualSize *IntegerType
types []eval.Type
}
var Tuple_Type eval.ObjectType
func init() {
Tuple_Type = newObjectType(`Pcore::TupleType`,
`Pcore::AnyType {
attributes => {
types => Array[Type],
size_type => {
type => Optional[Type[Integer]],
value => undef
}
}
}`, func(ctx eval.Context, args []eval.Value) eval.Value {
tupleArgs := args[0].(*ArrayValue).AppendTo([]eval.Value{})
if len(args) > 1 {
tupleArgs = append(tupleArgs, args[1].(*IntegerType).Parameters()...)
}
return NewTupleType2(tupleArgs...)
})
// Go constructor for Tuple instances is registered by ArrayType
}
func DefaultTupleType() *TupleType {
return tupleType_DEFAULT
}
func EmptyTupleType() *TupleType {
return tupleType_EMPTY
}
func NewTupleType(types []eval.Type, size *IntegerType) *TupleType {
var givenOrActualSize *IntegerType
sz := int64(len(types))
if size == nil {
givenOrActualSize = NewIntegerType(sz, sz)
} else {
if sz == 0 {
if *size == *IntegerType_POSITIVE {
return DefaultTupleType()
}
if *size == *IntegerType_ZERO {
return EmptyTupleType()
}
}
givenOrActualSize = size
}
return &TupleType{size, givenOrActualSize, types}
}
func NewTupleType2(args ...eval.Value) *TupleType {
return tupleFromArgs(false, WrapValues(args))
}
func NewTupleType3(args eval.List) *TupleType {
return tupleFromArgs(false, args)
}
func tupleFromArgs(callable bool, args eval.List) *TupleType {
argc := args.Len()
if argc == 0 {
return tupleType_DEFAULT
}
var rng, givenOrActualRng *IntegerType
var ok bool
var min int64
last := args.At(argc - 1)
max := int64(-1)
if _, ok = last.(*DefaultValue); ok {
max = math.MaxInt64
} else if n, ok := toInt(last); ok {
max = n
}
if max >= 0 {
if argc == 1 {
rng = NewIntegerType(min, math.MaxInt64)
argc = 0
} else {
if min, ok = toInt(args.At(argc - 2)); ok {
rng = NewIntegerType(min, max)
argc -= 2
} else {
argc--
rng = NewIntegerType(max, int64(argc))
}
}
givenOrActualRng = rng
} else {
rng = nil
givenOrActualRng = NewIntegerType(int64(argc), int64(argc))
}
if argc == 0 {
if *rng == *IntegerType_ZERO {
return tupleType_EMPTY
}
if callable {
return &TupleType{rng, rng, []eval.Type{DefaultUnitType()}}
}
if *rng == *IntegerType_POSITIVE {
return tupleType_DEFAULT
}
return &TupleType{rng, rng, []eval.Type{}}
}
var tupleTypes []eval.Type
ok = false
failIdx := -1
if argc == 1 {
// One arg can be either array of types or a type
tupleTypes, failIdx = toTypes(args.Slice(0, 1))
ok = failIdx < 0
}
if !ok {
tupleTypes, failIdx = toTypes(args.Slice(0, argc))
if failIdx >= 0 {
name := `Tuple[]`
if callable {
name = `Callable[]`
}
panic(NewIllegalArgumentType2(name, failIdx, `Type`, args.At(failIdx)))
}
}
return &TupleType{rng, givenOrActualRng, tupleTypes}
}
func (t *TupleType) Accept(v eval.Visitor, g eval.Guard) {
v(t)
t.size.Accept(v, g)
for _, c := range t.types {
c.Accept(v, g)
}
}
func (t *TupleType) At(i int) eval.Value {
if i >= 0 {
if i < len(t.types) {
return t.types[i]
}
if int64(i) < t.givenOrActualSize.max {
return t.types[len(t.types)-1]
}
}
return _UNDEF
}
func (t *TupleType) CommonElementType() eval.Type {
top := len(t.types)
if top == 0 {
return anyType_DEFAULT
}
cet := t.types[0]
for idx := 1; idx < top; idx++ {
cet = commonType(cet, t.types[idx])
}
return cet
}
func (t *TupleType) Default() eval.Type {
return tupleType_DEFAULT
}
func (t *TupleType) Equals(o interface{}, g eval.Guard) bool {
if ot, ok := o.(*TupleType); ok && len(t.types) == len(ot.types) && eval.GuardedEquals(t.size, ot.size, g) {
for idx, col := range t.types {
if !col.Equals(ot.types[idx], g) {
return false
}
}
return true
}
return false
}
func (t *TupleType) Generic() eval.Type {
return NewTupleType(alterTypes(t.types, generalize), t.size)
}
func (t *TupleType) Get(key string) (value eval.Value, ok bool) {
switch key {
case `types`:
tps := make([]eval.Value, len(t.types))
for i, t := range t.types {
tps[i] = t
}
return WrapValues(tps), true
case `size_type`:
if t.size == nil {
return _UNDEF, true
}
return t.size, true
}
return nil, false
}
func (t *TupleType) IsAssignable(o eval.Type, g eval.Guard) bool {
switch o.(type) {
case *ArrayType:
at := o.(*ArrayType)
if !GuardedIsInstance(t.givenOrActualSize, WrapInteger(at.size.Min()), g) {
return false
}
top := len(t.types)
if top == 0 {
return true
}
elemType := at.typ
for idx := 0; idx < top; idx++ {
if !GuardedIsAssignable(t.types[idx], elemType, g) {
return false
}
}
return true
case *TupleType:
tt := o.(*TupleType)
if !(t.size == nil || GuardedIsInstance(t.size, WrapInteger(tt.givenOrActualSize.Min()), g)) {
return false
}
if len(t.types) > 0 {
top := len(tt.types)
if top == 0 {
return t.givenOrActualSize.min == 0
}
last := len(t.types) - 1
for idx := 0; idx < top; idx++ {
myIdx := idx
if myIdx > last {
myIdx = last
}
if !GuardedIsAssignable(t.types[myIdx], tt.types[idx], g) {
return false
}
}
}
return true
default:
return false
}
}
func (t *TupleType) IsInstance(v eval.Value, g eval.Guard) bool {
if iv, ok := v.(*ArrayValue); ok {
return t.IsInstance2(iv, g)
}
return false
}
func (t *TupleType) IsInstance2(vs eval.List, g eval.Guard) bool {
osz := vs.Len()
if !t.givenOrActualSize.IsInstance3(osz) {
return false
}
last := len(t.types) - 1
if last < 0 {
return true
}
tdx := 0
for idx := 0; idx < osz; idx++ {
if !GuardedIsInstance(t.types[tdx], vs.At(idx), g) {
return false
}
if tdx < last {
tdx++
}
}
return true
}
func (t *TupleType) IsInstance3(vs []eval.Value, g eval.Guard) bool {
osz := len(vs)
if !t.givenOrActualSize.IsInstance3(osz) {
return false
}
last := len(t.types) - 1
if last < 0 {
return true
}
tdx := 0
for idx := 0; idx < osz; idx++ {
if !GuardedIsInstance(t.types[tdx], vs[idx], g) {
return false
}
if tdx < last {
tdx++
}
}
return true
}
func (t *TupleType) MetaType() eval.ObjectType {
return Tuple_Type
}
func (t *TupleType) Name() string {
return `Tuple`
}
func (t *TupleType) Resolve(c eval.Context) eval.Type {
rts := make([]eval.Type, len(t.types))
for i, ts := range t.types {
rts[i] = resolve(c, ts)
}
t.types = rts
return t
}
func (t *TupleType) CanSerializeAsString() bool {
for _, v := range t.types {
if !canSerializeAsString(v) {
return false
}
}
return true
}
func (t *TupleType) SerializationString() string {
return t.String()
}
func (t *TupleType) Size() *IntegerType {
return t.givenOrActualSize
}
func (t *TupleType) String() string {
return eval.ToString2(t, NONE)
}
func (t *TupleType) Parameters() []eval.Value {
top := len(t.types)
params := make([]eval.Value, 0, top+2)
for _, c := range t.types {
params = append(params, c)
}
if !(t.size == nil || top == 0 && *t.size == *IntegerType_POSITIVE) {
params = append(params, t.size.SizeParameters()...)
}
return params
}
func (t *TupleType) ToString(b io.Writer, s eval.FormatContext, g eval.RDetect) {
TypeToString(t, b, s, g)
}
func (t *TupleType) PType() eval.Type {
return &TypeType{t}
}
func (t *TupleType) Types() []eval.Type {
return t.types
}
var tupleType_DEFAULT = &TupleType{IntegerType_POSITIVE, IntegerType_POSITIVE, []eval.Type{}}
var tupleType_EMPTY = &TupleType{IntegerType_ZERO, IntegerType_ZERO, []eval.Type{}} | types/tupletype.go | 0.620507 | 0.493836 | tupletype.go | starcoder |
package day22
import (
"log"
"strconv"
)
type Hand []int
type HandScores struct {
score1, score2 int
}
// Plays a game of combat and returns the winner's score
func PlayCombat(player1Hand []string, player2Hand []string) int {
hand1 := parseHand(player1Hand)
hand2 := parseHand(player2Hand)
var winner Hand
for winner == nil {
num1 := hand1[0]
num2 := hand2[0]
hand1 = hand1[1:]
hand2 = hand2[1:]
if num1 > num2 {
hand1 = append(hand1, []int{num1, num2}...)
} else {
hand2 = append(hand2, []int{num2, num1}...)
}
if len(hand1) == 0 {
winner = hand2
} else if len(hand2) == 0 {
winner = hand1
}
}
return scoreHand(winner)
}
// Plays a game of recursive combat and returns the winner's score
func PlayRecursiveCombat(player1Hand []string, player2Hand []string) int {
hand1 := parseHand(player1Hand)
hand2 := parseHand(player2Hand)
_, score := playRecursiveCombat(hand1, hand2)
return score
}
// Playes a game of recurisve comabt and returns the winner and their score
func playRecursiveCombat(hand1, hand2 Hand) (int, int) {
var winnerNum int
seenScores := make(map[HandScores]bool)
for winnerNum == 0 {
handScores := handScores(hand1, hand2)
if seenScores[handScores] {
winnerNum = 1
continue
} else {
seenScores[handScores] = true
}
num1 := hand1[0]
num2 := hand2[0]
hand1 = hand1[1:]
hand2 = hand2[1:]
roundWinner := 2
if num1 <= len(hand1) && num2 <= len(hand2) {
hand1Copy := make(Hand, num1)
copy(hand1Copy, hand1)
hand2Copy := make(Hand, num2)
copy(hand2Copy, hand2)
roundWinner, _ = playRecursiveCombat(hand1Copy, hand2Copy)
} else if num1 > num2 {
roundWinner = 1
}
if roundWinner == 1 {
hand1 = append(hand1, []int{num1, num2}...)
} else {
hand2 = append(hand2, []int{num2, num1}...)
}
if len(hand1) == 0 {
winnerNum = 2
} else if len(hand2) == 0 {
winnerNum = 1
}
}
if winnerNum == 1 {
return 1, scoreHand(hand1)
}
return 2, scoreHand(hand2)
}
func handScores(hand1, hand2 Hand) HandScores {
return HandScores{scoreHand(hand1), scoreHand(hand2)}
}
func scoreHand(hand Hand) int {
handSize := len(hand)
score := 0
for i, v := range hand {
score += (v * (handSize - i))
}
return score
}
func parseHand(startHand []string) Hand {
hand := make(Hand, 0)
for i, v := range startHand {
// Skip first row as it's player number
if i == 0 {
continue
}
value, err := strconv.Atoi(v)
if err != nil {
log.Fatalf(err.Error())
}
hand = append(hand, value)
}
return hand
} | day22/day22.go | 0.682468 | 0.467757 | day22.go | starcoder |
package gogeom
import "math"
//Ax+By+c =0
type GeneralLine struct {
A, B, C float64
}
//Ax+By+c =0
//Dx+Ey+F=0
type GeneralLines struct {
A, B, C, D, E, F float64
}
type TwoPointFormLine struct {
X1, Y1, X2, Y2 float64
}
// Slope of the line
func (l *GeneralLine) SlopeOfLine() float64 {
return -(l.A / l.B)
}
//Y Intencept of the line
func (l *GeneralLine) YIntercept() float64 {
return -(l.C / l.B)
}
//X Intencept of the line
func (l *GeneralLine) XIntercept() float64 {
return -(l.C / l.A)
}
//Intersection of two lines Ax + By + C = 0 and Dx + Ey + F = 0
func (l *GeneralLines) IntersectionOfLines() (float64, float64) {
denominator := (l.A*l.E - l.B*l.D)
xNumerator := (l.B*l.F - l.C*l.E)
yNumerator := (l.C*l.D - l.A*l.F)
return xNumerator / denominator, yNumerator / denominator
}
// Slope of the line
func (l *TwoPointFormLine) SlopeOfLine() float64 {
return (l.Y2 - l.Y1) / (l.X2 - l.X1)
}
// Middle Point of the line
func (l *TwoPointFormLine) MidPoints() (float64, float64) {
return (l.X1 + l.X2) / 2, (l.Y1 + l.Y2) / 2
}
//Point (x, y) which divides the line connecting two points (x1 , y1) and (x2 , y2) in the ratio p:q
func (l *TwoPointFormLine) DividingPoints(p, q float64) (float64, float64) {
denominator := (p + q)
return ((p*l.X2 + q*l.X1) / denominator), ((p*l.Y2 + q*l.Y1) / denominator)
}
//Point (x, y) which divides the line connecting two points (x1 , y1) and (x2 , y2) externally at a ratio p:q
func (l *TwoPointFormLine) ExternalDividingPoints(p, q float64) (float64, float64) {
denominator := (p - q)
return ((p*l.X1 - q*l.X2) / denominator), ((p*l.Y1 + q*l.Y2) / denominator)
}
//A point (x, y) which is located at a distance d from a point (x1 , y1) on the line
func (l *GeneralLines) AngleBetweenTwoLines() float64 {
numerator := (l.A*l.D + l.B*l.E)
denominator := (math.Sqrt(PowerFunction(l.A, 2)+PowerFunction(l.B, 2)) * math.Sqrt(PowerFunction(l.D, 2)+PowerFunction(l.E, 2)))
return math.Acos(numerator / denominator)
}
//Equation of a line passing through two points (x1 , y1), (x2 , y2)
func (l *TwoPointFormLine) LineThroughTwoPoint() string {
slope := (l.Y2 - l.Y1) / (l.X2 - l.X1)
constant := (l.X1 * slope) + l.Y1
return "y = " + FloatToString(slope) + " x - ( " + FloatToString(constant) + " )"
}
//Equation of a line parallel to the line Ax + By + C = 0 and at a distance d from it.
func (l *GeneralLine) EquiDistantParallelLine(d float64) (string, string) {
constant := FloatToString(d * math.Sqrt(PowerFunction(l.A, 2)+PowerFunction(l.B, 2)))
return FloatToString(l.A) + "x + " + FloatToString(l.B) + "y + " + FloatToString(l.C) + " - " + constant, FloatToString(l.A) + "x + " + FloatToString(l.B) + "y + " + FloatToString(l.C) + " + " + constant
}
//Distance between two points (D)
func (l *TwoPointFormLine) DistanceBetweenTwoPoints() float64 {
return math.Sqrt((PowerFunction((l.X2 - l.X1), 2)) + (PowerFunction((l.Y2 - l.Y1), 2)))
}
//Distance between intercepts xi and yi
func (l *TwoPointFormLine) DistanceBetweenInterecepts() float64 {
return math.Sqrt((PowerFunction((l.X1), 2)) + (PowerFunction((l.Y1), 2)))
} | line.go | 0.77373 | 0.438785 | line.go | starcoder |
package core
import (
"reflect"
"strings"
)
const (
// DefAssignAddArr appends the array to array
DefAssignAddArr = `AssignAddºArr`
// DefAssignAddArrArr appends the array to array
DefAssignAddArrArr = `AssignAddºArrArr`
// DefAssignAddMap appends the map to array
DefAssignAddMap = `AssignAddºArrMap`
// DefAssignArr assigns one array to another
DefAssignArr = `AssignºArrArr`
// DefAssignMap assigns one map to another
DefAssignMap = `AssignºMapMap`
// DefLenArr returns the length of the array
DefLenArr = `LenºArr`
// DefLenMap returns the length of the map
DefLenMap = `LenºMap`
// DefAssignIntInt equals int = int
DefAssignIntInt = `#Assign#int#int`
// DefAssignStructStruct equals struct = struct
DefAssignStructStruct = `AssignºStructStruct`
// DefAssignBitAndStructStruct equals struct &= struct
DefAssignBitAndStructStruct = `AssignBitAndºStructStruct`
// DefAssignFnFn equals fn = fn
DefAssignFnFn = `AssignºFnFn`
// DefAssignFileFile equals file = file
DefAssignFileFile = `AssignºFileFile`
// DefAssignHandleHandle equals handle = handle
DefAssignHandleHandle = `AssignºHandleHandle`
// DefAssignBitAndArrArr equals arr &= arr
DefAssignBitAndArrArr = `AssignBitAndºArrArr`
// DefAssignBitAndMapMap equals map &= map
DefAssignBitAndMapMap = `AssignBitAndºMapMap`
// DefNewKeyValue returns a pair of key value
DefNewKeyValue = `NewKeyValue`
// DefGetEnv returns an environment variable
DefGetEnv = `GetEnv`
)
var (
defFuncs = map[string]bool{
DefAssignAddArr: true,
DefAssignAddArrArr: true,
DefAssignAddMap: true,
DefAssignArr: true,
DefAssignMap: true,
DefLenArr: true,
DefLenMap: true,
DefAssignIntInt: true,
DefAssignStructStruct: true,
DefAssignFileFile: true,
DefAssignHandleHandle: true,
DefAssignFnFn: true,
DefAssignBitAndStructStruct: true,
DefAssignBitAndArrArr: true,
DefAssignBitAndMapMap: true,
DefNewKeyValue: true,
DefGetEnv: true,
}
)
// NameToType searches the type by its name. It accepts names like name.name.name.
// It creates a new type if it absents.
func (unit *Unit) NameToType(name string) IObject {
obj := unit.FindType(name)
if obj == nil {
ins := strings.SplitN(name, `.`, 2)
if len(ins) == 2 {
if ins[0] == `arr` {
indexOf := unit.NameToType(ins[1])
if indexOf != nil {
obj = unit.NewType(name, reflect.TypeOf(Array{}), indexOf.(*TypeObject))
}
} else if ins[0] == `map` {
indexOf := unit.NameToType(ins[1])
if indexOf != nil {
obj = unit.NewType(name, reflect.TypeOf(Map{}), indexOf.(*TypeObject))
}
}
}
}
return obj
}
// ImportEmbed imports Embed funcs to Unit
func (unit *Unit) ImportEmbed(embed Embed) {
var (
code []Bcode
retType *TypeObject
parTypes []*TypeObject
fnc interface{}
)
if embed.Func == nil {
code = []Bcode{Bcode(embed.Code)}
} else {
fnc = int32(embed.Code)
}
if len(embed.Ret) > 0 {
retType = unit.NameToType(embed.Ret).(*TypeObject)
}
if len(embed.Pars) > 0 {
pars := strings.Split(embed.Pars, `,`)
parTypes = make([]*TypeObject, len(pars))
for i, item := range pars {
parTypes[i] = unit.NameToType(strings.TrimSpace(item)).(*TypeObject)
}
}
obj := unit.NewObject(&EmbedObject{
Object: Object{
Name: embed.Name,
Unit: unit,
BCode: Bytecode{
Code: code,
},
},
Func: fnc,
Return: retType,
Params: parTypes,
Variadic: embed.Variadic,
Runtime: embed.Runtime,
CanError: embed.CanError,
})
ind := len(unit.VM.Objects) - 1
if defFuncs[embed.Name] {
unit.NameSpace[embed.Name] = uint32(ind) | NSPub
if embed.Name == DefGetEnv {
unit.AddFunc(ind, obj, true)
}
return
}
if strings.HasSuffix(embed.Name, `Auto`) {
unit.NameSpace[`?`+embed.Name[:len(embed.Name)-4]] = uint32(ind) | NSPub
return
}
unit.AddFunc(ind, obj, true)
} | core/embed.go | 0.520009 | 0.429429 | embed.go | starcoder |
package model
import (
"encoding/json"
"strconv"
)
type AttributeMap struct {
values map[string]AttributeValue
}
func NewAttributeMap() *AttributeMap {
values := make(map[string]AttributeValue)
return &AttributeMap{values}
}
func NewAttributeMapWithValues(values map[string]AttributeValue) *AttributeMap {
return &AttributeMap{values: values}
}
func NewStringValue(value string) AttributeValue {
return &stringValue{value: value}
}
func NewIntValue(value int64) AttributeValue {
return &intValue{value: value}
}
func NewBoolValue(value bool) AttributeValue {
return &boolValue{value: value}
}
func (attributes *AttributeMap) Merge(other *AttributeMap) {
if other == nil {
return
}
for k, v := range other.values {
attributes.values[k] = v
}
}
func (attributes *AttributeMap) Size() int {
return len(attributes.values)
}
func (attributes *AttributeMap) IsEmpty() bool {
return len(attributes.values) == 0
}
func (attributes *AttributeMap) HasAttribute(key string) bool {
_, existing := attributes.values[key]
return existing
}
func (attributes *AttributeMap) GetStringValue(key string) string {
value := attributes.values[key]
if x, ok := value.(*stringValue); ok {
return x.value
}
return ""
}
func (attributes *AttributeMap) AddStringValue(key string, value string) {
attributes.values[key] = &stringValue{
value: value,
}
}
func (attributes *AttributeMap) UpdateAddStringValue(key string, value string) {
if v, ok := attributes.values[key]; ok {
v.(*stringValue).value = value
} else {
attributes.AddStringValue(key, value)
}
}
func (attributes *AttributeMap) GetIntValue(key string) int64 {
value := attributes.values[key]
if x, ok := value.(*intValue); ok {
return x.value
}
return 0
}
func (attributes *AttributeMap) AddIntValue(key string, value int64) {
attributes.values[key] = &intValue{
value: value,
}
}
func (attributes *AttributeMap) UpdateAddIntValue(key string, value int64) {
if v, ok := attributes.values[key]; ok {
v.(*intValue).value = value
} else {
attributes.AddIntValue(key, value)
}
}
func (attributes *AttributeMap) GetBoolValue(key string) bool {
value := attributes.values[key]
if x, ok := value.(*boolValue); ok {
return x.value
}
return false
}
func (attributes *AttributeMap) AddBoolValue(key string, value bool) {
attributes.values[key] = &boolValue{
value: value,
}
}
func (attributes *AttributeMap) UpdateAddBoolValue(key string, value bool) {
if v, ok := attributes.values[key]; ok {
v.(*boolValue).value = value
} else {
attributes.AddBoolValue(key, value)
}
}
func (attributes *AttributeMap) RemoveAttribute(key string) {
delete(attributes.values, key)
}
func (attributes *AttributeMap) ClearAttributes() {
attributes.values = make(map[string]AttributeValue)
}
func (attributes *AttributeMap) ToStringMap() map[string]string {
stringMap := make(map[string]string)
for k, v := range attributes.values {
stringMap[k] = v.ToString()
}
return stringMap
}
func (attributes *AttributeMap) GetValues() map[string]AttributeValue {
if attributes != nil {
return attributes.values
}
return nil
}
// ResetValues sets the default value for all elements. Used for implementing sync.Pool.
func (attributes *AttributeMap) ResetValues() {
for _, v := range attributes.values {
v.Reset()
}
}
func (attributes *AttributeMap) String() string {
json, _ := json.Marshal(attributes.ToStringMap())
return string(json)
}
type AttributeValue interface {
ToString() string
Reset()
}
type stringValue struct {
value string
}
func (v *stringValue) ToString() string {
return v.value
}
func (v *stringValue) Reset() {
v.value = ""
}
type intValue struct {
value int64
}
func (v *intValue) ToString() string {
return strconv.FormatInt(v.value, 10)
}
func (v *intValue) Reset() {
v.value = 0
}
type boolValue struct {
value bool
}
func (v *boolValue) ToString() string {
return strconv.FormatBool(v.value)
}
func (v *boolValue) Reset() {
v.value = false
} | collector/model/attribute_map.go | 0.736685 | 0.512388 | attribute_map.go | starcoder |
package main
import (
"log"
"math"
)
/**
a sevenish number is defined as a value that is a unique power of 7 or a sum of two unique powers of 7
this function is to find the sevenish number at n in the sequence (eg 1=1, 2=7, 3=8, 4=49, 5=50, 6=51 ...)
*/
func sevenishNumber(num uint64) uint64 {
if num < 1 {
log.Fatal("cannot get sevenish number in sequence that is less than 1")
}
/**
short circuit our uniques seed values
*/
if num == 1 {
return 1
}
if num == 2 {
return 7
}
/**
seed uniques with first 2 sevenish numbers
set max number of sevenish we can handle with our initial 2 uniques which can cover 3 values in the sequence
*/
uniques := []uint64{1, 7}
maxNum := uint64(3)
for num > maxNum {
/**
if the num requested is maxNum + 1 then get the next power of 7
which is the length of our uniques slice and return it
*/
if num == maxNum+1 {
return uint64(math.Pow(7, float64(len(uniques))))
}
/**
until maxNum is higher than num append the next unique and update the max number in the sequence we can handle
which is maxNum + how many uniques are in the updated list
*/
uniques = append(uniques, uint64(math.Pow(7, float64(len(uniques)))))
maxNum = maxNum + uint64(len(uniques))
}
/**
num 1, 2 and any num in sequence that is a unique power of 7 are handled at this point
we need to handle sevenish values that are sums of unique powers of 7
first we get the last unique value in our slice which we know will be the first power of 7 we are going to add
the next unique value we need to add we get by starting at the last unique power of 7 and subtract
maxNum - num + 1 so for example if maxNum == num then we just subtract 1 from the end of the slice and use that
*/
return uniques[len(uniques)-1] + uniques[uint64(len(uniques))-1-(maxNum-num+1)]
}
func main() {
log.Println(sevenishNumber(1))
log.Println(sevenishNumber(2))
log.Println(sevenishNumber(3))
log.Println(sevenishNumber(4))
log.Println(sevenishNumber(5))
log.Println(sevenishNumber(6))
log.Println(sevenishNumber(7))
log.Println(sevenishNumber(8))
log.Println(sevenishNumber(9))
log.Println(sevenishNumber(10))
log.Println(sevenishNumber(11))
log.Println(sevenishNumber(13))
log.Println(sevenishNumber(14))
log.Println(sevenishNumber(15))
log.Println(sevenishNumber(16))
log.Println(sevenishNumber(17))
log.Println(sevenishNumber(18))
log.Println(sevenishNumber(19))
log.Println(sevenishNumber(20))
log.Println(sevenishNumber(21))
log.Println(sevenishNumber(22))
log.Println(sevenishNumber(23))
} | dec1/main.go | 0.505615 | 0.545467 | main.go | starcoder |
package network
import (
"encoding/json"
"fmt"
"testing"
"github.com/ingrammicro/cio/api/types"
"github.com/ingrammicro/cio/utils"
"github.com/stretchr/testify/assert"
)
// ListListenersMocked test mocked function
func ListListenersMocked(t *testing.T, loadBalancerID string, listenersIn []*types.Listener) []*types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenersIn)
assert.Nil(err, "Listeners test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID)).Return(dIn, 200, nil)
listenersOut, err := ds.ListListeners(loadBalancerID)
assert.Nil(err, "Error getting listeners")
assert.Equal(listenersIn, listenersOut, "ListListeners returned different listeners")
return listenersOut
}
// ListListenersFailErrMocked test mocked function
func ListListenersFailErrMocked(t *testing.T, loadBalancerID string, listenersIn []*types.Listener) []*types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenersIn)
assert.Nil(err, "Listeners test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID)).
Return(dIn, 200, fmt.Errorf("mocked error"))
listenersOut, err := ds.ListListeners(loadBalancerID)
assert.NotNil(err, "We are expecting an error")
assert.Nil(listenersOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return listenersOut
}
// ListListenersFailStatusMocked test mocked function
func ListListenersFailStatusMocked(
t *testing.T,
loadBalancerID string,
listenersIn []*types.Listener,
) []*types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenersIn)
assert.Nil(err, "Listeners test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID)).Return(dIn, 499, nil)
listenersOut, err := ds.ListListeners(loadBalancerID)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(listenersOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return listenersOut
}
// ListListenersFailJSONMocked test mocked function
func ListListenersFailJSONMocked(t *testing.T, loadBalancerID string, listenersIn []*types.Listener) []*types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID)).Return(dIn, 200, nil)
listenersOut, err := ds.ListListeners(loadBalancerID)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(listenersOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return listenersOut
}
// GetListenerMocked test mocked function
func GetListenerMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 200, nil)
listenerOut, err := ds.GetListener(listenerIn.ID)
assert.Nil(err, "Error getting listener")
assert.Equal(*listenerIn, *listenerOut, "GetListener returned different listener")
return listenerOut
}
// GetListenerFailErrMocked test mocked function
func GetListenerFailErrMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 200, fmt.Errorf("mocked error"))
listenerOut, err := ds.GetListener(listenerIn.ID)
assert.NotNil(err, "We are expecting an error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return listenerOut
}
// GetListenerFailStatusMocked test mocked function
func GetListenerFailStatusMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 499, nil)
listenerOut, err := ds.GetListener(listenerIn.ID)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return listenerOut
}
// GetListenerFailJSONMocked test mocked function
func GetListenerFailJSONMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 200, nil)
listenerOut, err := ds.GetListener(listenerIn.ID)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return listenerOut
}
// CreateListenerMocked test mocked function
func CreateListenerMocked(t *testing.T, loadBalancerID string, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID), mapIn).Return(dOut, 200, nil)
listenerOut, err := ds.CreateListener(loadBalancerID, mapIn)
assert.Nil(err, "Error creating listener")
assert.Equal(listenerIn, listenerOut, "CreateListener returned different listener")
return listenerOut
}
// CreateListenerFailErrMocked test mocked function
func CreateListenerFailErrMocked(t *testing.T, loadBalancerID string, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID), mapIn).
Return(dOut, 200, fmt.Errorf("mocked error"))
listenerOut, err := ds.CreateListener(loadBalancerID, mapIn)
assert.NotNil(err, "We are expecting an error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return listenerOut
}
// CreateListenerFailStatusMocked test mocked function
func CreateListenerFailStatusMocked(t *testing.T, loadBalancerID string, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID), mapIn).Return(dOut, 499, nil)
listenerOut, err := ds.CreateListener(loadBalancerID, mapIn)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return listenerOut
}
// CreateListenerFailJSONMocked test mocked function
func CreateListenerFailJSONMocked(t *testing.T, loadBalancerID string, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkLoadBalancerListeners, loadBalancerID), mapIn).Return(dIn, 200, nil)
listenerOut, err := ds.CreateListener(loadBalancerID, mapIn)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return listenerOut
}
// UpdateListenerMocked test mocked function
func UpdateListenerMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID), mapIn).Return(dOut, 200, nil)
listenerOut, err := ds.UpdateListener(listenerIn.ID, mapIn)
assert.Nil(err, "Error updating listener")
assert.Equal(listenerIn, listenerOut, "UpdateListener returned different listener")
return listenerOut
}
// UpdateListenerFailErrMocked test mocked function
func UpdateListenerFailErrMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID), mapIn).
Return(dOut, 200, fmt.Errorf("mocked error"))
listenerOut, err := ds.UpdateListener(listenerIn.ID, mapIn)
assert.NotNil(err, "We are expecting an error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return listenerOut
}
// UpdateListenerFailStatusMocked test mocked function
func UpdateListenerFailStatusMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID), mapIn).Return(dOut, 499, nil)
listenerOut, err := ds.UpdateListener(listenerIn.ID, mapIn)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return listenerOut
}
// UpdateListenerFailJSONMocked test mocked function
func UpdateListenerFailJSONMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID), mapIn).Return(dIn, 200, nil)
listenerOut, err := ds.UpdateListener(listenerIn.ID, mapIn)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return listenerOut
}
// DeleteListenerMocked test mocked function
func DeleteListenerMocked(t *testing.T, listenerIn *types.Listener) {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Delete", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 200, nil)
listenerOut, err := ds.DeleteListener(listenerIn.ID)
assert.Nil(err, "Error deleting listener")
assert.Equal(listenerIn, listenerOut, "DeleteListener returned different listener")
}
// DeleteListenerFailErrMocked test mocked function
func DeleteListenerFailErrMocked(t *testing.T, listenerIn *types.Listener) {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Delete", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 200, fmt.Errorf("mocked error"))
listenerOut, err := ds.DeleteListener(listenerIn.ID)
assert.NotNil(err, "We are expecting an error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
}
// DeleteListenerFailStatusMocked test mocked function
func DeleteListenerFailStatusMocked(t *testing.T, listenerIn *types.Listener) {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Delete", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 499, nil)
listenerOut, err := ds.DeleteListener(listenerIn.ID)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
}
// DeleteListenerFailJSONMocked test mocked function
func DeleteListenerFailJSONMocked(t *testing.T, listenerIn *types.Listener) {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Delete", fmt.Sprintf(APIPathNetworkListener, listenerIn.ID)).Return(dIn, 200, nil)
listenerOut, err := ds.DeleteListener(listenerIn.ID)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
}
// RetryListenerMocked test mocked function
func RetryListenerMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRetry, listenerIn.ID), mapIn).Return(dOut, 200, nil)
listenerOut, err := ds.RetryListener(listenerIn.ID, mapIn)
assert.Nil(err, "Error retrying listener")
assert.Equal(listenerIn, listenerOut, "RetryListener returned different listener")
return listenerOut
}
// RetryListenerFailErrMocked test mocked function
func RetryListenerFailErrMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRetry, listenerIn.ID), mapIn).
Return(dOut, 200, fmt.Errorf("mocked error"))
listenerOut, err := ds.RetryListener(listenerIn.ID, mapIn)
assert.NotNil(err, "We are expecting an error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return listenerOut
}
// RetryListenerFailStatusMocked test mocked function
func RetryListenerFailStatusMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// to json
dOut, err := json.Marshal(listenerIn)
assert.Nil(err, "Listener test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRetry, listenerIn.ID), mapIn).Return(dOut, 499, nil)
listenerOut, err := ds.RetryListener(listenerIn.ID, mapIn)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return listenerOut
}
// RetryListenerFailJSONMocked test mocked function
func RetryListenerFailJSONMocked(t *testing.T, listenerIn *types.Listener) *types.Listener {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*listenerIn)
assert.Nil(err, "Listener test data corrupted")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRetry, listenerIn.ID), mapIn).Return(dIn, 200, nil)
listenerOut, err := ds.RetryListener(listenerIn.ID, mapIn)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(listenerOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return listenerOut
}
// ListRulesMocked test mocked function
func ListRulesMocked(t *testing.T, listenerID string, rulesIn []*types.ListenerRule) []*types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(rulesIn)
assert.Nil(err, "Rules test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListenerRules, listenerID)).Return(dIn, 200, nil)
rulesOut, err := ds.ListRules(listenerID)
assert.Nil(err, "Error getting rules")
assert.Equal(rulesIn, rulesOut, "ListRules returned different rules")
return rulesOut
}
// ListRulesFailErrMocked test mocked function
func ListRulesFailErrMocked(t *testing.T, listenerID string, rulesIn []*types.ListenerRule) []*types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(rulesIn)
assert.Nil(err, "Rules test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListenerRules, listenerID)).Return(dIn, 200, fmt.Errorf("mocked error"))
rulesOut, err := ds.ListRules(listenerID)
assert.NotNil(err, "We are expecting an error")
assert.Nil(rulesOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return rulesOut
}
// ListRulesFailStatusMocked test mocked function
func ListRulesFailStatusMocked(t *testing.T, listenerID string, rulesIn []*types.ListenerRule) []*types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(rulesIn)
assert.Nil(err, "Rules test data corrupted")
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListenerRules, listenerID)).Return(dIn, 499, nil)
rulesOut, err := ds.ListRules(listenerID)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(rulesOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return rulesOut
}
// ListRulesFailJSONMocked test mocked function
func ListRulesFailJSONMocked(t *testing.T, listenerID string, rulesIn []*types.ListenerRule) []*types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Get", fmt.Sprintf(APIPathNetworkListenerRules, listenerID)).Return(dIn, 200, nil)
rulesOut, err := ds.ListRules(listenerID)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(rulesOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return rulesOut
}
// CreateRuleMocked test mocked function
func CreateRuleMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// to json
dOut, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkListenerRules, listenerID), mapIn).Return(dOut, 200, nil)
ruleOut, err := ds.CreateRule(listenerID, mapIn)
assert.Nil(err, "Error creating rule")
assert.Equal(ruleIn, ruleOut, "CreateRule returned different rule")
return ruleOut
}
// CreateRuleFailErrMocked test mocked function
func CreateRuleFailErrMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// to json
dOut, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkListenerRules, listenerID), mapIn).
Return(dOut, 200, fmt.Errorf("mocked error"))
ruleOut, err := ds.CreateRule(listenerID, mapIn)
assert.NotNil(err, "We are expecting an error")
assert.Nil(ruleOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return ruleOut
}
// CreateRuleFailStatusMocked test mocked function
func CreateRuleFailStatusMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// to json
dOut, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkListenerRules, listenerID), mapIn).Return(dOut, 499, nil)
ruleOut, err := ds.CreateRule(listenerID, mapIn)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(ruleOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return ruleOut
}
// CreateRuleFailJSONMocked test mocked function
func CreateRuleFailJSONMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Post", fmt.Sprintf(APIPathNetworkListenerRules, listenerID), mapIn).Return(dIn, 200, nil)
ruleOut, err := ds.CreateRule(listenerID, mapIn)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(ruleOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return ruleOut
}
// UpdateRuleMocked test mocked function
func UpdateRuleMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// to json
dOut, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRule, listenerID, ruleIn.ID), mapIn).Return(dOut, 200, nil)
ruleOut, err := ds.UpdateRule(listenerID, ruleIn.ID, mapIn)
assert.Nil(err, "Error updating rule")
assert.Equal(ruleIn, ruleOut, "UpdateRule returned different rule")
return ruleOut
}
// UpdateRuleFailErrMocked test mocked function
func UpdateRuleFailErrMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// to json
dOut, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRule, listenerID, ruleIn.ID), mapIn).
Return(dOut, 200, fmt.Errorf("mocked error"))
ruleOut, err := ds.UpdateRule(listenerID, ruleIn.ID, mapIn)
assert.NotNil(err, "We are expecting an error")
assert.Nil(ruleOut, "Expecting nil output")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
return ruleOut
}
// UpdateRuleFailStatusMocked test mocked function
func UpdateRuleFailStatusMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// to json
dOut, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRule, listenerID, ruleIn.ID), mapIn).Return(dOut, 499, nil)
ruleOut, err := ds.UpdateRule(listenerID, ruleIn.ID, mapIn)
assert.NotNil(err, "We are expecting an status code error")
assert.Nil(ruleOut, "Expecting nil output")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
return ruleOut
}
// UpdateRuleFailJSONMocked test mocked function
func UpdateRuleFailJSONMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) *types.ListenerRule {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// convertMap
mapIn, err := utils.ItemConvertParams(*ruleIn)
assert.Nil(err, "Rule test data corrupted")
// wrong json
dIn := []byte{10, 20, 30}
// call service
cs.On("Put", fmt.Sprintf(APIPathNetworkListenerRule, listenerID, ruleIn.ID), mapIn).Return(dIn, 200, nil)
ruleOut, err := ds.UpdateRule(listenerID, ruleIn.ID, mapIn)
assert.NotNil(err, "We are expecting a marshalling error")
assert.Nil(ruleOut, "Expecting nil output")
assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'")
return ruleOut
}
// DeleteRuleMocked test mocked function
func DeleteRuleMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Delete", fmt.Sprintf(APIPathNetworkListenerRule, listenerID, ruleIn.ID)).Return(dIn, 200, nil)
err = ds.DeleteRule(listenerID, ruleIn.ID)
assert.Nil(err, "Error deleting rule")
}
// DeleteRuleFailErrMocked test mocked function
func DeleteRuleFailErrMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Delete", fmt.Sprintf(APIPathNetworkListenerRule, listenerID, ruleIn.ID)).
Return(dIn, 200, fmt.Errorf("mocked error"))
err = ds.DeleteRule(listenerID, ruleIn.ID)
assert.NotNil(err, "We are expecting an error")
assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'")
}
// DeleteRuleFailStatusMocked test mocked function
func DeleteRuleFailStatusMocked(t *testing.T, listenerID string, ruleIn *types.ListenerRule) {
assert := assert.New(t)
// wire up
cs := &utils.MockConcertoService{}
ds, err := NewListenerService(cs)
assert.Nil(err, "Couldn't load listener service")
assert.NotNil(ds, "Listener service not instanced")
// to json
dIn, err := json.Marshal(ruleIn)
assert.Nil(err, "Rule test data corrupted")
// call service
cs.On("Delete", fmt.Sprintf(APIPathNetworkListenerRule, listenerID, ruleIn.ID)).Return(dIn, 499, nil)
err = ds.DeleteRule(listenerID, ruleIn.ID)
assert.NotNil(err, "We are expecting an status code error")
assert.Contains(err.Error(), "499", "Error should contain http code 499")
} | api/network/listeners_api_mocked.go | 0.670177 | 0.402157 | listeners_api_mocked.go | starcoder |
package should
import (
"errors"
"fmt"
"math"
"reflect"
"runtime/debug"
"strings"
"time"
)
// Equal verifies that the actual value is equal to the expected value.
// It uses reflect.DeepEqual in most cases, but also compares numerics
// regardless of specific type and compares time.Time values using the
// time.Equal method.
func Equal(actual interface{}, EXPECTED ...interface{}) error {
err := validateExpected(1, EXPECTED)
if err != nil {
return err
}
expected := EXPECTED[0]
for _, spec := range specs {
if !spec.isSatisfiedBy(actual, expected) {
continue
}
if spec.areEqual(actual, expected) {
return nil
}
break
}
return failure(report(actual, expected))
}
// Equal negated!
func (negated) Equal(actual interface{}, expected ...interface{}) error {
err := Equal(actual, expected...)
if errors.Is(err, ErrAssertionFailure) {
return nil
}
if err != nil {
return err
}
return failure("\n"+
" expected: %#v\n"+
" to not equal: %#v\n"+
" (but it did)",
expected[0],
actual,
)
}
var specs = []specification{
numericEquality{},
timeEquality{},
deepEquality{},
}
func report(a, b interface{}) string {
aType := fmt.Sprintf("(%v)", reflect.TypeOf(a))
bType := fmt.Sprintf("(%v)", reflect.TypeOf(b))
longestType := int(math.Max(float64(len(aType)), float64(len(bType))))
aType += strings.Repeat(" ", longestType-len(aType))
bType += strings.Repeat(" ", longestType-len(bType))
aFormat := fmt.Sprintf(format(a), a)
bFormat := fmt.Sprintf(format(b), b)
typeDiff := diff(bType, aType)
valueDiff := diff(bFormat, aFormat)
builder := new(strings.Builder)
_, _ = fmt.Fprintf(builder, "\n")
_, _ = fmt.Fprintf(builder, "Expected: %s %s\n", bType, bFormat)
_, _ = fmt.Fprintf(builder, "Actual : %s %s\n", aType, aFormat)
_, _ = fmt.Fprintf(builder, " %s %s\n", typeDiff, valueDiff)
_, _ = fmt.Fprintf(builder, "Stack (filtered):\n%s\n", stack())
return builder.String()
}
func format(v interface{}) string {
if isNumeric(v) || isTime(v) {
return "%v"
} else {
return "%#v"
}
}
func diff(a, b string) string {
result := new(strings.Builder)
for x := 0; ; x++ {
if x >= len(a) && x >= len(b) {
break
}
if x >= len(a) || x >= len(b) || a[x] != b[x] {
result.WriteString("^")
} else {
result.WriteString(" ")
}
}
return result.String()
}
func stack() string {
lines := strings.Split(string(debug.Stack()), "\n")
var filtered []string
for x := 1; x < len(lines)-1; x += 2 {
if strings.Contains(lines[x+1], "_test.go:") {
filtered = append(filtered, lines[x], lines[x+1])
}
}
return "> " + strings.Join(filtered, "\n> ")
}
type formatter func(interface{}) string
type specification interface {
isSatisfiedBy(a, b interface{}) bool
areEqual(a, b interface{}) bool
}
// deepEquality compares any two values using reflect.DeepEqual.
// https://golang.org/pkg/reflect/#DeepEqual
type deepEquality struct{}
func (this deepEquality) isSatisfiedBy(a, b interface{}) bool {
return reflect.TypeOf(a) == reflect.TypeOf(b)
}
func (this deepEquality) areEqual(a, b interface{}) bool {
return reflect.DeepEqual(a, b)
}
// numericEquality compares numeric values using the built-in equality
// operator (`==`). Values of differing numeric reflect.Kind are each
// converted to the type of the other and are compared with `==` in both
// directions. https://golang.org/pkg/reflect/#Kind
type numericEquality struct{}
func (this numericEquality) isSatisfiedBy(a, b interface{}) bool {
return isNumeric(a) && isNumeric(b)
}
func (this numericEquality) areEqual(a, b interface{}) bool {
aValue := reflect.ValueOf(a)
bValue := reflect.ValueOf(b)
aAsB := aValue.Convert(bValue.Type()).Interface()
bAsA := bValue.Convert(aValue.Type()).Interface()
return a == bAsA && b == aAsB
}
func isNumeric(v interface{}) bool {
_, found := numericKinds[reflect.TypeOf(v).Kind()]
return found
}
// timeEquality compares values both of type time.Time using their Equal method.
// https://golang.org/pkg/time/#Time.Equal
type timeEquality struct{}
func (this timeEquality) isSatisfiedBy(a, b interface{}) bool {
return isTime(a) && isTime(b)
}
func (this timeEquality) areEqual(a, b interface{}) bool {
return a.(time.Time).Equal(b.(time.Time))
}
func isTime(v interface{}) bool {
_, ok := v.(time.Time)
return ok
}
var numericKinds = map[reflect.Kind]struct{}{
reflect.Int: {},
reflect.Int8: {},
reflect.Int16: {},
reflect.Int32: {},
reflect.Int64: {},
reflect.Uint: {},
reflect.Uint8: {},
reflect.Uint16: {},
reflect.Uint32: {},
reflect.Uint64: {},
reflect.Float32: {},
reflect.Float64: {},
} | should/equal.go | 0.704668 | 0.481881 | equal.go | starcoder |
package api
import (
"fmt"
"sort"
)
// DeepCopy returns a clone of the original Metrics. It provides a deep copy
// of both the key and the value of the original Hierarchy.
func (h Hierarchy) DeepCopy() Hierarchy {
clone := make(Hierarchy, len(h))
for k, v := range h {
var clonedV []string
clonedV = append(clonedV, v...)
clone[k] = clonedV
}
return clone
}
// AddHierarchyToMetrics takes the provided hierarchy structure, and uses it
// to determine how the metrics, m, are affected, incrementing parent metrics
// based on the value of the parents child/children metrics.
// Returns new Metrics, leaving metrics m in it's original state.
func (m Metrics) AddHierarchyToMetrics(hierarchy Hierarchy) Metrics {
metrics := m.DeepCopy()
for parent, children := range hierarchy {
for metric, v := range metrics {
if contains(metric, children) {
if _, known := metrics[parent]; known {
metrics.Add(parent, v)
} else {
metrics.Set(parent, v)
}
}
}
}
return metrics
}
// SubtractHierarchyFromMetrics takes the provided hierarchy structure, and uses it
// to determine how the metrics, m, are affected, decrementing parent metrics
// based on the value of the parents child/children metrics.
// Returns new Metrics, leaving metrics m in it's original state.
func (m Metrics) SubtractHierarchyFromMetrics(hierarchy Hierarchy) Metrics {
metrics := m.DeepCopy()
for parent, children := range hierarchy {
for metric, v := range metrics {
if contains(metric, children) {
if value, known := metrics[parent]; known {
newValue := value - v
if newValue < 0 {
delete(metrics, parent)
continue
}
metrics.Set(parent, newValue)
}
}
}
}
return metrics
}
// Add takes a provided key and value and adds them to the Metric 'm'
// If the metric already existed in 'm', then the value will be added (if positive) or subtracted (if negative) from the existing value.
// If a subtraction leads to a negative value Add returns an error and the change will be discarded.
// Returns the updated value (or current value in error cases) as well as the error.
func (m Metrics) Add(name string, value int) (int, error) {
if currentValue, ok := m[name]; ok {
newValue := currentValue + value
if newValue < 0 {
return currentValue, fmt.Errorf("invalid value for metric %s post computation. this will result in 403 from 3scale", name)
}
m[name] = newValue
return newValue, nil
}
m[name] = value
return value, nil
}
// Set takes a provided key and value and sets that value of the key in 'm', overwriting any value that exists previously.
func (m Metrics) Set(name string, value int) error {
if value < 0 {
return fmt.Errorf("invalid value for metric %s post computation. this will result in 403 from 3scale", name)
}
m[name] = value
return nil
}
// Delete a metric m['name'] if present
func (m Metrics) Delete(name string) {
delete(m, name)
}
// DeepCopy returns a clone of the original Metrics
func (m Metrics) DeepCopy() Metrics {
clone := make(Metrics, len(m))
for k, v := range m {
clone[k] = v
}
return clone
}
// String returns a string representation of the Period
func (p Period) String() string {
return [...]string{"minute", "hour", "day", "week", "month", "year", "eternity"}[p]
}
// IsEqual compares two PeriodWindows. They are equal if the period is the same
// and timestamps for start and end do not differ
func (pw PeriodWindow) IsEqual(window PeriodWindow) bool {
if pw != window {
return false
}
return true
}
func (ur UsageReport) IsForEternity() bool {
if ur.PeriodWindow.Period != Eternity {
return false
}
return true
}
func (ur UsageReport) IsForYear() bool {
if ur.PeriodWindow.Period != Year {
return false
}
return true
}
func (ur UsageReport) IsForMonth() bool {
if ur.PeriodWindow.Period != Month {
return false
}
return true
}
func (ur UsageReport) IsForWeek() bool {
if ur.PeriodWindow.Period != Week {
return false
}
return true
}
func (ur UsageReport) IsForDay() bool {
if ur.PeriodWindow.Period != Day {
return false
}
return true
}
func (ur UsageReport) IsForHour() bool {
if ur.PeriodWindow.Period != Hour {
return false
}
return true
}
func (ur UsageReport) IsForMinute() bool {
if ur.PeriodWindow.Period != Minute {
return false
}
return true
}
// IsSame does a comparison of two usage reports. They are considered the same only if their PeriodWindows are equal
// and the max value for the limit has not changed. Current limit values are ignored.
func (ur UsageReport) IsSame(usageReport UsageReport) bool {
if !ur.PeriodWindow.IsEqual(usageReport.PeriodWindow) {
return false
}
if ur.MaxValue != usageReport.MaxValue {
return false
}
return true
}
// OrderByAscendingGranularity sorts each slice in the usage reports in order of ascending granularity
func (urs UsageReports) OrderByAscendingGranularity() {
for _, reports := range urs {
sort.SliceStable(reports, func(i, j int) bool {
return reports[i].PeriodWindow.Period < reports[j].PeriodWindow.Period
})
}
}
// OrderByDescendingGranularity sorts each slice in the usage reports in order of descending granularity
func (urs UsageReports) OrderByDescendingGranularity() {
for _, reports := range urs {
sort.SliceStable(reports, func(i, j int) bool {
return reports[i].PeriodWindow.Period > reports[j].PeriodWindow.Period
})
}
}
func contains(key string, in []string) bool {
for _, i := range in {
if key == i {
return true
}
}
return false
} | threescale/api/utilities.go | 0.815085 | 0.550184 | utilities.go | starcoder |
package bitmap
import "sync"
var (
tA = [8]byte{1, 2, 4, 8, 16, 32, 64, 128}
tB = [8]byte{254, 253, 251, 247, 239, 223, 191, 127}
)
func dataOrCopy(d []byte, c bool) []byte {
if !c {
return d
}
ndata := make([]byte, len(d))
copy(ndata, d)
return ndata
}
// NewSlice creates a new byteslice with length l (in bits).
// The actual size in bits might be up to 7 bits larger because
// they are stored in a byteslice.
func NewSlice(l int) []byte {
remainder := l % 8
if remainder != 0 {
remainder = 1
}
return make([]byte, l/8+remainder)
}
// Get returns the value of bit i from map m.
// It doesn't check the bounds of the slice.
func Get(m []byte, i int) bool {
return m[i/8]&tA[i%8] != 0
}
// Set sets bit i of map m to value v.
// It doesn't check the bounds of the slice.
func Set(m []byte, i int, v bool) {
index := i / 8
bit := i % 8
if v {
m[index] = m[index] | tA[bit]
} else {
m[index] = m[index] & tB[bit]
}
}
// GetBit returns the value of bit i of byte b.
// The bit index must be between 0 and 7.
func GetBit(b byte, i int) bool {
return b&tA[i] != 0
}
// SetBit sets bit i of byte b to value v.
// The bit index must be between 0 and 7.
func SetBit(b byte, i int, v bool) byte {
if v {
return b | tA[i]
}
return b & tB[i]
}
// SetBitRef sets bit i of byte *b to value v.
func SetBitRef(b *byte, i int, v bool) {
if v {
*b = *b | tA[i]
} else {
*b = *b & tB[i]
}
}
// Len returns the length (in bits) of the provided byteslice.
// It will always be a multipile of 8 bits.
func Len(m []byte) int {
return len(m) * 8
}
// Bitmap is a byteslice with bitmap functions.
// Creating one form existing data is as simple as bitmap := Bitmap(data).
type Bitmap []byte
// New creates a new Bitmap instance with length l (in bits).
func New(l int) Bitmap {
return NewSlice(l)
}
// Len wraps around the Len function.
func (b Bitmap) Len() int {
return Len(b)
}
// Get wraps around the Get function.
func (b Bitmap) Get(i int) bool {
return Get(b, i)
}
// Set wraps around the Set function.
func (b Bitmap) Set(i int, v bool) {
Set(b, i, v)
}
// Data returns the data of the bitmap.
// If copy is false the actual underlying slice will be returned.
func (b Bitmap) Data(copy bool) []byte {
return dataOrCopy(b, copy)
}
// Threadsafe implements thread-safe read- and write locking for the bitmap.
type Threadsafe struct {
bm Bitmap
mu sync.RWMutex
}
// TSFromData creates a new Threadsafe using the provided data.
// If copy is true the actual slice will be used.
func TSFromData(data []byte, copy bool) *Threadsafe {
return &Threadsafe{
bm: Bitmap(dataOrCopy(data, copy)),
}
}
// NewTS creates a new Threadsafe instance.
func NewTS(length int) *Threadsafe {
return &Threadsafe{
bm: New(length),
}
}
// Data returns the data of the bitmap.
// If copy is false the actual underlying slice will be returned.
func (b *Threadsafe) Data(copy bool) []byte {
b.mu.RLock()
data := dataOrCopy(b.bm, copy)
b.mu.RUnlock()
return data
}
// Len wraps around the Len function.
func (b Threadsafe) Len() int {
b.mu.RLock()
l := b.bm.Len()
b.mu.RUnlock()
return l
}
// Get wraps around the Get function.
func (b Threadsafe) Get(i int) bool {
b.mu.RLock()
v := b.bm.Get(i)
b.mu.RUnlock()
return v
}
// Set wraps around the Set function.
func (b Threadsafe) Set(i int, v bool) {
b.mu.Lock()
b.bm.Set(i, v)
b.mu.Unlock()
}
// Concurrent is a bitmap implementation that achieves thread-safety
// using atomic operations along with some unsafe.
// It performs atomic operations on 32bits of data.
type Concurrent []byte
// NewConcurrent returns a concurrent bitmap.
// It will create a bitmap
func NewConcurrent(l int) Concurrent {
remainder := l % 8
if remainder != 0 {
remainder = 1
}
return make([]byte, l/8+remainder, l/8+remainder+3)
}
// Get wraps around the Get function.
func (c Concurrent) Get(b int) bool {
return Get(c, b)
}
// Set wraps around the SetAtomic function.
func (c Concurrent) Set(b int, v bool) {
SetAtomic(c, b, v)
}
// Len wraps around the Len function.
func (c Concurrent) Len() int {
return Len(c)
}
// Data returns the data of the bitmap.
// If copy is false the actual underlying slice will be returned.
func (c Concurrent) Data(copy bool) []byte {
return dataOrCopy(c, copy)
} | bitmap.go | 0.749637 | 0.455199 | bitmap.go | starcoder |
package matrixexp
import (
"github.com/gonum/blas"
"github.com/gonum/blas/blas64"
)
// Mul represents matrix multiplication.
type Mul struct {
Left MatrixExp
Right MatrixExp
}
// String implements the Stringer interface.
func (m1 *Mul) String() string {
return m1.Left.String() + ".Mul(" + m1.Right.String() + ")"
}
// Dims returns the matrix dimensions.
func (m1 *Mul) Dims() (r, c int) {
r, _ = m1.Left.Dims()
_, c = m1.Right.Dims()
return
}
// At returns the value at a given row, column index.
func (m1 *Mul) At(r, c int) float64 {
var v float64
_, n := m1.Left.Dims()
for i := 0; i < n; i++ {
v += m1.Left.At(r, i) * m1.Right.At(i, c)
}
return v
}
// Eval returns a matrix literal.
func (m1 *Mul) Eval() MatrixLiteral {
// This should be replaced with a call to Eval on each side, and then a type
// switch to handle the various matrix literals.
lm := m1.Left.Eval()
rm := m1.Right.Eval()
left := lm.AsGeneral()
right := rm.AsGeneral()
r, c := m1.Dims()
m := blas64.General{
Rows: r,
Cols: c,
Stride: c,
Data: make([]float64, r*c),
}
blas64.Gemm(blas.NoTrans, blas.NoTrans, 1, left, right, 0, m)
return &General{m}
}
// Copy creates a (deep) copy of the Matrix Expression.
func (m1 *Mul) Copy() MatrixExp {
return &Mul{
Left: m1.Left.Copy(),
Right: m1.Right.Copy(),
}
}
// Err returns the first error encountered while constructing the matrix expression.
func (m1 *Mul) Err() error {
if err := m1.Left.Err(); err != nil {
return err
}
if err := m1.Right.Err(); err != nil {
return err
}
_, c := m1.Left.Dims()
r, _ := m1.Right.Dims()
if c != r {
return ErrInnerDimMismatch{
R: r,
C: c,
}
}
return nil
}
// T transposes a matrix.
func (m1 *Mul) T() MatrixExp {
return &T{m1}
}
// Add two matrices together.
func (m1 *Mul) Add(m2 MatrixExp) MatrixExp {
return &Add{
Left: m1,
Right: m2,
}
}
// Sub subtracts the right matrix from the left matrix.
func (m1 *Mul) Sub(m2 MatrixExp) MatrixExp {
return &Sub{
Left: m1,
Right: m2,
}
}
// Scale performs scalar multiplication.
func (m1 *Mul) Scale(c float64) MatrixExp {
return &Scale{
C: c,
M: m1,
}
}
// Mul performs matrix multiplication.
func (m1 *Mul) Mul(m2 MatrixExp) MatrixExp {
return &Mul{
Left: m1,
Right: m2,
}
}
// MulElem performs element-wise multiplication.
func (m1 *Mul) MulElem(m2 MatrixExp) MatrixExp {
return &MulElem{
Left: m1,
Right: m2,
}
}
// DivElem performs element-wise division.
func (m1 *Mul) DivElem(m2 MatrixExp) MatrixExp {
return &DivElem{
Left: m1,
Right: m2,
}
} | mul.go | 0.908646 | 0.480966 | mul.go | starcoder |
package octal
var octByteToString = [256]string{
0: `000`,
1: `001`,
2: `002`,
3: `003`,
4: `004`,
5: `005`,
6: `006`,
7: `007`,
8: `010`,
9: `011`,
10: `012`,
11: `013`,
12: `014`,
13: `015`,
14: `016`,
15: `017`,
16: `020`,
17: `021`,
18: `022`,
19: `023`,
20: `024`,
21: `025`,
22: `026`,
23: `027`,
24: `030`,
25: `031`,
26: `032`,
27: `033`,
28: `034`,
29: `035`,
30: `036`,
31: `037`,
32: `040`,
33: `041`,
34: `042`,
35: `043`,
36: `044`,
37: `045`,
38: `046`,
39: `047`,
40: `050`,
41: `051`,
42: `052`,
43: `053`,
44: `054`,
45: `055`,
46: `056`,
47: `057`,
48: `060`,
49: `061`,
50: `062`,
51: `063`,
52: `064`,
53: `065`,
54: `066`,
55: `067`,
56: `070`,
57: `071`,
58: `072`,
59: `073`,
60: `074`,
61: `075`,
62: `076`,
63: `077`,
64: `100`,
65: `101`,
66: `102`,
67: `103`,
68: `104`,
69: `105`,
70: `106`,
71: `107`,
72: `110`,
73: `111`,
74: `112`,
75: `113`,
76: `114`,
77: `115`,
78: `116`,
79: `117`,
80: `120`,
81: `121`,
82: `122`,
83: `123`,
84: `124`,
85: `125`,
86: `126`,
87: `127`,
88: `130`,
89: `131`,
90: `132`,
91: `133`,
92: `134`,
93: `135`,
94: `136`,
95: `137`,
96: `140`,
97: `141`,
98: `142`,
99: `143`,
100: `144`,
101: `145`,
102: `146`,
103: `147`,
104: `150`,
105: `151`,
106: `152`,
107: `153`,
108: `154`,
109: `155`,
110: `156`,
111: `157`,
112: `160`,
113: `161`,
114: `162`,
115: `163`,
116: `164`,
117: `165`,
118: `166`,
119: `167`,
120: `170`,
121: `171`,
122: `172`,
123: `173`,
124: `174`,
125: `175`,
126: `176`,
127: `177`,
128: `200`,
129: `201`,
130: `202`,
131: `203`,
132: `204`,
133: `205`,
134: `206`,
135: `207`,
136: `210`,
137: `211`,
138: `212`,
139: `213`,
140: `214`,
141: `215`,
142: `216`,
143: `217`,
144: `220`,
145: `221`,
146: `222`,
147: `223`,
148: `224`,
149: `225`,
150: `226`,
151: `227`,
152: `230`,
153: `231`,
154: `232`,
155: `233`,
156: `234`,
157: `235`,
158: `236`,
159: `237`,
160: `240`,
161: `241`,
162: `242`,
163: `243`,
164: `244`,
165: `245`,
166: `246`,
167: `247`,
168: `250`,
169: `251`,
170: `252`,
171: `253`,
172: `254`,
173: `255`,
174: `256`,
175: `257`,
176: `260`,
177: `261`,
178: `262`,
179: `263`,
180: `264`,
181: `265`,
182: `266`,
183: `267`,
184: `270`,
185: `271`,
186: `272`,
187: `273`,
188: `274`,
189: `275`,
190: `276`,
191: `277`,
192: `300`,
193: `301`,
194: `302`,
195: `303`,
196: `304`,
197: `305`,
198: `306`,
199: `307`,
200: `310`,
201: `311`,
202: `312`,
203: `313`,
204: `314`,
205: `315`,
206: `316`,
207: `317`,
208: `320`,
209: `321`,
210: `322`,
211: `323`,
212: `324`,
213: `325`,
214: `326`,
215: `327`,
216: `330`,
217: `331`,
218: `332`,
219: `333`,
220: `334`,
221: `335`,
222: `336`,
223: `337`,
224: `340`,
225: `341`,
226: `342`,
227: `343`,
228: `344`,
229: `345`,
230: `346`,
231: `347`,
232: `350`,
233: `351`,
234: `352`,
235: `353`,
236: `354`,
237: `355`,
238: `356`,
239: `357`,
240: `360`,
241: `361`,
242: `362`,
243: `363`,
244: `364`,
245: `365`,
246: `366`,
247: `367`,
248: `370`,
249: `371`,
250: `372`,
251: `373`,
252: `374`,
253: `375`,
254: `376`,
255: `377`,
} | pkg/reader/byteFormatters/octal/oct_lookup.go | 0.63341 | 0.414366 | oct_lookup.go | starcoder |
package gjp
//--------------------
// IMPORTS
//--------------------
import "github.com/tideland/golib/errors"
//--------------------
// DIFFERENCE
//--------------------
// Diff manages the two parsed documents and their differences.
type Diff interface {
// FirstDocument returns the first document passed to Diff().
FirstDocument() Document
// SecondDocument returns the second document passed to Diff().
SecondDocument() Document
// Differences returns a list of paths where the documents
// have different content.
Differences() []string
// DifferenceAt returns the differences at the given path by
// returning the first and the second value.
DifferenceAt(path string) (Value, Value)
}
// diff implements Diff.
type diff struct {
first Document
second Document
paths []string
}
// Compare parses and compares the documents and returns their differences.
func Compare(first, second []byte, separator string) (Diff, error) {
fd, err := Parse(first, separator)
if err != nil {
return nil, err
}
sd, err := Parse(second, separator)
if err != nil {
return nil, err
}
d := &diff{
first: fd,
second: sd,
}
err = d.compare()
if err != nil {
return nil, err
}
return d, nil
}
// CompareDocuments compares the documents and returns their differences.
func CompareDocuments(first, second Document, separator string) (Diff, error) {
fd, ok := first.(*document)
if !ok {
return nil, errors.New(ErrInvalidDocument, errorMessages, "first")
}
fd.separator = separator
sd, ok := second.(*document)
if !ok {
return nil, errors.New(ErrInvalidDocument, errorMessages, "second")
}
sd.separator = separator
d := &diff{
first: fd,
second: sd,
}
err := d.compare()
if err != nil {
return nil, err
}
return d, nil
}
func (d *diff) FirstDocument() Document {
return d.first
}
func (d *diff) SecondDocument() Document {
return d.second
}
func (d *diff) Differences() []string {
return d.paths
}
func (d *diff) DifferenceAt(path string) (Value, Value) {
firstValue := d.first.ValueAt(path)
secondValue := d.second.ValueAt(path)
return firstValue, secondValue
}
func (d *diff) compare() error {
firstPaths := map[string]struct{}{}
firstProcessor := func(path string, value Value) error {
firstPaths[path] = struct{}{}
if !value.Equals(d.second.ValueAt(path)) {
d.paths = append(d.paths, path)
}
return nil
}
err := d.first.Process(firstProcessor)
if err != nil {
return err
}
secondProcessor := func(path string, value Value) error {
_, ok := firstPaths[path]
if ok {
// Been there, done that.
return nil
}
d.paths = append(d.paths, path)
return nil
}
return d.second.Process(secondProcessor)
}
// EOF | gjp/diff.go | 0.675336 | 0.435962 | diff.go | starcoder |
package glider
import (
"math"
)
type distanceFormula_t uint8
const (
DISTANCE_FORMULA_HAVERSINE distanceFormula_t = iota
DISTANCE_FORMULA_SPHERICAL_LAW_OF_COSINES
DISTANCE_FORMULA_EQUIRECTANGULAR
DISTANCE_FORMULA_CACHED_EQUIRECTANGULAR
)
// Calculate the distance between two points
func Distance(p1, p2 Point) Meters {
switch configuration.DistanceFormula {
case DISTANCE_FORMULA_HAVERSINE:
return haversineDistance(p1, p2)
case DISTANCE_FORMULA_SPHERICAL_LAW_OF_COSINES:
return sphericalLawOfCosinesDistance(p1, p2)
case DISTANCE_FORMULA_EQUIRECTANGULAR:
return equirectangularDistance(p1, p2)
case DISTANCE_FORMULA_CACHED_EQUIRECTANGULAR:
return cachedEquirectangularDistance(p1, p2)
default:
panic("Bad distanceFormula")
}
}
const RADIUS_M = 6371e3
func haversineDistance(p1, p2 Point) Meters {
// Taken from https://www.movable-type.co.uk/scripts/latlong.html
phi1 := ToCoordinateRadians(p1.Latitude)
phi2 := ToCoordinateRadians(p2.Latitude)
deltaPhi := ToCoordinateRadians(p2.Latitude - p1.Latitude)
deltaDelta := ToCoordinateRadians(p2.Longitude - p1.Longitude)
a := math.Sin(deltaPhi*0.5)*math.Sin(deltaPhi*0.5) + math.Cos(phi1)*math.Cos(phi2)*math.Sin(deltaDelta*0.5)*math.Sin(deltaDelta*0.5)
c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))
return RADIUS_M * c
}
func sphericalLawOfCosinesDistance(p1, p2 Point) Meters {
phi1 := ToCoordinateRadians(p1.Latitude)
phi2 := ToCoordinateRadians(p2.Latitude)
deltaLambda := ToCoordinateRadians(p2.Longitude - p1.Longitude)
return Meters(math.Acos(math.Sin(phi1)*math.Sin(phi2)+math.Cos(phi1)*math.Cos(phi2)*math.Cos(deltaLambda)) * RADIUS_M)
}
func latitudeDistance(lat1, lat2 Coordinate) Meters {
phi1 := ToCoordinateRadians(lat1)
phi2 := ToCoordinateRadians(lat2)
y := (phi2 - phi1)
return Meters(y * RADIUS_M)
}
func longitudeDistance(p1, p2 Point) Meters {
lambda1 := ToCoordinateRadians(p1.Longitude)
lambda2 := ToCoordinateRadians(p2.Longitude)
phi1 := ToCoordinateRadians(p1.Latitude)
phi2 := ToCoordinateRadians(p2.Latitude)
x := (lambda2 - lambda1) * math.Cos((phi1+phi2)*0.5)
return Meters(x * RADIUS_M)
}
func equirectangularDistance(p1, p2 Point) Meters {
x := latitudeDistance(p1.Latitude, p2.Latitude)
y := longitudeDistance(p1, p2)
return Meters(math.Sqrt(float64(x*x + y*y)))
}
// Like equirectangularDistance but uses a precomputed cosine value
var longitudeMultiplier *float64
func cachedLongitudeDistance(p1, p2 Point) Meters {
if longitudeMultiplier == nil {
phi1 := ToCoordinateRadians(p1.Latitude)
phi2 := ToCoordinateRadians(p2.Latitude)
temp := math.Cos((phi1+phi2)*0.5) * RADIUS_M
longitudeMultiplier = &temp
}
lambda1 := ToCoordinateRadians(p1.Longitude)
lambda2 := ToCoordinateRadians(p2.Longitude)
x := (lambda2 - lambda1) * *longitudeMultiplier
return Meters(x)
}
func cachedEquirectangularDistance(p1, p2 Point) Meters {
x := cachedLongitudeDistance(p1, p2)
y := latitudeDistance(p1.Latitude, p2.Latitude)
return Meters(math.Sqrt(float64(x*x + y*y)))
}
func equirectangularBearing(start, end Point) Radians {
y := latitudeDistance(start.Latitude, end.Latitude)
x := longitudeDistance(start, end)
theta_r := math.Atan2(y, x)
// atan returns anticlockwise direction, so negate it
bearing_r := ToRadians(90.0) - theta_r + ToRadians(360.0)
if bearing_r >= ToRadians(360.0) {
bearing_r -= ToRadians(360.0)
}
return bearing_r
}
func cachedEquirectangularBearing(start, end Point) Radians {
y := latitudeDistance(start.Latitude, end.Latitude)
x := cachedLongitudeDistance(start, end)
theta_r := math.Atan2(y, x)
bearing_r := ToRadians(90.0) - theta_r + ToRadians(360.0)
if bearing_r >= ToRadians(360.0) {
bearing_r -= ToRadians(360.0)
}
return bearing_r
}
type bearingFormula_t uint8
const (
BEARING_FORMULA_EQUIRECTANGULAR bearingFormula_t = iota
BEARING_FORMULA_CACHED_EQUIRECTANGULAR
)
// Returns the course from p1 to p2
func Course(p1, p2 Point) Radians {
switch configuration.BearingFormula {
case BEARING_FORMULA_EQUIRECTANGULAR:
return equirectangularBearing(p1, p2)
case BEARING_FORMULA_CACHED_EQUIRECTANGULAR:
return cachedEquirectangularBearing(p1, p2)
default:
panic("Bad bearingFormula")
}
}
type TurnDirection uint8
const (
Left TurnDirection = iota
Right
Straight
UTurn
)
func (td TurnDirection) String() string {
return []string{"Left", "Right", "Straight", "UTurn"}[td]
}
// Returns the direction needed to turn to get from start to end
func GetTurnDirection(bearing_r Radians, start, end Point) TurnDirection {
// Based on https://stackoverflow.com/questions/3419341/how-to-calculate-turning-direction
x := cachedLongitudeDistance(start, end)
y := latitudeDistance(start.Latitude, end.Latitude)
antiClockwise_r := ToRadians(360.0) - bearing_r
// Rotate the vector (0, -10)
offsetX := 10 * math.Sin(antiClockwise_r)
offsetY := -10 * math.Cos(antiClockwise_r)
crossProduct := y*offsetX - x*offsetY
if crossProduct < 0 {
return Left
}
if crossProduct > 0 {
return Right
}
dotProduct := y*offsetY + x*offsetX
if dotProduct > 0 {
return Straight
}
return UTurn
}
func GetAngleTo(bearing_r, goal_r Radians) Radians {
difference_r := goal_r - bearing_r
if difference_r > ToRadians(180.0) {
difference_r -= ToRadians(360.0)
} else if difference_r < -ToRadians(180.0) {
difference_r += ToRadians(360.0)
}
return difference_r
} | glider/navigation.go | 0.76533 | 0.61682 | navigation.go | starcoder |
package epoch
import (
"time"
)
// Monthly models an epoch that changes at the beginning of every month.
type Monthly struct{}
// GetData exposes data for monthly epoch.
func (Monthly) GetData() Data {
return Data{
"Once per month (monthly)",
"The last PR merge commit of each month, by UTC commit timestamp on master.",
time.Hour * 24 * 28,
time.Hour * 24 * 31,
"",
}
}
// IsEpochal indicates whether or not a monthly epochal change occur between prev and next.
func (Monthly) IsEpochal(prev time.Time, next time.Time) bool {
pu := prev.UTC()
pn := next.UTC()
if pu.Year() != pn.Year() {
return true
}
return pu.Month() != pn.Month()
}
// Weekly models an epoch that changes at the beginning of every week. Weeks begin on Mondays.
type Weekly struct{}
// GetData exposes data for weekly epoch.
func (Weekly) GetData() Data {
return Data{
"Once per week (weekly)",
"The last PR merge commit of each week, by UTC commit timestamp on master. Weeks start on Monday.",
time.Hour * 24 * 7,
time.Hour * 24 * 7,
"",
}
}
func weekday(t time.Time) int {
return (int(t.Weekday()) + 6) % 7
}
// IsEpochal indicates whether or not a weekly epochal change occur between prev and next.
func (e Weekly) IsEpochal(prev time.Time, next time.Time) bool {
pu := prev.UTC()
pn := next.UTC()
if pu.After(pn) {
return e.IsEpochal(pn, pu)
}
if pn.Sub(pu).Hours() >= 24*7 {
return true
}
return weekday(pu) > weekday(pn)
}
// Daily models an epoch that changes at the beginning of every day.
type Daily struct{}
// GetData exposes data for daily epoch.
func (Daily) GetData() Data {
return Data{
"Once per day (daily)",
"The last PR merge commit of each day, by UTC commit timestamp on master.",
time.Hour * 24,
time.Hour * 24,
"",
}
}
// IsEpochal indicates whether or not a daily epochal change occur between prev and next.
func (e Daily) IsEpochal(prev time.Time, next time.Time) bool {
pu := prev.UTC()
pn := next.UTC()
if pu.After(pn) {
return e.IsEpochal(pn, pu)
}
if pn.Sub(pu).Hours() >= 24 {
return true
}
return pu.Day() != pn.Day()
}
// Hourly models an epoch that changes at the beginning of every hour.
type Hourly struct{}
// GetData exposes data for hourly epoch.
func (Hourly) GetData() Data {
return Data{
"Once per hour (hourly)",
"The last PR merge commit of each hour, by UTC commit timestamp on master.",
time.Hour,
time.Hour,
"",
}
}
// IsEpochal indicates whether or not an hourly epochal change occur between prev and next.
func (e Hourly) IsEpochal(prev time.Time, next time.Time) bool {
pu := prev.UTC()
pn := next.UTC()
if pu.After(pn) {
return e.IsEpochal(pn, pu)
}
if pn.Sub(pu).Hours() >= 1 {
return true
}
return pu.Hour() != pn.Hour()
} | revisions/epoch/gregorian.go | 0.826151 | 0.606702 | gregorian.go | starcoder |
package samples
func init() {
sampleDataProposalCreateOperation[10] = `{
"expiration_time": "2016-01-18T23:59:59",
"extensions": [],
"fee": {
"amount": 1335,
"asset_id": "1.3.120"
},
"fee_paying_account": "1.2.282",
"proposed_ops": [
{
"op": [
43,
{
"amount_to_claim": {
"amount": "4741378900",
"asset_id": "1.3.103"
},
"extensions": [],
"fee": {
"amount": 668,
"asset_id": "1.3.120"
},
"issuer": "1.2.0"
}
]
},
{
"op": [
43,
{
"amount_to_claim": {
"amount": "7857053400",
"asset_id": "1.3.113"
},
"extensions": [],
"fee": {
"amount": 668,
"asset_id": "1.3.120"
},
"issuer": "1.2.0"
}
]
},
{
"op": [
43,
{
"amount_to_claim": {
"amount": 3070300,
"asset_id": "1.3.105"
},
"extensions": [],
"fee": {
"amount": 668,
"asset_id": "1.3.120"
},
"issuer": "1.2.0"
}
]
},
{
"op": [
43,
{
"amount_to_claim": {
"amount": "6908096900",
"asset_id": "1.3.121"
},
"extensions": [],
"fee": {
"amount": 668,
"asset_id": "1.3.120"
},
"issuer": "1.2.0"
}
]
},
{
"op": [
43,
{
"amount_to_claim": {
"amount": 371300,
"asset_id": "1.3.106"
},
"extensions": [],
"fee": {
"amount": 668,
"asset_id": "1.3.120"
},
"issuer": "1.2.0"
}
]
},
{
"op": [
43,
{
"amount_to_claim": {
"amount": 8899500,
"asset_id": "1.3.120"
},
"extensions": [],
"fee": {
"amount": 668,
"asset_id": "1.3.120"
},
"issuer": "1.2.0"
}
]
}
],
"review_period_seconds": 3600
}`
}
//end of file | gen/samples/proposalcreateoperation_10.go | 0.58261 | 0.461017 | proposalcreateoperation_10.go | starcoder |
package dymessage
import (
"math"
)
type (
// Depending on the context, the entity represents either a regular
// entity with its own primitive and reference values, or the collection
// of either primitive or reference values, sharing the same type.
Entity struct {
// The data type the entity belongs to. This must be DtEntity
// OR'ed with an index of the message definition in a registry.
// Use the GetMessageDef method of Registry to obtain the
// message definition, providing the data type of an entity.
DataType DataType
Data []byte // Memory for storing the primitive values
Entities []*Entity // The entities referenced from the current one
}
// A generic representation of the primitive values that provides
// methods for converting the value to any native primitive type. The
// provided methods do not keep track of the correct usage, meaning that
// the user must correlate between the methods and the value types.
Primitive uint64
// A generic representation of the reference values that provides
// methods for converting the value to any native reference type. The
// provided methods do not keep track of the correct usage, meaning that
// the user must correlate between the methods and the value types.
Reference struct{ *Entity }
)
// -----------------------------------------------------------------------------
// Type defaults
// GetDefaultPrimitive gets a default primitive value, which will evaluate to
// zero for all numeric types or false for boolean.
func GetDefaultPrimitive() Primitive { return Primitive(0) }
// GetDefaultReference gets a default reference value, which doesn't contain any
// data and will evaluate to nil for the reference native types or an empty
// string for string type.
func GetDefaultReference() Reference { return Reference{} }
// -----------------------------------------------------------------------------
// Entity implementation
// Reset resets the entity type and content, making it available for reuse.
func (e *Entity) Reset() {
if e.DataType == DtNone {
e.Data, e.Entities = e.Data[:0], e.Entities[:0]
}
}
// -----------------------------------------------------------------------------
// Primitive value conversions
func FromInt32(value int32) Primitive { return Primitive(value) }
func FromInt64(value int64) Primitive { return Primitive(value) }
func FromUint32(value uint32) Primitive { return Primitive(value) }
func FromUint64(value uint64) Primitive { return Primitive(value) }
func FromFloat32(value float32) Primitive { return Primitive(math.Float32bits(value)) }
func FromFloat64(value float64) Primitive { return Primitive(math.Float64bits(value)) }
func FromBool(value bool) Primitive {
if value {
return 1
} else {
return 0
}
}
func (p Primitive) ToInt32() int32 { return int32(p) }
func (p Primitive) ToInt64() int64 { return int64(p) }
func (p Primitive) ToUint32() uint32 { return uint32(p) }
func (p Primitive) ToUint64() uint64 { return uint64(p) }
func (p Primitive) ToFloat32() float32 { return math.Float32frombits(uint32(p)) }
func (p Primitive) ToFloat64() float64 { return math.Float64frombits(uint64(p)) }
func (p Primitive) ToBool() bool { return p != 0 }
// -----------------------------------------------------------------------------
// Reference value conversions
func FromEntity(value *Entity) Reference {
return Reference{value}
}
func FromString(value string) Reference {
return Reference{&Entity{Data: ([]byte)(value)}}
}
func FromBytes(value []byte, clone bool) Reference {
data := value
if clone {
data = make([]byte, len(value))
copy(data, value)
}
return Reference{&Entity{Data: data}}
}
func (r Reference) ToEntity() *Entity { return r.Entity }
func (r Reference) ToString() string { return string(r.ToBytes()) }
func (r Reference) ToBytes() []byte {
if r.Entity == nil {
return nil
}
return r.Entity.Data
} | datamodel.go | 0.774583 | 0.665078 | datamodel.go | starcoder |
package geario
import (
"fmt"
"regexp"
"strconv"
"strings"
)
type B float64
func (b B) String() string {
return BytesSize(b)
}
// See: http://en.wikipedia.org/wiki/Binary_prefix
const (
// Decimal
KB B = 1000
MB B = 1000 * KB
GB B = 1000 * MB
TB B = 1000 * GB
PB B = 1000 * TB
EB B = 1000 * PB
ZB B = 1000 * EB
YB B = 1000 * ZB
// Binary
KiB B = 1024
MiB B = 1024 * KiB
GiB B = 1024 * MiB
TiB B = 1024 * GiB
PiB B = 1024 * TiB
EiB B = 1024 * PiB
ZiB B = 1024 * EiB
YiB B = 1024 * ZiB
)
type unitMap map[string]B
var (
decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB, "e": EB, "z": ZB, "y": YB}
binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB, "e": EiB, "z": ZiB, "y": YiB}
sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpPeEzZyY])?[iI]?[bB]?$`)
)
var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
func getSizeAndUnit(size B, base B, _map []string) (B, string) {
i := 0
unitsLimit := len(_map) - 1
for size >= base && i < unitsLimit {
size = size / base
i++
}
return size, _map[i]
}
// CustomSize returns a human-readable approximation of a size
// using custom format.
func CustomSize(format string, size B, base B, _map []string) string {
size, unit := getSizeAndUnit(size, base, _map)
return fmt.Sprintf(format, size, unit)
}
// HumanSizeWithPrecision allows the size to be in any precision
func HumanSizeWithPrecision(size B, precision int) string {
size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs)
return fmt.Sprintf("%.*g%s", precision, size, unit)
}
// BytesSize returns a human-readable size in bytes, kibibytes,
// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB").
func BytesSize(size B) string {
return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs)
}
// FromHumanSize returns an integer from a human-readable specification of a
// size using SI standard (eg. "44kB", "17MB").
func FromHumanSize(size string) (B, error) {
return parseSize(size, decimalMap)
}
// FromBytesSize returns an integer from a human-readable specification of a
// size using binary standard (eg. "44kiB", "17MiB").
func FromBytesSize(size string) (B, error) {
return parseSize(size, binaryMap)
}
// Parses the human-readable size string into the amount it represents.
func parseSize(sizeStr string, uMap unitMap) (B, error) {
matches := sizeRegex.FindStringSubmatch(sizeStr)
if len(matches) != 4 {
return -1, fmt.Errorf("invalid size: '%s'", sizeStr)
}
size, err := strconv.ParseFloat(matches[1], 64)
if err != nil {
return -1, err
}
unitPrefix := strings.ToLower(matches[3])
if mul, ok := uMap[unitPrefix]; ok {
size *= float64(mul)
}
return B(size), nil
} | b.go | 0.794185 | 0.444203 | b.go | starcoder |
package value
import (
"fmt"
"strconv"
"unicode"
)
type (
// Value represents a value at runtime.
Value interface {
// Name returns the name of the type.
Name() string
// Comparable returns true if the 'other' value can be compared with the
// receiver.
Comparable(other Value) bool
// Equal returns true if the 'other' value is equal to the receiver.
Equal(other Value) bool
// String returns the human readable representation of the value.
String() string
}
Con interface {
Value
Len() int64
CanBeKey(Value) bool
CanHold(Value) bool
Delete(Value) (Con, Value)
}
OrdCon interface {
Con
InRange(int64) bool
At(int64) Value
Index(Value) int64
Slice(int64, int64) OrdCon
PushFront(...Value) OrdCon
PushBack(...Value) OrdCon
PopFront() (OrdCon, Value)
PopBack() (OrdCon, Value)
}
MutOrdCon interface {
OrdCon
Set(Value, Value) MutOrdCon
}
Joinable interface {
CanJoin(Value) bool
Join(Value) Value
}
Ident string
Bool bool
Num float64
)
func (Ident) Name() string { return "ident" }
func (Bool) Name() string { return "bool" }
func (Num) Name() string { return "number" }
func (a Ident) Comparable(b Value) bool { return Str(a).Comparable(b) }
func (a Bool) Comparable(b Value) bool { _, ok := b.(Bool); return ok }
func (a Num) Comparable(b Value) bool { _, ok := b.(Num); return ok }
func (a Ident) Equal(b Value) bool {
return a.Comparable(b) && Str(a) == b.(Str)
}
func (a Bool) Equal(b Value) bool {
return a.Comparable(b) && a == b.(Bool)
}
func (a Num) Equal(b Value) bool {
return a.Comparable(b) && a == b.(Num)
}
func (a Ident) String() string { return string(a) }
func (a Bool) String() string { return fmt.Sprintf("%v", bool(a)) }
func (a Num) String() string {
return strconv.FormatFloat(float64(a), 'f', -1, 64)
}
func (id Ident) Valid() Bool {
for i, ru := range string(id) {
if i == 0 && ru == '_' {
return false
}
if !unicode.IsLetter(ru) && ru != '_' {
return false
}
}
return true
}
func (a Bool) And(b Bool) Bool { return Bool(bool(a) && bool(b)) }
func (a Bool) Or(b Bool) Bool { return Bool(bool(a) || bool(b)) }
func (a Num) Int() int64 { return int64(a) }
func (a Ident) ToStr() Str { return Str(string(a)) } | scarlet/value/value.go | 0.802594 | 0.547162 | value.go | starcoder |
package rpctest
import (
"reflect"
"time"
"github.com/drcsuite/drc/chaincfg/chainhash"
"github.com/drcsuite/drc/rpcclient"
)
// JoinType is an enum representing a particular type of "node join". A node
// join is a synchronization tool used to wait until a subset of nodes have a
// consistent state with respect to an attribute.
type JoinType uint8
const (
// Blocks is a JoinType which waits until all nodes share the same
// block height.
Blocks JoinType = iota
// Mempools is a JoinType which blocks until all nodes have identical
// mempool.
Mempools
)
// JoinNodes is a synchronization tool used to block until all passed nodes are
// fully synced with respect to an attribute. This function will block for a
// period of time, finally returning once all nodes are synced according to the
// passed JoinType. This function be used to to ensure all active test
// harnesses are at a consistent state before proceeding to an assertion or
// check within rpc tests.
func JoinNodes(nodes []*Harness, joinType JoinType) error {
switch joinType {
case Blocks:
return syncBlocks(nodes)
case Mempools:
return syncMempools(nodes)
}
return nil
}
// syncMempools blocks until all nodes have identical mempools.
func syncMempools(nodes []*Harness) error {
poolsMatch := false
retry:
for !poolsMatch {
firstPool, err := nodes[0].Node.GetRawMempool()
if err != nil {
return err
}
// If all nodes have an identical mempool with respect to the
// first node, then we're done. Otherwise, drop back to the top
// of the loop and retry after a short wait period.
for _, node := range nodes[1:] {
nodePool, err := node.Node.GetRawMempool()
if err != nil {
return err
}
if !reflect.DeepEqual(firstPool, nodePool) {
time.Sleep(time.Millisecond * 100)
continue retry
}
}
poolsMatch = true
}
return nil
}
// syncBlocks blocks until all nodes report the same best chain.
func syncBlocks(nodes []*Harness) error {
blocksMatch := false
retry:
for !blocksMatch {
var prevHash *chainhash.Hash
var prevHeight int32
for _, node := range nodes {
blockHash, blockHeight, err := node.Node.GetBestBlock()
if err != nil {
return err
}
if prevHash != nil && (*blockHash != *prevHash ||
blockHeight != prevHeight) {
time.Sleep(time.Millisecond * 100)
continue retry
}
prevHash, prevHeight = blockHash, blockHeight
}
blocksMatch = true
}
return nil
}
// ConnectNode establishes a new peer-to-peer connection between the "from"
// harness and the "to" harness. The connection made is flagged as persistent,
// therefore in the case of disconnects, "from" will attempt to reestablish a
// connection to the "to" harness.
func ConnectNode(from *Harness, to *Harness) error {
peerInfo, err := from.Node.GetPeerInfo()
if err != nil {
return err
}
numPeers := len(peerInfo)
targetAddr := to.node.config.listen
if err := from.Node.AddNode(targetAddr, rpcclient.ANAdd); err != nil {
return err
}
// Block until a new connection has been established.
peerInfo, err = from.Node.GetPeerInfo()
if err != nil {
return err
}
for len(peerInfo) <= numPeers {
peerInfo, err = from.Node.GetPeerInfo()
if err != nil {
return err
}
}
return nil
}
// TearDownAll tears down all active test harnesses.
func TearDownAll() error {
harnessStateMtx.Lock()
defer harnessStateMtx.Unlock()
for _, harness := range testInstances {
if err := harness.tearDown(); err != nil {
return err
}
}
return nil
}
// ActiveHarnesses returns a slice of all currently active test harnesses. A
// test harness if considered "active" if it has been created, but not yet torn
// down.
func ActiveHarnesses() []*Harness {
harnessStateMtx.RLock()
defer harnessStateMtx.RUnlock()
activeNodes := make([]*Harness, 0, len(testInstances))
for _, harness := range testInstances {
activeNodes = append(activeNodes, harness)
}
return activeNodes
} | integration/rpctest/utils.go | 0.621081 | 0.462473 | utils.go | starcoder |
package aoc2020
/*
The small crab challenges you to a game! The crab is going to mix up some cups, and you have to predict where they'll end up.
The cups will be arranged in a circle and labeled clockwise (your puzzle input). For example, if your labeling were 32415, there would be five cups in the circle; going clockwise around the circle from the first cup, the cups would be labeled 3, 2, 4, 1, 5, and then back to 3 again.
Before the crab starts, it will designate the first cup in your list as the current cup. The crab is then going to do 100 moves.
Each move, the crab does the following actions:
The crab picks up the three cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle.
The crab selects a destination cup: the cup with a label equal to the current cup's label minus one. If this would select one of the cups that was just picked up, the crab will keep subtracting one until it finds a cup that wasn't just picked up. If at any point in this process the value goes below the lowest value on any cup's label, it wraps around to the highest value on any cup's label instead.
The crab places the cups it just picked up so that they are immediately clockwise of the destination cup. They keep the same order as when they were picked up.
The crab selects a new current cup: the cup which is immediately clockwise of the current cup.
For example, suppose your cup labeling were 389125467. If the crab were to do merely 10 moves, the following changes would occur:
-- move 1 --
cups: (3) 8 9 1 2 5 4 6 7
pick up: 8, 9, 1
destination: 2
-- move 2 --
cups: 3 (2) 8 9 1 5 4 6 7
pick up: 8, 9, 1
destination: 7
-- move 3 --
cups: 3 2 (5) 4 6 7 8 9 1
pick up: 4, 6, 7
destination: 3
-- move 4 --
cups: 7 2 5 (8) 9 1 3 4 6
pick up: 9, 1, 3
destination: 7
-- move 5 --
cups: 3 2 5 8 (4) 6 7 9 1
pick up: 6, 7, 9
destination: 3
-- move 6 --
cups: 9 2 5 8 4 (1) 3 6 7
pick up: 3, 6, 7
destination: 9
-- move 7 --
cups: 7 2 5 8 4 1 (9) 3 6
pick up: 3, 6, 7
destination: 8
-- move 8 --
cups: 8 3 6 7 4 1 9 (2) 5
pick up: 5, 8, 3
destination: 1
-- move 9 --
cups: 7 4 1 5 8 3 9 2 (6)
pick up: 7, 4, 1
destination: 5
-- move 10 --
cups: (5) 7 4 1 8 3 9 2 6
pick up: 7, 4, 1
destination: 3
-- final --
cups: 5 (8) 3 7 4 1 9 2 6
In the above example, the cups' values are the labels as they appear moving clockwise around the circle; the current cup is marked with ( ).
After the crab is done, what order will the cups be in? Starting after the cup labeled 1, collect the other cups' labels clockwise into a single string with no extra characters; each number except 1 should appear exactly once. In the above example, after 10 moves, the cups clockwise from 1 are labeled 9, 2, 6, 5, and so on, producing 92658374. If the crab were to complete all 100 moves, the order after cup 1 would be 67384529.
Using your labeling, simulate 100 moves. What are the labels on the cups after cup 1?
*/
import (
"fmt"
"strconv"
"time"
goutils "github.com/simonski/goutils"
)
// AOC_2020_20 is the entrypoint
func AOC_2020_23(cli *goutils.CLI) {
AOC_2020_23_part2_attempt1(cli)
}
func AOC_2020_23_part1_attempt1(cli *goutils.CLI) {
}
func AOC_2020_23_part2_attempt1(cli *goutils.CLI) {
start := time.Now()
input := "198753462"
SIZE := 1000000
ROUNDS := SIZE * 10
data := make([]int, SIZE)
for index := 0; index < len(input); index++ {
sval := input[index : index+1]
ival, _ := strconv.Atoi(sval)
data[index] = ival
}
inputSize := len(input)
for index := inputSize; index < SIZE; index++ {
data[index] = index + 1
}
ring := NewRing(data)
DEBUG := false
ring.Play(ROUNDS, DEBUG)
cup1 := ring.Find(1)
r1 := cup1.Next
r2 := cup1.Next.Next
fmt.Printf("r1.Value=%v, r2.Value=%v, %v x %v = %v\n", r1.Value, r2.Value, r1.Value, r2.Value, r1.Value*r2.Value)
end := time.Now()
fmt.Printf("%v\n", end.Sub(start))
}
type CrabCups struct {
OriginalData string
Data []int
}
func (cc *CrabCups) Play(Rounds int, DEBUG bool) string {
return cc.Play1(Rounds, DEBUG)
}
// func (cc *CrabCups) Play2(Rounds int, DEBUG bool) string {
// d := cc.Data
// currentCupValue := d[currentCupIndex]
// // take off the 3 cups
// for index, value := range d {
// // I want currentCupIndex+1, +2, +3 as my 3cups
// if index == (currentCupIndex+1)%len(d) {
// threeCups = append(threeCups, d[index])
// } else {
// remainder = append(remainder, d[index])
// }
// }
// }
func IndexOf(value int, data []int) int {
for index := 0; index < len(data); index++ {
if data[index] == value {
return index
}
}
return -1
}
func DebugLine(currentCup int, data []int) string {
line := ""
for _, v := range data {
if v == currentCup {
line += fmt.Sprintf("(%v) ", v)
} else {
line += fmt.Sprintf("%v ", v)
}
}
return line
}
func Shuffle(currentCup int, newIndexRequired int, data []int) []int {
index := IndexOf(currentCup, data)
offset := newIndexRequired - index
d := make([]int, len(data))
for index := 0; index < len(data); index++ {
new_index := (index + offset) % len(data)
if index+offset < 0 {
new_index = len(data) + (index + offset)
}
// fmt.Printf("Shuffle: index=%v, offset=%v, newIndex=%v len(data)=%v\n", index, offset, new_index, len(data))
d[new_index] = data[index]
}
// fmt.Printf("Shuffle: currentCup=%v, indexOfCurrentCup=%v, newIndex=%v, offset=%v, original=%v, new=%v\n", currentCup, index, index+offset, offset, data, d)
return d
}
func (cc *CrabCups) Play1(Rounds int, DEBUG bool) string {
d := cc.Data
currentCup := d[0]
lowestCup := 9
highestCup := 0
for _, value := range d {
lowestCup = goutils.Min(lowestCup, value)
highestCup = goutils.Max(highestCup, value)
}
fmt.Printf("\n%v Round(s)\n", Rounds)
for Round := 0; Round < Rounds; Round++ {
fmt.Printf("\n-- move %v --\n", Round+1)
d = Shuffle(currentCup, Round, d)
line := DebugLine(currentCup, d)
index := IndexOf(currentCup, d)
firstCupIndex := (index + 1) % len(d)
secondCupIndex := (index + 2) % len(d)
thirdCupIndex := (index + 3) % len(d)
firstCup := d[firstCupIndex]
secondCup := d[secondCupIndex]
thirdCup := d[thirdCupIndex]
remainder := make([]int, 0)
for index2 := 0; index2 < len(d); index2++ {
if d[index2] == firstCup || d[index2] == secondCup || d[index2] == thirdCup {
} else {
remainder = append(remainder, d[index2])
}
}
// fmt.Printf("(Round %v/%v d=%v, 3cups=%v,%v,%v remainder=%v\n", round, index, d, firstCup, secondCup, thirdCup, remainder)
// now threeCups holds the current set
// remainder holds everything else
// remainder := d[4:]
destinationCup := currentCup - 1
if destinationCup == 0 {
destinationCup = 9
}
for {
quit := true
// fmt.Printf("Desintation cup %v ? \n", destinationCup)
if destinationCup == firstCup || destinationCup == secondCup || destinationCup == thirdCup {
// fmt.Printf("Desintation cup equals one of our 3 cups %v yes \n", destinationCup)
destinationCup -= 1
if destinationCup < lowestCup {
// fmt.Printf("Desintation cup < lowestCup %v < %v yes, setting to %v\n ", destinationCup, lowestCup, highestCup)
destinationCup = highestCup
}
quit = false
}
if quit {
break
}
}
destinationIndex := 0
for x, value := range remainder {
if value == destinationCup {
destinationIndex = (x + 1) % len(d)
break
}
}
fmt.Printf("cups: %v\n", line)
fmt.Printf("pick up: %v, %v, %v\n", firstCup, secondCup, thirdCup)
fmt.Printf("destination: %v\n", destinationCup)
// fmt.Printf("Dstination cup is %v, index is %v\n", destinationCup, destinationIndex)
// fmt.Printf("(Round %v/[%v] - %v), currentCup: '%v', remainder: '%v'\n", round, index, d, currentCup, remainder)
leftPart := remainder[0:destinationIndex]
rightPart := remainder[destinationIndex:len(remainder)]
n := make([]int, 0)
n = append(n, leftPart...)
n = append(n, firstCup)
n = append(n, secondCup)
n = append(n, thirdCup)
n = append(n, rightPart...)
// fmt.Printf("(Round %v/[%v] - %v), currentCup: '%v', threeCups '%v,%v,%v', remainder: '%v', leftPart: '%v' rightPart: '%v', new data will be: %v\n",
// round, index, d, currentCup, firstCup, secondCup, thirdCup, remainder, leftPart, rightPart, n)
// d = append(leftPart, threeCups, rightPart)
d = n
index = IndexOf(currentCup, d) + 1
if index >= len(d) {
index = 0
}
currentCup = d[index]
}
cc.Data = d
return cc.StringValueAfter("1")
}
func (cc *CrabCups) StringValueAfter(after string) string {
d := cc.Data
offset := IndexOf(1, cc.Data)
line := ""
for index := 0; index < len(cc.Data); index++ {
new_index := (index + offset) % len(d)
if cc.Data[new_index] != 1 {
line += fmt.Sprintf("%v", d[new_index])
}
}
return line
}
func (cc *CrabCups) StringValue() string {
d := cc.Data
line := ""
for index := 0; index < len(cc.Data); index++ {
line += fmt.Sprintf("%v", d[index])
}
return line
}
func NewCrabCups(input string) *CrabCups {
cc := CrabCups{OriginalData: input}
cc.Reset()
return &cc
}
func (cc *CrabCups) Reset() {
arr := make([]int, 0)
input := cc.OriginalData
for index := 0; index < len(input); index++ {
sval := input[index : index+1]
ival, _ := strconv.Atoi(sval)
arr = append(arr, ival)
}
cc.Data = arr
} | app/aoc2020/aoc2020_23_part1.go | 0.527317 | 0.577912 | aoc2020_23_part1.go | starcoder |
package main
import (
"math/rand"
"strings"
)
type MazeCell struct {
Grid *MazeGrid `json:"grid"`
Room *Room `json:"room"`
Terrain int `json:"terrain"`
Wall bool `json:"wall"`
X int `json:"x"`
Y int `json:"y"`
}
type MazeGrid struct {
Game *Game `json:"game"`
Grid [][]*MazeCell `json:"grid"`
Width int `json:"width"`
Height int `json:"height"`
EntryX int `json:"entryX"`
EntryY int `json:"entryY"`
EndX int `json:"endX"`
EndY int `json:"endY"`
}
func (game *Game) NewMaze(width int, height int) *MazeGrid {
maze := &MazeGrid{
Game: game,
Grid: make([][]*MazeCell, width),
Width: width,
Height: height,
}
for i := 0; i < height; i++ {
maze.Grid[i] = make([]*MazeCell, height)
}
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
maze.Grid[x][y] = &MazeCell{
Room: nil,
Grid: maze,
X: x,
Y: y,
Wall: true,
Terrain: TerrainTypeCaveDeepWall1,
}
if rand.Intn(10) > 7 && x >= 1 && y >= 1 && x <= maze.Width-1 && y <= maze.Height-1 {
maze.Grid[x][y].Terrain = TerrainTypeCaveDeepWall1 + rand.Intn(4)
}
}
}
return maze
}
func (grid *MazeGrid) isValidPosition(x int, y int) bool {
return x >= 1 && x < grid.Width-1 && y >= 1 && y < grid.Height-1
}
func (cell *MazeCell) getAdjacentCells(wall bool, distance int, ordinals bool) *LinkedList {
list := NewLinkedList()
top := DirectionMax
if !ordinals {
top = DirectionNortheast
}
for direction := DirectionNorth; direction < top; direction++ {
var translatedX int = cell.X
var translatedY int = cell.Y
switch direction {
case DirectionNorth:
translatedX = cell.X
translatedY = cell.Y - distance
case DirectionEast:
translatedX = cell.X + distance
translatedY = cell.Y
case DirectionSouth:
translatedX = cell.X
translatedY = cell.Y + distance
case DirectionWest:
translatedX = cell.X - distance
translatedY = cell.Y
case DirectionNortheast:
translatedX = cell.X + distance
translatedY = cell.Y - distance
case DirectionSoutheast:
translatedX = cell.X + distance
translatedY = cell.Y + distance
case DirectionSouthwest:
translatedX = cell.X - distance
translatedY = cell.Y + distance
case DirectionNorthwest:
translatedX = cell.X - distance
translatedY = cell.Y - distance
}
if cell.Grid.isValidPosition(translatedX, translatedY) && cell.Grid.Grid[translatedX][translatedY].Wall == wall {
list.Insert(cell.Grid.Grid[translatedX][translatedY])
}
}
return list
}
func (cell *MazeCell) setAdjacentCellsTerrainType(wall bool, distance int, terrain int) {
cells := cell.getAdjacentCells(wall, distance, true)
for iter := cells.Head; iter != nil; iter = iter.Next {
cell := iter.Value.(*MazeCell)
if cell.Wall == wall {
cell.Terrain = terrain
}
}
}
/* Dig a maze using Prim's algorithm */
func (maze *MazeGrid) generatePrimMaze() {
maze.EntryX = rand.Intn(maze.Width-3) + 2
maze.EntryY = rand.Intn(maze.Height-3) + 2
var entryPoint *MazeCell = maze.Grid[maze.EntryX][maze.EntryY]
entryPoint.setWall(false)
entryPoint.Terrain = TerrainTypeCaveTunnel
frontiers := entryPoint.getAdjacentCells(true, 2, false)
for {
if len(frontiers.Values()) < 1 {
break
}
f := frontiers.GetRandomNode().Value.(*MazeCell)
neighbours := f.getAdjacentCells(false, 2, false)
if neighbours.Count > 0 {
neighbour := neighbours.GetRandomNode().Value.(*MazeCell)
passageX := (neighbour.X + f.X) / 2
passageY := (neighbour.Y + f.Y) / 2
f.setWall(false)
f.Terrain = TerrainTypeCaveTunnel
maze.Grid[passageX][passageY].setWall(false)
maze.Grid[passageX][passageY].Terrain = TerrainTypeCaveTunnel
neighbour.setWall(false)
neighbour.Terrain = TerrainTypeCaveTunnel
f.setAdjacentCellsTerrainType(true, 1, TerrainTypeCaveWall)
maze.Grid[passageX][passageY].setAdjacentCellsTerrainType(true, 1, TerrainTypeCaveWall)
neighbour.setAdjacentCellsTerrainType(true, 1, TerrainTypeCaveWall)
}
frontierCells := f.getAdjacentCells(true, 2, false)
frontiers.Concat(frontierCells)
frontiers.Remove(f)
continue
}
}
func (cell *MazeCell) setWall(wall bool) {
cell.Wall = wall
}
func (maze *MazeGrid) createRoom(x int, y int) *Room {
if maze.Grid[x][y].Room != nil {
return maze.Grid[x][y].Room
}
room := maze.Game.NewRoom()
room.Id = 0
room.Zone = nil
room.Virtual = true
room.Cell = maze.Grid[x][y]
room.Name = "In the Underground"
room.Description = "You are deep within the dark dungeons of development."
room.Exit = make(map[uint]*Exit)
room.Characters = NewLinkedList()
room.Objects = NewLinkedList()
maze.Grid[x][y].Room = room
return room
}
func (maze *MazeGrid) reify(z int) {
for y := 0; y < maze.Height; y++ {
for x := 0; x < maze.Width; x++ {
if !maze.Grid[x][y].Wall {
room := maze.createRoom(x, y)
room.X = x
room.Y = y
room.Z = z
for direction := DirectionNorth; direction < DirectionUp; direction++ {
var translatedX int = x
var translatedY int = y
switch direction {
case DirectionNorth:
translatedX = x
translatedY = y - 1
case DirectionEast:
translatedX = x + 1
translatedY = y
case DirectionSouth:
translatedX = x
translatedY = y + 1
case DirectionWest:
translatedX = x - 1
translatedY = y
}
if maze.isValidPosition(translatedX, translatedY) && !maze.Grid[translatedX][translatedY].Wall {
to := maze.createRoom(translatedX, translatedY)
exit := &Exit{Room: room}
exit.To = to
exit.Direction = uint(direction)
room.Exit[exit.Direction] = exit
}
}
}
}
}
}
func (ch *Character) CreateMazeMap() string {
var output strings.Builder
if ch.Room == nil || !ch.Room.Virtual || ch.Room.Cell == nil {
return ""
}
var maze *MazeGrid = ch.Room.Cell.Grid
if maze == nil {
return ""
}
for y := 0; y < maze.Height; y++ {
for x := 0; x < maze.Width; x++ {
if x == ch.Room.Cell.X && y == ch.Room.Cell.Y {
output.WriteString("{Y@")
} else if x == maze.EntryX && y == maze.EntryY {
output.WriteString("{M^")
} else if x == maze.EndX && y == maze.EndY {
output.WriteString("{Mv")
} else {
var terrain *Terrain = TerrainTable[maze.Grid[x][y].Terrain]
output.WriteString(terrain.GlyphColour)
output.WriteString(terrain.MapGlyph)
}
}
output.WriteString("\r\n")
}
return output.String()
} | src/maze.go | 0.659186 | 0.402744 | maze.go | starcoder |
package graph
import (
i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time"
i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization"
)
// SignIn provides operations to manage the auditLogRoot singleton.
type SignIn struct {
Entity
// App name displayed in the Azure Portal. Supports $filter (eq and startsWith operators only).
appDisplayName *string;
// Unique GUID representing the app ID in the Azure Active Directory. Supports $filter (eq operator only).
appId *string;
// A list of conditional access policies that are triggered by the corresponding sign-in activity.
appliedConditionalAccessPolicies []AppliedConditionalAccessPolicyable;
// Identifies the client used for the sign-in activity. Modern authentication clients include Browser and modern clients. Legacy authentication clients include Exchange ActiveSync, IMAP, MAPI, SMTP, POP, and other clients. Supports $filter (eq operator only).
clientAppUsed *string;
// Reports status of an activated conditional access policy. Possible values are: success, failure, notApplied, and unknownFutureValue. Supports $filter (eq operator only).
conditionalAccessStatus *ConditionalAccessStatus;
// The request ID sent from the client when the sign-in is initiated; used to troubleshoot sign-in activity. Supports $filter (eq operator only).
correlationId *string;
// Date and time (UTC) the sign-in was initiated. Example: midnight on Jan 1, 2014 is reported as 2014-01-01T00:00:00Z. Supports $orderby and $filter (eq, le, and ge operators only).
createdDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time;
// Device information from where the sign-in occurred; includes device ID, operating system, and browser. Supports $filter (eq and startsWith operators only) on browser and operatingSytem properties.
deviceDetail DeviceDetailable;
// IP address of the client used to sign in. Supports $filter (eq and startsWith operators only).
ipAddress *string;
// Indicates if a sign-in is interactive or not.
isInteractive *bool;
// Provides the city, state, and country code where the sign-in originated. Supports $filter (eq and startsWith operators only) on city, state, and countryOrRegion properties.
location SignInLocationable;
// Name of the resource the user signed into. Supports $filter (eq operator only).
resourceDisplayName *string;
// ID of the resource that the user signed into. Supports $filter (eq operator only).
resourceId *string;
// Provides the 'reason' behind a specific state of a risky user, sign-in or a risk event. The possible values are: none, adminGeneratedTemporaryPassword, userPerformedSecuredPasswordChange, userPerformedSecuredPasswordReset, adminConfirmedSigninSafe, aiConfirmedSigninSafe, userPassedMFADrivenByRiskBasedPolicy, adminDismissedAllRiskForUser, adminConfirmedSigninCompromised, unknownFutureValue. The value none means that no action has been performed on the user or sign-in so far. Supports $filter (eq operator only).Note: Details for this property require an Azure AD Premium P2 license. Other licenses return the value hidden.
riskDetail *RiskDetail;
// Risk event types associated with the sign-in. The possible values are: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, and unknownFutureValue. Supports $filter (eq operator only).
riskEventTypes []RiskEventType;
// The list of risk event types associated with the sign-in. Possible values: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, or unknownFutureValue. Supports $filter (eq and startsWith operators only).
riskEventTypes_v2 []string;
// Aggregated risk level. The possible values are: none, low, medium, high, hidden, and unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers will be returned hidden.
riskLevelAggregated *RiskLevel;
// Risk level during sign-in. The possible values are: none, low, medium, high, hidden, and unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers will be returned hidden.
riskLevelDuringSignIn *RiskLevel;
// Reports status of the risky user, sign-in, or a risk event. The possible values are: none, confirmedSafe, remediated, dismissed, atRisk, confirmedCompromised, unknownFutureValue. Supports $filter (eq operator only).
riskState *RiskState;
// Sign-in status. Includes the error code and description of the error (in case of a sign-in failure). Supports $filter (eq operator only) on errorCode property.
status SignInStatusable;
// Display name of the user that initiated the sign-in. Supports $filter (eq and startsWith operators only).
userDisplayName *string;
// ID of the user that initiated the sign-in. Supports $filter (eq operator only).
userId *string;
// User principal name of the user that initiated the sign-in. Supports $filter (eq and startsWith operators only).
userPrincipalName *string;
}
// NewSignIn instantiates a new signIn and sets the default values.
func NewSignIn()(*SignIn) {
m := &SignIn{
Entity: *NewEntity(),
}
return m
}
// CreateSignInFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateSignInFromDiscriminatorValue(parseNode i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable, error) {
return NewSignIn(), nil
}
// GetAppDisplayName gets the appDisplayName property value. App name displayed in the Azure Portal. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetAppDisplayName()(*string) {
if m == nil {
return nil
} else {
return m.appDisplayName
}
}
// GetAppId gets the appId property value. Unique GUID representing the app ID in the Azure Active Directory. Supports $filter (eq operator only).
func (m *SignIn) GetAppId()(*string) {
if m == nil {
return nil
} else {
return m.appId
}
}
// GetAppliedConditionalAccessPolicies gets the appliedConditionalAccessPolicies property value. A list of conditional access policies that are triggered by the corresponding sign-in activity.
func (m *SignIn) GetAppliedConditionalAccessPolicies()([]AppliedConditionalAccessPolicyable) {
if m == nil {
return nil
} else {
return m.appliedConditionalAccessPolicies
}
}
// GetClientAppUsed gets the clientAppUsed property value. Identifies the client used for the sign-in activity. Modern authentication clients include Browser and modern clients. Legacy authentication clients include Exchange ActiveSync, IMAP, MAPI, SMTP, POP, and other clients. Supports $filter (eq operator only).
func (m *SignIn) GetClientAppUsed()(*string) {
if m == nil {
return nil
} else {
return m.clientAppUsed
}
}
// GetConditionalAccessStatus gets the conditionalAccessStatus property value. Reports status of an activated conditional access policy. Possible values are: success, failure, notApplied, and unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) GetConditionalAccessStatus()(*ConditionalAccessStatus) {
if m == nil {
return nil
} else {
return m.conditionalAccessStatus
}
}
// GetCorrelationId gets the correlationId property value. The request ID sent from the client when the sign-in is initiated; used to troubleshoot sign-in activity. Supports $filter (eq operator only).
func (m *SignIn) GetCorrelationId()(*string) {
if m == nil {
return nil
} else {
return m.correlationId
}
}
// GetCreatedDateTime gets the createdDateTime property value. Date and time (UTC) the sign-in was initiated. Example: midnight on Jan 1, 2014 is reported as 2014-01-01T00:00:00Z. Supports $orderby and $filter (eq, le, and ge operators only).
func (m *SignIn) GetCreatedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {
if m == nil {
return nil
} else {
return m.createdDateTime
}
}
// GetDeviceDetail gets the deviceDetail property value. Device information from where the sign-in occurred; includes device ID, operating system, and browser. Supports $filter (eq and startsWith operators only) on browser and operatingSytem properties.
func (m *SignIn) GetDeviceDetail()(DeviceDetailable) {
if m == nil {
return nil
} else {
return m.deviceDetail
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *SignIn) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["appDisplayName"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAppDisplayName(val)
}
return nil
}
res["appId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAppId(val)
}
return nil
}
res["appliedConditionalAccessPolicies"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAppliedConditionalAccessPolicyFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AppliedConditionalAccessPolicyable, len(val))
for i, v := range val {
res[i] = v.(AppliedConditionalAccessPolicyable)
}
m.SetAppliedConditionalAccessPolicies(res)
}
return nil
}
res["clientAppUsed"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetClientAppUsed(val)
}
return nil
}
res["conditionalAccessStatus"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParseConditionalAccessStatus)
if err != nil {
return err
}
if val != nil {
m.SetConditionalAccessStatus(val.(*ConditionalAccessStatus))
}
return nil
}
res["correlationId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetCorrelationId(val)
}
return nil
}
res["createdDateTime"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetTimeValue()
if err != nil {
return err
}
if val != nil {
m.SetCreatedDateTime(val)
}
return nil
}
res["deviceDetail"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(CreateDeviceDetailFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetDeviceDetail(val.(DeviceDetailable))
}
return nil
}
res["ipAddress"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetIpAddress(val)
}
return nil
}
res["isInteractive"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetIsInteractive(val)
}
return nil
}
res["location"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(CreateSignInLocationFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetLocation(val.(SignInLocationable))
}
return nil
}
res["resourceDisplayName"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetResourceDisplayName(val)
}
return nil
}
res["resourceId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetResourceId(val)
}
return nil
}
res["riskDetail"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskDetail)
if err != nil {
return err
}
if val != nil {
m.SetRiskDetail(val.(*RiskDetail))
}
return nil
}
res["riskEventTypes"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetCollectionOfEnumValues(ParseRiskEventType)
if err != nil {
return err
}
if val != nil {
res := make([]RiskEventType, len(val))
for i, v := range val {
res[i] = *(v.(*RiskEventType))
}
m.SetRiskEventTypes(res)
}
return nil
}
res["riskEventTypes_v2"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetCollectionOfPrimitiveValues("string")
if err != nil {
return err
}
if val != nil {
res := make([]string, len(val))
for i, v := range val {
res[i] = *(v.(*string))
}
m.SetRiskEventTypes_v2(res)
}
return nil
}
res["riskLevelAggregated"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskLevel)
if err != nil {
return err
}
if val != nil {
m.SetRiskLevelAggregated(val.(*RiskLevel))
}
return nil
}
res["riskLevelDuringSignIn"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskLevel)
if err != nil {
return err
}
if val != nil {
m.SetRiskLevelDuringSignIn(val.(*RiskLevel))
}
return nil
}
res["riskState"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskState)
if err != nil {
return err
}
if val != nil {
m.SetRiskState(val.(*RiskState))
}
return nil
}
res["status"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetObjectValue(CreateSignInStatusFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetStatus(val.(SignInStatusable))
}
return nil
}
res["userDisplayName"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUserDisplayName(val)
}
return nil
}
res["userId"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUserId(val)
}
return nil
}
res["userPrincipalName"] = func (o interface{}, n i<PASSWORD>b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUserPrincipalName(val)
}
return nil
}
return res
}
// GetIpAddress gets the ipAddress property value. IP address of the client used to sign in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetIpAddress()(*string) {
if m == nil {
return nil
} else {
return m.ipAddress
}
}
// GetIsInteractive gets the isInteractive property value. Indicates if a sign-in is interactive or not.
func (m *SignIn) GetIsInteractive()(*bool) {
if m == nil {
return nil
} else {
return m.isInteractive
}
}
// GetLocation gets the location property value. Provides the city, state, and country code where the sign-in originated. Supports $filter (eq and startsWith operators only) on city, state, and countryOrRegion properties.
func (m *SignIn) GetLocation()(SignInLocationable) {
if m == nil {
return nil
} else {
return m.location
}
}
// GetResourceDisplayName gets the resourceDisplayName property value. Name of the resource the user signed into. Supports $filter (eq operator only).
func (m *SignIn) GetResourceDisplayName()(*string) {
if m == nil {
return nil
} else {
return m.resourceDisplayName
}
}
// GetResourceId gets the resourceId property value. ID of the resource that the user signed into. Supports $filter (eq operator only).
func (m *SignIn) GetResourceId()(*string) {
if m == nil {
return nil
} else {
return m.resourceId
}
}
// GetRiskDetail gets the riskDetail property value. Provides the 'reason' behind a specific state of a risky user, sign-in or a risk event. The possible values are: none, adminGeneratedTemporaryPassword, userPerformedSecuredPasswordChange, userPerformedSecuredPasswordReset, adminConfirmedSigninSafe, aiConfirmedSigninSafe, userPassedMFADrivenByRiskBasedPolicy, adminDismissedAllRiskForUser, adminConfirmedSigninCompromised, unknownFutureValue. The value none means that no action has been performed on the user or sign-in so far. Supports $filter (eq operator only).Note: Details for this property require an Azure AD Premium P2 license. Other licenses return the value hidden.
func (m *SignIn) GetRiskDetail()(*RiskDetail) {
if m == nil {
return nil
} else {
return m.riskDetail
}
}
// GetRiskEventTypes gets the riskEventTypes property value. Risk event types associated with the sign-in. The possible values are: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, and unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) GetRiskEventTypes()([]RiskEventType) {
if m == nil {
return nil
} else {
return m.riskEventTypes
}
}
// GetRiskEventTypes_v2 gets the riskEventTypes_v2 property value. The list of risk event types associated with the sign-in. Possible values: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, or unknownFutureValue. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetRiskEventTypes_v2()([]string) {
if m == nil {
return nil
} else {
return m.riskEventTypes_v2
}
}
// GetRiskLevelAggregated gets the riskLevelAggregated property value. Aggregated risk level. The possible values are: none, low, medium, high, hidden, and unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers will be returned hidden.
func (m *SignIn) GetRiskLevelAggregated()(*RiskLevel) {
if m == nil {
return nil
} else {
return m.riskLevelAggregated
}
}
// GetRiskLevelDuringSignIn gets the riskLevelDuringSignIn property value. Risk level during sign-in. The possible values are: none, low, medium, high, hidden, and unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers will be returned hidden.
func (m *SignIn) GetRiskLevelDuringSignIn()(*RiskLevel) {
if m == nil {
return nil
} else {
return m.riskLevelDuringSignIn
}
}
// GetRiskState gets the riskState property value. Reports status of the risky user, sign-in, or a risk event. The possible values are: none, confirmedSafe, remediated, dismissed, atRisk, confirmedCompromised, unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) GetRiskState()(*RiskState) {
if m == nil {
return nil
} else {
return m.riskState
}
}
// GetStatus gets the status property value. Sign-in status. Includes the error code and description of the error (in case of a sign-in failure). Supports $filter (eq operator only) on errorCode property.
func (m *SignIn) GetStatus()(SignInStatusable) {
if m == nil {
return nil
} else {
return m.status
}
}
// GetUserDisplayName gets the userDisplayName property value. Display name of the user that initiated the sign-in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetUserDisplayName()(*string) {
if m == nil {
return nil
} else {
return m.userDisplayName
}
}
// GetUserId gets the userId property value. ID of the user that initiated the sign-in. Supports $filter (eq operator only).
func (m *SignIn) GetUserId()(*string) {
if m == nil {
return nil
} else {
return m.userId
}
}
// GetUserPrincipalName gets the userPrincipalName property value. User principal name of the user that initiated the sign-in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetUserPrincipalName()(*string) {
if m == nil {
return nil
} else {
return m.userPrincipalName
}
}
func (m *SignIn) IsNil()(bool) {
return m == nil
}
// Serialize serializes information the current object
func (m *SignIn) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteStringValue("appDisplayName", m.GetAppDisplayName())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("appId", m.GetAppId())
if err != nil {
return err
}
}
if m.GetAppliedConditionalAccessPolicies() != nil {
cast := make([]i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable, len(m.GetAppliedConditionalAccessPolicies()))
for i, v := range m.GetAppliedConditionalAccessPolicies() {
cast[i] = v.(i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable)
}
err = writer.WriteCollectionOfObjectValues("appliedConditionalAccessPolicies", cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("clientAppUsed", m.GetClientAppUsed())
if err != nil {
return err
}
}
if m.GetConditionalAccessStatus() != nil {
cast := (*m.GetConditionalAccessStatus()).String()
err = writer.WriteStringValue("conditionalAccessStatus", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("correlationId", m.GetCorrelationId())
if err != nil {
return err
}
}
{
err = writer.WriteTimeValue("createdDateTime", m.GetCreatedDateTime())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("deviceDetail", m.GetDeviceDetail())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("ipAddress", m.GetIpAddress())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("isInteractive", m.GetIsInteractive())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("location", m.GetLocation())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("resourceDisplayName", m.GetResourceDisplayName())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("resourceId", m.GetResourceId())
if err != nil {
return err
}
}
if m.GetRiskDetail() != nil {
cast := (*m.GetRiskDetail()).String()
err = writer.WriteStringValue("riskDetail", &cast)
if err != nil {
return err
}
}
if m.GetRiskEventTypes() != nil {
err = writer.WriteCollectionOfStringValues("riskEventTypes", SerializeRiskEventType(m.GetRiskEventTypes()))
if err != nil {
return err
}
}
if m.GetRiskEventTypes_v2() != nil {
err = writer.WriteCollectionOfStringValues("riskEventTypes_v2", m.GetRiskEventTypes_v2())
if err != nil {
return err
}
}
if m.GetRiskLevelAggregated() != nil {
cast := (*m.GetRiskLevelAggregated()).String()
err = writer.WriteStringValue("riskLevelAggregated", &cast)
if err != nil {
return err
}
}
if m.GetRiskLevelDuringSignIn() != nil {
cast := (*m.GetRiskLevelDuringSignIn()).String()
err = writer.WriteStringValue("riskLevelDuringSignIn", &cast)
if err != nil {
return err
}
}
if m.GetRiskState() != nil {
cast := (*m.GetRiskState()).String()
err = writer.WriteStringValue("riskState", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("status", m.GetStatus())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("userDisplayName", m.GetUserDisplayName())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("userId", m.GetUserId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("userPrincipalName", m.GetUserPrincipalName())
if err != nil {
return err
}
}
return nil
}
// SetAppDisplayName sets the appDisplayName property value. App name displayed in the Azure Portal. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetAppDisplayName(value *string)() {
if m != nil {
m.appDisplayName = value
}
}
// SetAppId sets the appId property value. Unique GUID representing the app ID in the Azure Active Directory. Supports $filter (eq operator only).
func (m *SignIn) SetAppId(value *string)() {
if m != nil {
m.appId = value
}
}
// SetAppliedConditionalAccessPolicies sets the appliedConditionalAccessPolicies property value. A list of conditional access policies that are triggered by the corresponding sign-in activity.
func (m *SignIn) SetAppliedConditionalAccessPolicies(value []AppliedConditionalAccessPolicyable)() {
if m != nil {
m.appliedConditionalAccessPolicies = value
}
}
// SetClientAppUsed sets the clientAppUsed property value. Identifies the client used for the sign-in activity. Modern authentication clients include Browser and modern clients. Legacy authentication clients include Exchange ActiveSync, IMAP, MAPI, SMTP, POP, and other clients. Supports $filter (eq operator only).
func (m *SignIn) SetClientAppUsed(value *string)() {
if m != nil {
m.clientAppUsed = value
}
}
// SetConditionalAccessStatus sets the conditionalAccessStatus property value. Reports status of an activated conditional access policy. Possible values are: success, failure, notApplied, and unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) SetConditionalAccessStatus(value *ConditionalAccessStatus)() {
if m != nil {
m.conditionalAccessStatus = value
}
}
// SetCorrelationId sets the correlationId property value. The request ID sent from the client when the sign-in is initiated; used to troubleshoot sign-in activity. Supports $filter (eq operator only).
func (m *SignIn) SetCorrelationId(value *string)() {
if m != nil {
m.correlationId = value
}
}
// SetCreatedDateTime sets the createdDateTime property value. Date and time (UTC) the sign-in was initiated. Example: midnight on Jan 1, 2014 is reported as 2014-01-01T00:00:00Z. Supports $orderby and $filter (eq, le, and ge operators only).
func (m *SignIn) SetCreatedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {
if m != nil {
m.createdDateTime = value
}
}
// SetDeviceDetail sets the deviceDetail property value. Device information from where the sign-in occurred; includes device ID, operating system, and browser. Supports $filter (eq and startsWith operators only) on browser and operatingSytem properties.
func (m *SignIn) SetDeviceDetail(value DeviceDetailable)() {
if m != nil {
m.deviceDetail = value
}
}
// SetIpAddress sets the ipAddress property value. IP address of the client used to sign in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetIpAddress(value *string)() {
if m != nil {
m.ipAddress = value
}
}
// SetIsInteractive sets the isInteractive property value. Indicates if a sign-in is interactive or not.
func (m *SignIn) SetIsInteractive(value *bool)() {
if m != nil {
m.isInteractive = value
}
}
// SetLocation sets the location property value. Provides the city, state, and country code where the sign-in originated. Supports $filter (eq and startsWith operators only) on city, state, and countryOrRegion properties.
func (m *SignIn) SetLocation(value SignInLocationable)() {
if m != nil {
m.location = value
}
}
// SetResourceDisplayName sets the resourceDisplayName property value. Name of the resource the user signed into. Supports $filter (eq operator only).
func (m *SignIn) SetResourceDisplayName(value *string)() {
if m != nil {
m.resourceDisplayName = value
}
}
// SetResourceId sets the resourceId property value. ID of the resource that the user signed into. Supports $filter (eq operator only).
func (m *SignIn) SetResourceId(value *string)() {
if m != nil {
m.resourceId = value
}
}
// SetRiskDetail sets the riskDetail property value. Provides the 'reason' behind a specific state of a risky user, sign-in or a risk event. The possible values are: none, adminGeneratedTemporaryPassword, userPerformedSecuredPasswordChange, userPerformedSecuredPasswordReset, adminConfirmedSigninSafe, aiConfirmedSigninSafe, userPassedMFADrivenByRiskBasedPolicy, adminDismissedAllRiskForUser, adminConfirmedSigninCompromised, unknownFutureValue. The value none means that no action has been performed on the user or sign-in so far. Supports $filter (eq operator only).Note: Details for this property require an Azure AD Premium P2 license. Other licenses return the value hidden.
func (m *SignIn) SetRiskDetail(value *RiskDetail)() {
if m != nil {
m.riskDetail = value
}
}
// SetRiskEventTypes sets the riskEventTypes property value. Risk event types associated with the sign-in. The possible values are: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, and unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) SetRiskEventTypes(value []RiskEventType)() {
if m != nil {
m.riskEventTypes = value
}
}
// SetRiskEventTypes_v2 sets the riskEventTypes_v2 property value. The list of risk event types associated with the sign-in. Possible values: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, or unknownFutureValue. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetRiskEventTypes_v2(value []string)() {
if m != nil {
m.riskEventTypes_v2 = value
}
}
// SetRiskLevelAggregated sets the riskLevelAggregated property value. Aggregated risk level. The possible values are: none, low, medium, high, hidden, and unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers will be returned hidden.
func (m *SignIn) SetRiskLevelAggregated(value *RiskLevel)() {
if m != nil {
m.riskLevelAggregated = value
}
}
// SetRiskLevelDuringSignIn sets the riskLevelDuringSignIn property value. Risk level during sign-in. The possible values are: none, low, medium, high, hidden, and unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers will be returned hidden.
func (m *SignIn) SetRiskLevelDuringSignIn(value *RiskLevel)() {
if m != nil {
m.riskLevelDuringSignIn = value
}
}
// SetRiskState sets the riskState property value. Reports status of the risky user, sign-in, or a risk event. The possible values are: none, confirmedSafe, remediated, dismissed, atRisk, confirmedCompromised, unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) SetRiskState(value *RiskState)() {
if m != nil {
m.riskState = value
}
}
// SetStatus sets the status property value. Sign-in status. Includes the error code and description of the error (in case of a sign-in failure). Supports $filter (eq operator only) on errorCode property.
func (m *SignIn) SetStatus(value SignInStatusable)() {
if m != nil {
m.status = value
}
}
// SetUserDisplayName sets the userDisplayName property value. Display name of the user that initiated the sign-in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetUserDisplayName(value *string)() {
if m != nil {
m.userDisplayName = value
}
}
// SetUserId sets the userId property value. ID of the user that initiated the sign-in. Supports $filter (eq operator only).
func (m *SignIn) SetUserId(value *string)() {
if m != nil {
m.userId = value
}
}
// SetUserPrincipalName sets the userPrincipalName property value. User principal name of the user that initiated the sign-in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetUserPrincipalName(value *string)() {
if m != nil {
m.userPrincipalName = value
}
} | models/microsoft/graph/sign_in.go | 0.737442 | 0.508483 | sign_in.go | starcoder |
package lorawan
import (
"go.thethings.network/lorawan-stack/pkg/errors"
)
var (
errDecode = errors.Define("decode", "could not decode `{lorawan_field}`")
errEncode = errors.Define("encode", "could not encode `{lorawan_field}`")
errEncodedFieldLengthBound = errors.DefineInvalidArgument("encoded_field_length_bound", "`{lorawan_field}` encoded length `{value}` should between `{min}` and `{max}`", valueKey)
errEncodedFieldLengthEqual = errors.DefineInvalidArgument("encoded_field_length_equal", "`{lorawan_field}` encoded length `{value}` should be `{expected}`", valueKey)
errEncodedFieldLengthTwoChoices = errors.DefineInvalidArgument("encoded_field_length_multiple_choices", "`{lorawan_field}` encoded length `{value}` should be equal to `{expected_1}` or `{expected_2}`", valueKey)
errFieldBound = errors.DefineInvalidArgument("field_bound", "`{lorawan_field}` should be between `{min}` and `{max}`", valueKey)
errFieldHasMax = errors.DefineInvalidArgument("field_with_max", "`{lorawan_field}` value `{value}` should be lower or equal to `{max}`", valueKey)
errFieldLengthEqual = errors.DefineInvalidArgument("field_length_equal", "`{lorawan_field}` length `{value}` should be equal to `{expected}`", valueKey)
errFieldLengthHasMax = errors.DefineInvalidArgument("field_length_with_max", "`{lorawan_field}` length `{value}` should be lower or equal to `{max}`", valueKey)
errFieldLengthHasMin = errors.DefineInvalidArgument("field_length_with_min", "`{lorawan_field}` length `{value}` should be higher or equal to `{min}`", valueKey)
errFieldLengthTwoChoices = errors.DefineInvalidArgument("field_length_with_multiple_choices", "`{lorawan_field}` length `{value}` should be equal to `{expected_1}` or `{expected_2}`", valueKey)
errUnknownField = errors.DefineInvalidArgument("unknown_field", "unknown `{lorawan_field}`", valueKey)
)
const valueKey = "value"
type valueErr func(interface{}) errors.Error
func unexpectedValue(err interface {
WithAttributes(kv ...interface{}) errors.Error
}) valueErr {
return func(value interface{}) errors.Error {
return err.WithAttributes(valueKey, value)
}
}
func errExpectedLowerOrEqual(lorawanField string, max interface{}) valueErr {
return unexpectedValue(errFieldHasMax.WithAttributes("lorawan_field", lorawanField, "max", max))
}
func errExpectedLengthEqual(lorawanField string, expected interface{}) valueErr {
return unexpectedValue(errFieldLengthEqual.WithAttributes("lorawan_field", lorawanField, "expected", expected))
}
func errExpectedLengthLowerOrEqual(lorawanField string, max interface{}) valueErr {
return unexpectedValue(errFieldLengthHasMax.WithAttributes("lorawan_field", lorawanField, "max", max))
}
func errExpectedLengthHigherOrEqual(lorawanField string, min interface{}) valueErr {
return unexpectedValue(errFieldLengthHasMin.WithAttributes("lorawan_field", lorawanField, "min", min))
}
func errExpectedLengthTwoChoices(lorawanField string, expected1, expected2 interface{}) valueErr {
return unexpectedValue(errFieldLengthTwoChoices.WithAttributes("lorawan_field", lorawanField, "expected_1", expected1, "expected_2", expected2))
}
func errExpectedLengthEncodedBound(lorawanField string, min, max interface{}) valueErr {
return unexpectedValue(errEncodedFieldLengthBound.WithAttributes("lorawan_field", lorawanField, "min", min, "max", max))
}
func errExpectedLengthEncodedEqual(lorawanField string, expected interface{}) valueErr {
return unexpectedValue(errEncodedFieldLengthEqual.WithAttributes("lorawan_field", lorawanField, "expected", expected))
}
func errExpectedLengthEncodedTwoChoices(lorawanField string, expected1, expected2 interface{}) valueErr {
return unexpectedValue(errEncodedFieldLengthTwoChoices.WithAttributes("lorawan_field", lorawanField, "expected_1", expected1, "expected_2", expected2))
}
func errFailedEncoding(lorawanField string) errors.Error {
return errEncode.WithAttributes("lorawan_field", lorawanField)
}
func errFailedDecoding(lorawanField string) errors.Error {
return errDecode.WithAttributes("lorawan_field", lorawanField)
}
func errUnknown(lorawanField string) valueErr {
return unexpectedValue(errUnknownField.WithAttributes("lorawan_field", lorawanField))
}
func errMissing(lorawanField string) errors.Error {
return errUnknownField.WithAttributes("lorawan_field", lorawanField)
}
func errExpectedBetween(lorawanField string, min, max interface{}) valueErr {
return unexpectedValue(errFieldBound.WithAttributes("lorawan_field", lorawanField, "min", min, "max", max))
} | pkg/encoding/lorawan/errors.go | 0.645567 | 0.480966 | errors.go | starcoder |
package mapper
import (
"reflect"
"strings"
"github.com/pulumi/pulumi/pkg/util/contract"
)
// Mapper can map from weakly typed JSON-like property bags to strongly typed structs, and vice versa.
type Mapper interface {
// Decode decodes a JSON-like object into the target pointer to a structure.
Decode(obj map[string]interface{}, target interface{}) MappingError
// DecodeField decodes a single JSON-like value (with a given type and name) into a target pointer to a structure.
DecodeValue(obj map[string]interface{}, ty reflect.Type, key string, target interface{}, optional bool) FieldError
// Encode encodes an object into a JSON-like in-memory object.
Encode(source interface{}) (map[string]interface{}, MappingError)
// EncodeValue encodes a value into its JSON-like in-memory value format.
EncodeValue(v interface{}) (interface{}, MappingError)
}
// New allocates a new mapper object with the given options.
func New(opts *Opts) Mapper {
var initOpts Opts
if opts != nil {
initOpts = *opts
}
if initOpts.CustomDecoders == nil {
initOpts.CustomDecoders = make(Decoders)
}
return &mapper{opts: initOpts}
}
// Opts controls the way mapping occurs; for default behavior, simply pass an empty struct.
type Opts struct {
Tags []string // the tag names to recognize (`json` and `pulumi` if unspecified).
OptionalTags []string // the tags to interpret to mean "optional" (`optional` if unspecified).
SkipTags []string // the tags to interpret to mean "skip" (`skip` if unspecified).
CustomDecoders Decoders // custom decoders.
IgnoreMissing bool // ignore missing required fields.
IgnoreUnrecognized bool // ignore unrecognized fields.
}
type mapper struct {
opts Opts
}
// Map decodes an entire map into a target object, using an anonymous decoder and tag-directed mappings.
func Map(obj map[string]interface{}, target interface{}) MappingError {
return New(nil).Decode(obj, target)
}
// MapI decodes an entire map into a target object, using an anonymous decoder and tag-directed mappings. This variant
// ignores any missing required fields in the payload in addition to any unrecognized fields.
func MapI(obj map[string]interface{}, target interface{}) MappingError {
return New(&Opts{
IgnoreMissing: true,
IgnoreUnrecognized: true,
}).Decode(obj, target)
}
// MapIM decodes an entire map into a target object, using an anonymous decoder and tag-directed mappings. This variant
// ignores any missing required fields in the payload.
func MapIM(obj map[string]interface{}, target interface{}) MappingError {
return New(&Opts{IgnoreMissing: true}).Decode(obj, target)
}
// MapIU decodes an entire map into a target object, using an anonymous decoder and tag-directed mappings. This variant
// ignores any unrecognized fields in the payload.
func MapIU(obj map[string]interface{}, target interface{}) MappingError {
return New(&Opts{IgnoreUnrecognized: true}).Decode(obj, target)
}
// Unmap translates an already mapped target object into a raw, unmapped form.
func Unmap(obj interface{}) (map[string]interface{}, error) {
return New(nil).Encode(obj)
}
// structFields digs into a type to fetch all fields, including its embedded structs, for a given type.
func structFields(t reflect.Type) []reflect.StructField {
contract.Assertf(t.Kind() == reflect.Struct,
"StructFields only valid on struct types; %v is not one (kind %v)", t, t.Kind())
var fldinfos []reflect.StructField
fldtypes := []reflect.Type{t}
for len(fldtypes) > 0 {
fldtype := fldtypes[0]
fldtypes = fldtypes[1:]
for i := 0; i < fldtype.NumField(); i++ {
if fldinfo := fldtype.Field(i); fldinfo.Anonymous {
// If an embedded struct, push it onto the queue to visit.
if fldinfo.Type.Kind() == reflect.Struct {
fldtypes = append(fldtypes, fldinfo.Type)
}
} else {
// Otherwise, we will go ahead and consider this field in our decoding.
fldinfos = append(fldinfos, fldinfo)
}
}
}
return fldinfos
}
// defaultTags fetches the mapper's tag names from the options, or supplies defaults if not present.
func (md *mapper) defaultTags() (tags []string, optionalTags []string, skipTags []string) {
if md.opts.Tags == nil {
tags = []string{"json", "pulumi"}
} else {
tags = md.opts.Tags
}
if md.opts.OptionalTags == nil {
optionalTags = []string{"omitempty", "optional"}
} else {
optionalTags = md.opts.OptionalTags
}
if md.opts.SkipTags == nil {
skipTags = []string{"skip"}
} else {
skipTags = md.opts.SkipTags
}
return tags, optionalTags, skipTags
}
// structFieldTags includes a field's information plus any parsed tags.
type structFieldTags struct {
Info reflect.StructField // the struct field info.
Optional bool // true if this can be missing.
Skip bool // true to skip a field.
Key string // the JSON key name.
}
// structFieldsTags digs into a type to fetch all fields, including embedded structs, plus any associated tags.
func (md *mapper) structFieldsTags(t reflect.Type) []structFieldTags {
// Fetch the tag names to use.
tags, optionalTags, skipTags := md.defaultTags()
// Now walk the field infos and parse the tags to create the requisite structures.
var fldtags []structFieldTags
for _, fldinfo := range structFields(t) {
for _, tagname := range tags {
if tag := fldinfo.Tag.Get(tagname); tag != "" {
var key string // the JSON key name.
var optional bool // true if this can be missing.
var skip bool // true if we should skip auto-marshaling.
// Decode the tag.
tagparts := strings.Split(tag, ",")
contract.Assertf(len(tagparts) > 0,
"Expected >0 tagparts on field %v.%v; got %v", t.Name(), fldinfo.Name, len(tagparts))
key = tagparts[0]
if key == "-" {
skip = true // a name of "-" means skip
}
for _, part := range tagparts[1:] {
var match bool
for _, optionalTag := range optionalTags {
if part == optionalTag {
optional = true
match = true
break
}
}
if !match {
for _, skipTag := range skipTags {
if part == skipTag {
skip = true
match = true
break
}
}
}
contract.Assertf(match, "Unrecognized tagpart on field %v.%v: %v", t.Name(), fldinfo.Name, part)
}
fldtags = append(fldtags, structFieldTags{
Key: key,
Optional: optional,
Skip: skip,
Info: fldinfo,
})
}
}
}
return fldtags
} | pkg/util/mapper/mapper.go | 0.703753 | 0.413181 | mapper.go | starcoder |
package gcp
import (
"context"
"fmt"
"sync"
"time"
"cloud.google.com/go/pubsub"
"github.com/benthosdev/benthos/v4/internal/batch"
"github.com/benthosdev/benthos/v4/internal/bloblang/field"
"github.com/benthosdev/benthos/v4/internal/bundle"
"github.com/benthosdev/benthos/v4/internal/component"
"github.com/benthosdev/benthos/v4/internal/component/metrics"
"github.com/benthosdev/benthos/v4/internal/component/output"
"github.com/benthosdev/benthos/v4/internal/component/output/processors"
"github.com/benthosdev/benthos/v4/internal/docs"
"github.com/benthosdev/benthos/v4/internal/log"
"github.com/benthosdev/benthos/v4/internal/message"
"github.com/benthosdev/benthos/v4/internal/metadata"
)
func init() {
err := bundle.AllOutputs.Add(processors.WrapConstructor(func(c output.Config, nm bundle.NewManagement) (output.Streamed, error) {
return newGCPPubSubOutput(c, nm, nm.Logger(), nm.Metrics())
}), docs.ComponentSpec{
Name: "gcp_pubsub",
Summary: `Sends messages to a GCP Cloud Pub/Sub topic. [Metadata](/docs/configuration/metadata) from messages are sent as attributes.`,
Description: output.Description(true, false, `
For information on how to set up credentials check out [this guide](https://cloud.google.com/docs/authentication/production).
### Troubleshooting
If you're consistently seeing `+"`Failed to send message to gcp_pubsub: context deadline exceeded`"+` error logs without any further information it is possible that you are encountering https://github.com/benthosdev/benthos/issues/1042, which occurs when metadata values contain characters that are not valid utf-8. This can frequently occur when consuming from Kafka as the key metadata field may be populated with an arbitrary binary value, but this issue is not exclusive to Kafka.
If you are blocked by this issue then a work around is to delete either the specific problematic keys:
`+"```yaml"+`
pipeline:
processors:
- bloblang: |
meta kafka_key = deleted()
`+"```"+`
Or delete all keys with:
`+"```yaml"+`
pipeline:
processors:
- bloblang: meta = deleted()
`+"```"+``),
Config: docs.FieldComponent().WithChildren(
docs.FieldString("project", "The project ID of the topic to publish to."),
docs.FieldString("topic", "The topic to publish to.").IsInterpolated(),
docs.FieldInt("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."),
docs.FieldString("publish_timeout", "The maximum length of time to wait before abandoning a publish attempt for a message.", "10s", "5m", "60m").Advanced(),
docs.FieldString("ordering_key", "The ordering key to use for publishing messages.").IsInterpolated().Advanced(),
docs.FieldObject("metadata", "Specify criteria for which metadata values are sent as attributes.").WithChildren(metadata.ExcludeFilterFields()...),
).ChildDefaultAndTypesFromStruct(output.NewGCPPubSubConfig()),
Categories: []string{
"Services",
"GCP",
},
})
if err != nil {
panic(err)
}
}
func newGCPPubSubOutput(conf output.Config, mgr bundle.NewManagement, log log.Modular, stats metrics.Type) (output.Streamed, error) {
a, err := newGCPPubSubWriter(conf.GCPPubSub, mgr, log)
if err != nil {
return nil, err
}
w, err := output.NewAsyncWriter("gcp_pubsub", conf.GCPPubSub.MaxInFlight, a, mgr)
if err != nil {
return nil, err
}
return output.OnlySinglePayloads(w), nil
}
type gcpPubSubWriter struct {
conf output.GCPPubSubConfig
client *pubsub.Client
publishTimeout time.Duration
metaFilter *metadata.ExcludeFilter
orderingEnabled bool
orderingKey *field.Expression
topicID *field.Expression
topics map[string]*pubsub.Topic
topicMut sync.Mutex
log log.Modular
}
func newGCPPubSubWriter(conf output.GCPPubSubConfig, mgr bundle.NewManagement, log log.Modular) (*gcpPubSubWriter, error) {
client, err := pubsub.NewClient(context.Background(), conf.ProjectID)
if err != nil {
return nil, err
}
topic, err := mgr.BloblEnvironment().NewField(conf.TopicID)
if err != nil {
return nil, fmt.Errorf("failed to parse topic expression: %v", err)
}
orderingKey, err := mgr.BloblEnvironment().NewField(conf.OrderingKey)
if err != nil {
return nil, fmt.Errorf("failed to parse ordering key: %v", err)
}
pubTimeout, err := time.ParseDuration(conf.PublishTimeout)
if err != nil {
return nil, fmt.Errorf("failed to parse publish timeout duration: %w", err)
}
metaFilter, err := conf.Metadata.Filter()
if err != nil {
return nil, fmt.Errorf("failed to construct metadata filter: %w", err)
}
return &gcpPubSubWriter{
conf: conf,
log: log,
metaFilter: metaFilter,
client: client,
publishTimeout: pubTimeout,
topicID: topic,
orderingKey: orderingKey,
orderingEnabled: len(conf.OrderingKey) > 0,
}, nil
}
func (c *gcpPubSubWriter) ConnectWithContext(ctx context.Context) error {
c.topicMut.Lock()
defer c.topicMut.Unlock()
if c.topics != nil {
return nil
}
c.topics = map[string]*pubsub.Topic{}
c.log.Infof("Sending GCP Cloud Pub/Sub messages to project '%v' and topic '%v'\n", c.conf.ProjectID, c.conf.TopicID)
return nil
}
func (c *gcpPubSubWriter) getTopic(ctx context.Context, t string) (*pubsub.Topic, error) {
c.topicMut.Lock()
defer c.topicMut.Unlock()
if c.topics == nil {
return nil, component.ErrNotConnected
}
if t, exists := c.topics[t]; exists {
return t, nil
}
topic := c.client.Topic(t)
exists, err := topic.Exists(ctx)
if err != nil {
return nil, fmt.Errorf("failed to validate topic '%v': %v", t, err)
}
if !exists {
return nil, fmt.Errorf("topic '%v' does not exist", t)
}
topic.PublishSettings.Timeout = c.publishTimeout
topic.EnableMessageOrdering = c.orderingEnabled
c.topics[t] = topic
return topic, nil
}
func (c *gcpPubSubWriter) WriteWithContext(ctx context.Context, msg *message.Batch) error {
topics := make([]*pubsub.Topic, msg.Len())
if err := msg.Iter(func(i int, _ *message.Part) error {
var tErr error
topics[i], tErr = c.getTopic(ctx, c.topicID.String(i, msg))
return tErr
}); err != nil {
return err
}
results := make([]*pubsub.PublishResult, msg.Len())
_ = msg.Iter(func(i int, part *message.Part) error {
topic := topics[i]
attr := map[string]string{}
_ = c.metaFilter.Iter(part, func(k, v string) error {
attr[k] = v
return nil
})
gmsg := &pubsub.Message{
Data: part.Get(),
}
if c.orderingEnabled {
gmsg.OrderingKey = c.orderingKey.String(i, msg)
}
if len(attr) > 0 {
gmsg.Attributes = attr
}
results[i] = topic.Publish(ctx, gmsg)
return nil
})
var batchErr *batch.Error
for i, r := range results {
if _, err := r.Get(ctx); err != nil {
if batchErr == nil {
batchErr = batch.NewError(msg, err)
}
batchErr.Failed(i, err)
}
}
if batchErr != nil {
return batchErr
}
return nil
}
func (c *gcpPubSubWriter) CloseAsync() {
go func() {
c.topicMut.Lock()
defer c.topicMut.Unlock()
if c.topics != nil {
for _, t := range c.topics {
t.Stop()
}
c.topics = nil
}
}()
}
func (c *gcpPubSubWriter) WaitForClose(time.Duration) error {
return nil
} | internal/impl/gcp/output_pubsub.go | 0.606498 | 0.417093 | output_pubsub.go | starcoder |
package geocube
//go:generate enumer -json -sql -type DatasetStatus -trimprefix DatasetStatus
import (
"fmt"
"strings"
"github.com/google/uuid"
"github.com/twpayne/go-geom"
pb "github.com/airbusgeo/geocube/internal/pb"
"github.com/airbusgeo/geocube/internal/utils"
"github.com/airbusgeo/geocube/internal/utils/affine"
"github.com/airbusgeo/geocube/internal/utils/proj"
"github.com/airbusgeo/godal"
)
type DatasetStatus int
const (
DatasetStatusACTIVE DatasetStatus = iota
DatasetStatusTODELETE
DatasetStatusINACTIVE
)
type Dataset struct {
persistenceState
ID string
RecordID string
InstanceID string
ContainerURI string
ContainerSubDir string
Bands []int64
DataMapping DataMapping
Status DatasetStatus
Shape proj.Shape ///< Valid shape in the crs of the dataset (may be smaller than the extent when there is nodata)
GeogShape proj.GeographicShape ///< Approximation of the valid shape in geographic coordinates
GeomShape proj.GeometricShape ///< Approximation of the valid shape in 4326 coordinates
Overviews bool
}
// NewDatasetFromProtobuf creates a new dataset from protobuf
// Only returns validationError
func NewDatasetFromProtobuf(pbd *pb.Dataset, uri string) (*Dataset, error) {
d := Dataset{
persistenceState: persistenceStateNEW,
ID: uuid.New().String(),
RecordID: pbd.GetRecordId(),
InstanceID: pbd.GetInstanceId(),
ContainerURI: uri,
ContainerSubDir: pbd.GetContainerSubdir(),
Bands: pbd.GetBands(),
DataMapping: DataMapping{
DataFormat: *NewDataFormatFromProtobuf(pbd.GetDformat()),
RangeExt: Range{Min: pbd.GetRealMinValue(), Max: pbd.GetRealMaxValue()},
Exponent: pbd.GetExponent(),
},
Status: DatasetStatusACTIVE}
if err := d.validate(); err != nil {
return nil, err
}
return &d, nil
}
// IncompleteDatasetFromConsolidation returns a dataset partially initialized from the ConsolidationContainer of a consolidation task
// Only returns validationError
func IncompleteDatasetFromConsolidation(c *ConsolidationContainer, instanceID string) (*Dataset, error) {
d := Dataset{
persistenceState: persistenceStateNEW, // Set to New during the initialization
InstanceID: instanceID,
ContainerURI: c.URI,
Bands: make([]int64, c.BandsCount),
DataMapping: c.DatasetFormat,
Status: DatasetStatusINACTIVE,
Overviews: c.OverviewsMinSize != NO_OVERVIEW,
}
// Init GeoBBox
transform := affine.Affine(c.Transform)
p := proj.NewPolygonFromExtent(&transform, c.Width, c.Height)
mp := geom.NewMultiPolygonFlat(geom.XY, p.FlatCoords(), [][]int{{10}})
if err := d.SetShape(mp, c.CRS); err != nil {
return nil, err
}
// Init bands
for i := range d.Bands {
d.Bands[i] = int64(i + 1)
}
d.persistenceState = persistenceStateUNKNOWN // Ensure that it cannot be persisted
return &d, nil
}
// NewDatasetFromIncomplete creates a new dataset from dataset created by NewIncompleteDatasetFromConsolidation
// Only returns ValidationError
func NewDatasetFromIncomplete(d Dataset, consolidationRecord ConsolidationRecord, subdir string) (*Dataset, error) {
d.persistenceState = persistenceStateNEW
d.ID = uuid.New().String()
d.RecordID = consolidationRecord.ID
d.ContainerSubDir = subdir
if consolidationRecord.ValidShape != nil {
d.Shape = *consolidationRecord.ValidShape
crs, err := proj.CRSFromEPSG(d.Shape.SRID())
if err != nil {
return nil, fmt.Errorf("NewDatasetFromIncomplete.%w", err)
}
if err := d.setGeomGeogShape(crs); err != nil {
return nil, fmt.Errorf("NewDatasetFromIncomplete.%w", err)
}
}
if err := d.validate(); err != nil {
return nil, err
}
return &d, nil
}
// SetShape sets the shape in a given CRS and bounding boxes of a new dataset
func (d *Dataset) SetShape(shape *geom.MultiPolygon, crsS string) error {
if !d.IsNew() {
return NewValidationError("Set the shape of a dataset that is not new is forbidden")
}
crs, srid, err := proj.CRSFromUserInput(crsS)
if err != nil {
return NewValidationError("Invalid Crs: " + crsS)
}
defer crs.Close()
d.Shape = proj.NewShape(srid, shape)
return d.setGeomGeogShape(crs)
}
// SetShape sets the shape in a given CRS and bounding boxes of a new dataset
func (d *Dataset) setGeomGeogShape(crs *godal.SpatialRef) (err error) {
d.GeomShape, err = proj.NewGeometricShapeFromShape(d.Shape, crs)
if err != nil {
return NewValidationError("Invalid crs or bbox: " + err.Error())
}
d.GeogShape, err = proj.NewGeographicShapeFromShape(d.Shape, crs)
if err != nil {
return NewValidationError("Invalid crs or bbox: " + err.Error())
}
return nil
}
// SetOverviews sets the overviews flag of a new dataset
func (d *Dataset) SetOverviews(hasOverviews bool) error {
if !d.IsNew() {
return NewValidationError("Set Overviews of a dataset that is not new is forbidden")
}
d.Overviews = hasOverviews
return nil
}
// SetDataType sets the datatype flag of a new dataset
func (d *Dataset) SetDataType(dtype DType) error {
if !d.IsNew() {
return NewValidationError("Set DataType of a dataset that is not new is forbidden")
}
d.DataMapping.DType = dtype
if err := d.DataMapping.validate(); err != nil {
return NewValidationError("Invalid Dataset.DFormat (%s): %v", d.DataMapping.string(), err)
}
return nil
}
// ValidateWithVariable validates the instance using the full definition of the variable
// Only returns ValidationError
func (d *Dataset) ValidateWithVariable(v *Variable) error {
if len(d.Bands) != len(v.Bands) {
return NewValidationError("Wrong number of bands in dataset")
}
if !d.DataMapping.canCastTo(&v.DFormat) {
return NewValidationError("Data format of dataset is incorrect as it cannot be cast to the data format of the variable")
}
if d.DataMapping.RangeExt.Min >= v.DFormat.Range.Max || d.DataMapping.RangeExt.Max <= v.DFormat.Range.Min {
return NewValidationError(
fmt.Sprintf("Range of external values of the dataset [%f,%f] does not intersect the range of values of the variable [%f,%f]",
d.DataMapping.RangeExt.Min, d.DataMapping.RangeExt.Max, v.DFormat.Range.Min, v.DFormat.Range.Max))
}
return nil
}
// validate validates the fields of a Dataset
// Only returns ValidationError
func (d *Dataset) validate() error {
if _, err := uuid.Parse(d.RecordID); err != nil {
return NewValidationError("Invalid record id: " + d.RecordID)
}
if _, err := uuid.Parse(d.InstanceID); err != nil {
return NewValidationError("Invalid instance id: " + d.InstanceID)
}
if err := d.DataMapping.validate(); err != nil {
return NewValidationError("Invalid Dataset.DataMapping (%s): %v", d.DataMapping.string(), err)
}
return nil
}
// ToStorageClass returns the geocube sorage class equivalent
func ToStorageClass(s string) (StorageClass, error) {
switch strings.ToUpper(s) {
case "STANDARD", "REGIONAL":
return StorageClassSTANDARD, nil
case "NEARLINE":
return StorageClassINFREQUENT, nil
case "COLDLINE":
return StorageClassARCHIVE, nil
case "ARCHIVE":
return StorageClassDEEPARCHIVE, nil
}
return StorageClassUNDEFINED, NewValidationError("Unknown storage class: " + s)
}
// identicalTo compares two datasets and returns true if they are equals with exception of ID and persistentState
func (d *Dataset) identicalTo(d2 *Dataset) bool {
return d.RecordID == d2.RecordID &&
d.InstanceID == d2.InstanceID &&
d.ContainerURI == d2.ContainerURI &&
d.ContainerSubDir == d2.ContainerSubDir &&
d.DataMapping == d2.DataMapping &&
d.Status == d2.Status &&
d.Overviews == d2.Overviews &&
d.Shape.Equal(&d2.Shape) &&
d.GeogShape.Equal(&d2.GeogShape.Shape) &&
d.GeomShape.Equal(&d2.GeomShape.Shape) &&
utils.SliceInt64Equal(d.Bands, d2.Bands)
}
func (d *Dataset) GDALURI() string {
return GDALURI(d.ContainerURI, d.ContainerSubDir)
}
func GDALURI(uri, subdir string) string {
if subdir != "" {
return fmt.Sprintf("%s:%s", subdir, uri)
}
return uri
} | internal/geocube/dataset.go | 0.730482 | 0.53358 | dataset.go | starcoder |
package critpath
/*
From LeetCode Critical Path detector
https://leetcode.com/problems/critical-connections-in-a-network/
Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]
Output: [[1,3]]
Explanation: [[3,1]] is also accepted.
This uses Tarjan's algorith. The idea is to iterate over all the nodes
each time, while marking each node as we execute a DFS recursion. As we
reach each node it is marked with the lowest visible node seen. This
has the effect of detecting cycles in a graph. Once the dfs recursion
returns, we compare the returned id and if it doesn't match our lowest
node visible it means that there is no cycle. seen.
*/
var (
lowTimes []int
time int
critical [][]int
)
// tdfs implements Tarjan's algorithm using depths first search
func tdfs(graph [][]int, visited []int, node int, parent int) {
if visited[node] != -1 {
return
}
min := func(a int, b int) int {
switch {
case a < b:
return a
case b < a:
return b
default:
return a
}
}
time = time + 1
visited[node] = time
lowTimes[node] = time
neighbors := graph[node]
for _, nbr := range neighbors {
if nbr == parent {
continue
}
if visited[nbr] == -1 {
tdfs(graph, visited, nbr, node)
lowTimes[node] = min(lowTimes[node], lowTimes[nbr])
if visited[node] < lowTimes[nbr] {
critical = append(critical, []int{node, nbr})
}
} else {
lowTimes[node] = min(lowTimes[node], visited[nbr])
}
}
}
func criticalConnections(n int, connections [][]int) [][]int {
critical = make([][]int, 0)
for i := range critical {
critical[i] = make([]int, 0)
}
lowTimes = make([]int, n)
// make a graph of neighbors for each node
graph := make([][]int, n)
for i := range graph {
graph[i] = make([]int, 0)
}
// make neighbors graph
for _, c := range connections {
graph[c[0]] = append(graph[c[0]], c[1])
graph[c[1]] = append(graph[c[1]], c[0])
}
visited := make([]int, n)
for i := range visited {
visited[i] = -1
}
tdfs(graph, visited, 0, -1)
return critical
} | criticalPath/critPathTarjan.go | 0.83622 | 0.459258 | critPathTarjan.go | starcoder |
package rof
import (
"fmt"
"reflect"
"time"
)
type Interpreter struct {
Globals *Environment
Env *Environment
}
func NewInterpreter() Interpreter {
var i Interpreter
i.Globals = NewEnv(nil)
i.Env = i.Globals
i.Globals.Define("clock", NativeFunction{NativeCall: func(Interpreter, []Expr) interface{} { return float64(time.Now().Second()) }, A: 0})
return i
}
func (i Interpreter) Interpret(stmts []Stmt) (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
for _, stmt := range stmts {
i.execute(stmt)
}
return nil
}
func (i Interpreter) evaluate(expr Expr) interface{} {
switch t := expr.(type) {
case Binary:
return i.BinaryExpr(t)
case Grouping:
return i.GroupingExpr(t)
case Literal:
return i.LiteralExpr(t)
case Unary:
return i.UnaryExpr(t)
case Variable:
return i.VariableExpr(t)
case Assign:
return i.AssignExpr(t)
case Logical:
return i.LogicalExpr(t)
case Call:
return i.CallExpr(t)
default:
fmt.Println("[ERROR] Type -> ", reflect.TypeOf(t))
return nil
}
}
func (i Interpreter) execute(stmt Stmt) {
switch t := stmt.(type) {
case Expression:
i.ExprStmt(t)
case Print:
i.PrintStmt(t)
case Var:
i.VarStmt(t)
case Block:
i.BlockStmt(t)
case If:
i.IfStmt(t)
case While:
i.WhileStmt(t)
default:
fmt.Println("[ERROR] Type -> ", reflect.TypeOf(t))
}
}
func (i Interpreter) BinaryExpr(expr Binary) interface{} {
right := i.evaluate(expr.Right)
left := i.evaluate(expr.Left)
//fmt.Println("[DEBUG] BinaryExpr Called -> ", expr, "\n\n RIGHT -> ", right, "\n LEFT -> ", left, "\n Operator -> ", expr.Operator)
switch expr.Operator.TokenType {
case GREATER:
l, r := i.checkNumberOperands(expr.Operator, left, right)
return l > r
case GREATER_EQUAL:
l, r := i.checkNumberOperands(expr.Operator, left, right)
return l >= r
case LESS:
l, r := i.checkNumberOperands(expr.Operator, left, right)
return l < r
case LESS_EQUAL:
l, r := i.checkNumberOperands(expr.Operator, left, right)
return l <= r
case MINUS:
l, r := i.checkNumberOperands(expr.Operator, left, right)
return l - r
case SLASH:
l, r := i.checkNumberOperands(expr.Operator, left, right)
return l / r
case STAR:
l, r := i.checkNumberOperands(expr.Operator, left, right)
return l * r
case PLUS:
switch l := left.(type) {
case float64:
return l + right.(float64)
case string:
return l + fmt.Sprint(right)
}
case EQUAL_EQUAL:
return i.isEqual(left, right)
case BANG_EQUAL:
return !i.isEqual(left, right)
}
// Non raggiungibile
return nil
}
func (i Interpreter) GroupingExpr(expr Grouping) interface{} {
return i.evaluate(expr.Expr)
}
func (i Interpreter) LiteralExpr(expr Literal) interface{} {
return expr.Value
}
func (i Interpreter) UnaryExpr(expr Unary) interface{} {
right := i.evaluate(expr)
switch expr.Operator.TokenType {
case BANG:
return !i.isTruthy(right)
case MINUS:
r := i.checkNumberOperand(expr.Operator, right)
return -r
}
// Non raggiungibile
return nil
}
func (i Interpreter) VariableExpr(expr Variable) interface{} {
return i.Env.Get(expr.Name)
}
func (i Interpreter) AssignExpr(expr Assign) interface{} {
value := i.evaluate(expr.Value)
i.Env.Assign(expr.Name, value)
return value
}
func (i Interpreter) LogicalExpr(expr Logical) interface{} {
left := i.evaluate(expr.Left)
if expr.Operator.TokenType == OR {
if i.isTruthy(left) {
return left
}
} else {
if !i.isTruthy(left) {
return left
}
}
return i.evaluate(expr.Right)
}
func (i Interpreter) CallExpr(expr Call) interface{} {
callee := i.evaluate(expr.Callee)
var args []Expr
for _, arg := range expr.Args {
args = append(args, i.evaluate(arg).(Expr))
}
if _, ok := callee.(Callable); !ok {
panic(&RuntimeError{expr.Paren, "Can only call functions and classes."})
}
function, _ := callee.(Callable)
if len(args) != function.Arity() {
panic(&RuntimeError{expr.Paren, "Expected " +
string(function.Arity()) + " arguments but got " +
string(len(args)) + "."})
}
return function.Call(i, args)
}
func (i Interpreter) ExprStmt(stmt Expression) {
i.evaluate(stmt.Expr)
}
func (i Interpreter) PrintStmt(stmt Print) {
//fmt.Println("[DEBUG] Print Called ->", stmt)
value := i.evaluate(stmt.Expr)
fmt.Println(Stringify(value))
}
func (i Interpreter) VarStmt(stmt Var) {
var value interface{}
if stmt.Initializer != nil {
value = i.evaluate(stmt.Initializer)
}
//fmt.Println("[DEBUG] Create var ", stmt.Name.Lexeme, " -> ", value)
i.Env.Define(stmt.Name.Lexeme, value)
}
func (i Interpreter) BlockStmt(stmt Block) {
previous := i.Env
i.Env = NewEnv(previous)
defer func() { i.Env = previous }()
for _, s := range stmt.Statements {
i.execute(s)
}
}
func (i Interpreter) IfStmt(stmt If) {
if i.isTruthy(i.evaluate(stmt.Condition)) {
i.execute(stmt.ThenBranch)
} else if stmt.ElseBranch != nil {
i.execute(stmt.ElseBranch)
}
}
func (i Interpreter) WhileStmt(stmt While) {
for i.isTruthy(i.evaluate(stmt.Condition)) {
i.execute(stmt.Body)
}
}
// Helper
func (i Interpreter) isTruthy(obj interface{}) bool {
if obj == nil {
return false
}
if reflect.TypeOf(obj).String() == "bool" {
return obj.(bool)
}
return true
}
func (i Interpreter) isEqual(obj1, obj2 interface{}) bool {
return obj1 == obj2
}
func (i Interpreter) checkNumberOperand(operator Token, operand interface{}) float64 {
var n float64
ok := false
switch t := operand.(type) {
case float64:
ok = true
n = t
}
if !ok {
panic(&RuntimeError{operator, "Operand must be number"})
}
return n
}
func (i Interpreter) checkNumberOperands(operator Token, left, right interface{}) (float64, float64) {
ok1, ok2 := false, false
var n1, n2 float64
switch t := left.(type) {
case float64:
ok1 = true
n1 = t
}
switch t := right.(type) {
case float64:
ok2 = true
n2 = t
}
if !ok1 || !ok2 {
panic(&RuntimeError{operator, "Operands must be numbers"})
}
return n1, n2
}
func Stringify(obj interface{}) string {
if obj == nil {
return "nil"
}
//fmt.Println("[DEBUG] Print -> ", obj)
switch t := obj.(type) {
case string:
return t
case float64:
return fmt.Sprintf("%v", t)
case bool:
return fmt.Sprintf("%v", t)
default:
return "nil"
}
} | rof/interpreter.go | 0.51562 | 0.407216 | interpreter.go | starcoder |
package pngutil
import (
"errors"
"io"
)
/*
skipReadSeeker represents a view into a larger reader. It starts at
offset and ends at limit. Once it has read up to limit the Read
method returns an io.EOF error.
In this package all instances of skipReadSeeker use the same underlying
reader passed to ReplaceMeta.
*/
type skipReadSeeker struct {
name string
rs io.ReadSeeker
start int64
end int64
/*
offset is relative to start. That is,
it always begins at zero even if start
is not.
*/
offset int64
}
func (srs *skipReadSeeker) Read(p []byte) (n int, err error) {
if srs.offset >= srs.end {
return 0, io.EOF
}
toRead := srs.end - srs.offset
if toRead > int64(len(p)) {
toRead = int64(len(p))
}
n, err = srs.rs.Read(p[:toRead])
srs.offset += int64(n)
return n, err
}
func (srs *skipReadSeeker) Seek(offset int64, whence int) (n int64, err error) {
switch whence {
case io.SeekStart:
offset += srs.start
case io.SeekCurrent:
offset += srs.start + srs.offset
case io.SeekEnd:
offset = srs.end + offset
}
if offset < srs.start {
return n, errors.New("pngutil: skipReadSeeker seeking before start")
}
n, err = srs.rs.Seek(offset, io.SeekStart)
srs.offset = offset
return offset, err
}
type multiReadSeeker struct {
overall int64
rsIdx int
readSeekers []*skipReadSeeker
sizes []int64
size int64
}
/*
Returns a new multireader that is a concatenation of
rs. All read seekers and the multireader itself will
be seeked to the start.
*/
func newMultiReadSeeker(readSeekers ...*skipReadSeeker) (mrs *multiReadSeeker, err error) {
var sizes []int64
var size int64
for _, rs := range readSeekers {
sz := rs.end - rs.start
sizes = append(sizes, sz)
size += sz
}
mrs = &multiReadSeeker{
readSeekers: readSeekers,
sizes: sizes,
size: size,
}
/*
ReplaceMeta uses its input read seeker to create
two or more of the read seekers supplied to this
function. Therefore we seek to the start here to
ensure all readers are in the correct position.
*/
if _, err := mrs.Seek(0, io.SeekStart); err != nil {
return nil, err
}
return mrs, nil
}
func (mrs *multiReadSeeker) Read(p []byte) (n int, err error) {
read := 0
for {
if read == len(p) {
break
}
n, err = mrs.readSeekers[mrs.rsIdx].Read(p[read:])
read += n
mrs.overall += int64(n)
// If we reach the end of the current readseeker...
if errors.Is(err, io.EOF) {
// ...return if this is the last readseeker.
if mrs.rsIdx == len(mrs.readSeekers)-1 {
return read, err
}
/*
Otherwise increment readseeker index, ensure
said readseekers's cursor is at the start,
then resume reading.
*/
mrs.rsIdx++
_, _ = mrs.readSeekers[mrs.rsIdx].Seek(0, io.SeekStart)
continue
}
// Immediately return on non-EOF error.
if err != nil {
return read, err
}
}
return read, nil
}
func (mrs *multiReadSeeker) Seek(offset int64, whence int) (n int64, err error) {
switch whence {
case io.SeekStart:
// to prevent default case
case io.SeekCurrent:
offset += mrs.overall
case io.SeekEnd:
offset = mrs.size + offset
default:
return 0, errors.New("pngutil: invalid whence value for multiReadSeeker")
}
var total int64
for i, s := range mrs.sizes {
if offset >= total && offset < total+s {
mrs.rsIdx = i
rsOffset := offset - total
_, err := mrs.readSeekers[mrs.rsIdx].Seek(rsOffset, io.SeekStart)
if err != nil {
return 0, err
}
mrs.overall = offset
return offset, nil
}
total += s
}
return 0, errors.New("pngutil: seek out of bounds for multiReadSeeker")
}
func (mrs *multiReadSeeker) Size() (n int64) {
return mrs.size
} | pngutil/readers.go | 0.600891 | 0.418519 | readers.go | starcoder |
package standard
type andOperator struct {
arg1, arg2 interface{}
}
func (op *andOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
first, err := getBoolean(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getBoolean(op.arg2, parameters)
if err != nil {
return nil, err
}
return first && second, nil
}
type orOperator struct {
arg1, arg2 interface{}
}
func (op *orOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
first, err := getBoolean(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getBoolean(op.arg2, parameters)
if err != nil {
return nil, err
}
return first || second, nil
}
type lessThanOperator struct {
arg1, arg2 interface{}
}
func (op *lessThanOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
first, err := getNumber(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getNumber(op.arg2, parameters)
if err != nil {
return nil, err
}
return first < second, nil
}
type lessThanOrEqualOperator struct {
arg1, arg2 interface{}
}
func (op *lessThanOrEqualOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
first, err := getNumber(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getNumber(op.arg2, parameters)
if err != nil {
return nil, err
}
return first <= second, nil
}
type greaterThanOperator struct {
arg1, arg2 interface{}
}
func (op *greaterThanOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
first, err := getNumber(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getNumber(op.arg2, parameters)
if err != nil {
return nil, err
}
return first > second, nil
}
type greaterThanOrEqualOperator struct {
arg1, arg2 interface{}
}
func (op *greaterThanOrEqualOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
first, err := getNumber(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getNumber(op.arg2, parameters)
if err != nil {
return nil, err
}
return first >= second, nil
}
type equalsOperator struct {
arg1, arg2 interface{}
}
func (op *equalsOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
if firstNumber, err := getNumber(op.arg1, parameters); err == nil {
if secondNumber, err := getNumber(op.arg2, parameters); err == nil {
return firstNumber == secondNumber, nil
}
}
first, err := getString(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getString(op.arg2, parameters)
if err != nil {
return nil, err
}
return first == second, nil
}
type notEqualsOperator struct {
arg1, arg2 interface{}
}
func (op *notEqualsOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
if firstNumber, err := getNumber(op.arg1, parameters); err == nil {
if secondNumber, err := getNumber(op.arg2, parameters); err == nil {
return firstNumber != secondNumber, nil
}
}
first, err := getString(op.arg1, parameters)
if err != nil {
return nil, err
}
second, err := getString(op.arg2, parameters)
if err != nil {
return nil, err
}
return first != second, nil
}
type notOperator struct {
arg interface{}
}
func (op *notOperator) Evaluate(parameters map[string]interface{}) (interface{}, error) {
result, err := getBoolean(op.arg, parameters)
if err != nil {
return nil, err
}
return !result, nil
} | script/standard/logic_operators.go | 0.623262 | 0.45744 | logic_operators.go | starcoder |
package main
import (
"github.com/threagile/threagile/model"
)
type accidentalLoggingOfSensitiveDataRule string
var CustomRiskRule accidentalLoggingOfSensitiveDataRule
func (r accidentalLoggingOfSensitiveDataRule) Category() model.RiskCategory {
return model.RiskCategory{
Id: "accidental-logging-of-sensitive-data",
Title: "Logging of Sensitive Data",
Description: "When storing or processing sensitive data there is a risk that the data is written to logfiles.",
Impact: "Bypassing access controls to the sensitive data",
ASVS: "v4.0.2-7.1 - Log Content",
CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html#data-to-exclude",
Action: "Logging and monitoring",
Mitigation: "Review log statements and ensure that sensitive data, such as personal indenfiable information and credentials, is not logged without a legit reason.",
Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?",
Function: model.Development,
STRIDE: model.InformationDisclosure,
DetectionLogic: "Entities processing, or storing, data with confidentiality class restricted or higher which sends data to a monitoring target.",
RiskAssessment: "The risk rating depends on the sensitivity of the data processed or stored",
FalsePositives: "None, either the risk is mitigated or accepted",
ModelFailurePossibleReason: false,
CWE: 532,
}
}
func (r accidentalLoggingOfSensitiveDataRule) SupportedTags() []string {
return []string{"PII", "credential"}
}
func (r accidentalLoggingOfSensitiveDataRule) GenerateRisks() []model.Risk {
risks := make([]model.Risk, 0)
for _, id := range model.SortedTechnicalAssetIDs() {
technicalAsset := model.ParsedModelRoot.TechnicalAssets[id]
if technicalAsset.OutOfScope || technicalAsset.Technology == model.Monitoring {
continue
}
hasSensitiveData := false
sensitiveData := make([]string, 0)
impact := model.MediumImpact
datas := append(technicalAsset.DataAssetsProcessedSorted(), technicalAsset.DataAssetsStoredSorted()...)
for _, data := range datas {
if data.Confidentiality >= model.Restricted || data.IsTaggedWithAny(r.SupportedTags()...) {
hasSensitiveData = true
if data.Confidentiality == model.Confidential && impact == model.MediumImpact {
impact = model.HighImpact
}
if data.Confidentiality == model.StrictlyConfidential && impact <= model.HighImpact {
impact = model.VeryHighImpact
}
sensitiveData = append(sensitiveData, data.Id)
}
}
if hasSensitiveData {
commLinks := technicalAsset.CommunicationLinks
for _, commLink := range commLinks {
destination := model.ParsedModelRoot.TechnicalAssets[commLink.TargetId]
if destination.Technology == model.Monitoring {
risks = append(risks, createRisk(technicalAsset, impact, sensitiveData))
}
}
}
}
return risks
}
func createRisk(technicalAsset model.TechnicalAsset, impact model.RiskExploitationImpact, dataIds []string) model.Risk {
title := "<b>Logging of Sensitive Data</b> risk at <b>" + technicalAsset.Title + "</b>"
risk := model.Risk{
Category: CustomRiskRule.Category(),
Severity: model.CalculateSeverity(model.Likely, impact),
ExploitationLikelihood: model.Likely,
ExploitationImpact: impact,
Title: title,
MostRelevantTechnicalAssetId: technicalAsset.Id,
DataBreachProbability: model.Possible,
DataBreachTechnicalAssetIDs: dataIds,
}
risk.SyntheticId = risk.Category.Id + "@" + technicalAsset.Id
return risk
} | risks/accidental-logging-of-sensitive-data/accidental-logging-of-sensitive-data-rule.go | 0.531939 | 0.481515 | accidental-logging-of-sensitive-data-rule.go | starcoder |
package parser
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// EncoderToNodeOpts Options for the encoderToNode.
type EncoderToNodeOpts struct {
OmitEmpty bool
TagName string
AllowSliceAsStruct bool
}
// EncodeToNode converts an element to a node.
// element -> nodes.
func EncodeToNode(element interface{}, rootName string, opts EncoderToNodeOpts) (*Node, error) {
rValue := reflect.ValueOf(element)
node := &Node{Name: rootName}
encoder := encoderToNode{EncoderToNodeOpts: opts}
err := encoder.setNodeValue(node, rValue)
if err != nil {
return nil, err
}
return node, nil
}
type encoderToNode struct {
EncoderToNodeOpts
}
func (e encoderToNode) setNodeValue(node *Node, rValue reflect.Value) error {
switch rValue.Kind() {
case reflect.String:
node.Value = rValue.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
node.Value = strconv.FormatInt(rValue.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
node.Value = strconv.FormatUint(rValue.Uint(), 10)
case reflect.Float32, reflect.Float64:
node.Value = strconv.FormatFloat(rValue.Float(), 'f', 6, 64)
case reflect.Bool:
node.Value = strconv.FormatBool(rValue.Bool())
case reflect.Struct:
return e.setStructValue(node, rValue)
case reflect.Ptr:
return e.setNodeValue(node, rValue.Elem())
case reflect.Map:
return e.setMapValue(node, rValue)
case reflect.Slice:
return e.setSliceValue(node, rValue)
default:
// noop
}
return nil
}
func (e encoderToNode) setStructValue(node *Node, rValue reflect.Value) error {
rType := rValue.Type()
for i := 0; i < rValue.NumField(); i++ {
field := rType.Field(i)
fieldValue := rValue.Field(i)
if !IsExported(field) {
continue
}
if field.Tag.Get(e.TagName) == "-" {
continue
}
if err := isSupportedType(field); err != nil {
return err
}
if e.isSkippedField(field, fieldValue) {
continue
}
nodeName := field.Name
if e.AllowSliceAsStruct && field.Type.Kind() == reflect.Slice && len(field.Tag.Get(TagLabelSliceAsStruct)) != 0 {
nodeName = field.Tag.Get(TagLabelSliceAsStruct)
}
if field.Anonymous {
if err := e.setNodeValue(node, fieldValue); err != nil {
return err
}
continue
}
child := &Node{Name: nodeName, FieldName: field.Name, Description: field.Tag.Get(TagDescription)}
if err := e.setNodeValue(child, fieldValue); err != nil {
return err
}
if field.Type.Kind() == reflect.Ptr {
if field.Type.Elem().Kind() != reflect.Struct && fieldValue.IsNil() {
continue
}
if field.Type.Elem().Kind() == reflect.Struct && len(child.Children) == 0 {
if field.Tag.Get(e.TagName) != TagLabelAllowEmpty {
continue
}
child.Value = "true"
}
}
node.Children = append(node.Children, child)
}
return nil
}
func (e encoderToNode) setMapValue(node *Node, rValue reflect.Value) error {
if rValue.Type().Elem().Kind() == reflect.Interface {
node.RawValue = rValue.Interface()
return nil
}
for _, key := range rValue.MapKeys() {
child := &Node{Name: key.String(), FieldName: key.String()}
node.Children = append(node.Children, child)
if err := e.setNodeValue(child, rValue.MapIndex(key)); err != nil {
return err
}
}
return nil
}
func (e encoderToNode) setSliceValue(node *Node, rValue reflect.Value) error {
// label-slice-as-struct
if rValue.Type().Elem().Kind() == reflect.Struct && !strings.EqualFold(node.Name, node.FieldName) {
if rValue.Len() > 1 {
return fmt.Errorf("node %s has too many slice entries: %d", node.Name, rValue.Len())
}
return e.setNodeValue(node, rValue.Index(0))
}
if rValue.Type().Elem().Kind() == reflect.Struct ||
rValue.Type().Elem().Kind() == reflect.Ptr && rValue.Type().Elem().Elem().Kind() == reflect.Struct {
for i := 0; i < rValue.Len(); i++ {
child := &Node{Name: "[" + strconv.Itoa(i) + "]"}
eValue := rValue.Index(i)
err := e.setNodeValue(child, eValue)
if err != nil {
return err
}
node.Children = append(node.Children, child)
}
return nil
}
var values []string
for i := 0; i < rValue.Len(); i++ {
eValue := rValue.Index(i)
switch eValue.Kind() {
case reflect.String:
values = append(values, eValue.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
values = append(values, strconv.FormatInt(eValue.Int(), 10))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
values = append(values, strconv.FormatUint(eValue.Uint(), 10))
case reflect.Float32, reflect.Float64:
values = append(values, strconv.FormatFloat(eValue.Float(), 'f', 6, 64))
case reflect.Bool:
values = append(values, strconv.FormatBool(eValue.Bool()))
default:
// noop
}
}
node.Value = strings.Join(values, ", ")
return nil
}
func (e encoderToNode) isSkippedField(field reflect.StructField, fieldValue reflect.Value) bool {
if e.OmitEmpty && field.Type.Kind() == reflect.String && fieldValue.Len() == 0 {
return true
}
if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct && fieldValue.IsNil() {
return true
}
if e.OmitEmpty && (field.Type.Kind() == reflect.Slice) &&
(fieldValue.IsNil() || fieldValue.Len() == 0) {
return true
}
if (field.Type.Kind() == reflect.Map) &&
(fieldValue.IsNil() || fieldValue.Len() == 0) {
return true
}
return false
} | pkg/config/parser/element_nodes.go | 0.683842 | 0.483953 | element_nodes.go | starcoder |
package cryptypes
import "database/sql/driver"
// EncryptedFloat64 supports encrypting Float64 data
type EncryptedFloat64 struct {
Field
Raw float64
}
// Scan converts the value from the DB into a usable EncryptedFloat64 value
func (s *EncryptedFloat64) Scan(value interface{}) error {
return decrypt(value.([]byte), &s.Raw)
}
// Value converts an initialized EncryptedFloat64 value into a value that can safely be stored in the DB
func (s EncryptedFloat64) Value() (driver.Value, error) {
return encrypt(s.Raw)
}
// NullEncryptedFloat64 supports encrypting nullable Float64 data
type NullEncryptedFloat64 struct {
Field
Raw float64
Empty bool
}
// Scan converts the value from the DB into a usable NullEncryptedFloat64 value
func (s *NullEncryptedFloat64) Scan(value interface{}) error {
if value == nil {
s.Raw = 0
s.Empty = true
return nil
}
return decrypt(value.([]byte), &s.Raw)
}
// Value converts an initialized NullEncryptedFloat64 value into a value that can safely be stored in the DB
func (s NullEncryptedFloat64) Value() (driver.Value, error) {
if s.Empty {
return nil, nil
}
return encrypt(s.Raw)
}
// SignedFloat64 supports signing Float64 data
type SignedFloat64 struct {
Field
Raw float64
Valid bool
}
// Scan converts the value from the DB into a usable SignedFloat64 value
func (s *SignedFloat64) Scan(value interface{}) (err error) {
s.Valid, err = verify(value.([]byte), &s.Raw)
return
}
// Value converts an initialized SignedFloat64 value into a value that can safely be stored in the DB
func (s SignedFloat64) Value() (driver.Value, error) {
return sign(s.Raw)
}
// NullSignedFloat64 supports signing nullable Float64 data
type NullSignedFloat64 struct {
Field
Raw float64
Empty bool
Valid bool
}
// Scan converts the value from the DB into a usable NullSignedFloat64 value
func (s *NullSignedFloat64) Scan(value interface{}) (err error) {
if value == nil {
s.Raw = 0
s.Empty = true
s.Valid = true
return nil
}
s.Valid, err = verify(value.([]byte), &s.Raw)
return
}
// Value converts an initialized NullSignedFloat64 value into a value that can safely be stored in the DB
func (s NullSignedFloat64) Value() (driver.Value, error) {
if s.Empty {
return nil, nil
}
return sign(s.Raw)
}
// SignedEncryptedFloat64 supports signing and encrypting Float64 data
type SignedEncryptedFloat64 struct {
Field
Raw float64
Valid bool
}
// Scan converts the value from the DB into a usable SignedEncryptedFloat64 value
func (s *SignedEncryptedFloat64) Scan(value interface{}) (err error) {
s.Valid, err = decryptVerify(value.([]byte), &s.Raw)
return
}
// Value converts an initialized SignedEncryptedFloat64 value into a value that can safely be stored in the DB
func (s SignedEncryptedFloat64) Value() (driver.Value, error) {
return encryptSign(s.Raw)
}
// NullSignedEncryptedFloat64 supports signing and encrypting nullable Float64 data
type NullSignedEncryptedFloat64 struct {
Field
Raw float64
Empty bool
Valid bool
}
// Scan converts the value from the DB into a usable NullSignedEncryptedFloat64 value
func (s *NullSignedEncryptedFloat64) Scan(value interface{}) (err error) {
if value == nil {
s.Raw = 0
s.Empty = true
s.Valid = true
return nil
}
s.Valid, err = decryptVerify(value.([]byte), &s.Raw)
return
}
// Value converts an initialized NullSignedEncryptedFloat64 value into a value that can safely be stored in the DB
func (s NullSignedEncryptedFloat64) Value() (driver.Value, error) {
if s.Empty {
return nil, nil
}
return encryptSign(s.Raw)
} | cryptypes/type_float64.go | 0.828627 | 0.639975 | type_float64.go | starcoder |
package conf
// Int64Var defines an int64 flag and environment variable with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag and/or environment variable.
func (c *Configurator) Int64Var(p *int64, name string, value int64, usage string) {
c.env().Int64Var(p, name, value, usage)
c.flag().Int64Var(p, name, value, usage)
}
// Int64 defines an int64 flag and environment variable with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag and/or environment variable.
func (c *Configurator) Int64(name string, value int64, usage string) *int64 {
p := new(int64)
c.Int64Var(p, name, value, usage)
return p
}
// Int64VarE defines an int64 environment variable with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the environment variable.
func (c *Configurator) Int64VarE(p *int64, name string, value int64, usage string) {
c.env().Int64Var(p, name, value, usage)
}
// Int64E defines an int64 environment variable with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the environment variable.
func (c *Configurator) Int64E(name string, value int64, usage string) *int64 {
p := new(int64)
c.Int64VarE(p, name, value, usage)
return p
}
// Int64VarF defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func (c *Configurator) Int64VarF(p *int64, name string, value int64, usage string) {
c.flag().Int64Var(p, name, value, usage)
}
// Int64F defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func (c *Configurator) Int64F(name string, value int64, usage string) *int64 {
p := new(int64)
c.Int64VarF(p, name, value, usage)
return p
}
// Int64Var defines an int64 flag and environment variable with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag and/or environment variable.
func Int64Var(p *int64, name string, value int64, usage string) {
Global.Int64Var(p, name, value, usage)
}
// Int64 defines an int64 flag and environment variable with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag and/or environment variable.
func Int64(name string, value int64, usage string) *int64 {
return Global.Int64(name, value, usage)
}
// Int64VarE defines an int64 environment variable with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the environment variable.
func Int64VarE(p *int64, name string, value int64, usage string) {
Global.Int64VarE(p, name, value, usage)
}
// Int64E defines an int64 environment variable with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the environment variable.
func Int64E(name string, value int64, usage string) *int64 {
return Global.Int64E(name, value, usage)
}
// Int64VarF defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func Int64VarF(p *int64, name string, value int64, usage string) {
Global.Int64VarF(p, name, value, usage)
}
// Int64F defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func Int64F(name string, value int64, usage string) *int64 {
return Global.Int64F(name, value, usage)
} | value_int64.go | 0.747984 | 0.668809 | value_int64.go | starcoder |
package synopsis
//SmoothedSeries compresses time series data by representing it as a sequence of averages
type SmoothedSeries struct {
length int
data []float64
caps []int
pos int
fill int
}
//NewSmoothedSeries is a constructor for SmoothedSeries
func NewSmoothedSeries(n int, capFn func(int) int) *SmoothedSeries {
data := make([]float64, n)
caps := make([]int, n)
for index := range caps {
caps[index] = capFn(index)
}
return &SmoothedSeries{length: n, data: data, caps: caps}
}
//Insert inserts a sequence of values into the SmoothedSeries, in the order they are provided.
func (s *SmoothedSeries) Insert(values ...float64) {
for _, v := range values {
if s.pos < s.length { //Series is not at capacity yet
pWt := s.partialWeight()
if s.pos > 0 { //Series is past first element
s.data[s.pos] = (1-pWt)*s.data[s.pos] + pWt*s.data[s.pos-1]
for index := s.pos - 1; index > 0; index-- {
wt := s.weight(index)
s.data[index] = (1-wt)*s.data[index] + wt*s.data[index-1]
}
wt := s.weight(0)
s.data[0] = (1-wt)*s.data[0] + wt*v
} else { //Series is still filling first element
s.data[0] = (1-pWt)*s.data[0] + pWt*v
}
s.updatePos()
} else { //Series is at capacity
for index := s.length - 1; index > 0; index-- {
wt := s.weight(index)
s.data[index] = (1-wt)*s.data[index] + wt*s.data[index-1]
}
wt := s.weight(0)
s.data[0] = (1-wt)*s.data[0] + wt*v
}
}
}
func (s *SmoothedSeries) updatePos() {
s.fill++
if s.fill == s.caps[s.pos] {
s.fill = 0
s.pos++
}
}
func (s *SmoothedSeries) weight(ind int) float64 {
return 1 / float64(s.caps[ind])
}
func (s *SmoothedSeries) partialWeight() float64 {
return 1 / float64(s.fill+1)
}
//Mean returns the average value
func (s *SmoothedSeries) Mean() float64 {
mean := float64(0)
for ind := 0; ind < s.pos; ind++ {
mean += s.weight(ind) * s.data[ind]
}
if s.pos < s.length {
mean += s.partialWeight() * s.data[s.pos]
}
return mean
}
//SetData sets the data slice
func (s *SmoothedSeries) SetData(data []float64) {
if len(data) == s.length {
s.data = data
}
//todo: fails silently on bad input
}
//Rescale multiplies all of the data by a constant factor
func (s *SmoothedSeries) Rescale(scale float64) {
for ind := 0; ind < s.length; ind++ {
s.data[ind] *= scale
}
}
//ExponentialSmoothedSeries tracks a smoothed history of length k * (2^n - 1) using k*n values
func ExponentialSmoothedSeries(n, k int) *SmoothedSeries {
return NewSmoothedSeries(
n*k,
func(r int) int { return 1 << uint(r/k) }, //2 ^ floor(r/k)
)
} | kit/synopsis/smoothedseries.go | 0.726231 | 0.721755 | smoothedseries.go | starcoder |
package eoy
import (
"fmt"
"time"
)
//Month is used to provide a primary key for storing stats by month.
type Month struct {
//ID is YYYY-MM
ID string
Month int
Year int
CreatedDate *time.Time
}
//MonthResult holds a month and a stats record.
type MonthResult struct {
ID string
Month int
Year int
Stat
}
//MOMonth is used to provide a primary key for storing stats by month.
type MOMonth struct {
Month
}
//MOMonthResult holds a month and a stats record for the "month over month" sheet.
type MOMonthResult struct {
MonthResult
}
//KeyValue implements KeyValuer by returning the value of a key for the
//MonthResult object.
func (r MonthResult) KeyValue(i int) (key interface{}) {
switch i {
case 0:
key = r.Month
case 1:
key = r.Year
default:
fmt.Printf("Error in MonthResult\n%+v\n", r)
err := fmt.Errorf("Not a valid MonthResult index, %v", i)
panic(err)
}
return key
}
//FillKeys implements KeyFiller by filling Excel cells with keys from the
//month table.
func (r MonthResult) FillKeys(rt *Runtime, sheet Sheet, row, col int) int {
for j := 0; j < len(sheet.KeyNames); j++ {
v := r.KeyValue(j)
s := sheet.KeyStyles[j]
rt.Cell(sheet.Name, row, col+j, v, s)
}
return row
}
//FillKeys implements KeyFiller by filling Excel cells with keys from the
//month table.
func (r MOMonthResult) FillKeys(rt *Runtime, sheet Sheet, row, col int) int {
m := MonthResult{}
return m.FillKeys(rt, sheet, row, col)
}
//Fill implements Filler by filling in a spreadsheet using data from the years table.
func (r Month) Fill(rt *Runtime, sheet Sheet, row, col int) int {
var a []MonthResult
rt.DB.Order("id").Where("months.year = ?", rt.Year).Table("months").Select("month, stats.*").Joins("left join stats on stats.id = months.id").Scan(&a)
for _, r := range a {
rt.Spreadsheet.InsertRow(sheet.Name, row+1)
r.FillKeys(rt, sheet, row, 0)
r.Stat.Fill(rt, sheet.Name, row, len(sheet.KeyNames))
row++
}
return row
}
//Fill implements Filler by filling in a spreadsheet using data from the years table.
func (r MOMonth) Fill(rt *Runtime, sheet Sheet, row, col int) int {
var a []MonthResult
rt.DB.Order("id, year desc").Table("months").Select("month, year, stats.*").Joins("left join stats on stats.id = months.id").Scan(&a)
for _, r := range a {
rt.Spreadsheet.InsertRow(sheet.Name, row+1)
r.FillKeys(rt, sheet, row, 0)
r.Stat.Fill(rt, sheet.Name, row, len(sheet.KeyNames))
row++
}
return row
}
//NewMonthSheet builds the data used to decorate the "month over month" sheet.
func (rt *Runtime) NewMonthSheet() Sheet {
filler := Month{}
result := MonthResult{}
name := fmt.Sprintf("Months, %d", rt.Year)
sheet := Sheet{
Titles: []string{
fmt.Sprintf("Results by month for %d", rt.Year),
},
Name: name,
KeyNames: []string{"Month"},
KeyStyles: []int{rt.KeyStyle, rt.KeyStyle},
Filler: filler,
KeyFiller: result,
}
return sheet
}
//NewMOMonthSheet builds the data used to decorate the "month over month" sheet.
func (rt *Runtime) NewMOMonthSheet() Sheet {
filler := MOMonth{}
result := MOMonthResult{}
sheet := Sheet{
Titles: []string{
"Month over Month results",
},
Name: "Month over month",
KeyNames: []string{"Month", "Year"},
KeyStyles: []int{rt.KeyStyle, rt.KeyStyle},
Filler: filler,
KeyFiller: result,
}
return sheet
} | pkg/month.go | 0.54819 | 0.419113 | month.go | starcoder |
package rendering
import (
"math"
. "github.com/locatw/go-ray-tracer/element"
. "github.com/locatw/go-ray-tracer/image"
. "github.com/locatw/go-ray-tracer/vector"
)
type Screen struct {
Center Vector
XAxis Vector
YAxis Vector
Resolution Resolution
Width float64
Height float64
}
func CreateScreen(camera *Camera, resolution Resolution) Screen {
aspect := resolution.Aspect()
center := Add(camera.Origin, camera.Direction)
xAxis := Normalize(Cross(camera.Direction, camera.Up))
yAxis := Multiply(-1.0, camera.Up)
height := 2.0 * math.Tan(camera.Fov/2.0)
width := height * aspect
return Screen{
Center: center,
XAxis: xAxis,
YAxis: yAxis,
Resolution: resolution,
Width: width,
Height: height,
}
}
func (screen *Screen) CreatePixelRays(context renderingContext, camera *Camera, x int, y int, samplingCount int) []Ray {
pixel := screen.createPixel(x, y)
rays := make([]Ray, samplingCount)
for i := 0; i < samplingCount; i++ {
x := context.Random.Float64() - 0.5
y := context.Random.Float64() - 0.5
subPixelPos := pixel.calculateSubPixelPosition(screen, x, y)
rays[i] = CreateRay(camera.Origin, Subtract(subPixelPos, camera.Origin))
}
return rays
}
func (screen *Screen) createPixel(x int, y int) pixel {
leftTopPixel := screen.createLeftTopPixel()
center := Add(leftTopPixel.Center, Multiply(float64(x)*leftTopPixel.Width, screen.XAxis))
center = Add(center, Multiply(float64(y)*leftTopPixel.Height, screen.YAxis))
return pixel{Center: center, Width: leftTopPixel.Width, Height: leftTopPixel.Height}
}
func (screen *Screen) createLeftTopPixel() pixel {
pixelWidth := screen.Width / float64(screen.Resolution.Width)
pixelHeight := screen.Height / float64(screen.Resolution.Height)
offset := Multiply(pixelWidth/2.0, screen.XAxis)
offset = Add(offset, Multiply(pixelHeight/2.0, screen.YAxis))
center := Subtract(screen.Center, Multiply(screen.Width/2.0, screen.XAxis))
center = Subtract(center, Multiply(screen.Height/2.0, screen.YAxis))
center = Add(center, offset)
return pixel{Center: center, Width: pixelWidth, Height: pixelHeight}
}
type pixel struct {
Center Vector
Width float64
Height float64
}
func (pixel *pixel) calculateSubPixelPosition(screen *Screen, x float64, y float64) Vector {
return AddAll(pixel.Center, Multiply(x*pixel.Width, screen.XAxis), Multiply(y*pixel.Height, screen.YAxis))
} | src/github.com/locatw/go-ray-tracer/rendering/screen.go | 0.865053 | 0.487673 | screen.go | starcoder |
package condition
import (
"github.com/Jeffail/benthos/lib/log"
"github.com/Jeffail/benthos/lib/metrics"
"github.com/Jeffail/benthos/lib/types"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeCount] = TypeSpec{
constructor: NewCount,
description: `
Counts messages starting from one, returning true until the counter reaches its
target, at which point it will return false and reset the counter. This
condition is useful when paired with the ` + "`read_until`" + ` input, as it can
be used to cut the input stream off once a certain number of messages have been
read.
It is worth noting that each discrete count condition will have its own counter.
Parallel processors containing a count condition will therefore count
independently. It is, however, possible to share the counter across processor
pipelines by defining the count condition as a resource.`,
}
}
//------------------------------------------------------------------------------
// CountConfig is a configuration struct containing fields for the Count
// condition.
type CountConfig struct {
Arg int `json:"arg" yaml:"arg"`
}
// NewCountConfig returns a CountConfig with default values.
func NewCountConfig() CountConfig {
return CountConfig{
Arg: 100,
}
}
//------------------------------------------------------------------------------
// Count is a condition that counts each message and returns false once a target
// count has been reached, at which point it resets the counter and starts
// again.
type Count struct {
arg int
ctr int
}
// NewCount returns a Count processor.
func NewCount(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
return &Count{
arg: conf.Count.Arg,
ctr: 0,
}, nil
}
//------------------------------------------------------------------------------
// Check attempts to check a message part against a configured condition.
func (c *Count) Check(msg types.Message) bool {
c.ctr++
if c.ctr < c.arg {
return true
}
c.ctr = 0
return false
}
//------------------------------------------------------------------------------ | lib/processor/condition/count.go | 0.67971 | 0.468791 | count.go | starcoder |
package math32
// Box3 represents a 3D bounding box defined by two points:
// the point with minimum coordinates and the point with maximum coordinates.
type Box3 struct {
Min Vector3
Max Vector3
}
// NewBox3 creates and returns a pointer to a new Box3 defined
// by its minimum and maximum coordinates.
func NewBox3(min, max *Vector3) *Box3 {
b := new(Box3)
b.Set(min, max)
return b
}
// Set sets this bounding box minimum and maximum coordinates.
// Returns pointer to this updated bounding box.
func (b *Box3) Set(min, max *Vector3) *Box3 {
if min != nil {
b.Min = *min
} else {
b.Min.Set(Infinity, Infinity, Infinity)
}
if max != nil {
b.Max = *max
} else {
b.Max.Set(-Infinity, -Infinity, -Infinity)
}
return b
}
// SetFromPoints set this bounding box from the specified array of points.
// Returns pointer to this updated bounding box.
func (b *Box3) SetFromPoints(points []Vector3) *Box3 {
b.MakeEmpty()
for i := 0; i < len(points); i++ {
b.ExpandByPoint(&points[i])
}
return b
}
// SetFromCenterAndSize set this bounding box from a center point and size.
// Size is a vector from the minimum point to the maximum point.
// Returns pointer to this updated bounding box.
func (b *Box3) SetFromCenterAndSize(center, size *Vector3) *Box3 {
v1 := NewVector3(0, 0, 0)
halfSize := v1.Copy(size).MultiplyScalar(0.5)
b.Min.Copy(center).Sub(halfSize)
b.Max.Copy(center).Add(halfSize)
return b
}
// Copy copy other to this bounding box.
// Returns pointer to this updated bounding box.
func (b *Box3) Copy(other *Box3) *Box3 {
b.Min = other.Min
b.Max = other.Max
return b
}
// MakeEmpty set this bounding box to empty.
// Returns pointer to this updated bounding box.
func (b *Box3) MakeEmpty() *Box3 {
b.Min.X = Infinity
b.Min.Y = Infinity
b.Min.Z = Infinity
b.Max.X = -Infinity
b.Max.Y = -Infinity
b.Max.Z = -Infinity
return b
}
// Empty returns if this bounding box is empty.
func (b *Box3) Empty() bool {
return (b.Max.X < b.Min.X) || (b.Max.Y < b.Min.Y) || (b.Max.Z < b.Min.Z)
}
// Center calculates the center point of this bounding box and
// stores its pointer to optionalTarget, if not nil, and also returns it.
func (b *Box3) Center(optionalTarget *Vector3) *Vector3 {
var result *Vector3
if optionalTarget == nil {
result = NewVector3(0, 0, 0)
} else {
result = optionalTarget
}
return result.AddVectors(&b.Min, &b.Max).MultiplyScalar(0.5)
}
// Size calculates the size of this bounding box: the vector from
// its minimum point to its maximum point.
// Store pointer to the calculated size into optionalTarget, if not nil,
// and also returns it.
func (b *Box3) Size(optionalTarget *Vector3) *Vector3 {
var result *Vector3
if optionalTarget == nil {
result = NewVector3(0, 0, 0)
} else {
result = optionalTarget
}
return result.SubVectors(&b.Min, &b.Max)
}
// ExpandByPoint may expand this bounding box to include the specified point.
// Returns pointer to this updated bounding box.
func (b *Box3) ExpandByPoint(point *Vector3) *Box3 {
b.Min.Min(point)
b.Max.Max(point)
return b
}
// ExpandByVector expands this bounding box by the specified vector.
// Returns pointer to this updated bounding box.
func (b *Box3) ExpandByVector(vector *Vector3) *Box3 {
b.Min.Sub(vector)
b.Max.Add(vector)
return b
}
// ExpandByScalar expands this bounding box by the specified scalar.
// Returns pointer to this updated bounding box.
func (b *Box3) ExpandByScalar(scalar float32) *Box3 {
b.Min.AddScalar(-scalar)
b.Max.AddScalar(scalar)
return b
}
// ContainsPoint returns if this bounding box contains the specified point.
func (b *Box3) ContainsPoint(point *Vector3) bool {
if point.X < b.Min.X || point.X > b.Max.X ||
point.Y < b.Min.Y || point.Y > b.Max.Y ||
point.Z < b.Min.Z || point.Z > b.Max.Z {
return false
}
return true
}
// ContainsBox returns if this bounding box contains other box.
func (b *Box3) ContainsBox(box *Box3) bool {
if (b.Min.X <= box.Max.X) && (box.Max.X <= b.Max.X) &&
(b.Min.Y <= box.Min.Y) && (box.Max.Y <= b.Max.Y) &&
(b.Min.Z <= box.Min.Z) && (box.Max.Z <= b.Max.Z) {
return true
}
return false
}
// IsIntersectionBox returns if other box intersects this one.
func (b *Box3) IsIntersectionBox(other *Box3) bool {
// using 6 splitting planes to rule out intersections.
if other.Max.X < b.Min.X || other.Min.X > b.Max.X ||
other.Max.Y < b.Min.Y || other.Min.Y > b.Max.Y ||
other.Max.Z < b.Min.Z || other.Min.Z > b.Max.Z {
return false
}
return true
}
// ClampPoint calculates a new point which is the specified point clamped inside this box.
// Stores the pointer to this new point into optionaTarget, if not nil, and also returns it.
func (b *Box3) ClampPoint(point *Vector3, optionalTarget *Vector3) *Vector3 {
var result *Vector3
if optionalTarget == nil {
result = NewVector3(0, 0, 0)
} else {
result = optionalTarget
}
return result.Copy(point).Clamp(&b.Min, &b.Max)
}
// DistanceToPoint returns the distance from this box to the specified point.
func (b *Box3) DistanceToPoint(point *Vector3) float32 {
var v1 Vector3
clampedPoint := v1.Copy(point).Clamp(&b.Min, &b.Max)
return clampedPoint.Sub(point).Length()
}
// GetBoundingSphere creates a bounding sphere to this bounding box.
// Store its pointer into optionalTarget, if not nil, and also returns it.
func (b *Box3) GetBoundingSphere(optionalTarget *Sphere) *Sphere {
var v1 Vector3
var result *Sphere
if optionalTarget == nil {
result = NewSphere(nil, 0)
} else {
result = optionalTarget
}
result.Center = *b.Center(nil)
result.Radius = b.Size(&v1).Length() * 0.5
return result
}
// Intersect sets this box to the intersection with other box.
// Returns pointer to this updated bounding box.
func (b *Box3) Intersect(other *Box3) *Box3 {
b.Min.Max(&other.Min)
b.Max.Min(&other.Max)
return b
}
// Union set this box to the union with other box.
// Returns pointer to this updated bounding box.
func (b *Box3) Union(other *Box3) *Box3 {
b.Min.Min(&other.Min)
b.Max.Max(&other.Max)
return b
}
// ApplyMatrix4 applies the specified matrix to the vertices of this bounding box.
// Returns pointer to this updated bounding box.
func (b *Box3) ApplyMatrix4(m *Matrix4) *Box3 {
xax := m[0] * b.Min.X
xay := m[1] * b.Min.X
xaz := m[2] * b.Min.X
xbx := m[0] * b.Max.X
xby := m[1] * b.Max.X
xbz := m[2] * b.Max.X
yax := m[4] * b.Min.Y
yay := m[5] * b.Min.Y
yaz := m[6] * b.Min.Y
ybx := m[4] * b.Max.Y
yby := m[5] * b.Max.Y
ybz := m[6] * b.Max.Y
zax := m[8] * b.Min.Z
zay := m[9] * b.Min.Z
zaz := m[10] * b.Min.Z
zbx := m[8] * b.Max.Z
zby := m[9] * b.Max.Z
zbz := m[10] * b.Max.Z
b.Min.X = Min(xax, xbx) + Min(yax, ybx) + Min(zax, zbx) + m[12]
b.Min.Y = Min(xay, xby) + Min(yay, yby) + Min(zay, zby) + m[13]
b.Min.Z = Min(xaz, xbz) + Min(yaz, ybz) + Min(zaz, zbz) + m[14]
b.Max.X = Max(xax, xbx) + Max(yax, ybx) + Max(zax, zbx) + m[12]
b.Max.Y = Max(xay, xby) + Max(yay, yby) + Max(zay, zby) + m[13]
b.Max.Z = Max(xaz, xbz) + Max(yaz, ybz) + Max(zaz, zbz) + m[14]
return b
}
// Translate translates the position of this box by offset.
// Returns pointer to this updated box.
func (b *Box3) Translate(offset *Vector3) *Box3 {
b.Min.Add(offset)
b.Max.Add(offset)
return b
}
// Equals returns if this box is equal to other
func (b *Box3) Equals(other *Box3) bool {
return other.Min.Equals(&b.Min) && other.Max.Equals(&b.Max)
}
// Clone creates and returns a pointer to copy of this bounding box
func (b *Box3) Clone() *Box3 {
return NewBox3(&b.Min, &b.Max)
} | math32/box3.go | 0.961452 | 0.663369 | box3.go | starcoder |
package appoptics
import (
"fmt"
"time"
log "github.com/sirupsen/logrus"
)
// MeasurementsBatch is a collection of Measurements persisted to the API at the same time.
// It can optionally have tags that are applied to all contained Measurements.
type MeasurementsBatch struct {
// Measurements is the collection of timeseries entries being sent to the server
Measurements []Measurement `json:"measurements,omitempty"`
// Period is a slice of time measured in seconds, used in service-side aggregation
Period int64 `json:"period,omitempty"`
// Time is a Unix epoch timestamp used to align a group of Measurements on a time boundary
Time int64 `json:"time"`
// Tags are key-value identifiers that will be applied to all Measurements in the batch
Tags *map[string]string `json:"tags,omitempty"`
}
// BatchPersister implements persistence to AppOptics and enforces error limits
type BatchPersister struct {
// mc is the MeasurementsCommunicator used to talk to the AppOptics API
mc MeasurementsCommunicator
// errors holds the errors received in attempting to persist to AppOptics
errors []error
// errorLimit is the number of persistence errors that will be tolerated
errorLimit int
// prepChan is a channel of Measurements slices
prepChan chan []Measurement
// batchChan is used to create MeasurementsBatches for persistence to AppOptics
batchChan chan *MeasurementsBatch
// stopBatchingChan is used to cease persisting MeasurementsBatches to AppOptics
stopBatchingChan chan bool
// stopPersistingChan is used to cease persisting MeasurementsBatches to AppOptics
stopPersistingChan chan bool
// stopErrorChan is used to cease the error checking for/select
stopErrorChan chan bool
// errorChan is used to tally errors that occur in batching/persisting
errorChan chan error
// maximumPushInterval is the max time (in milliseconds) to wait before pushing a batch whether its length is equal
// to the MeasurementPostMaxBatchSize or not
maximumPushInterval int
// sendStats is a flag for whether to persist to AppOptics or simply print messages to stdout
sendStats bool
}
// NewBatchPersister sets up a new instance of batched persistence capabilities using the provided MeasurementsCommunicator
func NewBatchPersister(mc MeasurementsCommunicator, sendStats bool) *BatchPersister {
return &BatchPersister{
mc: mc,
errorLimit: DefaultPersistenceErrorLimit,
prepChan: make(chan []Measurement),
batchChan: make(chan *MeasurementsBatch),
stopBatchingChan: make(chan bool),
stopErrorChan: make(chan bool),
stopPersistingChan: make(chan bool),
errorChan: make(chan error),
errors: []error{},
maximumPushInterval: 2000,
sendStats: sendStats,
}
}
func NewMeasurementsBatch(m []Measurement, tags *map[string]string) *MeasurementsBatch {
return &MeasurementsBatch{
Measurements: m,
Tags: tags,
Time: time.Now().UTC().Unix(),
}
}
// MeasurementsSink gives calling code write-only access to the Measurements prep channel
func (bp *BatchPersister) MeasurementsSink() chan<- []Measurement {
return bp.prepChan
}
// MeasurementsStopBatchingChannel gives calling code write-only access to the Measurements batching control channel
func (bp *BatchPersister) MeasurementsStopBatchingChannel() chan<- bool {
return bp.stopBatchingChan
}
// MeasurementsErrorChannel gives calling code write-only access to the Measurements error channel
func (bp *BatchPersister) MeasurementsErrorChannel() chan<- error {
return bp.errorChan
}
// MaxiumumPushIntervalMilliseconds returns the number of milliseconds the system will wait before pushing any
// accumulated Measurements to AppOptics
func (bp *BatchPersister) MaximumPushInterval() int {
return bp.maximumPushInterval
}
// SetMaximumPushInterval sets the number of milliseconds the system will wait before pushing any accumulated
// Measurements to AppOptics
func (bp *BatchPersister) SetMaximumPushInterval(ms int) {
bp.maximumPushInterval = ms
}
// batchMeasurements reads slices of Measurements off a channel and packages them into batches conforming to the
// limitations imposed by the API. If Measurements are arriving slowly, collected Measurements will be pushed on an
// interval defined by maximumPushIntervalMilliseconds
func (bp *BatchPersister) batchMeasurements() {
var currentMeasurements = []Measurement{}
ticker := time.NewTicker(time.Millisecond * time.Duration(bp.maximumPushInterval))
LOOP:
for {
select {
case receivedMeasurements := <-bp.prepChan:
currentMeasurements = append(currentMeasurements, receivedMeasurements...)
if len(currentMeasurements) >= MeasurementPostMaxBatchSize {
bp.batchChan <- &MeasurementsBatch{Measurements: currentMeasurements[:MeasurementPostMaxBatchSize]}
currentMeasurements = currentMeasurements[MeasurementPostMaxBatchSize:]
}
case <-ticker.C:
if len(currentMeasurements) > 0 {
pushBatch := &MeasurementsBatch{}
if len(currentMeasurements) >= MeasurementPostMaxBatchSize {
pushBatch.Measurements = currentMeasurements[:MeasurementPostMaxBatchSize]
bp.batchChan <- pushBatch
currentMeasurements = currentMeasurements[MeasurementPostMaxBatchSize:]
} else {
pushBatch.Measurements = currentMeasurements
bp.batchChan <- pushBatch
currentMeasurements = []Measurement{}
}
}
case <-bp.stopBatchingChan:
ticker.Stop()
if len(currentMeasurements) > 0 {
if len(bp.errors) < bp.errorLimit {
bp.batchChan <- &MeasurementsBatch{Measurements: currentMeasurements[:MeasurementPostMaxBatchSize]}
}
}
close(bp.batchChan)
bp.stopPersistingChan <- true
bp.stopErrorChan <- true
break LOOP
}
}
}
// BatchAndPersistMeasurementsForever continually packages up Measurements from the channel returned by MeasurementSink()
// and persists them to AppOptics.
func (bp *BatchPersister) BatchAndPersistMeasurementsForever() {
go bp.batchMeasurements()
go bp.persistBatches()
go bp.managePersistenceErrors()
}
// persistBatches reads maximal slices of Measurements off a channel and persists them to the remote AppOptics
// API. Errors are placed on the error channel.
func (bp *BatchPersister) persistBatches() {
ticker := time.NewTicker(time.Millisecond * 500)
LOOP:
for {
select {
case <-ticker.C:
batch := <-bp.batchChan
if batch != nil {
err := bp.persistBatch(batch)
if err != nil {
bp.errorChan <- err
}
}
case <-bp.stopPersistingChan:
if len(bp.errors) > bp.errorLimit {
batch := <-bp.batchChan
if batch != nil {
bp.persistBatch(batch)
}
}
ticker.Stop()
break LOOP
}
}
}
// managePersistenceErrors tracks errors on the provided channel and sends a stop signal if the ErrorLimit is reached.
func (bp *BatchPersister) managePersistenceErrors() {
LOOP:
for {
select {
case err := <-bp.errorChan:
bp.errors = append(bp.errors, err)
if len(bp.errors) == bp.errorLimit {
bp.stopBatchingChan <- true
break LOOP
}
case <-bp.stopErrorChan:
break LOOP
}
}
}
// persistBatch sends to the remote AppOptics endpoint unless config.SendStats() returns false, when it prints to stdout
func (bp *BatchPersister) persistBatch(batch *MeasurementsBatch) error {
if bp.sendStats {
// TODO: make this conditional upon log level
log.Printf("persisting %d Measurements to AppOptics\n", len(batch.Measurements))
resp, err := bp.mc.Create(batch)
if resp == nil {
fmt.Println("response is nil")
return err
}
// TODO: make this conditional upon log level
dumpResponse(resp)
} else {
// TODO: make this more verbose upon log level
log.Printf("received %d Measurements for persistence\n", len(batch.Measurements))
//printMeasurements(batch.Measurements)
}
return nil
} | measurements_batching.go | 0.720467 | 0.434401 | measurements_batching.go | starcoder |
Graphical Plots of Waveforms
Produces python code viewable using the plot.ly library.
*/
//-----------------------------------------------------------------------------
package main
import (
"fmt"
"os"
"github.com/deadsy/babi/core"
"github.com/deadsy/babi/module/dx"
"github.com/deadsy/babi/module/osc"
"github.com/deadsy/babi/module/view"
)
//-----------------------------------------------------------------------------
func envDx() {
cfg := &view.PlotConfig{
Name: "envDx",
Title: fmt.Sprintf("DX7 Envelope"),
Y0: "amplitude",
Duration: 2.0,
}
levels := &[4]int{99, 80, 99, 0}
rates := &[4]int{80, 80, 70, 80}
s := dx.NewEnv(nil, levels, rates)
core.EventInFloat(s, "gate", 1.0)
p := view.NewPlot(nil, cfg)
core.EventInBool(p, "trigger", true)
for i := 0; i < 12; i++ {
var y core.Buf
s.Process(&y)
p.Process(nil, &y)
}
core.EventInFloat(s, "gate", 0.0)
for i := 0; i < 4; i++ {
var y core.Buf
s.Process(&y)
p.Process(nil, &y)
}
p.Stop()
}
//-----------------------------------------------------------------------------
func goom() {
freq := float32(110.0)
cfg := &view.PlotConfig{
Name: "goom",
Title: fmt.Sprintf("%.1f Hz Goom Wave", freq),
Y0: "amplitude",
Duration: 2.0,
}
s := osc.NewGoom(nil)
core.EventInFloat(s, "frequency", freq)
core.EventInFloat(s, "duty", 0.3)
core.EventInFloat(s, "slope", 1.0)
p := view.NewPlot(nil, cfg)
core.EventInBool(p, "trigger", true)
for i := 0; i < 10; i++ {
var y core.Buf
s.Process(&y)
p.Process(nil, &y)
}
p.Stop()
}
//-----------------------------------------------------------------------------
func lfoDx() {
cfg := &view.PlotConfig{
Name: "lfo",
Title: "DX7 LFO Wave",
Y0: "amplitude",
Duration: 2.0,
}
s := dx.NewLFO(nil, nil)
core.EventInInt(s, "rate", 70)
core.EventInInt(s, "wave", int(dx.LfoTriangle))
p := view.NewPlot(nil, cfg)
core.EventInBool(p, "trigger", true)
for i := 0; i < 50; i++ {
var y core.Buf
s.Process(&y)
p.Process(nil, &y)
}
p.Stop()
}
//-----------------------------------------------------------------------------
func lfoOsc() {
cfg := &view.PlotConfig{
Name: "lfo",
Title: "LFO Wave",
Y0: "amplitude",
Duration: 2.0,
}
s := osc.NewLFO(nil)
core.EventInFloat(s, "rate", 20.0)
core.EventInFloat(s, "depth", 1.0)
core.EventInInt(s, "shape", int(osc.LfoSine))
p := view.NewPlot(nil, cfg)
core.EventInBool(p, "trigger", true)
for i := 0; i < 50; i++ {
var y core.Buf
s.Process(&y)
p.Process(nil, &y)
}
p.Stop()
}
//-----------------------------------------------------------------------------
func main() {
//goom()
//envDx()
//lfoDx()
lfoOsc()
os.Exit(0)
}
//----------------------------------------------------------------------------- | cmd/plots/main.go | 0.591605 | 0.41567 | main.go | starcoder |
package cross_site_scripting
import (
"github.com/damianmcgrath/threagile/model"
)
func Category() model.RiskCategory {
return model.RiskCategory{
Id: "cross-site-scripting",
Title: "Cross-Site Scripting (XSS)",
Description: "For each web application Cross-Site Scripting (XSS) risks might arise. In terms " +
"of the overall risk level take other applications running on the same domain into account as well.",
Impact: "If this risk remains unmitigated, attackers might be able to access individual victim sessions and steal or modify user data.",
ASVS: "V5 - Validation, Sanitization and Encoding Verification Requirements",
CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html",
Action: "XSS Prevention",
Mitigation: "Try to encode all values sent back to the browser and also handle DOM-manipulations in a safe way " +
"to avoid DOM-based XSS. " +
"When a third-party product is used instead of custom developed software, check if the product applies the proper mitigation and ensure a reasonable patch-level.",
Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?",
Function: model.Development,
STRIDE: model.Tampering,
DetectionLogic: "In-scope web applications.",
RiskAssessment: "The risk rating depends on the sensitivity of the data processed or stored in the web application.",
FalsePositives: "When the technical asset " +
"is not accessed via a browser-like component (i.e not by a human user initiating the request that " +
"gets passed through all components until it reaches the web application) this can be considered a false positive.",
ModelFailurePossibleReason: false,
CWE: 79,
}
}
func SupportedTags() []string {
return []string{}
}
func GenerateRisks() []model.Risk {
risks := make([]model.Risk, 0)
for _, id := range model.SortedTechnicalAssetIDs() {
technicalAsset := model.ParsedModelRoot.TechnicalAssets[id]
if technicalAsset.OutOfScope || !technicalAsset.Technology.IsWebApplication() { // TODO: also mobile clients or rich-clients as long as they use web-view...
continue
}
risks = append(risks, createRisk(technicalAsset))
}
return risks
}
func createRisk(technicalAsset model.TechnicalAsset) model.Risk {
title := "<b>Cross-Site Scripting (XSS)</b> risk at <b>" + technicalAsset.Title + "</b>"
impact := model.MediumImpact
if technicalAsset.HighestConfidentiality() == model.StrictlyConfidential || technicalAsset.HighestIntegrity() == model.MissionCritical {
impact = model.HighImpact
}
risk := model.Risk{
Category: Category(),
Severity: model.CalculateSeverity(model.Likely, impact),
ExploitationLikelihood: model.Likely,
ExploitationImpact: impact,
Title: title,
MostRelevantTechnicalAssetId: technicalAsset.Id,
DataBreachProbability: model.Possible,
DataBreachTechnicalAssetIDs: []string{technicalAsset.Id},
}
risk.SyntheticId = risk.Category.Id + "@" + technicalAsset.Id
return risk
} | risks/built-in/cross-site-scripting/cross-site-scripting-rule.go | 0.55447 | 0.466846 | cross-site-scripting-rule.go | starcoder |
package types
import (
"encoding/hex"
"fmt"
"math/big"
"golang.org/x/crypto/sha3"
"github.com/spacemeshos/go-spacemesh/common/util"
"github.com/spacemeshos/go-spacemesh/log"
)
const (
// AddressLength is the expected length of the address.
AddressLength = 20
)
// Address represents the address of a spacemesh account with AddressLength length.
type Address [AddressLength]byte
// BytesToAddress returns Address with value b.
// If b is larger than len(h), b will be cropped from the left.
func BytesToAddress(b []byte) Address {
var a Address
a.SetBytes(b)
return a
}
// BigToAddress returns Address with byte values of b.
// If b is larger than len(h), b will be cropped from the left.
func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }
// HexToAddress returns Address with byte values of s.
// If s is larger than len(h), s will be cropped from the left.
func HexToAddress(s string) Address { return BytesToAddress(util.FromHex(s)) }
// Bytes gets the string representation of the underlying address.
func (a Address) Bytes() []byte { return a[:] }
// Big converts an address to a big integer.
func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }
// Hash converts an address to a hash by left-padding it with zeros.
func (a Address) Hash() Hash32 { return CalcHash32(a[:]) }
// Hex returns an EIP55-compliant hex string representation of the address.
func (a Address) Hex() string {
unchecksummed := hex.EncodeToString(a[:])
sha := sha3.NewLegacyKeccak256()
sha.Write([]byte(unchecksummed))
hash := sha.Sum(nil)
result := []byte(unchecksummed)
for i := 0; i < len(result); i++ {
hashByte := hash[i/2]
if i%2 == 0 {
hashByte = hashByte >> 4
} else {
hashByte &= 0xf
}
if result[i] > '9' && hashByte > 7 {
result[i] -= 32
}
}
return "0x" + string(result)
}
// String implements fmt.Stringer.
func (a Address) String() string {
return a.Hex()
}
// Field returns a log field. Implements the LoggableField interface.
func (a Address) Field() log.Field { return log.String("address", a.String()) }
// Short returns the first 7 characters of the address hex representation (incl. "0x"), for logging purposes.
func (a Address) Short() string {
hx := a.Hex()
return hx[:util.Min(7, len(hx))]
}
// Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
// without going through the stringer interface used for logging.
func (a Address) Format(s fmt.State, c rune) {
_, _ = fmt.Fprintf(s, "%"+string(c), a[:])
}
// SetBytes sets the address to the value of b.
// If b is larger than len(a) it will panic.
func (a *Address) SetBytes(b []byte) {
if len(b) > len(a) {
b = b[len(b)-AddressLength:]
}
copy(a[AddressLength-len(b):], b)
}
// GenerateAddress generates an address from a public key.
func GenerateAddress(publicKey []byte) Address {
var addr Address
addr.SetBytes(publicKey)
return addr
} | common/types/address.go | 0.817829 | 0.490602 | address.go | starcoder |
package iso20022
// Completion of a securities settlement instruction, wherein securities are delivered/debited from a securities account and received/credited to the designated securities account.
type Transfer2 struct {
// Unique and unambiguous identifier for a transfer execution, as assigned by a confirming party.
TransferConfirmationReference *Max35Text `xml:"TrfConfRef"`
// Reference that identifies the whole transfer out transaction.
TransferReference *Max35Text `xml:"TrfRef"`
// Date and optionally time at which a transaction is completed and cleared, ie, securities are delivered.
EffectiveTransferDate *DateAndDateTimeChoice `xml:"FctvTrfDt"`
// Date when the transfer was received and processed.
TradeDate *ISODate `xml:"TradDt"`
// Total quantity of securities settled.
TotalUnitsNumber *FinancialInstrumentQuantity1 `xml:"TtlUnitsNb"`
// Information about the units to be transferred.
UnitsDetails []*Unit1 `xml:"UnitsDtls,omitempty"`
// Total quantity of securities settled.
PortfolioTransferOutRate *PercentageRate `xml:"PrtflTrfOutRate,omitempty"`
// Indicates whether the transfer results in a change of beneficial owner.
OwnAccountTransferIndicator *YesNoIndicator `xml:"OwnAcctTrfInd"`
// Value of a security, as booked in an account. Book value is often different from the current market value of the security.
AveragePrice *ActiveOrHistoricCurrencyAnd13DecimalAmount `xml:"AvrgPric,omitempty"`
}
func (t *Transfer2) SetTransferConfirmationReference(value string) {
t.TransferConfirmationReference = (*Max35Text)(&value)
}
func (t *Transfer2) SetTransferReference(value string) {
t.TransferReference = (*Max35Text)(&value)
}
func (t *Transfer2) AddEffectiveTransferDate() *DateAndDateTimeChoice {
t.EffectiveTransferDate = new(DateAndDateTimeChoice)
return t.EffectiveTransferDate
}
func (t *Transfer2) SetTradeDate(value string) {
t.TradeDate = (*ISODate)(&value)
}
func (t *Transfer2) AddTotalUnitsNumber() *FinancialInstrumentQuantity1 {
t.TotalUnitsNumber = new(FinancialInstrumentQuantity1)
return t.TotalUnitsNumber
}
func (t *Transfer2) AddUnitsDetails() *Unit1 {
newValue := new (Unit1)
t.UnitsDetails = append(t.UnitsDetails, newValue)
return newValue
}
func (t *Transfer2) SetPortfolioTransferOutRate(value string) {
t.PortfolioTransferOutRate = (*PercentageRate)(&value)
}
func (t *Transfer2) SetOwnAccountTransferIndicator(value string) {
t.OwnAccountTransferIndicator = (*YesNoIndicator)(&value)
}
func (t *Transfer2) SetAveragePrice(value, currency string) {
t.AveragePrice = NewActiveOrHistoricCurrencyAnd13DecimalAmount(value, currency)
} | Transfer2.go | 0.820613 | 0.448306 | Transfer2.go | starcoder |
package bpemodel
import (
"container/heap"
"math/rand"
)
// Symbol is an abstract reference to a sequence of characters.
type Symbol struct {
// Unique identifier, which implicitly refers to a sequence of characters.
// For example, it might be the ID of a word in a vocabulary.
ID int
// The length in bytes of the implicit sequence of characters.
Length int
}
// WordSymbol expands a Symbol with contextual information related to the
// Word that contains it.
type WordSymbol struct {
Symbol
// Prev is the index of the previous symbol in the Word.
// -1 means no previous symbol.
Prev int
// Prev is the index of the next symbol in the Word.
// -1 means no next symbol.
Next int
}
// MergeWith merges the current WordSymbol with the other one.
// In order to update prev/next, we consider the receiver to be the WordSymbol
// on the left, and other to be the next one on the right.
func (s *WordSymbol) MergeWith(other *WordSymbol, newSymbolID int) {
s.ID = newSymbolID
s.Length += other.Length
s.Next = other.Next
}
func (s *WordSymbol) HasPrev() bool {
return s.Prev != -1
}
func (s *WordSymbol) HasNext() bool {
return s.Next != -1
}
// Word is a slice of WordSymbol.
type Word []*WordSymbol
// NewWord returns a new empty Word.
func NewWord() *Word {
w := make(Word, 0)
return &w
}
// NewWordWithCapacity returns a new empty Word with the given capacity.
func NewWordWithCapacity(capacity int) *Word {
w := make(Word, 0, capacity)
return &w
}
func (w *Word) Len() int {
return len(*w)
}
func (w *Word) getSymbolID(index int) int {
return (*w)[index].ID
}
// Add appends a new symbol to the Word.
func (w *Word) Add(symbolID, byteLen int) {
sym := &WordSymbol{
Symbol: Symbol{
ID: symbolID,
Length: byteLen,
},
Prev: w.Len() - 1,
Next: -1,
}
if sym.Prev != -1 {
(*w)[sym.Prev].Next = w.Len()
}
*w = append(*w, sym)
}
func (w *Word) MergeAll(merges *MergeMap, dropout float64) {
symbolsLen := w.Len()
queue := make(WordMergeHeap, 0, symbolsLen)
skip := make([]WordMerge, 0, symbolsLen)
lastSymbolIndex := symbolsLen - 1
for index := 0; index < lastSymbolIndex; index++ {
if m, ok := merges.Get(w.getSymbolID(index), w.getSymbolID(index+1)); ok {
heap.Push(&queue, WordMerge{MergeValue: m, Pos: index})
}
}
hasDropout := dropout > 0
for queue.Len() > 0 {
top := heap.Pop(&queue).(WordMerge)
if hasDropout && rand.Float64() < dropout {
skip = append(skip, top)
continue
}
// Re-insert the skipped elements
for _, s := range skip {
heap.Push(&queue, s)
}
skip = skip[:0] // empty `skip` without reallocating memory
if (*w)[top.Pos].Length == 0 || !(*w)[top.Pos].HasNext() {
// Do nothing if the symbol is empty, or if it's the last symbol
continue
}
nextPos := (*w)[top.Pos].Next
right := (*w)[nextPos]
// Make sure we are not processing an expired queue entry
if m, ok := merges.Get((*w)[top.Pos].ID, right.ID); !ok || m.ID != top.ID {
continue
}
// Otherwise, let's merge
(*w)[top.Pos].MergeWith(right, top.ID)
// Tag the right part as removed
(*w)[nextPos].Length = 0
// Update `prev` on the new `next` to the current pos
if right.HasNext() && right.Next < w.Len() {
(*w)[right.Next].Prev = top.Pos
}
// Insert the new pair formed with the previous symbol
current := (*w)[top.Pos]
if current.HasPrev() {
prevSymbol := (*w)[current.Prev]
if m, ok := merges.Get(prevSymbol.ID, current.ID); ok {
heap.Push(&queue, WordMerge{MergeValue: m, Pos: current.Prev})
}
}
// Insert the new pair formed with the next symbol
if current.HasNext() && current.Next < w.Len() {
nextSymbol := (*w)[current.Next]
if m, ok := merges.Get(current.ID, nextSymbol.ID); ok {
heap.Push(&queue, WordMerge{MergeValue: m, Pos: top.Pos})
}
}
}
// Filter out the removed symbols
for i := 0; i < w.Len(); {
if (*w)[i].Length == 0 {
w.removeSymbol(i)
continue
}
i++
}
}
func (w *Word) removeSymbol(index int) {
*w = append((*w)[:index], (*w)[index+1:]...)
} | models/bpemodel/word.go | 0.729134 | 0.400808 | word.go | starcoder |
package hook
import (
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
)
// Batching is a datastore with hooks that also supports batching
type Batching struct {
ds datastore.Batching
hds *Datastore
}
// NewBatching wraps a datastore.Batching datastore and adds optional before and after hooks into it's methods
func NewBatching(ds datastore.Batching, options ...Option) *Batching {
return &Batching{ds: ds, hds: NewDatastore(ds, options...)}
}
// Put stores the object `value` named by `key`, it calls OnBeforePut and OnAfterPut hooks.
func (bds *Batching) Put(key datastore.Key, value []byte) error {
return bds.hds.Put(key, value)
}
// Delete removes the value for given `key`, it calls OnBeforeDelete and OnAfterDelete hooks.
func (bds *Batching) Delete(key datastore.Key) error {
return bds.hds.Delete(key)
}
// Get retrieves the object `value` named by `key`, it calls OnBeforeGet and OnAfterGet hooks.
func (bds *Batching) Get(key datastore.Key) ([]byte, error) {
return bds.hds.Get(key)
}
// Has returns whether the `key` is mapped to a `value`.
func (bds *Batching) Has(key datastore.Key) (bool, error) {
return bds.hds.Has(key)
}
// GetSize returns the size of the `value` named by `key`.
func (bds *Batching) GetSize(key datastore.Key) (int, error) {
return bds.hds.GetSize(key)
}
// Query searches the datastore and returns a query result.
func (bds *Batching) Query(q query.Query) (query.Results, error) {
return bds.hds.Query(q)
}
// Batch creates a container for a group of updates, it calls OnBeforeBatch and OnAfterBatch hooks.
func (bds *Batching) Batch() (datastore.Batch, error) {
if bds.hds.options.BeforeBatch != nil {
bds.hds.options.BeforeBatch()
}
bch, err := bds.ds.Batch()
if bds.hds.options.AfterBatch != nil {
bch, err = bds.hds.options.AfterBatch(bch, err)
}
return bch, err
}
// Sync guarantees that any Put or Delete calls under prefix that returned
// before Sync(prefix) was called will be observed after Sync(prefix)
// returns, even if the program crashes.
func (bds *Batching) Sync(prefix datastore.Key) error {
return bds.hds.Sync(prefix)
}
// Close closes the underlying datastore
func (bds *Batching) Close() error {
return bds.hds.Close()
} | batching.go | 0.838647 | 0.444022 | batching.go | starcoder |
package constants
import (
"time"
)
const (
PhysicsFrameDuration = 20 * time.Millisecond
UpdateSendInterval = 10 * time.Millisecond
// DirtyFramesTimeout is a timeout measured in frames after which the ship is marked dirty.
DirtyFramesTimeout = 50
// BoundaryAnnulusWidth is the width of boundary region (in .01 units), i.e. from WorldRadius till when no more movement is possible
BoundaryAnnulusWidth = 40000
// FrictionCoefficient is the coefficient saying how fast a spaceship will slow down when not using acceleration
FrictionCoefficient = 0.005
// MinFireInterval is a minimum time between firing.
MinFireInterval = 250 * time.Millisecond
// RandomPositionEmptyRadius describes the minimum radius around randomized
// initial position that needs to be free of any objects.
RandomPositionEmptyRadius = 5000.0
// Acceleration is spaceship's linear acceleration on thruster.
SpaceshipAcceleration = 50.0
// Maximum angular velocity added on user input.
SpaceshipMaxAngularVelocity = 0.12
SpaceshipLinearAngularAcceleration = 0.0001
SpaceshipNonlinearAngularAcceleration = 2.0
SpaceshipAngularFriction = 0.2
// SpaceshipMass is mass of the spaceship, used for calculating inertia
SpaceshipMass = 100.0
// SpaceshipTurnToAngleP is TurnToTarget propotional gain.
SpaceshipTurnToAngleP = 0.9
// MaxSpeed maximum speed of the spacecraft
SpaceshipMaxSpeed = 600
// SpaceshipBoostFactor is the multiplier for maximum speed when boost is active
SpaceshipBoostFactor = 2.5
// SpaceshipSize is spaceship's radius
SpaceshipSize = 2200
// SpaceshipInitialHP spaceship HP
SpaceshipInitialHP = 500
// SpaceshipInitialEnergy spaceship Energy
SpaceshipInitialEnergy = 2000
// Part of killed player's Max HP that killing player receives
KillRewardRatio = 0.2
// Energy reward for each
KillEnergyRewardRatio = 0.2
// Energy cost of a single shot
BasicWeaponEnergyCost = 100
// Energy cost of frame of boosting
BoostPerFrameEnergyCost = 20
// WorldRadius is the radius of playable world (in .01 units)
WorldRadius = 100000
// AutoRepairDelay is time after which spaceship will repair itself
AutoRepairDelay = 1000
// AutoRepairInterval is the time between repairs
AutoRepairInterval = 1
// AutoRepair is the amount of HP player will receive after AutoRepairDelay
AutoRepairAmount = 2
// EnergyRecharge is the amount of Energy player will receive after AutoRepairDelay
AutoEnergyRechargeAmount = 3
// Number of best players in Leaderboard
LeaderboardLength = 10
// MinimumUsernameLength is minimal the number of characters in username
MinimumUsernameLength = 3
// MaximumUsernameLength is maximal the number of characters in username
MaximumUsernameLength = 25
// ProjectileSpeed describes projectile speed. Captain Obvious
ProjectileSpeed = 4000
// DefaultTTL describes the default number of frames the projectile lives
ProjectileDefaultTTL = 15
// ProjectileDamage is the damage that is inflicted on a user upon colliding with projectile
ProjectileDamage = 50
// ProjectileImpulseStrength is the amount of push back projectile delivers on hit
ProjectileImpulseStrength = 100.0
// ProjectileRotationalImpulse is the ratio of impulse that will be applied to angular velocity
ProjectileRotationalImpulse = 0.2
// AsteroidVelocity defines asteroids' initial velocity
AsteroidVelocity = 100
// AsteroidSpawnRadius defines the radius of the circle on which asteroids spawn
AsteroidSpawnRadius = WorldRadius * 2
// AsteroidPresenceBoundary defines the radius of the circle beyond which asteroids are removed
AsteroidRemoveRadius = AsteroidSpawnRadius + 100
// AsteroidCountLimit limits the number of asteroids
AsteroidCountLimit = 20
// Damage made by hitting an asteroid
AsteroidDamageValue = 200
// Damage made by hitting an asteroid
AsteroidInitialHp = 10
// Reward gained on destroying an asteroid
AsteroidKillReward = 10
// Energy reward gained on destroying an asteroid
AsteroidKillEnergyReward = 10
// Max number of clients that server will handle
MaxNumberOfClients = 50
) | backend/constants/constants.go | 0.673729 | 0.517449 | constants.go | starcoder |
package values
import (
"fmt"
"reflect"
"strings"
yaml "gopkg.in/yaml.v2"
)
// A Value is a Liquid runtime value.
type Value interface {
// Value retrieval
Interface() interface{}
Int() int
// Comparison
Equal(Value) bool
Less(Value) bool
Contains(Value) bool
IndexValue(Value) Value
PropertyValue(Value) Value
// Predicate
Test() bool
}
// ValueOf returns a Value that wraps its argument.
// If the argument is already a Value, it returns this.
func ValueOf(value interface{}) Value { // nolint: gocyclo
// interned values
switch value {
case nil:
return nilValue
case true:
return trueValue
case false:
return falseValue
case 0:
return zeroValue
case 1:
return oneValue
}
// interfaces
switch v := value.(type) {
case drop:
return &dropWrapper{d: v}
case yaml.MapSlice:
return mapSliceValue{slice: v}
case Value:
return v
}
switch reflect.TypeOf(value).Kind() {
case reflect.Ptr:
rv := reflect.ValueOf(value)
if rv.Type().Elem().Kind() == reflect.Struct {
return structValue{wrapperValue{value}}
}
return ValueOf(rv.Elem().Interface())
case reflect.String:
return stringValue{wrapperValue{value}}
case reflect.Array, reflect.Slice:
return arrayValue{wrapperValue{value}}
case reflect.Map:
return mapValue{wrapperValue{value}}
case reflect.Struct:
return structValue{wrapperValue{value}}
default:
return wrapperValue{value}
}
}
const (
firstKey = "first"
lastKey = "last"
sizeKey = "size"
)
// embed this in a struct to "inherit" default implementations of the Value interface
type valueEmbed struct{}
func (v valueEmbed) Equal(Value) bool { return false }
func (v valueEmbed) Less(Value) bool { return false }
func (v valueEmbed) IndexValue(Value) Value { return nilValue }
func (v valueEmbed) Contains(Value) bool { return false }
func (v valueEmbed) Int() int { panic(conversionError("", v, reflect.TypeOf(1))) }
func (v valueEmbed) PropertyValue(Value) Value { return nilValue }
func (v valueEmbed) Test() bool { return true }
// A wrapperValue wraps a Go value.
type wrapperValue struct{ value interface{} }
func (v wrapperValue) Equal(other Value) bool { return Equal(v.value, other.Interface()) }
func (v wrapperValue) Less(other Value) bool { return Less(v.value, other.Interface()) }
func (v wrapperValue) IndexValue(Value) Value { return nilValue }
func (v wrapperValue) Contains(Value) bool { return false }
func (v wrapperValue) Interface() interface{} { return v.value }
func (v wrapperValue) PropertyValue(Value) Value { return nilValue }
func (v wrapperValue) Test() bool { return v.value != nil && v.value != false }
func (v wrapperValue) Int() int {
if n, ok := v.value.(int); ok {
return n
}
panic(conversionError("", v.value, reflect.TypeOf(1)))
}
// interned values
var NilValue = wrapperValue{nil}
var nilValue = wrapperValue{nil}
var falseValue = wrapperValue{false}
var trueValue = wrapperValue{true}
var zeroValue = wrapperValue{0}
var oneValue = wrapperValue{1}
// container values
type arrayValue struct{ wrapperValue }
type mapValue struct{ wrapperValue }
type stringValue struct{ wrapperValue }
func (av arrayValue) Contains(ev Value) bool {
ar := reflect.ValueOf(av.value)
e := ev.Interface()
for i, len := 0, ar.Len(); i < len; i++ {
if Equal(ar.Index(i).Interface(), e) {
return true
}
}
return false
}
func (av arrayValue) IndexValue(iv Value) Value {
ar := reflect.ValueOf(av.value)
var n int
switch ix := iv.Interface().(type) {
case int:
n = ix
case float32:
// Ruby array indexing truncates floats
n = int(ix)
case float64:
n = int(ix)
default:
return nilValue
}
if n < 0 {
n += ar.Len()
}
if 0 <= n && n < ar.Len() {
return ValueOf(ar.Index(n).Interface())
}
return nilValue
}
func (av arrayValue) PropertyValue(iv Value) Value {
ar := reflect.ValueOf(av.value)
switch iv.Interface() {
case firstKey:
if ar.Len() > 0 {
return ValueOf(ar.Index(0).Interface())
}
case lastKey:
if ar.Len() > 0 {
return ValueOf(ar.Index(ar.Len() - 1).Interface())
}
case sizeKey:
return ValueOf(ar.Len())
}
return nilValue
}
func (mv mapValue) Contains(iv Value) bool {
mr := reflect.ValueOf(mv.value)
ir := reflect.ValueOf(iv.Interface())
if ir.IsValid() && mr.Type().Key() == ir.Type() {
return mr.MapIndex(ir).IsValid()
}
return false
}
func (mv mapValue) IndexValue(iv Value) Value {
mr := reflect.ValueOf(mv.value)
ir := reflect.ValueOf(iv.Interface())
kt := mr.Type().Key()
if ir.IsValid() && ir.Type().ConvertibleTo(kt) && ir.Type().Comparable() {
er := mr.MapIndex(ir.Convert(kt))
if er.IsValid() {
return ValueOf(er.Interface())
}
}
return nilValue
}
func (mv mapValue) PropertyValue(iv Value) Value {
mr := reflect.ValueOf(mv.Interface())
ir := reflect.ValueOf(iv.Interface())
if !ir.IsValid() {
return nilValue
}
er := mr.MapIndex(ir)
switch {
case er.IsValid():
return ValueOf(er.Interface())
case iv.Interface() == sizeKey:
return ValueOf(mr.Len())
default:
return nilValue
}
}
func (sv stringValue) Contains(substr Value) bool {
s, ok := substr.Interface().(string)
if !ok {
s = fmt.Sprint(substr.Interface())
}
return strings.Contains(sv.value.(string), s)
}
func (sv stringValue) PropertyValue(iv Value) Value {
if iv.Interface() == sizeKey {
return ValueOf(len(sv.value.(string)))
}
return nilValue
} | values/value.go | 0.738952 | 0.444927 | value.go | starcoder |
package gt
import (
"database/sql/driver"
"encoding/json"
"fmt"
"time"
)
/*
Shortcut: parses successfully or panics. Should be used only in root scope. When
error handling is relevant, use `.Parse`.
*/
func ParseInterval(src string) (val Interval) {
try(val.Parse(src))
return
}
// Simplified interval constructor without a time constituent.
func DateInterval(years, months, days int) Interval {
return Interval{Years: years, Months: months, Days: days}
}
// Simplified interval constructor without a date constituent.
func TimeInterval(hours, mins, secs int) Interval {
return Interval{Hours: hours, Minutes: mins, Seconds: secs}
}
// Simplified interval constructor.
func IntervalFrom(years, months, days, hours, mins, secs int) Interval {
return Interval{years, months, days, hours, mins, secs}
}
// Uses `.SetDuration` and returns the resulting interval.
func DurationInterval(src time.Duration) (val Interval) {
val.SetDuration(src)
return
}
/*
Represents an ISO 8601 time interval that has only duration (no timestamps, no
range).
Features:
* Reversible encoding/decoding in text.
* Reversible encoding/decoding in JSON.
* Reversible encoding/decoding in SQL.
Text encoding and decoding uses the standard ISO 8601 format:
P0Y0M0DT0H0M0S
When interacting with a database, to make intervals parsable, configure your DB
to always output them in the standard ISO 8601 format.
Limitations:
* Supports only the standard machine-readable format.
* Doesn't support decimal fractions.
For a nullable variant, see `gt.NullInterval`.
*/
type Interval struct {
Years int `json:"years" db:"years"`
Months int `json:"months" db:"months"`
Days int `json:"days" db:"days"`
Hours int `json:"hours" db:"hours"`
Minutes int `json:"minutes" db:"minutes"`
Seconds int `json:"seconds" db:"seconds"`
}
var (
_ = Encodable(Interval{})
_ = Decodable((*Interval)(nil))
)
// Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.
func (self Interval) IsZero() bool { return self == Interval{} }
// Implement `gt.Nullable`. Always `false`.
func (self Interval) IsNull() bool { return false }
// Implement `gt.Getter`, using `.String` to return a string representation.
func (self Interval) Get() interface{} { return self.String() }
// Implement `gt.Setter`, using `.Scan`. Panics on error.
func (self *Interval) Set(src interface{}) { try(self.Scan(src)) }
// Implement `gt.Zeroer`, zeroing the receiver.
func (self *Interval) Zero() {
if self != nil {
*self = Interval{}
}
}
/*
Implement `fmt.Stringer`, returning a text representation in the standard
machine-readable ISO 8601 format.
*/
func (self Interval) String() string {
if self.IsZero() {
return zeroInterval
}
return bytesString(self.Append(nil))
}
// Implement `gt.Parser`, parsing a valid machine-readable ISO 8601 representation.
func (self *Interval) Parse(src string) error { return self.parse(src) }
// Implement `gt.Appender`, using the same representation as `.String`.
func (self Interval) Append(buf []byte) []byte {
if self.IsZero() {
return append(buf, zeroInterval...)
}
buf = Raw(buf).Grow(self.bufLen())
buf = append(buf, 'P')
buf = appendIntervalPart(buf, self.Years, 'Y')
buf = appendIntervalPart(buf, self.Months, 'M')
buf = appendIntervalPart(buf, self.Days, 'D')
if self.HasTime() {
buf = append(buf, 'T')
buf = appendIntervalPart(buf, self.Hours, 'H')
buf = appendIntervalPart(buf, self.Minutes, 'M')
buf = appendIntervalPart(buf, self.Seconds, 'S')
}
return buf
}
// Implement `encoding.TextMarhaler`, using the same representation as `.String`.
func (self Interval) MarshalText() ([]byte, error) {
return self.Append(nil), nil
}
// Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.
func (self *Interval) UnmarshalText(src []byte) error {
return self.Parse(bytesString(src))
}
// Implement `json.Marshaler`, using the same representation as `.String`.
func (self Interval) MarshalJSON() ([]byte, error) {
return json.Marshal(self.Get())
}
// Implement `json.Unmarshaler`, using the same algorithm as `.Parse`.
func (self *Interval) UnmarshalJSON(src []byte) error {
if isJsonStr(src) {
return self.UnmarshalText(cutJsonStr(src))
}
return errJsonString(src, self)
}
// Implement `driver.Valuer`, using `.Get`.
func (self Interval) Value() (driver.Value, error) {
return self.Get(), nil
}
/*
Implement `sql.Scanner`, converting an arbitrary input to `gt.Interval` and
modifying the receiver. Acceptable inputs:
* `string` -> use `.Parse`
* `[]byte` -> use `.UnmarshalText`
* `time.Duration` -> use `.SetDuration`
* `gt.Interval` -> assign
* `gt.NullInterval` -> assign
* `gt.Getter` -> scan underlying value
*/
func (self *Interval) Scan(src interface{}) error {
switch src := src.(type) {
case string:
return self.Parse(src)
case []byte:
return self.UnmarshalText(src)
case time.Duration:
self.SetDuration(src)
return nil
case Interval:
*self = src
return nil
case NullInterval:
*self = Interval(src)
return nil
default:
val, ok := get(src)
if ok {
return self.Scan(val)
}
return errScanType(self, src)
}
}
/*
Sets the interval to an approximate value of the given duration, expressed in
hours, minutes, seconds, truncating any fractions that don't fit.
*/
func (self *Interval) SetDuration(val time.Duration) {
const minSecs = 60
const hourMins = 60
// TODO simpler math.
hours := int(val.Hours())
minutes := int(val.Minutes()) - (hours * hourMins)
seconds := int(val.Seconds()) - (minutes * minSecs) - (hours * hourMins * minSecs)
*self = Interval{Hours: hours, Minutes: minutes, Seconds: seconds}
}
// Returns the date portion of the interval, disregarding the time portion. The
// result can be passed to `time.Time.AddDate` and `gt.NullTime.AddDate`.
func (self Interval) Date() (years int, months int, days int) {
return self.Years, self.Months, self.Days
}
// Returns only the date portion of this interval, with other fields set to 0.
func (self Interval) OnlyDate() Interval {
return Interval{Years: self.Years, Months: self.Months, Days: self.Days}
}
// Returns only the time portion of this interval, with other fields set to 0.
func (self Interval) OnlyTime() Interval {
return Interval{Hours: self.Hours, Minutes: self.Minutes, Seconds: self.Seconds}
}
// True if the interval has years, months, or days.
func (self Interval) HasDate() bool {
return self.Years != 0 || self.Months != 0 || self.Days != 0
}
// True if the interval has hours, minutes, or seconds.
func (self Interval) HasTime() bool {
return self.Hours != 0 || self.Minutes != 0 || self.Seconds != 0
}
/*
Returns the duration of ONLY the time portion of this interval. Panics if the
interval has a date constituent. To make it clear that you're explicitly
disregarding the date part, call `.OnlyTime` first. Warning: there are no
overflow checks. Usage example:
someInterval.OnlyTime().Duration()
*/
func (self Interval) Duration() time.Duration {
if self.HasDate() {
panic(fmt.Errorf(`[gt] failed to convert interval %q to duration: days/months/years can't be converted to nanoseconds`, &self))
}
return time.Duration(self.Hours)*time.Hour +
time.Duration(self.Minutes)*time.Minute +
time.Duration(self.Seconds)*time.Second
}
// Returns a version of this interval with `.Years = val`.
func (self Interval) WithYears(val int) Interval {
self.Years = val
return self
}
// Returns a version of this interval with `.Months = val`.
func (self Interval) WithMonths(val int) Interval {
self.Months = val
return self
}
// Returns a version of this interval with `.Days = val`.
func (self Interval) WithDays(val int) Interval {
self.Days = val
return self
}
// Returns a version of this interval with `.Hours = val`.
func (self Interval) WithHours(val int) Interval {
self.Hours = val
return self
}
// Returns a version of this interval with `.Minutes = val`.
func (self Interval) WithMinutes(val int) Interval {
self.Minutes = val
return self
}
// Returns a version of this interval with `.Seconds = val`.
func (self Interval) WithSeconds(val int) Interval {
self.Seconds = val
return self
}
// Returns a version of this interval with `.Years += val`.
func (self Interval) AddYears(val int) Interval {
self.Years += val
return self
}
// Returns a version of this interval with `.Months += val`.
func (self Interval) AddMonths(val int) Interval {
self.Months += val
return self
}
// Returns a version of this interval with `.Days += val`.
func (self Interval) AddDays(val int) Interval {
self.Days += val
return self
}
// Returns a version of this interval with `.Hours += val`.
func (self Interval) AddHours(val int) Interval {
self.Hours += val
return self
}
// Returns a version of this interval with `.Minutes += val`.
func (self Interval) AddMinutes(val int) Interval {
self.Minutes += val
return self
}
// Returns a version of this interval with `.Seconds += val`.
func (self Interval) AddSeconds(val int) Interval {
self.Seconds += val
return self
}
/*
Adds every field of one interval to every field of another interval, returning
the sum. Does NOT convert different time units, such as seconds to minutes or
vice versa.
*/
func (self Interval) Add(val Interval) Interval {
return Interval{
Years: self.Years + val.Years,
Months: self.Months + val.Months,
Days: self.Days + val.Days,
Hours: self.Hours + val.Hours,
Minutes: self.Minutes + val.Minutes,
Seconds: self.Seconds + val.Seconds,
}
}
/*
Subtracts every field of one interval from every corresponding field of another
interval, returning the difference. Does NOT convert different time units, such
as seconds to minutes or vice versa.
*/
func (self Interval) Sub(val Interval) Interval {
return self.Add(val.Neg())
}
/*
Returns a version of this interval with every field inverted: positive fields
become negative, and negative fields become positive.
*/
func (self Interval) Neg() Interval {
return Interval{
Years: -self.Years,
Months: -self.Months,
Days: -self.Days,
Hours: -self.Hours,
Minutes: -self.Minutes,
Seconds: -self.Seconds,
}
}
func (self Interval) bufLen() (num int) {
if self.IsZero() {
return len(zeroInterval)
}
num += len(`P`)
addIntervalPartLen(&num, self.Years)
addIntervalPartLen(&num, self.Months)
addIntervalPartLen(&num, self.Days)
if self.HasTime() {
num += len(`T`)
}
addIntervalPartLen(&num, self.Hours)
addIntervalPartLen(&num, self.Minutes)
addIntervalPartLen(&num, self.Seconds)
return
} | gt_interval.go | 0.817756 | 0.475118 | gt_interval.go | starcoder |
package mat
import (
"fmt"
"github.com/jacsmith21/gnn/vec"
"strconv"
)
// Make initializes a matrix with i rows and j cols
func Make(i, j int) Matrix {
vecs := make([]vec.Vector, j)
for k := 0; k < j; k++ {
vecs[k] = vec.Make(i)
}
return Matrix{vecs}
}
// InitRows initializes a Matrix with given row vectors
func InitRows(rows ...vec.Vector) Matrix {
mat := Matrix{rows}
mat.Transpose()
return mat
}
// InitCols initializes a Matrix with given col vectors
func InitCols(cols ...vec.Vector) Matrix {
return Matrix{cols}
}
// Copy returns a copy of the given Matrix
func Copy(from Matrix) Matrix {
cols := make([]vec.Vector, len(from.cols))
for i, c := range from.cols {
cols[i] = vec.Copy(c)
}
return Matrix{cols}
}
// Slice returns a slice of the Matrix
func Slice(m Matrix, from, to int) Matrix {
return Matrix{m.cols[from:to]}
}
// Mul performs the matrix multiplication m1 x m2
func Mul(m1, m2 Matrix) Matrix {
if m1.ColCount() != m2.RowCount() {
panic(fmt.Sprintf("m1 column count does not match m2 row count: %v vs. %v", m1.ColCount(), m2.RowCount()))
}
res := Make(m1.RowCount(), m2.ColCount())
for i := 0; i < m1.RowCount(); i++ {
for j := 0; j < m2.ColCount(); j++ {
sum := 0.
for index := 0; index < m1.ColCount(); index++ {
sum += m1.At(i, index) * m2.At(index, j)
}
res.Set(i, j, sum)
}
}
return res
}
// SumCols sums the columns of the given matrix and returns the sum vector
func SumCols(m Matrix) vec.Vector {
sums := vec.Make(m.RowCount())
for i := 0; i < m.RowCount(); i++ {
sum := 0.
for j := 0; j < m.ColCount(); j++ {
sum += m.At(i, j)
}
sums.Set(i, sum)
}
return sums
}
// Sub subtracts the two matrices and returns the result
func Sub(m1, m2 Matrix) Matrix {
copy := Copy(m1)
copy.Sub(m2)
return copy
}
// Transpose copies and transposes the given matrix
func Transpose(m Matrix) Matrix {
copy := Copy(m)
copy.Transpose()
return copy
}
// InitFromStringArray initilizes an array from a 2D array of strings
func InitFromStringArray(s [][]string) Matrix {
if len(s) == 0 {
return Make(0, 0)
}
m := Make(len(s), len(s[0]))
for i := 0; i < m.RowCount(); i++ {
for j := 0; j < m.ColCount(); j++ {
f, err := strconv.ParseFloat(s[i][j], 64)
if err != nil {
panic(fmt.Sprintf("cannot convert %v to a float", s[i][j]))
}
m.Set(i, j, f)
}
}
return m
} | mat/util.go | 0.87183 | 0.660843 | util.go | starcoder |
package series
import (
"fmt"
"math"
"strings"
)
type boolElement struct {
e *bool
}
func (e boolElement) Set(value interface{}) Element {
var val bool
switch value.(type) {
case string:
if value.(string) == "NaN" {
e.e = nil
return e
}
switch strings.ToLower(value.(string)) {
case "true", "t", "1":
val = true
case "false", "f", "0":
val = false
default:
e.e = nil
return e
}
case int:
switch value.(int) {
case 1:
val = true
case 0:
val = false
default:
e.e = nil
return e
}
case float64:
switch value.(float64) {
case 1:
val = true
case 0:
val = false
default:
e.e = nil
return e
}
case bool:
val = value.(bool)
case Element:
b, err := value.(Element).Bool()
if err != nil {
e.e = nil
return e
}
val = b
default:
e.e = nil
return e
}
e.e = &val
return e
}
func (e boolElement) Copy() Element {
if e.e == nil {
return boolElement{nil}
}
copy := bool(*e.e)
return boolElement{©}
}
func (e boolElement) IsNA() bool {
if e.e == nil {
return true
}
return false
}
func (e boolElement) Type() Type {
return Bool
}
func (e boolElement) Val() ElementValue {
if e.IsNA() {
return nil
}
return bool(*e.e)
}
func (e boolElement) String() string {
if e.e == nil {
return "NaN"
}
if *e.e {
return "true"
}
return "false"
}
func (e boolElement) Int() (int, error) {
if e.IsNA() {
return 0, fmt.Errorf("can't convert NaN to int")
}
if *e.e == true {
return 1, nil
}
return 0, nil
}
func (e boolElement) Float() float64 {
if e.IsNA() {
return math.NaN()
}
if *e.e {
return 1.0
}
return 0.0
}
func (e boolElement) Bool() (bool, error) {
if e.IsNA() {
return false, fmt.Errorf("can't convert NaN to bool")
}
return bool(*e.e), nil
}
func (e boolElement) Addr() string {
return fmt.Sprint(e.e)
}
func (e boolElement) Eq(elem Element) bool {
b, err := elem.Bool()
if err != nil || e.IsNA() {
return false
}
return *e.e == b
}
func (e boolElement) Neq(elem Element) bool {
b, err := elem.Bool()
if err != nil || e.IsNA() {
return false
}
return *e.e != b
}
func (e boolElement) Less(elem Element) bool {
b, err := elem.Bool()
if err != nil || e.IsNA() {
return false
}
return !*e.e && b
}
func (e boolElement) LessEq(elem Element) bool {
b, err := elem.Bool()
if err != nil || e.IsNA() {
return false
}
return !*e.e || b
}
func (e boolElement) Greater(elem Element) bool {
b, err := elem.Bool()
if err != nil || e.IsNA() {
return false
}
return *e.e && !b
}
func (e boolElement) GreaterEq(elem Element) bool {
b, err := elem.Bool()
if err != nil || e.IsNA() {
return false
}
return *e.e || !b
} | vendor/github.com/kniren/gota/series/type-bool.go | 0.58676 | 0.488161 | type-bool.go | starcoder |
package visor
import (
"errors"
"fmt"
"github.com/samoslab/haicoin/src/coin"
"github.com/samoslab/haicoin/src/util/fee"
)
/*
verify.go: Methods for handling transaction verification
There are two levels of transaction constraint: HARD and SOFT
There are two situations in which transactions are verified:
* When included in a block
* When not in a block
For transactions in a block, use VerifyBlockTxnConstraints.
For transactions outside of a block, use VerifySingleTxnHardConstraints and VerifySingleTxnSoftConstraints.
VerifyBlockTxnConstraints only checks hard constraints. Soft constraints do not apply for transactions inside of a block.
Soft and hard constraints have special handling for single transactions.
When the transaction is received over the network, a transaction is not injected to the pool if it violates the HARD constraints.
If it violates soft constraints, it is still injected to the pool (TODO: with expiration) but is not rebroadcast to peers.
If it does not violate any constraints it is injected and rebroadcast to peers.
When the transaction is created by the user (with create_rawtx or /spend), SOFT and HARD constraints apply, to prevent
the user from injecting a transaction to their local pool that cannot be confirmed.
When creating a new block from transactions, SOFT and HARD constraints apply.
Transactions in the unconfirmed pool are periodically checked for validity. (TODO: audit/implement this feature)
The transaction pool state transfer phases are as follows:
valid -> hard_invalid: remove
valid -> soft_invalid: mark as invalid
soft_invalid -> valid: mark as valid, broadcast
soft_invalid -> hard_invalid: remove
soft_invalid -> expired: remove
HARD constraints can NEVER be violated. These include:
- Malformed transaction
- Double spends
- NOTE: Double spend verification must be done against the unspent output set,
the methods here do not operate on the unspent output set.
They accept a `uxIn coin.UxArray` argument, which are the unspents associated
with the transaction's inputs. The unspents must be queried from the unspent
output set first, thus if any unspent is not found for the input, it cannot be spent.
SOFT constraints are based upon mutable parameters. These include:
- Max block size (transaction must not be larger than this value)
- Insufficient coin hour burn fee
- Timelocked distribution addresses
- Decimal place restrictions
NOTE: Due to a bug which allowed overflowing output coin hours to be included in a block,
overflowing output coin hours are not checked when adding a signed block, so that the existing blocks can be processed.
When creating or receiving a single transaction from the network, it is treated as a HARD constraint.
These methods should be called via the Blockchain object when possible,
using Blockchain.VerifyBlockTxnConstraints, Blockchain.VerifySingleTxnHardConstraints and Blockchain.VerifySingleTxnSoftHardConstraints
since data from the blockchain and unspent output set are required to fully validate a transaction.
*/
var (
errTxnExceedsMaxBlockSize = errors.New("Transaction size bigger than max block size")
errTxnIsLocked = errors.New("Transaction has locked address inputs")
)
// ErrTxnViolatesHardConstraint is returned when a transaction violates hard constraints
type ErrTxnViolatesHardConstraint struct {
Err error
}
// NewErrTxnViolatesHardConstraint creates ErrTxnViolatesHardConstraint
func NewErrTxnViolatesHardConstraint(err error) error {
if err == nil {
return nil
}
return ErrTxnViolatesHardConstraint{
Err: err,
}
}
func (e ErrTxnViolatesHardConstraint) Error() string {
return fmt.Sprintf("Transaction violates hard constraint: %v", e.Err)
}
// ErrTxnViolatesSoftConstraint is returned when a transaction violates soft constraints
type ErrTxnViolatesSoftConstraint struct {
Err error
}
// NewErrTxnViolatesSoftConstraint creates ErrTxnViolatesSoftConstraint
func NewErrTxnViolatesSoftConstraint(err error) error {
if err == nil {
return nil
}
return ErrTxnViolatesSoftConstraint{
Err: err,
}
}
func (e ErrTxnViolatesSoftConstraint) Error() string {
return fmt.Sprintf("Transaction violates soft constraint: %v", e.Err)
}
// ErrTxnViolatesUserConstraint is returned when a transaction violates user constraints
type ErrTxnViolatesUserConstraint struct {
Err error
}
// NewErrTxnViolatesUserConstraint creates ErrTxnViolatesUserConstraint
func NewErrTxnViolatesUserConstraint(err error) error {
if err == nil {
return nil
}
return ErrTxnViolatesUserConstraint{
Err: err,
}
}
func (e ErrTxnViolatesUserConstraint) Error() string {
return fmt.Sprintf("Transaction violates user constraint: %v", e.Err)
}
// VerifySingleTxnSoftConstraints returns an error if any "soft" constraint are violated.
// "soft" constaints are enforced at the network and block publication level,
// but are not enforced at the blockchain level.
// Clients will not accept blocks that violate hard constraints, but will
// accept blocks that violate soft constraints.
// Checks:
// * That the transaction size is not greater than the max block total transaction size
// * That the transaction burn enough coin hours (the fee)
// * That if that transaction does not spend from a locked distribution address
// * That the transaction does not create outputs with a higher decimal precision than is allowed
func VerifySingleTxnSoftConstraints(txn coin.Transaction, headTime uint64, uxIn coin.UxArray, maxSize int) error {
if err := verifyTxnSoftConstraints(txn, headTime, uxIn, maxSize); err != nil {
return NewErrTxnViolatesSoftConstraint(err)
}
return nil
}
func verifyTxnSoftConstraints(txn coin.Transaction, headTime uint64, uxIn coin.UxArray, maxSize int) error {
if txn.Size() > maxSize {
return errTxnExceedsMaxBlockSize
}
f, err := fee.TransactionFee(&txn, headTime, uxIn)
if err != nil {
return err
}
if err := fee.VerifyTransactionFee(&txn, f); err != nil {
return err
}
if TransactionIsLocked(uxIn) {
return errTxnIsLocked
}
// Reject transactions that do not conform to decimal restrictions
for _, o := range txn.Out {
if err := DropletPrecisionCheck(o.Coins); err != nil {
return err
}
}
return nil
}
// VerifySingleTxnHardConstraints returns an error if any "hard" constraints are violated.
// "hard" constraints are always enforced and if violated the transaction
// should not be included in any block and any block that includes such a transaction
// should be rejected.
// Checks:
// * That the inputs to the transaction exist
// * That the transaction does not create or destroy coins
// * That the signatures on the transaction are valid
// * That there are no duplicate ux inputs
// * That there are no duplicate outputs
// * That the transaction input and output coins do not overflow uint64
// * That the transaction input and output hours do not overflow uint64
// NOTE: Double spends are checked against the unspent output pool when querying for uxIn
func VerifySingleTxnHardConstraints(txn coin.Transaction, head *coin.SignedBlock, uxIn coin.UxArray) error {
// Check for output hours overflow
// When verifying a single transaction, this is considered a hard constraint.
// For transactions inside of a block, it is a soft constraint.
// This is due to a bug which allowed some blocks to be published with overflowing hours,
// otherwise this would always be a hard constraint.
if _, err := txn.OutputHours(); err != nil {
return NewErrTxnViolatesHardConstraint(err)
}
// Check for input CoinHours calculation overflow, since it is ignored by
// VerifyTransactionHoursSpending
for _, ux := range uxIn {
if _, err := ux.CoinHours(head.Time()); err != nil {
return NewErrTxnViolatesHardConstraint(err)
}
}
if err := verifyTxnHardConstraints(txn, head, uxIn); err != nil {
return NewErrTxnViolatesHardConstraint(err)
}
return nil
}
// VerifyBlockTxnConstraints returns an error if any "hard" constraints are violated.
// "hard" constraints are always enforced and if violated the transaction
// should not be included in any block and any block that includes such a transaction
// should be rejected.
// Checks:
// * That the inputs to the transaction exist
// * That the transaction does not create or destroy coins
// * That the signatures on the transaction are valid
// * That there are no duplicate ux inputs
// * That there are no duplicate outputs
// * That the transaction input and output coins do not overflow uint64
// * That the transaction input hours do not overflow uint64
// NOTE: Double spends are checked against the unspent output pool when querying for uxIn
// NOTE: output hours overflow is treated as a soft constraint for transactions inside of a block, due to a bug
// which allowed some blocks to be published with overflowing output hours.
func VerifyBlockTxnConstraints(txn coin.Transaction, head *coin.SignedBlock, uxIn coin.UxArray) error {
if err := verifyTxnHardConstraints(txn, head, uxIn); err != nil {
return NewErrTxnViolatesHardConstraint(err)
}
return nil
}
func verifyTxnHardConstraints(txn coin.Transaction, head *coin.SignedBlock, uxIn coin.UxArray) error {
//CHECKLIST: DONE: check for duplicate ux inputs/double spending
// NOTE: Double spends are checked against the unspent output pool when querying for uxIn
//CHECKLIST: DONE: check that inputs of transaction have not been spent
//CHECKLIST: DONE: check there are no duplicate outputs
// Q: why are coin hours based on last block time and not
// current time?
// A: no two computers will agree on system time. Need system clock
// indepedent timing that everyone agrees on. fee values would depend on
// local clock
// Check transaction type and length
// Check for duplicate outputs
// Check for duplicate inputs
// Check for invalid hash
// Check for no inputs
// Check for no outputs
// Check for zero coin outputs
// Check valid looking signatures
if err := txn.Verify(); err != nil {
return err
}
// Checks whether ux inputs exist,
// Check that signatures are allowed to spend inputs
if err := txn.VerifyInput(uxIn); err != nil {
return err
}
uxOut := coin.CreateUnspents(head.Head, txn)
// Check that there are any duplicates within this set
// NOTE: This should already be checked by txn.Verify()
if uxOut.HasDupes() {
return errors.New("Duplicate output in transaction")
}
// Check that no coins are created or destroyed
if err := coin.VerifyTransactionCoinsSpending(uxIn, uxOut); err != nil {
return err
}
// Check that no hours are created
// NOTE: this check doesn't catch overflow errors in the addition of hours
// Some blocks had their hours overflow, and if this rule was checked here,
// existing blocks would invalidate.
// The hours overflow check is handled as an extra step in the SingleTxnHard constraints,
// to allow existing blocks which violate the overflow rules to pass.
return coin.VerifyTransactionHoursSpending(head.Time(), uxIn, uxOut)
}
// VerifySingleTxnUserConstraints applies additional verification for a
// transaction created by the user.
// This is distinct from transactions created by other users (i.e. received over the network),
// and from transactions included in blocks.
func VerifySingleTxnUserConstraints(txn coin.Transaction) error {
for _, o := range txn.Out {
if o.Address.Null() {
err := errors.New("Transaction output is sent to the null address")
return NewErrTxnViolatesUserConstraint(err)
}
}
return nil
} | src/visor/verify.go | 0.551332 | 0.512144 | verify.go | starcoder |
package clr
import (
"fmt"
"math"
)
// RGB Represents a point in the RGB Colorspace.
type RGB struct {
R int `json:"r"`
G int `json:"g"`
B int `json:"b"`
}
// Valid checks if the RGB instance is a valid point in the RGB ColorSpace.
func (rgb RGB) Valid() bool {
return rgb.R <= 255 && rgb.G <= 255 && rgb.B <= 255
}
// RGB returns the RGB components for the given point.
func (rgb RGB) RGB() (int, int, int) {
return rgb.R, rgb.G, rgb.B
}
// RGBA is similar to RGB but adds an alpha channel. It conforms with the
// color.Color interface, so values need to be upscaled accordingly.
func (rgb RGB) RGBA() (r, g, b, a uint32) {
r = uint32(rgb.R)
r |= r << 8
g = uint32(rgb.G)
g |= g << 8
b = uint32(rgb.B)
b |= b << 8
a = 255
a |= a << 8
return
}
// HSL converts RGB values into HSL ones in which
// H = 0 - 360, S = 0 - 100 and V = 0 - 100
func (rgb RGB) HSL() (int, int, int) {
var h, s, l float64
R := float64(rgb.R) / 255
G := float64(rgb.G) / 255
B := float64(rgb.B) / 255
minVal := min(R, G, B)
maxVal := max(R, G, B)
delta := maxVal - minVal
l = (maxVal + minVal) / 2.0
if delta == 0 {
h = 0
s = 0
} else {
d := maxVal - minVal
if l > 0.5 {
s = d / (2 - maxVal - minVal)
} else {
s = d / (maxVal + minVal)
}
switch maxVal {
case R:
if G < B {
h = (G-B)/d + 6
} else {
h = (G-B)/d + 0
}
case G:
h = (B-R)/d + 2
case B:
h = (R-G)/d + 4
}
h /= 6
}
return int(h * 360), int(s * 100), int(l * 100)
}
// HSV converts RGB values into HSV ones in which
// H = 0 - 360, S = 0 - 100 and V = 0 - 100
func (rgb RGB) HSV() (int, int, int) {
var h, s, v float64
R := float64(rgb.R) / 255
G := float64(rgb.G) / 255
B := float64(rgb.B) / 255
minVal := min(R, G, B)
maxVal := max(R, G, B)
delta := maxVal - minVal
v = maxVal
if delta == 0 {
h = 0
s = 0
} else {
d := maxVal - minVal
s = delta / maxVal
switch maxVal {
case R:
if G < B {
h = (G-B)/d + 6
} else {
h = (G-B)/d + 0
}
case G:
h = (B-R)/d + 2
case B:
h = (R-G)/d + 4
}
h /= 6
}
return int(h * 360), int(s * 100), int(v * 100)
}
// CMYK converts RGB colorspace into CMYK
func (rgb RGB) CMYK() (int, int, int, int) {
r := float64(rgb.R) / 255.0
g := float64(rgb.G) / 255.0
b := float64(rgb.B) / 255.0
var dc, dy, dm, dk float64
dk = (1.0 - max(r, g, b))
dc = (1 - r - dk) / (1 - dk)
dm = (1 - g - dk) / (1 - dk)
dy = (1 - b - dk) / (1 - dk)
return int(dc * 100), int(dm * 100), int(dy * 100), int(dk * 100)
}
// Hex formats rgb in Hex
func (rgb RGB) Hex() string {
return fmt.Sprintf("%02X%02X%02X", rgb.R, rgb.G, rgb.B)
}
// ColorName matches this RGB color to a color name
func (rgb RGB) ColorName(colors ColorTable) ColorSpace {
var minHex string
minDist := math.MaxFloat64
var hex = rgb.Hex()
for _, c := range colors.Iterate() {
if c.Hex() == hex {
return colors.Lookup(c.Hex())
}
dist := rgb.Distance(c)
if dist < minDist {
minHex = c.Hex()
minDist = dist
}
}
return colors.Lookup(minHex)
}
// Distance calculates the distance between colors in CIELAB using
// simple Euclidean distance.
func (rgb RGB) Distance(c Color) float64 {
l1, a1, b1 := rgb.CIELAB()
l2, a2, b2 := c.CIELAB()
return math.Sqrt(
math.Pow(l1-l2, 2) +
math.Pow(a1-a2, 2) +
math.Pow(b1-b2, 2))
}
// XYZ Converts to the XYZ Colorspace.
func (rgb RGB) XYZ() (float64, float64, float64) {
r := float64(rgb.R) / 255.0
g := float64(rgb.G) / 255.0
b := float64(rgb.B) / 255.0
if r > 0.04045 {
r = math.Pow((r+0.055)/1.055, 2.4)
} else {
r = r / 12.92
}
if g > 0.04045 {
g = math.Pow((g+0.055)/1.055, 2.4)
} else {
g = g / 12.92
}
if b > 0.04045 {
b = math.Pow((b+0.055)/1.055, 2.4)
} else {
b = b / 12.92
}
r *= 100
g *= 100
b *= 100
x := r*0.4124 + g*0.3576 + b*0.1805
y := r*0.2126 + g*0.7152 + b*0.0722
z := r*0.0193 + g*0.1192 + b*0.9505
return x, y, z
}
// CIELAB converts RGB to CIELAB, which is useful for comparing
// between colors how people actually view them.
func (rgb RGB) CIELAB() (l, a, b float64) {
x, y, z := rgb.XYZ()
x /= 95.682
y /= 100
z /= 92.149
if x > 0.008856 {
x = math.Pow(x, 1.0/3.0)
} else {
x = (7.787 * x) + (16.0 / 116)
}
if y > 0.008856 {
y = math.Pow(y, 1.0/3.0)
} else {
y = (7.787 * y) + (16.0 / 116)
}
if z > 0.008856 {
z = math.Pow(z, 1.0/3.0)
} else {
z = (7.787 * z) + (16.0 / 116)
}
l = (116 * x) - 16
a = 500 * (x - y)
b = 200 * (y - z)
return l, a, b
} | clr/rgb.go | 0.894507 | 0.420481 | rgb.go | starcoder |
package main
/*
Testing of semantics of length and capacity of slices and append.
# Result
-> slices are basically equivalent to ArrayList (Java). An auto-grown array
implementation (i.e., Vector in other parlance).
-> append will grow a slice if needed.
-> append adds an element at position [len(slice)].
-> so len is like the 'current number of elements in slice / arraylist'
-> cap is size of actual underlying array, e.g., how many we can append before
we'll need to grow the array.
*/
import (
"fmt"
)
func append10(slice []int) []int {
for i := 0; i < 10; i++ {
slice = append(slice, i)
}
return slice
}
func printSliceByLen(slice []int) {
fmt.Printf(" printing slice by len (%d)...\n", len(slice))
fmt.Printf(" slice[..] = [")
for i := 0; i < len(slice) - 1; i++ {
fmt.Printf("%d, ", slice[i])
}
fmt.Printf("%d]\n", slice[len(slice) - 1])
}
func printSliceByCap(slice []int) {
fmt.Printf(" printing slice by cap (%d)...\n", cap(slice))
fmt.Printf(" slice[..] = [")
for i := 0; i < cap(slice) - 1; i++ {
fmt.Printf("%d, ", slice[i])
}
fmt.Printf("%d]\n", slice[cap(slice) - 1])
}
func main() {
// slice with len: 0, cap: 0.
slice1 := make([]int, 0, 0)
// slice with len: 0, cap: 10.
slice2 := make([]int, 0, 10)
// slice with len: 10, cap: 10.
slice3 := make([]int, 10, 10)
// slice with len: 10, cap: 20.
slice4 := make([]int, 10, 20)
slice1 = append10(slice1)
fmt.Println("slice of len: 0, cap: 0")
printSliceByLen(slice1)
// XXX: below causes error if left in as cap is outside len range here.
// printSliceByCap(slice1)
slice2 = append10(slice2)
fmt.Println("slice of len: 0, cap: 10")
printSliceByLen(slice2)
printSliceByCap(slice2)
slice3 = append10(slice3)
fmt.Println("slice of len: 10, cap: 10")
printSliceByLen(slice3)
printSliceByCap(slice3)
slice4 = append10(slice4)
fmt.Println("slice of len: 10, cap: 20")
printSliceByLen(slice4)
printSliceByCap(slice4)
// slice with len: 10, cap: ? (i.e., what does Go set my cap to?)
slice5 := make([]int, 10)
// slice with len: ?, cap: ? (i.e., what does Go set my cap to?)
var slice6 []int
// XXX: Below is invalid syntax, make needs a length argument.
// slice6 := make([]int)
fmt.Printf("make([]int, 10) => len: %d, cap: %d\n", len(slice5), cap(slice5))
slice5 = append10(slice5)
printSliceByLen(slice5)
printSliceByCap(slice5)
fmt.Printf("make([]int) => len: %d, cap: %d\n", len(slice6), cap(slice6))
slice6 = append10(slice6)
printSliceByLen(slice6)
// printSliceByCap(slice6)
} | go/SliceAppend.go | 0.519278 | 0.523481 | SliceAppend.go | starcoder |
package vm
import (
"strconv"
"strings"
"time"
)
func (r *Value) EqualTo(to Value, opt CompareOption) (bool, error) {
switch to.Type {
case ValueNull:
return r.IsNil(), nil
case ValueBool:
return r.EqualToBool(to.BoolValue(), opt)
case ValueString:
return r.EqualToString(to.Str, opt)
case ValueInt64:
return r.EqualToInt64(to.Int64, opt)
case ValueUint64:
return r.EqualToUint64(to.Uint64, opt)
case ValueFloat64:
return r.EqualToFloat64(to.Float64, opt)
case ValueDatetime:
return r.EqualToDatetime(to.Int64, opt)
case ValueInterval:
return r.EqualToInterval(time.Duration(to.Int64), opt)
default:
return false, NewTypeMismatch(r.Type.String(), "unknown")
}
}
func (r *Value) EqualToBool(to bool, opt CompareOption) (bool, error) {
switch r.Type {
case ValueNull:
return false, nil
case ValueBool:
return r.BoolValue() == to, nil
case ValueString:
if opt.Weak {
switch r.Str {
case "1", "t", "T", "true", "TRUE", "True":
return to == true, nil
case "0", "f", "F", "false", "FALSE", "False":
return to == false, nil
}
}
case ValueInt64:
if opt.Weak {
return (r.Int64 != 0) == to, nil
}
case ValueUint64:
if opt.Weak {
return (r.Uint64 != 0) == to, nil
}
}
return false, NewTypeMismatch(r.Type.String(), "boolean")
}
func (r *Value) EqualToString(to string, opt CompareOption) (bool, error) {
switch r.Type {
case ValueNull:
return false, NewTypeMismatch(r.Type.String(), "string")
case ValueBool:
if opt.Weak {
switch r.Str {
case "1", "t", "T", "true", "TRUE", "True":
return r.BoolValue() == true, nil
case "0", "f", "F", "false", "FALSE", "False":
return r.BoolValue() == false, nil
}
}
return false, NewTypeMismatch(r.Type.String(), "string")
case ValueString:
if opt.IgnoreCase {
return strings.EqualFold(r.Str, to), nil
}
return r.Str == to, nil
case ValueInt64:
if opt.Weak {
i64, err := strconv.ParseInt(to, 10, 64)
if err == nil {
return r.Int64 == i64, nil
}
}
return false, NewTypeMismatch(r.Type.String(), "string")
case ValueUint64:
if opt.Weak {
u64, err := strconv.ParseUint(to, 10, 64)
if err == nil {
return r.Uint64 == u64, nil
}
}
return false, NewTypeMismatch(r.Type.String(), "string")
case ValueFloat64:
return false, NewTypeMismatch(r.Type.String(), "string")
default:
return false, NewTypeMismatch(r.Type.String(), "string")
}
}
func (r *Value) EqualToInt64(to int64, opt CompareOption) (bool, error) {
switch r.Type {
case ValueNull:
return false, NewTypeMismatch(r.Type.String(), "int")
case ValueBool:
if opt.Weak {
return (to != 0) == r.BoolValue(), nil
}
return false, NewTypeMismatch(r.Type.String(), "int")
case ValueString:
if opt.Weak {
i64, err := strconv.ParseInt(r.Str, 10, 64)
if err == nil {
return i64 == to, nil
}
}
return false, NewTypeMismatch(r.Type.String(), "int")
case ValueInt64:
return r.Int64 == to, nil
case ValueUint64:
if to < 0 {
return false, nil
}
return r.Uint64 == uint64(to), nil
case ValueFloat64:
return false, NewTypeMismatch(r.Type.String(), "int")
default:
return false, NewTypeMismatch(r.Type.String(), "int")
}
}
func (r *Value) EqualToUint64(to uint64, opt CompareOption) (bool, error) {
switch r.Type {
case ValueNull:
return false, NewTypeMismatch(r.Type.String(), "uint")
case ValueBool:
if opt.Weak {
return (to != 0) == r.BoolValue(), nil
}
return false, NewTypeMismatch(r.Type.String(), "uint")
case ValueString:
if opt.Weak {
u64, err := strconv.ParseUint(r.Str, 10, 64)
if err == nil {
return u64 == to, nil
}
}
return false, NewTypeMismatch(r.Type.String(), "uint")
case ValueInt64:
if r.Int64 < 0 {
return false, nil
}
return uint64(r.Int64) == to, nil
case ValueUint64:
return r.Uint64 == to, nil
case ValueFloat64:
return false, NewTypeMismatch(r.Type.String(), "uint")
default:
return false, NewTypeMismatch(r.Type.String(), "uint")
}
}
func (r *Value) EqualToFloat64(to float64, opt CompareOption) (bool, error) {
return false, NewTypeMismatch(r.Type.String(), "float")
}
func (r *Value) EqualToDatetime(to int64, opt CompareOption) (bool, error) {
if r.Type == ValueDatetime {
return r.Int64 == to, nil
}
return false, NewTypeMismatch(r.Type.String(), "datetime")
}
func (r *Value) EqualToInterval(to time.Duration, opt CompareOption) (bool, error) {
if r.Type == ValueInterval {
return time.Duration(r.Int64) == to, nil
}
return false, NewTypeMismatch(r.Type.String(), "interval")
} | vm/equal.go | 0.57081 | 0.636353 | equal.go | starcoder |
package iso20022
// Cash movements from or to a fund as a result of investment funds transactions, eg, subscriptions or redemptions.
type FundCashForecast3 struct {
// Unique technical identifier for an instance of a fund cash forecast within a fund cash forecast report as assigned by the issuer of the report.
Identification *Max35Text `xml:"Id"`
// Date and, if required, the time, at which the price has been applied.
TradeDateTime *DateAndDateTimeChoice `xml:"TradDtTm"`
// Previous date and time at which a price was applied.
PreviousTradeDateTime *DateAndDateTimeChoice `xml:"PrvsTradDtTm,omitempty"`
// Investment fund class to which a cash flow is related.
FinancialInstrumentDetails *FinancialInstrument9 `xml:"FinInstrmDtls"`
// Total value of all the holdings, less the fund's liabilities, attributable to a specific investment fund class.
TotalNAV *ActiveOrHistoricCurrencyAndAmount `xml:"TtlNAV,omitempty"`
// Previous value of all the holdings, less the fund's liabilities, attributable to a specific investment fund class.
PreviousTotalNAV *ActiveOrHistoricCurrencyAndAmount `xml:"PrvsTtlNAV,omitempty"`
// Total number of investment fund class units that have been issued.
TotalUnitsNumber *FinancialInstrumentQuantity1 `xml:"TtlUnitsNb,omitempty"`
// Previous total number of investment fund class units that have been issued.
PreviousTotalUnitsNumber *FinancialInstrumentQuantity1 `xml:"PrvsTtlUnitsNb,omitempty"`
// Rate of change of the net asset value.
TotalNAVChangeRate *PercentageRate `xml:"TtlNAVChngRate,omitempty"`
// Currency of the investment fund class.
InvestmentCurrency []*ActiveOrHistoricCurrencyCode `xml:"InvstmtCcy,omitempty"`
// Indicates whether the net cash flow is exceptional.
ExceptionalNetCashFlowIndicator *YesNoIndicator `xml:"XcptnlNetCshFlowInd"`
// Cash movements into the fund as a result of investment funds transactions, eg, subscriptions or switch-in.
CashInForecastDetails []*CashInForecast4 `xml:"CshInFcstDtls,omitempty"`
// Cash movements out of the fund as a result of investment funds transactions, eg, redemptions or switch-out.
CashOutForecastDetails []*CashOutForecast4 `xml:"CshOutFcstDtls,omitempty"`
// Cash movements from or to a fund as a result of investment funds transactions.
NetCashForecastDetails []*NetCashForecast2 `xml:"NetCshFcstDtls,omitempty"`
}
func (f *FundCashForecast3) SetIdentification(value string) {
f.Identification = (*Max35Text)(&value)
}
func (f *FundCashForecast3) AddTradeDateTime() *DateAndDateTimeChoice {
f.TradeDateTime = new(DateAndDateTimeChoice)
return f.TradeDateTime
}
func (f *FundCashForecast3) AddPreviousTradeDateTime() *DateAndDateTimeChoice {
f.PreviousTradeDateTime = new(DateAndDateTimeChoice)
return f.PreviousTradeDateTime
}
func (f *FundCashForecast3) AddFinancialInstrumentDetails() *FinancialInstrument9 {
f.FinancialInstrumentDetails = new(FinancialInstrument9)
return f.FinancialInstrumentDetails
}
func (f *FundCashForecast3) SetTotalNAV(value, currency string) {
f.TotalNAV = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}
func (f *FundCashForecast3) SetPreviousTotalNAV(value, currency string) {
f.PreviousTotalNAV = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}
func (f *FundCashForecast3) AddTotalUnitsNumber() *FinancialInstrumentQuantity1 {
f.TotalUnitsNumber = new(FinancialInstrumentQuantity1)
return f.TotalUnitsNumber
}
func (f *FundCashForecast3) AddPreviousTotalUnitsNumber() *FinancialInstrumentQuantity1 {
f.PreviousTotalUnitsNumber = new(FinancialInstrumentQuantity1)
return f.PreviousTotalUnitsNumber
}
func (f *FundCashForecast3) SetTotalNAVChangeRate(value string) {
f.TotalNAVChangeRate = (*PercentageRate)(&value)
}
func (f *FundCashForecast3) AddInvestmentCurrency(value string) {
f.InvestmentCurrency = append(f.InvestmentCurrency, (*ActiveOrHistoricCurrencyCode)(&value))
}
func (f *FundCashForecast3) SetExceptionalNetCashFlowIndicator(value string) {
f.ExceptionalNetCashFlowIndicator = (*YesNoIndicator)(&value)
}
func (f *FundCashForecast3) AddCashInForecastDetails() *CashInForecast4 {
newValue := new(CashInForecast4)
f.CashInForecastDetails = append(f.CashInForecastDetails, newValue)
return newValue
}
func (f *FundCashForecast3) AddCashOutForecastDetails() *CashOutForecast4 {
newValue := new(CashOutForecast4)
f.CashOutForecastDetails = append(f.CashOutForecastDetails, newValue)
return newValue
}
func (f *FundCashForecast3) AddNetCashForecastDetails() *NetCashForecast2 {
newValue := new(NetCashForecast2)
f.NetCashForecastDetails = append(f.NetCashForecastDetails, newValue)
return newValue
} | FundCashForecast3.go | 0.860838 | 0.430925 | FundCashForecast3.go | starcoder |
package xsens
// DataType represents an Xsens data type.
type DataType uint16
//go:generate stringer -type DataType -trimprefix DataType
// Data group: Temperature.
const (
DataTypeTemperature DataType = 0x0810
)
// Data group: Timestamp.
const (
DataTypeUTCTime DataType = 0x1010
DataTypePacketCounter DataType = 0x1020
DataTypeITOW DataType = 0x1030
DataTypeGPSAge DataType = 0x1040
DataTypePressureAge DataType = 0x1050
DataTypeSampleTimeFine DataType = 0x1060
DataTypeSampleTimeCoarse DataType = 0x1070
)
// Data group: Orientation.
const (
DataTypeQuaternion DataType = 0x2010
DataTypeRotationMatrix DataType = 0x2020
DataTypeEulerAngles DataType = 0x2030
)
// Data group: Pressure.
const (
DataTypeBaroPressure DataType = 0x3010
)
// Data group: Acceleration.
const (
DataTypeDeltaV DataType = 0x4010
DataTypeAcceleration DataType = 0x4020
DataTypeFreeAcceleration DataType = 0x4030
DataTypeAccelerationHR DataType = 0x4040
)
// Data group: Position.
const (
DataTypeAltitudeEllipsoid DataType = 0x5020
DataTypePositionECEF DataType = 0x5030
DataTypeLatLon DataType = 0x5040
)
// Data group: GNSS.
const (
DataTypeGNSSPVTData DataType = 0x7010
DataTypeGNSSSatInfo DataType = 0x7020
)
// Data group: Angular velocity.
const (
DataTypeRateOfTurn DataType = 0x8020
DataTypeDeltaQ DataType = 0x8030
DataTypeRateOfTurnHR DataType = 0x8040
)
// Data group: GPS.
const (
DataTypeGPSDOP DataType = 0x8830
DataTypeGPSSOL DataType = 0x8840
DataTypeGPSTimeUTC DataType = 0x8880
DataTypeGPSSVInfo DataType = 0x88a0
)
// Data group: Magnetic.
const (
DataTypeMagneticField DataType = 0xc020
)
// Data group: Velocity.
const (
DataTypeVelocityXYZ DataType = 0xd010
)
// Data group: Status.
const (
DataTypeStatusByte DataType = 0xe010
DataTypeStatusWord DataType = 0xe020
)
// HasPrecision returns true for data types which support configurable output precision.
func (d DataType) HasPrecision() bool {
switch d {
case
// temperature
DataTypeTemperature,
// orientation
DataTypeQuaternion, DataTypeRotationMatrix, DataTypeEulerAngles,
// acceleration
DataTypeDeltaV, DataTypeAcceleration, DataTypeFreeAcceleration, DataTypeAccelerationHR,
// position
DataTypeAltitudeEllipsoid, DataTypePositionECEF, DataTypeLatLon,
// angular velocity
DataTypeDeltaQ, DataTypeRateOfTurn, DataTypeRateOfTurnHR,
// velocity
DataTypeVelocityXYZ,
// magnetic
DataTypeMagneticField:
return true
default:
return false
}
}
// HasCoordinateSystem returns true for data types which support configurable coordinate system.
func (d DataType) HasCoordinateSystem() bool {
switch d {
case
// orientation
DataTypeQuaternion, DataTypeRotationMatrix, DataTypeEulerAngles,
// velocity
DataTypeVelocityXYZ:
return true
default:
return false
}
} | datatype.go | 0.6137 | 0.862641 | datatype.go | starcoder |
package ztest
import (
"fmt"
"github.com/dollarshaveclub/node-auto-repair-operator/pkg/naro"
"github.com/montanaflynn/stats"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const (
// The z-score values for certain percentiles.
ZScore95 = 1.6449
ZScore99 = 2.3263
)
// A FeatureExtractor extracts a single float64 feature from a
// naro.NodeTimePeriodSummary.
type FeatureExtractor interface {
String() string
Extract(*naro.NodeTimePeriodSummary) (float64, error)
}
// Detector can run z-tests on naro.NodeTimePeriodSummary
// instances. More information:
// http://colingorrie.github.io/outlier-detection.html
type Detector struct {
mean float64
stddev float64
zthreshold float64
extractor FeatureExtractor
}
// String returns the string representation of a Detector.
func (d *Detector) String() string {
return fmt.Sprintf("Detector: mean(%f), stddev(%f), z-threshold(%f), extractor(%s)",
d.mean, d.stddev, d.zthreshold, d.extractor)
}
// NewDetector creates a new Detector instance.
func NewDetector(zthreshold float64, extractor FeatureExtractor) *Detector {
return &Detector{
zthreshold: zthreshold,
extractor: extractor,
}
}
// Train prepares the Detector for testing new
// naro.NodeTimePeriodSummary instances.
func (d *Detector) Train(summaries []*naro.NodeTimePeriodSummary) error {
var features []float64
// TODO: process these in a stream.
for _, ns := range summaries {
feature, err := d.extractor.Extract(ns)
if err != nil {
return errors.Wrapf(err, "error extracting feature from naro.NodeTimePeriodSummary")
}
features = append(features, feature)
}
logrus.Debugf("Detector: features: %v", features)
mean, err := stats.Mean(features)
if err != nil {
return errors.Wrapf(err, "error calculating mean")
}
stddev, err := stats.StandardDeviation(features)
if err != nil {
return errors.Wrapf(err, "error calculating standard deviation")
}
d.mean = mean
d.stddev = stddev
return nil
}
// IsAnomalous returns true if the naro.NodeTimePeriodSummary is
// anomalous.
func (d *Detector) IsAnomalous(ns *naro.NodeTimePeriodSummary) (bool, string, error) {
feature, err := d.extractor.Extract(ns)
if err != nil {
return false, "", errors.Wrapf(err, "error extracting feature from naro.NodeTimePeriodSummary")
}
zscore := (feature - d.mean) / d.stddev
return zscore >= d.zthreshold, fmt.Sprintf("z-score: %f", zscore), nil
} | pkg/naro/statistics/ztest/ztest.go | 0.710929 | 0.408395 | ztest.go | starcoder |
package tx
import "math/big"
// Transaction struct
type Transaction struct {
id []byte // A SHA2-256 hash of the signature
lastTx string // The ID of the last transaction made from the account. If no previous transactions have been made from the address this field is set to an empty string.
owner *big.Int // The modulus of the RSA key pair corresponding to the wallet making the transaction
target string // If making a financial transaction this field contains the wallet address of the recipient base64url encoded. If the transaction is not a financial this field is set to an empty string.
quantity string // If making a financial transaction this field contains the amount in Winston to be sent to the receiving wallet. If the transaction is not financial this field is set to the string "0". 1 AR = 1000000000000 (1e+12) Winston
data []byte // If making an archiving transaction this field contains the data to be archived base64url encoded. If the transaction is not archival this field is set to an empty string.
reward string // This field contains the mining reward for the transaction in Winston.
tags []Tag // Transaction tags
signature []byte // Signature using the RSA-PSS signature scheme using SHA256 as the MGF1 masking algorithm
}
// Transaction struct
type TransactionV2 struct {
id []byte // A SHA2-256 hash of the signature
lastTx string // The ID of the last transaction made from the account. If no previous transactions have been made from the address this field is set to an empty string.
owner *big.Int // The modulus of the RSA key pair corresponding to the wallet making the transaction
target string // If making a financial transaction this field contains the wallet address of the recipient base64url encoded. If the transaction is not a financial this field is set to an empty string.
quantity string // If making a financial transaction this field contains the amount in Winston to be sent to the receiving wallet. If the transaction is not financial this field is set to the string "0". 1 AR = 1000000000000 (1e+12) Winston
data []byte // If making an archiving transaction this field contains the data to be archived base64url encoded. If the transaction is not archival this field is set to an empty string.
reward string // This field contains the mining reward for the transaction in Winston.
tags []Tag // Transaction tags
signature []byte // Signature using the RSA-PSS signature scheme using SHA256 as the MGF1 masking algorithm
format int
dataSize string
dataRoot string
dataTree []interface{}
}
// Transaction struct
type TransactionNew struct {
id []byte // A SHA2-256 hash of the signature
lastTx string // The ID of the last transaction made from the account. If no previous transactions have been made from the address this field is set to an empty string.
owner *big.Int // The modulus of the RSA key pair corresponding to the wallet making the transaction
target string // If making a financial transaction this field contains the wallet address of the recipient base64url encoded. If the transaction is not a financial this field is set to an empty string.
quantity string // If making a financial transaction this field contains the amount in Winston to be sent to the receiving wallet. If the transaction is not financial this field is set to the string "0". 1 AR = 1000000000000 (1e+12) Winston
data []byte // If making an archiving transaction this field contains the data to be archived base64url encoded. If the transaction is not archival this field is set to an empty string.
reward string // This field contains the mining reward for the transaction in Winston.
transType string
signature []byte // Signature using the RSA-PSS signature scheme using SHA256 as the MGF1 masking algorithm
}
// Transaction encoded transaction to send to the arweave client
type transactionJSON struct {
// Id A SHA2-256 hash of the signature, based 64 URL encoded.
ID string `json:"id"`
// LastTx represents the ID of the last transaction made from the same address base64url encoded. If no previous transactions have been made from the address this field is set to an empty string.
LastTx string `json:"last_tx"`
//Owner is the modulus of the RSA key pair corresponding to the wallet making the transaction, base64url encoded.
Owner string `json:"owner"`
// Target if making a financial transaction this field contains the wallet address of the recipient base64url encoded. If the transaction is not a financial this field is set to an empty string.
Target string `json:"target"`
// Quantity If making a financial transaction this field contains the amount in Winston to be sent to the receiving wallet. If the transaction is not financial this field is set to the string "0". 1 AR = 1000000000000 (1e+12) Winston
Quantity string `json:"quantity"`
// Data If making an archiving transaction this field contains the data to be archived base64url encoded. If the transaction is not archival this field is set to an empty string.
Data string `json:"data"`
// Reward This field contains the mining reward for the transaction in Winston.
Reward string `json:"reward"`
// Signature using the RSA-PSS signature scheme using SHA256 as the MGF1 masking algorithm
Signature string `json:"signature"`
// Tags Transaction tags
Tags []Tag `json:"tags"`
}
// Transaction encoded transaction to send to the arweave client
type transactionV2JSON struct {
Format int `json:"format"`
// Id A SHA2-256 hash of the signature, based 64 URL encoded.
ID string `json:"id"`
// LastTx represents the ID of the last transaction made from the same address base64url encoded. If no previous transactions have been made from the address this field is set to an empty string.
LastTx string `json:"last_tx"`
//Owner is the modulus of the RSA key pair corresponding to the wallet making the transaction, base64url encoded.
Owner string `json:"owner"`
// Target if making a financial transaction this field contains the wallet address of the recipient base64url encoded. If the transaction is not a financial this field is set to an empty string.
Target string `json:"target"`
// Quantity If making a financial transaction this field contains the amount in Winston to be sent to the receiving wallet. If the transaction is not financial this field is set to the string "0". 1 AR = 1000000000000 (1e+12) Winston
Quantity string `json:"quantity"`
// Data If making an archiving transaction this field contains the data to be archived base64url encoded. If the transaction is not archival this field is set to an empty string.
Data string `json:"data"`
// Reward This field contains the mining reward for the transaction in Winston.
Reward string `json:"reward"`
// Signature using the RSA-PSS signature scheme using SHA256 as the MGF1 masking algorithm
Signature string `json:"signature"`
// Tags Transaction tags
Tags []Tag `json:"tags"`
DataSize string `json:"data_size"`
DataRoot string `json:"data_root"`
DataTree []interface{} `json:"data_tree"`
}
// Tag contains any tags the user wants to add to the transaction
type Tag struct {
Name string `json:"name"`
Value string `json:"value"`
}
// Transaction encoded transaction to send to the arweave client
type transactionNewJSON struct {
// Id A SHA2-256 hash of the signature, based 64 URL encoded.
ID string `json:"id"`
// LastTx represents the ID of the last transaction made from the same address base64url encoded. If no previous transactions have been made from the address this field is set to an empty string.
LastTx string `json:"last_tx"`
//Owner is the modulus of the RSA key pair corresponding to the wallet making the transaction, base64url encoded.
Owner string `json:"owner"`
// Target if making a financial transaction this field contains the wallet address of the recipient base64url encoded. If the transaction is not a financial this field is set to an empty string.
Target string `json:"target"`
// Quantity If making a financial transaction this field contains the amount in Winston to be sent to the receiving wallet. If the transaction is not financial this field is set to the string "0". 1 AR = 1000000000000 (1e+12) Winston
Quantity string `json:"quantity"`
// Data If making an archiving transaction this field contains the data to be archived base64url encoded. If the transaction is not archival this field is set to an empty string.
Data string `json:"data"`
// Reward This field contains the mining reward for the transaction in Winston.
Reward string `json:"reward"`
// Signature using the RSA-PSS signature scheme using SHA256 as the MGF1 masking algorithm
Signature string `json:"signature"`
// Tags Transaction tags
Type string `json:"type"`
} | tx/types.go | 0.741019 | 0.535584 | types.go | starcoder |
package parametric2d
import (
"fmt"
"sort"
"github.com/gmlewis/go-poly2tri"
"github.com/gmlewis/go3d/float64/vec2"
"github.com/gmlewis/go3d/float64/vec3"
)
// Path represents a 2D collection of SubPaths.
type Path struct {
SubPaths []*SubPath
}
// BBox returns the minimum bounding box of the Path.
func (p *Path) BBox() vec2.Rect {
if len(p.SubPaths) == 0 {
return vec2.Rect{}
}
bbox := p.SubPaths[0].BBox()
for _, sp := range p.SubPaths[1:] {
v := sp.BBox()
bbox = vec2.Joined(&bbox, &v)
}
return bbox
}
// Wall extrudes a path into a 3D wall. `maxDegrees` determines the smoothness
// of the wall along the path.
func (p *Path) Wall(height, maxDegrees float64) []Triangle3D {
if len(p.SubPaths) == 0 {
return []Triangle3D{}
}
bbox := p.SubPaths[0].BBox()
r := make([]Triangle3D, 0, 100)
var sc *poly2tri.SweepContext
for i, sp := range p.SubPaths {
w := sp.Wall(height, maxDegrees)
r = append(r, w...)
if i == 0 {
fmt.Printf("Initializing %v Floor points, #p.SubPaths=%v\n", len(sp.FloorPts), len(p.SubPaths))
sc = poly2tri.New(sp.FloorPts)
} else {
subBBox := sp.BBox()
fmt.Printf("Checking if floor bbox %v contains subBBox %v...\n", bbox, subBBox)
if bbox.Contains(&subBBox) {
fmt.Printf("Adding %v Floor hole points\n", len(sp.FloorPts))
sc.AddHole(sp.FloorPts)
} else {
fmt.Printf("SubPath not contained by parent... Adding %v new Floor points\n", len(sp.FloorPts))
r = Triangulate(sc.Triangulate(), r, p.SubPaths[0].FloorZ)
sc = poly2tri.New(sp.FloorPts)
}
}
}
r = Triangulate(sc.Triangulate(), r, p.SubPaths[0].FloorZ)
return r
}
// Bevel returns a 3D beveled object based on the provided path.
func (p *Path) Bevel(height, offset, deg, maxDegrees float64) []Triangle3D {
if len(p.SubPaths) == 0 {
return []Triangle3D{}
}
bbox := p.SubPaths[0].BBox()
r := make([]Triangle3D, 0, 100)
var sc *poly2tri.SweepContext
for i, sp := range p.SubPaths {
w := sp.Bevel(height, offset, deg, maxDegrees)
r = append(r, w...)
if i == 0 {
fmt.Printf("Initializing %v Bevel points, #p.SubPaths=%v\n", len(sp.BevelPts), len(p.SubPaths))
if len(p.SubPaths) == 1 {
fmt.Printf("\nvar in = PointArray{\n")
for _, t := range sp.BevelPts {
fmt.Printf(" NewPoint(%v, %v),\n", t.X, t.Y)
}
fmt.Printf("}\n\n")
}
sc = poly2tri.New(sp.BevelPts)
} else {
subBBox := sp.BBox()
fmt.Printf("Checking if bevel bbox %v contains subBBox %v...\n", bbox, subBBox)
if bbox.Contains(&subBBox) {
fmt.Printf("Adding %v Bevel hole points\n", len(sp.BevelPts))
sc.AddHole(sp.BevelPts)
} else {
fmt.Printf("SubPath not contained by parent... Adding %v new Bevel points\n", len(sp.BevelPts))
r = Triangulate(sc.Triangulate(), r, p.SubPaths[0].BevelZ)
sc = poly2tri.New(sp.BevelPts)
}
}
}
r = Triangulate(sc.Triangulate(), r, p.SubPaths[0].BevelZ)
return r
}
// Triangulate converts 2D points to 3D triangles and appends them to a slice.
func Triangulate(m poly2tri.TriArray, r []Triangle3D, z float64) []Triangle3D {
for _, t := range m {
p0 := vec3.T{t.Point[0].X, t.Point[0].Y, z}
p1 := vec3.T{t.Point[1].X, t.Point[1].Y, z}
p2 := vec3.T{t.Point[2].X, t.Point[2].Y, z}
tri := Triangle3D{p0, p1, p2}
r = append(r, tri)
}
return r
}
// AutoFlipNormals analyzes the first subpath to determine if its normals
// are currently facing the correct direction (outward), and if not,
// sets the 'FlipNormals' flag on each segment of each subpath.
func (p *Path) AutoFlipNormals() {
if len(p.SubPaths) == 0 {
return
}
// First, sort the subpaths by bounding box square area... Largest first
sort.Sort(byBBoxArea(p.SubPaths))
p.SubPaths[0].IsOuter = true
p.SubPaths[0].AutoFlipNormals()
if p.SubPaths[0].FlipNormals {
for _, sp := range p.SubPaths[1:] {
sp.FlipNormals = true
}
}
}
type byBBoxArea []*SubPath // slice of *SubPath
func (x byBBoxArea) Len() int { return len(x) }
func (x byBBoxArea) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x byBBoxArea) Less(i, j int) bool {
iBBox := x[i].BBox()
jBBox := x[j].BBox()
return jBBox.Area() < iBBox.Area()
} | path.go | 0.763572 | 0.411939 | path.go | starcoder |
package githubissue
import (
"entgo.io/ent/dialect/gremlin/graph/dsl"
"entgo.io/ent/dialect/gremlin/graph/dsl/__"
"entgo.io/ent/dialect/gremlin/graph/dsl/p"
"github.com/giantswarm/graph/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.HasID(id)
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.HasID(p.EQ(id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.HasID(p.NEQ(id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
t.HasID(p.Within(v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
t.HasID(p.Without(v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.HasID(p.GT(id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.HasID(p.GTE(id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.HasID(p.LT(id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.HasID(p.LTE(id))
})
}
// GithubID applies equality check predicate on the "github_id" field. It's identical to GithubIDEQ.
func GithubID(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.EQ(v))
})
}
// Number applies equality check predicate on the "number" field. It's identical to NumberEQ.
func Number(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.EQ(v))
})
}
// Title applies equality check predicate on the "title" field. It's identical to TitleEQ.
func Title(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.EQ(v))
})
}
// Body applies equality check predicate on the "body" field. It's identical to BodyEQ.
func Body(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.EQ(v))
})
}
// HTMLURL applies equality check predicate on the "html_url" field. It's identical to HTMLURLEQ.
func HTMLURL(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.EQ(v))
})
}
// Locked applies equality check predicate on the "locked" field. It's identical to LockedEQ.
func Locked(v bool) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldLocked, p.EQ(v))
})
}
// ActiveLockReason applies equality check predicate on the "active_lock_reason" field. It's identical to ActiveLockReasonEQ.
func ActiveLockReason(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.EQ(v))
})
}
// CommentsCount applies equality check predicate on the "comments_count" field. It's identical to CommentsCountEQ.
func CommentsCount(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.EQ(v))
})
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.EQ(v))
})
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.EQ(v))
})
}
// ClosedAt applies equality check predicate on the "closed_at" field. It's identical to ClosedAtEQ.
func ClosedAt(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.EQ(v))
})
}
// AuthorAssociation applies equality check predicate on the "author_association" field. It's identical to AuthorAssociationEQ.
func AuthorAssociation(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.EQ(v))
})
}
// GithubIDEQ applies the EQ predicate on the "github_id" field.
func GithubIDEQ(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.EQ(v))
})
}
// GithubIDNEQ applies the NEQ predicate on the "github_id" field.
func GithubIDNEQ(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.NEQ(v))
})
}
// GithubIDIn applies the In predicate on the "github_id" field.
func GithubIDIn(vs ...int) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.Within(v...))
})
}
// GithubIDNotIn applies the NotIn predicate on the "github_id" field.
func GithubIDNotIn(vs ...int) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.Without(v...))
})
}
// GithubIDGT applies the GT predicate on the "github_id" field.
func GithubIDGT(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.GT(v))
})
}
// GithubIDGTE applies the GTE predicate on the "github_id" field.
func GithubIDGTE(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.GTE(v))
})
}
// GithubIDLT applies the LT predicate on the "github_id" field.
func GithubIDLT(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.LT(v))
})
}
// GithubIDLTE applies the LTE predicate on the "github_id" field.
func GithubIDLTE(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldGithubID, p.LTE(v))
})
}
// NumberEQ applies the EQ predicate on the "number" field.
func NumberEQ(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.EQ(v))
})
}
// NumberNEQ applies the NEQ predicate on the "number" field.
func NumberNEQ(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.NEQ(v))
})
}
// NumberIn applies the In predicate on the "number" field.
func NumberIn(vs ...int) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.Within(v...))
})
}
// NumberNotIn applies the NotIn predicate on the "number" field.
func NumberNotIn(vs ...int) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.Without(v...))
})
}
// NumberGT applies the GT predicate on the "number" field.
func NumberGT(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.GT(v))
})
}
// NumberGTE applies the GTE predicate on the "number" field.
func NumberGTE(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.GTE(v))
})
}
// NumberLT applies the LT predicate on the "number" field.
func NumberLT(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.LT(v))
})
}
// NumberLTE applies the LTE predicate on the "number" field.
func NumberLTE(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldNumber, p.LTE(v))
})
}
// TitleEQ applies the EQ predicate on the "title" field.
func TitleEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.EQ(v))
})
}
// TitleNEQ applies the NEQ predicate on the "title" field.
func TitleNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.NEQ(v))
})
}
// TitleIn applies the In predicate on the "title" field.
func TitleIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.Within(v...))
})
}
// TitleNotIn applies the NotIn predicate on the "title" field.
func TitleNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.Without(v...))
})
}
// TitleGT applies the GT predicate on the "title" field.
func TitleGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.GT(v))
})
}
// TitleGTE applies the GTE predicate on the "title" field.
func TitleGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.GTE(v))
})
}
// TitleLT applies the LT predicate on the "title" field.
func TitleLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.LT(v))
})
}
// TitleLTE applies the LTE predicate on the "title" field.
func TitleLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.LTE(v))
})
}
// TitleContains applies the Contains predicate on the "title" field.
func TitleContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.Containing(v))
})
}
// TitleHasPrefix applies the HasPrefix predicate on the "title" field.
func TitleHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.StartingWith(v))
})
}
// TitleHasSuffix applies the HasSuffix predicate on the "title" field.
func TitleHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldTitle, p.EndingWith(v))
})
}
// BodyEQ applies the EQ predicate on the "body" field.
func BodyEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.EQ(v))
})
}
// BodyNEQ applies the NEQ predicate on the "body" field.
func BodyNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.NEQ(v))
})
}
// BodyIn applies the In predicate on the "body" field.
func BodyIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.Within(v...))
})
}
// BodyNotIn applies the NotIn predicate on the "body" field.
func BodyNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.Without(v...))
})
}
// BodyGT applies the GT predicate on the "body" field.
func BodyGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.GT(v))
})
}
// BodyGTE applies the GTE predicate on the "body" field.
func BodyGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.GTE(v))
})
}
// BodyLT applies the LT predicate on the "body" field.
func BodyLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.LT(v))
})
}
// BodyLTE applies the LTE predicate on the "body" field.
func BodyLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.LTE(v))
})
}
// BodyContains applies the Contains predicate on the "body" field.
func BodyContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.Containing(v))
})
}
// BodyHasPrefix applies the HasPrefix predicate on the "body" field.
func BodyHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.StartingWith(v))
})
}
// BodyHasSuffix applies the HasSuffix predicate on the "body" field.
func BodyHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldBody, p.EndingWith(v))
})
}
// HTMLURLEQ applies the EQ predicate on the "html_url" field.
func HTMLURLEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.EQ(v))
})
}
// HTMLURLNEQ applies the NEQ predicate on the "html_url" field.
func HTMLURLNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.NEQ(v))
})
}
// HTMLURLIn applies the In predicate on the "html_url" field.
func HTMLURLIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.Within(v...))
})
}
// HTMLURLNotIn applies the NotIn predicate on the "html_url" field.
func HTMLURLNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.Without(v...))
})
}
// HTMLURLGT applies the GT predicate on the "html_url" field.
func HTMLURLGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.GT(v))
})
}
// HTMLURLGTE applies the GTE predicate on the "html_url" field.
func HTMLURLGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.GTE(v))
})
}
// HTMLURLLT applies the LT predicate on the "html_url" field.
func HTMLURLLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.LT(v))
})
}
// HTMLURLLTE applies the LTE predicate on the "html_url" field.
func HTMLURLLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.LTE(v))
})
}
// HTMLURLContains applies the Contains predicate on the "html_url" field.
func HTMLURLContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.Containing(v))
})
}
// HTMLURLHasPrefix applies the HasPrefix predicate on the "html_url" field.
func HTMLURLHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.StartingWith(v))
})
}
// HTMLURLHasSuffix applies the HasSuffix predicate on the "html_url" field.
func HTMLURLHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldHTMLURL, p.EndingWith(v))
})
}
// StateEQ applies the EQ predicate on the "state" field.
func StateEQ(v State) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldState, p.EQ(v))
})
}
// StateNEQ applies the NEQ predicate on the "state" field.
func StateNEQ(v State) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldState, p.NEQ(v))
})
}
// StateIn applies the In predicate on the "state" field.
func StateIn(vs ...State) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldState, p.Within(v...))
})
}
// StateNotIn applies the NotIn predicate on the "state" field.
func StateNotIn(vs ...State) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldState, p.Without(v...))
})
}
// LockedEQ applies the EQ predicate on the "locked" field.
func LockedEQ(v bool) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldLocked, p.EQ(v))
})
}
// LockedNEQ applies the NEQ predicate on the "locked" field.
func LockedNEQ(v bool) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldLocked, p.NEQ(v))
})
}
// ActiveLockReasonEQ applies the EQ predicate on the "active_lock_reason" field.
func ActiveLockReasonEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.EQ(v))
})
}
// ActiveLockReasonNEQ applies the NEQ predicate on the "active_lock_reason" field.
func ActiveLockReasonNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.NEQ(v))
})
}
// ActiveLockReasonIn applies the In predicate on the "active_lock_reason" field.
func ActiveLockReasonIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.Within(v...))
})
}
// ActiveLockReasonNotIn applies the NotIn predicate on the "active_lock_reason" field.
func ActiveLockReasonNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.Without(v...))
})
}
// ActiveLockReasonGT applies the GT predicate on the "active_lock_reason" field.
func ActiveLockReasonGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.GT(v))
})
}
// ActiveLockReasonGTE applies the GTE predicate on the "active_lock_reason" field.
func ActiveLockReasonGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.GTE(v))
})
}
// ActiveLockReasonLT applies the LT predicate on the "active_lock_reason" field.
func ActiveLockReasonLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.LT(v))
})
}
// ActiveLockReasonLTE applies the LTE predicate on the "active_lock_reason" field.
func ActiveLockReasonLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.LTE(v))
})
}
// ActiveLockReasonContains applies the Contains predicate on the "active_lock_reason" field.
func ActiveLockReasonContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.Containing(v))
})
}
// ActiveLockReasonHasPrefix applies the HasPrefix predicate on the "active_lock_reason" field.
func ActiveLockReasonHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.StartingWith(v))
})
}
// ActiveLockReasonHasSuffix applies the HasSuffix predicate on the "active_lock_reason" field.
func ActiveLockReasonHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldActiveLockReason, p.EndingWith(v))
})
}
// CommentsCountEQ applies the EQ predicate on the "comments_count" field.
func CommentsCountEQ(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.EQ(v))
})
}
// CommentsCountNEQ applies the NEQ predicate on the "comments_count" field.
func CommentsCountNEQ(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.NEQ(v))
})
}
// CommentsCountIn applies the In predicate on the "comments_count" field.
func CommentsCountIn(vs ...int) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.Within(v...))
})
}
// CommentsCountNotIn applies the NotIn predicate on the "comments_count" field.
func CommentsCountNotIn(vs ...int) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.Without(v...))
})
}
// CommentsCountGT applies the GT predicate on the "comments_count" field.
func CommentsCountGT(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.GT(v))
})
}
// CommentsCountGTE applies the GTE predicate on the "comments_count" field.
func CommentsCountGTE(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.GTE(v))
})
}
// CommentsCountLT applies the LT predicate on the "comments_count" field.
func CommentsCountLT(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.LT(v))
})
}
// CommentsCountLTE applies the LTE predicate on the "comments_count" field.
func CommentsCountLTE(v int) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCommentsCount, p.LTE(v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.EQ(v))
})
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.NEQ(v))
})
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.Within(v...))
})
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.Without(v...))
})
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.GT(v))
})
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.GTE(v))
})
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.LT(v))
})
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.LTE(v))
})
}
// CreatedAtContains applies the Contains predicate on the "created_at" field.
func CreatedAtContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.Containing(v))
})
}
// CreatedAtHasPrefix applies the HasPrefix predicate on the "created_at" field.
func CreatedAtHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.StartingWith(v))
})
}
// CreatedAtHasSuffix applies the HasSuffix predicate on the "created_at" field.
func CreatedAtHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldCreatedAt, p.EndingWith(v))
})
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.EQ(v))
})
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.NEQ(v))
})
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.Within(v...))
})
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.Without(v...))
})
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.GT(v))
})
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.GTE(v))
})
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.LT(v))
})
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.LTE(v))
})
}
// UpdatedAtContains applies the Contains predicate on the "updated_at" field.
func UpdatedAtContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.Containing(v))
})
}
// UpdatedAtHasPrefix applies the HasPrefix predicate on the "updated_at" field.
func UpdatedAtHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.StartingWith(v))
})
}
// UpdatedAtHasSuffix applies the HasSuffix predicate on the "updated_at" field.
func UpdatedAtHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldUpdatedAt, p.EndingWith(v))
})
}
// ClosedAtEQ applies the EQ predicate on the "closed_at" field.
func ClosedAtEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.EQ(v))
})
}
// ClosedAtNEQ applies the NEQ predicate on the "closed_at" field.
func ClosedAtNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.NEQ(v))
})
}
// ClosedAtIn applies the In predicate on the "closed_at" field.
func ClosedAtIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.Within(v...))
})
}
// ClosedAtNotIn applies the NotIn predicate on the "closed_at" field.
func ClosedAtNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.Without(v...))
})
}
// ClosedAtGT applies the GT predicate on the "closed_at" field.
func ClosedAtGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.GT(v))
})
}
// ClosedAtGTE applies the GTE predicate on the "closed_at" field.
func ClosedAtGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.GTE(v))
})
}
// ClosedAtLT applies the LT predicate on the "closed_at" field.
func ClosedAtLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.LT(v))
})
}
// ClosedAtLTE applies the LTE predicate on the "closed_at" field.
func ClosedAtLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.LTE(v))
})
}
// ClosedAtContains applies the Contains predicate on the "closed_at" field.
func ClosedAtContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.Containing(v))
})
}
// ClosedAtHasPrefix applies the HasPrefix predicate on the "closed_at" field.
func ClosedAtHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.StartingWith(v))
})
}
// ClosedAtHasSuffix applies the HasSuffix predicate on the "closed_at" field.
func ClosedAtHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldClosedAt, p.EndingWith(v))
})
}
// AuthorAssociationEQ applies the EQ predicate on the "author_association" field.
func AuthorAssociationEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.EQ(v))
})
}
// AuthorAssociationNEQ applies the NEQ predicate on the "author_association" field.
func AuthorAssociationNEQ(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.NEQ(v))
})
}
// AuthorAssociationIn applies the In predicate on the "author_association" field.
func AuthorAssociationIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.Within(v...))
})
}
// AuthorAssociationNotIn applies the NotIn predicate on the "author_association" field.
func AuthorAssociationNotIn(vs ...string) predicate.GitHubIssue {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.Without(v...))
})
}
// AuthorAssociationGT applies the GT predicate on the "author_association" field.
func AuthorAssociationGT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.GT(v))
})
}
// AuthorAssociationGTE applies the GTE predicate on the "author_association" field.
func AuthorAssociationGTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.GTE(v))
})
}
// AuthorAssociationLT applies the LT predicate on the "author_association" field.
func AuthorAssociationLT(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.LT(v))
})
}
// AuthorAssociationLTE applies the LTE predicate on the "author_association" field.
func AuthorAssociationLTE(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.LTE(v))
})
}
// AuthorAssociationContains applies the Contains predicate on the "author_association" field.
func AuthorAssociationContains(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.Containing(v))
})
}
// AuthorAssociationHasPrefix applies the HasPrefix predicate on the "author_association" field.
func AuthorAssociationHasPrefix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.StartingWith(v))
})
}
// AuthorAssociationHasSuffix applies the HasSuffix predicate on the "author_association" field.
func AuthorAssociationHasSuffix(v string) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.Has(Label, FieldAuthorAssociation, p.EndingWith(v))
})
}
// HasAssignees applies the HasEdge predicate on the "assignees" edge.
func HasAssignees() predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.OutE(AssigneesLabel).OutV()
})
}
// HasAssigneesWith applies the HasEdge predicate on the "assignees" edge with a given conditions (other predicates).
func HasAssigneesWith(preds ...predicate.GitHubUser) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
tr := __.InV()
for _, p := range preds {
p(tr)
}
t.OutE(AssigneesLabel).Where(tr).OutV()
})
}
// HasAuthor applies the HasEdge predicate on the "author" edge.
func HasAuthor() predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.InE(AuthorInverseLabel).InV()
})
}
// HasAuthorWith applies the HasEdge predicate on the "author" edge with a given conditions (other predicates).
func HasAuthorWith(preds ...predicate.GitHubUser) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
tr := __.OutV()
for _, p := range preds {
p(tr)
}
t.InE(AuthorInverseLabel).Where(tr).InV()
})
}
// HasClosedBy applies the HasEdge predicate on the "closed_by" edge.
func HasClosedBy() predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
t.InE(ClosedByInverseLabel).InV()
})
}
// HasClosedByWith applies the HasEdge predicate on the "closed_by" edge with a given conditions (other predicates).
func HasClosedByWith(preds ...predicate.GitHubUser) predicate.GitHubIssue {
return predicate.GitHubIssue(func(t *dsl.Traversal) {
tr := __.OutV()
for _, p := range preds {
p(tr)
}
t.InE(ClosedByInverseLabel).Where(tr).InV()
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.GitHubIssue) predicate.GitHubIssue {
return predicate.GitHubIssue(func(tr *dsl.Traversal) {
trs := make([]interface{}, 0, len(predicates))
for _, p := range predicates {
t := __.New()
p(t)
trs = append(trs, t)
}
tr.Where(__.And(trs...))
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.GitHubIssue) predicate.GitHubIssue {
return predicate.GitHubIssue(func(tr *dsl.Traversal) {
trs := make([]interface{}, 0, len(predicates))
for _, p := range predicates {
t := __.New()
p(t)
trs = append(trs, t)
}
tr.Where(__.Or(trs...))
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.GitHubIssue) predicate.GitHubIssue {
return predicate.GitHubIssue(func(tr *dsl.Traversal) {
t := __.New()
p(t)
tr.Where(__.Not(t))
})
} | ent/githubissue/where.go | 0.549761 | 0.419826 | where.go | starcoder |
package godash
import (
"errors"
"reflect"
)
// Intersection creates a slice of unique values that were present in both of the provided slices.
// The order of the items in the resulting slice is determined by the first given slice.
// The new slice is returned as an interface{} and may need to have a type assertion applied to it afterwards.
func Intersection(slice1 interface{}, slice2 interface{}) (interface{}, error) {
sliceVal1 := reflect.ValueOf(slice1)
sliceVal2 := reflect.ValueOf(slice2)
if sliceVal1.Type().Kind() != reflect.Slice {
return nil, errors.New("godash: invalid parameter type. Intersection func expects parameter 1 to be a slice")
}
if sliceVal2.Type().Kind() != reflect.Slice {
return nil, errors.New("godash: invalid parameter type. Intersection func expects parameter 2 to be a slice")
}
if sliceVal1.Type().Elem() != sliceVal2.Type().Elem() {
return nil, errors.New("godash: invalid parameter type. Intersection func expects two slice parameters of the same type")
}
dest := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(slice1).Elem()), 0, sliceVal1.Len())
m := make(map[interface{}]bool)
for i := 0; i < sliceVal2.Len(); i++ {
val := sliceVal2.Index(i).Interface()
m[val] = false
}
for i := 0; i < sliceVal1.Len(); i++ {
val := sliceVal1.Index(i).Interface()
appended, exists := m[val]
if exists {
if !appended {
dest = reflect.Append(dest, sliceVal1.Index(i))
}
m[val] = true
}
}
return dest.Interface(), nil
}
// IntersectionBy passes items from two provided slices through a provided mutator function and creates a new slice with items that resulted in common mutated values.
// The supplied mutator function must accept an interface{} parameter and return interface{} with the value to be compared.
// The order and values of the items in the resulting slice are determined by the first given slice.
// The new slice is returned as an interface{} and may need to have a type assertion applied to it afterwards.
func IntersectionBy(slice1 interface{}, slice2 interface{}, fn mutator) (interface{}, error) {
sliceVal1 := reflect.ValueOf(slice1)
sliceVal2 := reflect.ValueOf(slice2)
if sliceVal1.Type().Kind() != reflect.Slice {
return nil, errors.New("godash: invalid parameter type. IntersectionBy func expects parameter 1 to be a slice")
}
if sliceVal2.Type().Kind() != reflect.Slice {
return nil, errors.New("godash: invalid parameter type. IntersectionBy func expects parameter 2 to be a slice")
}
if sliceVal1.Type().Elem() != sliceVal2.Type().Elem() {
return nil, errors.New("godash: invalid parameter type. IntersectionBy func expects two slice parameters of the same type")
}
dest := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(slice1).Elem()), 0, sliceVal1.Len())
m := make(map[interface{}]bool)
for i := 0; i < sliceVal2.Len(); i++ {
item := sliceVal2.Index(i).Interface()
val := fn(item)
m[val] = false
}
for i := 0; i < sliceVal1.Len(); i++ {
item := sliceVal1.Index(i).Interface()
val := fn(item)
appended, exists := m[val]
if exists {
if !appended {
dest = reflect.Append(dest, sliceVal1.Index(i))
}
m[val] = true
}
}
return dest.Interface(), nil
} | intersection.go | 0.756807 | 0.49762 | intersection.go | starcoder |
package raster
import (
"image"
"image/color"
"unsafe"
)
const (
SUBPIXEL_SHIFT = 5
SUBPIXEL_COUNT = 1 << SUBPIXEL_SHIFT
)
var SUBPIXEL_OFFSETS = SUBPIXEL_OFFSETS_SAMPLE_32_FIXED
type SUBPIXEL_DATA uint32
type NON_ZERO_MASK_DATA_UNIT uint8
type Rasterizer8BitsSample struct {
MaskBuffer []SUBPIXEL_DATA
WindingBuffer []NON_ZERO_MASK_DATA_UNIT
Width int
BufferWidth int
Height int
ClipBound [4]float64
RemappingMatrix [6]float64
}
/* width and height define the maximum output size for the filler.
* The filler will output to larger bitmaps as well, but the output will
* be cropped.
*/
func NewRasterizer8BitsSample(width, height int) *Rasterizer8BitsSample {
var r Rasterizer8BitsSample
// Scale the coordinates by SUBPIXEL_COUNT in vertical direction
// The sampling point for the sub-pixel is at the top right corner. This
// adjustment moves it to the pixel center.
r.RemappingMatrix = [6]float64{1, 0, 0, SUBPIXEL_COUNT, 0.5 / SUBPIXEL_COUNT, -0.5 * SUBPIXEL_COUNT}
r.Width = width
r.Height = height
// The buffer used for filling needs to be one pixel wider than the bitmap.
// This is because the end flag that turns the fill of is the first pixel
// after the actually drawn edge.
r.BufferWidth = width + 1
r.MaskBuffer = make([]SUBPIXEL_DATA, r.BufferWidth*height)
r.WindingBuffer = make([]NON_ZERO_MASK_DATA_UNIT, r.BufferWidth*height*SUBPIXEL_COUNT)
r.ClipBound = clip(0, 0, width, height, SUBPIXEL_COUNT)
return &r
}
func clip(x, y, width, height, scale int) [4]float64 {
var clipBound [4]float64
offset := 0.99 / float64(scale)
clipBound[0] = float64(x) + offset
clipBound[2] = float64(x+width) - offset
clipBound[1] = float64(y * scale)
clipBound[3] = float64((y + height) * scale)
return clipBound
}
func intersect(r1, r2 [4]float64) [4]float64 {
if r1[0] < r2[0] {
r1[0] = r2[0]
}
if r1[2] > r2[2] {
r1[2] = r2[2]
}
if r1[0] > r1[2] {
r1[0] = r1[2]
}
if r1[1] < r2[1] {
r1[1] = r2[1]
}
if r1[3] > r2[3] {
r1[3] = r2[3]
}
if r1[1] > r1[3] {
r1[1] = r1[3]
}
return r1
}
func (r *Rasterizer8BitsSample) RenderEvenOdd(img *image.RGBA, color *color.RGBA, polygon *Polygon, tr [6]float64) {
// memset 0 the mask buffer
r.MaskBuffer = make([]SUBPIXEL_DATA, r.BufferWidth*r.Height)
// inline matrix multiplication
transform := [6]float64{
tr[0]*r.RemappingMatrix[0] + tr[1]*r.RemappingMatrix[2],
tr[1]*r.RemappingMatrix[3] + tr[0]*r.RemappingMatrix[1],
tr[2]*r.RemappingMatrix[0] + tr[3]*r.RemappingMatrix[2],
tr[3]*r.RemappingMatrix[3] + tr[2]*r.RemappingMatrix[1],
tr[4]*r.RemappingMatrix[0] + tr[5]*r.RemappingMatrix[2] + r.RemappingMatrix[4],
tr[5]*r.RemappingMatrix[3] + tr[4]*r.RemappingMatrix[1] + r.RemappingMatrix[5],
}
clipRect := clip(img.Bounds().Min.X, img.Bounds().Min.Y, img.Bounds().Dx(), img.Bounds().Dy(), SUBPIXEL_COUNT)
clipRect = intersect(clipRect, r.ClipBound)
p := 0
l := len(*polygon) / 2
var edges [32]PolygonEdge
for p < l {
edgeCount := polygon.getEdges(p, 16, edges[:], transform, clipRect)
for k := 0; k < edgeCount; k++ {
r.addEvenOddEdge(&edges[k])
}
p += 16
}
r.fillEvenOdd(img, color, clipRect)
}
//! Adds an edge to be used with even-odd fill.
func (r *Rasterizer8BitsSample) addEvenOddEdge(edge *PolygonEdge) {
x := Fix(edge.X * FIXED_FLOAT_COEF)
slope := Fix(edge.Slope * FIXED_FLOAT_COEF)
slopeFix := Fix(0)
if edge.LastLine-edge.FirstLine >= SLOPE_FIX_STEP {
slopeFix = Fix(edge.Slope*SLOPE_FIX_STEP*FIXED_FLOAT_COEF) - slope<<SLOPE_FIX_SHIFT
}
var mask SUBPIXEL_DATA
var ySub uint32
var xp, yLine int
for y := edge.FirstLine; y <= edge.LastLine; y++ {
ySub = uint32(y & (SUBPIXEL_COUNT - 1))
xp = int((x + SUBPIXEL_OFFSETS[ySub]) >> FIXED_SHIFT)
mask = SUBPIXEL_DATA(1 << ySub)
yLine = y >> SUBPIXEL_SHIFT
r.MaskBuffer[yLine*r.BufferWidth+xp] ^= mask
x += slope
if y&SLOPE_FIX_MASK == 0 {
x += slopeFix
}
}
}
//! Adds an edge to be used with non-zero winding fill.
func (r *Rasterizer8BitsSample) addNonZeroEdge(edge *PolygonEdge) {
x := Fix(edge.X * FIXED_FLOAT_COEF)
slope := Fix(edge.Slope * FIXED_FLOAT_COEF)
slopeFix := Fix(0)
if edge.LastLine-edge.FirstLine >= SLOPE_FIX_STEP {
slopeFix = Fix(edge.Slope*SLOPE_FIX_STEP*FIXED_FLOAT_COEF) - slope<<SLOPE_FIX_SHIFT
}
var mask SUBPIXEL_DATA
var ySub uint32
var xp, yLine int
winding := NON_ZERO_MASK_DATA_UNIT(edge.Winding)
for y := edge.FirstLine; y <= edge.LastLine; y++ {
ySub = uint32(y & (SUBPIXEL_COUNT - 1))
xp = int((x + SUBPIXEL_OFFSETS[ySub]) >> FIXED_SHIFT)
mask = SUBPIXEL_DATA(1 << ySub)
yLine = y >> SUBPIXEL_SHIFT
r.MaskBuffer[yLine*r.BufferWidth+xp] |= mask
r.WindingBuffer[(yLine*r.BufferWidth+xp)*SUBPIXEL_COUNT+int(ySub)] += winding
x += slope
if y&SLOPE_FIX_MASK == 0 {
x += slopeFix
}
}
}
// Renders the mask to the canvas with even-odd fill.
func (r *Rasterizer8BitsSample) fillEvenOdd(img *image.RGBA, color *color.RGBA, clipBound [4]float64) {
var x, y uint32
minX := uint32(clipBound[0])
maxX := uint32(clipBound[2])
minY := uint32(clipBound[1]) >> SUBPIXEL_SHIFT
maxY := uint32(clipBound[3]) >> SUBPIXEL_SHIFT
//pixColor := (uint32(color.R) << 24) | (uint32(color.G) << 16) | (uint32(color.B) << 8) | uint32(color.A)
pixColor := (*uint32)(unsafe.Pointer(color))
cs1 := *pixColor & 0xff00ff
cs2 := *pixColor >> 8 & 0xff00ff
stride := uint32(img.Stride)
var mask SUBPIXEL_DATA
for y = minY; y < maxY; y++ {
tp := img.Pix[y*stride:]
mask = 0
for x = minX; x <= maxX; x++ {
p := (*uint32)(unsafe.Pointer(&tp[x]))
mask ^= r.MaskBuffer[y*uint32(r.BufferWidth)+x]
// 8bits
//alpha := uint32(coverageTable[mask])
// 16bits
//alpha := uint32(coverageTable[mask & 0xff] + coverageTable[(mask >> 8) & 0xff])
// 32bits
alpha := uint32(coverageTable[mask&0xff] + coverageTable[mask>>8&0xff] + coverageTable[mask>>16&0xff] + coverageTable[mask>>24&0xff])
// alpha is in range of 0 to SUBPIXEL_COUNT
invAlpha := uint32(SUBPIXEL_COUNT) - alpha
ct1 := *p & 0xff00ff * invAlpha
ct2 := *p >> 8 & 0xff00ff * invAlpha
ct1 = (ct1 + cs1*alpha) >> SUBPIXEL_SHIFT & 0xff00ff
ct2 = (ct2 + cs2*alpha) << (8 - SUBPIXEL_SHIFT) & 0xff00ff00
*p = ct1 + ct2
}
}
}
/*
* Renders the polygon with non-zero winding fill.
* param aTarget the target bitmap.
* param aPolygon the polygon to render.
* param aColor the color to be used for rendering.
* param aTransformation the transformation matrix.
*/
func (r *Rasterizer8BitsSample) RenderNonZeroWinding(img *image.RGBA, color *color.RGBA, polygon *Polygon, tr [6]float64) {
r.MaskBuffer = make([]SUBPIXEL_DATA, r.BufferWidth*r.Height)
r.WindingBuffer = make([]NON_ZERO_MASK_DATA_UNIT, r.BufferWidth*r.Height*SUBPIXEL_COUNT)
// inline matrix multiplication
transform := [6]float64{
tr[0]*r.RemappingMatrix[0] + tr[1]*r.RemappingMatrix[2],
tr[1]*r.RemappingMatrix[3] + tr[0]*r.RemappingMatrix[1],
tr[2]*r.RemappingMatrix[0] + tr[3]*r.RemappingMatrix[2],
tr[3]*r.RemappingMatrix[3] + tr[2]*r.RemappingMatrix[1],
tr[4]*r.RemappingMatrix[0] + tr[5]*r.RemappingMatrix[2] + r.RemappingMatrix[4],
tr[5]*r.RemappingMatrix[3] + tr[4]*r.RemappingMatrix[1] + r.RemappingMatrix[5],
}
clipRect := clip(img.Bounds().Min.X, img.Bounds().Min.Y, img.Bounds().Dx(), img.Bounds().Dy(), SUBPIXEL_COUNT)
clipRect = intersect(clipRect, r.ClipBound)
p := 0
l := len(*polygon) / 2
var edges [32]PolygonEdge
for p < l {
edgeCount := polygon.getEdges(p, 16, edges[:], transform, clipRect)
for k := 0; k < edgeCount; k++ {
r.addNonZeroEdge(&edges[k])
}
p += 16
}
r.fillNonZero(img, color, clipRect)
}
//! Renders the mask to the canvas with non-zero winding fill.
func (r *Rasterizer8BitsSample) fillNonZero(img *image.RGBA, color *color.RGBA, clipBound [4]float64) {
var x, y uint32
minX := uint32(clipBound[0])
maxX := uint32(clipBound[2])
minY := uint32(clipBound[1]) >> SUBPIXEL_SHIFT
maxY := uint32(clipBound[3]) >> SUBPIXEL_SHIFT
//pixColor := (uint32(color.R) << 24) | (uint32(color.G) << 16) | (uint32(color.B) << 8) | uint32(color.A)
pixColor := (*uint32)(unsafe.Pointer(color))
cs1 := *pixColor & 0xff00ff
cs2 := *pixColor >> 8 & 0xff00ff
stride := uint32(img.Stride)
var mask SUBPIXEL_DATA
var n uint32
var values [SUBPIXEL_COUNT]NON_ZERO_MASK_DATA_UNIT
for n = 0; n < SUBPIXEL_COUNT; n++ {
values[n] = 0
}
for y = minY; y < maxY; y++ {
tp := img.Pix[y*stride:]
mask = 0
for x = minX; x <= maxX; x++ {
p := (*uint32)(unsafe.Pointer(&tp[x]))
temp := r.MaskBuffer[y*uint32(r.BufferWidth)+x]
if temp != 0 {
var bit SUBPIXEL_DATA = 1
for n = 0; n < SUBPIXEL_COUNT; n++ {
if temp&bit != 0 {
t := values[n]
values[n] += r.WindingBuffer[(y*uint32(r.BufferWidth)+x)*SUBPIXEL_COUNT+n]
if (t == 0 || values[n] == 0) && t != values[n] {
mask ^= bit
}
}
bit <<= 1
}
}
// 8bits
//alpha := uint32(coverageTable[mask])
// 16bits
//alpha := uint32(coverageTable[mask & 0xff] + coverageTable[(mask >> 8) & 0xff])
// 32bits
alpha := uint32(coverageTable[mask&0xff] + coverageTable[mask>>8&0xff] + coverageTable[mask>>16&0xff] + coverageTable[mask>>24&0xff])
// alpha is in range of 0 to SUBPIXEL_COUNT
invAlpha := uint32(SUBPIXEL_COUNT) - alpha
ct1 := *p & 0xff00ff * invAlpha
ct2 := *p >> 8 & 0xff00ff * invAlpha
ct1 = (ct1 + cs1*alpha) >> SUBPIXEL_SHIFT & 0xff00ff
ct2 = (ct2 + cs2*alpha) << (8 - SUBPIXEL_SHIFT) & 0xff00ff00
*p = ct1 + ct2
}
}
} | draw2d/raster/fillerV2/fillerAA.go | 0.564699 | 0.422624 | fillerAA.go | starcoder |
package nett
import (
"math"
"math/rand"
"strconv"
"strings"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
type Matrix [][]float64
func NewMatrix(r, c int) Matrix {
m := make([][]float64, r)
for i := range m {
m[i] = make([]float64, c)
}
return m
}
func NewMatrixFromSlice(s []float64) Matrix {
m := NewMatrix(1, len(s))
for i, v := range s {
m.Set(i, 0, float64(v))
}
return m
}
// Dims return the dimensions of a matrix (rows, columns).
func (m Matrix) Dims() (int, int) {
return len(m), len(m[0])
}
// At returns the value in the matrix at [x, y].
func (m Matrix) At(x, y int) float64 {
return m[y][x]
}
// Set sets the value at [x, y] to v.
func (m Matrix) Set(x, y int, v float64) {
m[y][x] = v
}
// Row returns a row for a matrix.
func (m Matrix) Row(y int) []float64 {
return m[y][0:]
}
// Flatten returns all elements of a matrix in a single slice.
func (m Matrix) Flatten() []float64 {
r, c := m.Dims()
flat := make([]float64, r*c)
var i int
for y := 0; y < r; y++ {
for x := 0; x < c; x++ {
flat[i] = m.At(x, y)
i++
}
}
return flat
}
// SetForEach executes f on each value of the matrix and sets the value to the return value of f.
func (m Matrix) SetForEach(f func(val float64, x, y int) float64) {
r, c := m.Dims()
for y := 0; y < r; y++ {
for x := 0; x < c; x++ {
v := m.At(x, y)
m.Set(x, y, f(v, x, y))
}
}
}
// SetForEachNew is the same as ForEach except without overriding the original matrix.
func (m Matrix) SetForEachNew(f func(val float64, x, y int) float64) Matrix {
r, c := m.Dims()
n := NewMatrix(r, c)
for y := 0; y < r; y++ {
for x := 0; x < c; x++ {
v := m.At(x, y)
n.Set(x, y, f(v, x, y))
}
}
return n
}
// Dot performs the cross/dot product between two matrices.
func Dot(a, b Matrix) Matrix {
ar, ac := a.Dims()
br, bc := b.Dims()
if ac != br {
panic("Dot: Dimension mismatch")
}
m := NewMatrix(ar, bc)
for i := 0; i < ar; i++ {
for j := 0; j < bc; j++ {
var val float64
for k := 0; k < br; k++ {
val += b[k][j] * a[i][k]
}
m.Set(j, i, val)
}
}
return m
}
// Sum sums a matrix into a single value.
func (m Matrix) Sum() float64 {
var sum float64
r, c := m.Dims()
for y := 0; y < r; y++ {
for x := 0; x < c; x++ {
sum += m.At(x, y)
}
}
return sum
}
func (m Matrix) T() Matrix {
x, y := m.Dims()
out := NewMatrix(y, x)
for i := 0; i < x; i++ {
for j := 0; j < y; j++ {
out.Set(i, j, m.At(j, i))
}
}
return out
}
func Sigmoid(n float64, deriv bool) float64 {
if deriv {
return n * (1 - n)
}
return 1 / (1 + math.Exp(-n))
}
func Softmax(n float64, deriv bool) float64 {
// TODO (sno6): Implement.
return n
}
func Relu(n float64, deriv bool) float64 {
if deriv {
if n > 0 {
return 1
}
return 0
}
return math.Max(0, n)
}
func DotWithActivation(a, b Matrix, f ActivationFunc) Matrix {
out := Dot(a, b)
out.SetForEach(func(v float64, x, y int) float64 {
return f(v, false)
})
return out
}
func NewWeightMatrix(r, c int) Matrix {
m := NewMatrix(r, c)
m.SetForEach(func(v float64, x, y int) float64 {
return rand.Float64()
})
return m
}
func EuclideanLoss(t float64, p float64, deriv bool) float64 {
if deriv {
return p - t
}
return (1.0 / 2.0) * math.Pow(p-t, 2)
}
func (m Matrix) Pretty() string {
var b strings.Builder
r, c := m.Dims()
for y := 0; y < r; y++ {
b.WriteString("[ ")
for x := 0; x < c; x++ {
v := m.At(x, y)
b.WriteString(strconv.FormatFloat(v, 'f', 4, 64) + " ")
}
b.WriteString(" ]\n")
}
return b.String()
} | matrix.go | 0.741768 | 0.617484 | matrix.go | starcoder |
package naturel
import (
"image"
"image/color"
_ "image/gif"
_ "image/jpeg"
"image/png"
"os"
)
// Based on code from https://golang.org/pkg/image for reading
// image pixels and code from a pornscanner withen in python using
// the Python Image Library (PIL)
// Checks given file name for the skin ratio in the image
// returning if we think it's porn and what our skinRaito
// value came to
func IsPorn(imgPath string) (isPorn bool, skinRatio float64, err error) {
// Read in our Image
reader, err := os.Open(imgPath)
if err != nil {
return
}
defer reader.Close()
// Decode the image
m, _, err := image.Decode(reader)
if err != nil {
return
}
bounds := m.Bounds()
var skin int
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, _ := m.At(x, y).RGBA()
// Look for a particular red color and variations of blue and green could reperesnt a skin color
if r > 60 && float64(g) < (float64(r)*0.85) && float64(b) < (float64(r)*0.7) && float64(g) > (float64(r)*0.4) && float64(b) > (float64(r)*0.2) {
skin++
}
}
}
size := bounds.Size()
skinRatio = float64(skin) / float64(size.Y*size.X) * 100
if skinRatio > 30 {
isPorn = true
}
return
}
// Outputs a PNG image with Red being where we thing skin is
func HighlightSkin(imgPath string) error {
// Read in our Image
reader, err := os.Open(imgPath)
if err != nil {
return err
}
defer reader.Close()
// Decode the image
m, _, err := image.Decode(reader)
if err != nil {
return err
}
bounds := m.Bounds()
size := bounds.Size()
outImgFile, err := os.OpenFile(imgPath+"_skin.png", os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer outImgFile.Close()
outImg := image.NewNRGBA(image.Rectangle{Min: image.Point{0, 0}, Max: image.Point{size.X, size.Y}})
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, _ := m.At(x, y).RGBA()
// Look for a particular red color and variations of blue and green could reperesnt a skin color
if r > 60 && float64(g) < (float64(r)*0.85) && float64(b) < (float64(r)*0.7) && float64(g) > (float64(r)*0.4) && float64(b) > (float64(r)*0.2) {
outImg.SetNRGBA(x-bounds.Min.X, y-bounds.Min.Y, color.NRGBA{255, 0, 0, 255})
}
}
}
return png.Encode(outImgFile, outImg)
} | naturel.go | 0.707506 | 0.428712 | naturel.go | starcoder |
package cbor
import (
// "bufio"
"bytes"
"encoding/binary"
"fmt"
"io"
"reflect"
"strings"
)
type reader interface {
io.ByteReader
io.Reader
}
func Unmarshal(bs []byte, v interface{}) error {
r := bytes.NewReader(bs)
return unmarshal(r, reflect.ValueOf(v).Elem())
}
func unmarshal(r reader, v reflect.Value) error {
b, err := r.ReadByte()
if err != nil {
return err
}
switch m, a, k := b&0xE0, b&0x1F, v.Kind(); m {
case Uint:
err = unmarshalUint(r, a, v)
case Int:
err = unmarshalInt(r, a, v)
case Bin:
case String:
err = unmarshalString(r, a, v)
case Array:
err = unmarshalArray(r, a, v)
case Map:
if k == reflect.Map {
return unmarshalMap(r, a, v)
}
if k == reflect.Struct || k == reflect.Ptr {
return unmarshalStruct(r, a, v)
}
return expectedType("map/struct", k)
case Other:
return unmarshalSimple(r, a, v)
case Tag:
return unmarshalTagged(r, a, v)
}
return err
}
func unmarshalTagged(r reader, a byte, v reflect.Value) error {
switch a {
default:
case Len1:
b, err := r.ReadByte()
if err != nil {
return err
}
a = b
case Len2:
case Len4:
case Len8:
}
switch a {
default:
return fmt.Errorf("unsupported tagged item %02x", a)
case TagURI, TagRFC3339, TagUnix:
return unmarshal(r, v)
}
return nil
}
func unmarshalSimple(r reader, a byte, v reflect.Value) error {
switch k := v.Kind(); a {
default:
if isInt(k) {
v.SetInt(int64(a))
} else if isUint(k) {
v.SetUint(uint64(a))
} else {
return expectedType("int/uint", k)
}
case Simple:
b, err := r.ReadByte()
if err != nil {
return err
}
if isInt(k) {
v.SetInt(int64(b))
} else if isUint(k) {
v.SetUint(uint64(b))
} else {
return expectedType("int/uint", k)
}
case False:
if k != reflect.Bool {
return expectedType("bool", k)
}
v.SetBool(false)
case True:
if k != reflect.Bool {
return expectedType("bool", k)
}
v.SetBool(true)
case Nil, Undefined:
case Float16:
return fmt.Errorf("float16 not yet supported")
case Float32:
if k == reflect.Float32 || k == reflect.Float64 {
var f float32
if err := binary.Read(r, binary.BigEndian, &f); err != nil {
return err
}
v.SetFloat(float64(f))
} else {
return expectedType("float32", k)
}
case Float64:
if k == reflect.Float64 {
var f float64
if err := binary.Read(r, binary.BigEndian, &f); err != nil {
return err
}
v.SetFloat(f)
} else {
return expectedType("float64", k)
}
}
return nil
}
func unmarshalMap(r reader, a byte, v reflect.Value) error {
size, err := sizeof(r, a)
if err != nil {
return err
}
if v.IsNil() {
v.Set(reflect.MakeMapWithSize(v.Type(), size))
}
seen := make(map[string]struct{})
for i := 0; i < size; i++ {
k := reflect.New(v.Type().Key()).Elem()
if err := unmarshal(r, k); err != nil {
return err
}
if _, ok := seen[k.String()]; ok {
return fmt.Errorf("duplicate field %s", k)
}
seen[k.String()] = struct{}{}
f := reflect.New(v.Type().Elem()).Elem()
if err := unmarshal(r, f); err != nil {
return err
}
v.SetMapIndex(k, f)
}
return nil
}
func unmarshalStruct(r reader, a byte, v reflect.Value) error {
size, err := sizeof(r, a)
if err != nil {
return err
}
vs := make(map[string]reflect.Value)
for i, t := 0, v.Type(); i < v.NumField(); i++ {
f := v.Field(i)
if !f.CanSet() {
continue
}
j := t.Field(i)
switch n := j.Tag.Get("cbor"); strings.ToLower(n) {
case "-":
continue
case "":
vs[j.Name] = f
default:
vs[n] = f
}
}
seen := make(map[string]struct{})
for i := 0; i < size; i++ {
var k string
f := reflect.New(reflect.TypeOf(k)).Elem()
if err := unmarshal(r, f); err != nil {
return err
}
k = f.String()
if _, ok := seen[k]; ok {
return fmt.Errorf("duplicate field %s", k)
}
seen[k] = struct{}{}
f, ok := vs[k]
if !ok {
return fmt.Errorf("field not found %s", k)
}
if err := unmarshal(r, f); err != nil {
return err
}
}
return nil
}
func unmarshalArray(r reader, a byte, v reflect.Value) error {
if k := v.Kind(); !(k == reflect.Array || k == reflect.Slice) {
return expectedType("array/slice", k)
}
size, err := sizeof(r, a)
if err != nil {
return err
}
if k := v.Kind(); k == reflect.Array && size >= v.Len() {
return fmt.Errorf("array length too short (got: %d, want: %d)", v.Len(), size)
}
if v.IsNil() {
v.Set(reflect.MakeSlice(v.Type(), size, size))
}
for i := 0; i < size; i++ {
var f reflect.Value
if i < v.Len() {
f = v.Index(i)
} else {
f = reflect.New(v.Type().Elem()).Elem()
}
if err := unmarshal(r, f); err != nil {
return err
}
if i >= v.Len() {
v.Set(reflect.Append(v, f))
}
}
return nil
}
func unmarshalString(r reader, a byte, v reflect.Value) error {
if k := v.Kind(); k != reflect.String {
return expectedType("string", k)
}
size, err := sizeof(r, a)
if err != nil {
return err
}
bs := make([]byte, size)
if _, err := io.ReadFull(r, bs); err != nil {
return err
}
v.SetString(string(bs))
// v.SetBytes(bs)
return nil
}
func unmarshalInt(r reader, a byte, v reflect.Value) error {
var (
i int64
err error
)
switch a {
default:
i = int64(a)
case Len1:
var v int8
err = binary.Read(r, binary.BigEndian, &v)
i = int64(v)
case Len2:
var v int16
err = binary.Read(r, binary.BigEndian, &v)
i = int64(v)
case Len4:
var v int32
err = binary.Read(r, binary.BigEndian, &v)
i = int64(v)
case Len8:
var v int64
err = binary.Read(r, binary.BigEndian, &v)
i = int64(v)
}
if err != nil {
return err
}
if k := v.Kind(); !isInt(k) {
return expectedType("int", k)
}
v.SetInt(-1 - int64(i))
return nil
}
func unmarshalUint(r reader, a byte, v reflect.Value) error {
var (
i uint64
err error
)
switch a {
default:
i = uint64(a)
case Len1:
var v uint8
err = binary.Read(r, binary.BigEndian, &v)
i = uint64(v)
case Len2:
var v uint16
err = binary.Read(r, binary.BigEndian, &v)
i = uint64(v)
case Len4:
var v uint32
err = binary.Read(r, binary.BigEndian, &v)
i = uint64(v)
case Len8:
var v uint64
err = binary.Read(r, binary.BigEndian, &v)
i = uint64(v)
}
if err != nil {
return err
}
switch k := v.Kind(); {
case isUint(k):
v.SetUint(i)
case isInt(k):
v.SetInt(int64(i))
default:
return expectedType("uint/int", k)
}
return nil
}
func isInt(k reflect.Kind) bool {
return k == reflect.Int || k == reflect.Int8 || k == reflect.Int16 || k == reflect.Int32 || k == reflect.Int64
}
func isUint(k reflect.Kind) bool {
return k == reflect.Uint || k == reflect.Uint8 || k == reflect.Uint16 || k == reflect.Uint32 || k == reflect.Uint64
}
func isFloat(k reflect.Kind) bool {
return k == reflect.Float32 || k == reflect.Float64
}
func expectedType(n string, k reflect.Kind) error {
return fmt.Errorf("expected %s, got %s", n, k)
} | unmarshal.go | 0.529507 | 0.425367 | unmarshal.go | starcoder |
package models
import "fmt"
// BoardWidth in cells
const BoardWidth = 16
// BoardHeight in cells
const BoardHeight = 16
// Grid is a two-dimensional array of bytes, representing the Grid state
// The lower left corner has coordinates 0, 0
type Grid [BoardWidth][BoardHeight]Cell
// Board rerpesents a game board:
// - P1, P2 - reference to players
// - Grid - a two dimensional array, containing the board state
type Board struct {
P1 *Player
P2 *Player
Grid *Grid
}
const (
// NoWinner if the game continues
NoWinner = iota
// Draw if reached end game and the game is draw
Draw
// P1Wins if player 1 wins
P1Wins
// P2Wins if player 2 wins
P2Wins
)
// Winner representation, enum above shows possible values
type Winner byte
// GetCell the value of a board cell
func (b *Board) GetCell(p Position) Cell {
return b.Grid[p.X][p.Y]
}
func (b *Board) setCell(p Position, value Cell) {
b.Grid[p.X][p.Y] = value
}
// Advance the game 1 move
// Returns a Winner and a Board
// This is a comment
func (b *Board) Advance() (Winner, *Board) {
b.P1.PrevDirection = b.P1.Direction
b.P2.PrevDirection = b.P2.Direction
p1neck := b.findCell(P1Head)
p1head := p1neck.nextPosition(b.P1.Direction)
p2neck := b.findCell(P2Head)
p2head := p2neck.nextPosition(b.P2.Direction)
p1crash := false
p2crash := false
if p1head == p2head {
p1crash = true
p2crash = true
b.setCell(p1head, Crash)
} else {
if b.isOutside(p1head) || b.GetCell(p1head) != EmptyCell {
p1crash = true
b.setCell(p1neck, Crash)
} else {
b.setCell(p1neck, P1Tail)
b.setCell(p1head, P1Head)
}
if b.isOutside(p2head) || b.GetCell(p2head) != EmptyCell {
p2crash = true
b.setCell(p2neck, Crash)
} else {
b.setCell(p2neck, P2Tail)
b.setCell(p2head, P2Head)
}
}
if p1crash && p2crash {
return Draw, b
} else if p1crash && !p2crash {
return P2Wins, b
} else if !p1crash && p2crash {
return P1Wins, b
} else {
return NoWinner, b
}
}
func (b *Board) isOutside(p Position) bool {
return p.X < 0 || p.X >= BoardWidth || p.Y < 0 || p.Y >= BoardHeight
}
// findsCell iterates through the board and finds the cell coordinates
// works only with P1Head or P2Head cell values
func (b *Board) findCell(c Cell) (p Position) {
for i := 0; i < BoardWidth; i++ {
for j := 0; j < BoardHeight; j++ {
if b.GetCell(Position{X: i, Y: j}) == c {
p.X = i
p.Y = j
return
}
}
}
panic(fmt.Sprintf("Could not find cell %d", c))
}
// InitialBoard creates an initial board
func InitialBoard() *Board {
P1 := Player{Name: "Player 1", Direction: Right, PrevDirection: Right}
P2 := Player{Name: "Player 2", Direction: Left, PrevDirection: Left}
Grid := new(Grid)
b := new(Board)
b.P1 = &P1
b.P2 = &P2
b.Grid = Grid
for i := range b.Grid {
for j := range b.Grid[i] {
b.Grid[i][j] = EmptyCell
}
}
b.Grid[0][BoardHeight/2+BoardHeight%2] = P1Head
b.Grid[BoardWidth-1][BoardHeight/2+BoardHeight%2] = P2Head
return b
} | models/board.go | 0.709824 | 0.539772 | board.go | starcoder |
package stripe
import "encoding/json"
// RecipientTransferDestinationType consts represent valid recipient_transfer destinations.
type RecipientTransferDestinationType string
// RecipientTransferFailCode is the list of allowed values for the recipient_transfer's failure code.
// Allowed values are "insufficient_funds", "account_closed", "no_account",
// "invalid_account_number", "debit_not_authorized", "bank_ownership_changed",
// "account_frozen", "could_not_process", "bank_account_restricted", "invalid_currency".
type RecipientTransferFailCode string
// RecipientTransferSourceType is the list of allowed values for the recipient_transfer's source_type field.
// Allowed values are "alipay_account", bank_account", "bitcoin_receiver", "card".
type RecipientTransferSourceType string
// RecipientTransferStatus is the list of allowed values for the recipient_transfer's status.
// Allowed values are "paid", "pending", "in_transit", "failed".
type RecipientTransferStatus string
// RecipientTransferType is the list of allowed values for the recipient_transfer's type.
// Allowed values are "bank_account" or "card".
type RecipientTransferType string
const (
// RecipientTransferDestinationBankAccount is a constant representing a recipient_transfer destination
// which is a bank account.
RecipientTransferDestinationBankAccount RecipientTransferDestinationType = "bank_account"
// RecipientTransferDestinationCard is a constant representing a recipient_transfer destination
// which is a card.
RecipientTransferDestinationCard RecipientTransferDestinationType = "card"
)
// RecipientTransferMethodType represents the type of recipient_transfer
type RecipientTransferMethodType string
const (
// RecipientTransferMethodInstant is a constant representing an instant recipient_transfer
RecipientTransferMethodInstant RecipientTransferMethodType = "instant"
// RecipientTransferMethodStandard is a constant representing a standard recipient_transfer
RecipientTransferMethodStandard RecipientTransferMethodType = "standard"
)
// RecipientTransferDestination describes the destination of a RecipientTransfer.
// The Type should indicate which object is fleshed out
// For more details see https://stripe.com/docs/api/go#recipient_transfer_object
type RecipientTransferDestination struct {
BankAccount *BankAccount `json:"-"`
Card *Card `json:"-"`
ID string `json:"id"`
Type RecipientTransferDestinationType `json:"object"`
}
// RecipientTransfer is the resource representing a Stripe recipient_transfer.
// For more details see https://stripe.com/docs/api#recipient_transfers.
type RecipientTransfer struct {
Amount int64 `json:"amount"`
AmountReversed int64 `json:"amount_reversed"`
BalanceTransaction *Transaction `json:"balance_transaction"`
Bank *BankAccount `json:"bank_account"`
Card *Card `json:"card"`
Created int64 `json:"created"`
Currency Currency `json:"currency"`
Date int64 `json:"date"`
Desc string `json:"description"`
Dest RecipientTransferDestination `json:"destination"`
FailCode RecipientTransferFailCode `json:"failure_code"`
FailMsg string `json:"failure_message"`
ID string `json:"id"`
Live bool `json:"livemode"`
Meta map[string]string `json:"metadata"`
Method RecipientTransferMethodType `json:"method"`
Recipient *Recipient `json:"recipient"`
Reversals *ReversalList `json:"reversals"`
Reversed bool `json:"reversed"`
SourceTx *TransactionSource `json:"source_transaction"`
SourceType RecipientTransferSourceType `json:"source_type"`
Statement string `json:"statement_descriptor"`
Status RecipientTransferStatus `json:"status"`
Type RecipientTransferType `json:"type"`
}
// UnmarshalJSON handles deserialization of a RecipientTransfer.
// This custom unmarshaling is needed because the resulting
// property may be an id or the full struct if it was expanded.
func (t *RecipientTransfer) UnmarshalJSON(data []byte) error {
type transfer RecipientTransfer
var tb transfer
err := json.Unmarshal(data, &tb)
if err == nil {
*t = RecipientTransfer(tb)
} else {
// the id is surrounded by "\" characters, so strip them
t.ID = string(data[1 : len(data)-1])
}
return nil
}
// UnmarshalJSON handles deserialization of a RecipientTransferDestination.
// This custom unmarshaling is needed because the specific
// type of destination it refers to is specified in the JSON
func (d *RecipientTransferDestination) UnmarshalJSON(data []byte) error {
type dest RecipientTransferDestination
var dd dest
err := json.Unmarshal(data, &dd)
if err == nil {
*d = RecipientTransferDestination(dd)
switch d.Type {
case RecipientTransferDestinationBankAccount:
err = json.Unmarshal(data, &d.BankAccount)
case RecipientTransferDestinationCard:
err = json.Unmarshal(data, &d.Card)
}
if err != nil {
return err
}
} else {
// the id is surrounded by "\" characters, so strip them
d.ID = string(data[1 : len(data)-1])
}
return nil
}
// MarshalJSON handles serialization of a RecipientTransferDestination.
// This custom marshaling is needed because we can only send a string
// ID as a destination, even though it can be expanded to a full
// object when retrieving
func (d *RecipientTransferDestination) MarshalJSON() ([]byte, error) {
return json.Marshal(d.ID)
} | recipienttransfer.go | 0.6488 | 0.460713 | recipienttransfer.go | starcoder |
package array
import (
"sort"
)
// Equal checks whether two slices a and b are identical (true) or not (false)
// If importing external library is allowed, use cmp.Equal instead
func Equal(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
// Mean calculates the average of array a
func Mean(a []int) float64 {
var sum float64
for _, v := range a {
sum += float64(v)
}
return sum / float64(len(a))
}
// Median calculates the middle value of array a
func Median(a []int) float64 {
sort.Ints(a)
if len(a)%2 == 1 {
midIndex := len(a) / 2
return float64(a[midIndex])
} else {
midIndex1 := len(a)/2 - 1
midIndex2 := midIndex1 + 1
sum := a[midIndex1] + a[midIndex2]
return float64(sum) / 2
}
}
// Min finds the minimum value of array a
func Min(a []int) (minValue int) {
if len(a) == 0 {
return 0
}
minValue = a[0]
for _, v := range a {
if v < minValue {
minValue = v
}
}
return minValue
}
// Max finds the maximum value of array a
func Max(a []int) (maxValue int) {
if len(a) == 0 {
return 0
}
maxValue = a[0]
for _, v := range a {
if v > maxValue {
maxValue = v
}
}
return maxValue
}
// Reverse returns the array a in reversed order
func Reverse(a []int) []int {
reversed := make([]int, len(a))
copy(reversed, a)
for i := 0; i < len(reversed)/2; i++ {
temp := reversed[i]
reversed[i] = reversed[len(a)-1-i]
reversed[len(a)-1-i] = temp
}
return reversed
}
// Uniq returns distinct elements from the array a while preserving order
func Uniq(a []int) (result []int) {
if len(a) == 0 {
return []int{}
}
distinct := make(map[int]bool)
for _, v := range a {
distinct[v] = true
}
// This is needed to preserve order
for _, v := range a {
if distinct[v] {
result = append(result, v)
delete(distinct, v)
}
}
return result
}
// Union merges set a and b while preserving order
func Union(a, b []int) (result []int) {
if len(a) == 0 && len(b) == 0 {
return []int{}
}
counter := make(map[int]bool)
for _, v := range a {
counter[v] = true
}
for _, v := range b {
counter[v] = true
}
// This is needed to preserve order
for _, v := range a {
if counter[v] {
result = append(result, v)
delete(counter, v)
}
}
for _, v := range b {
if counter[v] {
result = append(result, v)
delete(counter, v)
}
}
return result
}
// Intersection finds distinct common elements between a and b while preserving order
func Intersection(a, b []int) (result []int) {
if len(a) == 0 && len(b) == 0 {
return []int{}
}
common := make(map[int]bool)
result = []int{}
for _, v := range b {
common[v] = true
}
for _, v := range a {
if common[v] {
result = append(result, v)
delete(common, v)
}
}
return result
}
// Difference finds distinct uncommon elements between a and b while preserving order
func Difference(a, b []int) (result []int) {
if len(a) == 0 && len(b) == 0 {
return []int{}
}
common := make(map[int]int)
result = []int{}
const (
NewElement = 0
CommonElement = 1
OnlyInA = 2
OnlyInB = 3
)
for _, v := range a {
common[v] = OnlyInA
}
for _, v := range b {
if common[v] == OnlyInA {
common[v] = CommonElement
} else if common[v] == NewElement {
common[v] = OnlyInB
}
}
// This is needed to preserve order
for _, v := range a {
if common[v] == OnlyInA {
result = append(result, v)
delete(common, v)
}
}
for _, v := range b {
if common[v] == OnlyInB {
result = append(result, v)
delete(common, v)
}
}
return result
}
// TODO
func Permutation(a []int) (result [][]int) {
return [][]int{}
}
// TODO
func Combination(a []int) (result [][]int) {
return [][]int{}
} | datastructures/array/array.go | 0.675978 | 0.488405 | array.go | starcoder |
package hll
import (
"math/bits"
"sort"
)
const RHOW_BITS = 6
const RHOW_MASK = uint64(1<<RHOW_BITS) - 1
func encode(sparseIndex uint32, sparseRhoW uint8, p, pPrime uint) uint32 {
mask := (uint32(1) << (pPrime - p)) - 1
if (sparseIndex & mask) != 0 {
return sparseIndex
}
var rhoEncodedFlag uint32
if pPrime >= p+RHOW_BITS {
rhoEncodedFlag = uint32(1) << pPrime
} else {
rhoEncodedFlag = uint32(1) << (p + RHOW_BITS)
}
normalIndex := sparseIndex >> (pPrime - p)
return rhoEncodedFlag | normalIndex<<RHOW_BITS | uint32(sparseRhoW)
}
func computeRhoW(value uint64, bts uint8) uint8 {
// Strip of the index and move the rhoW to a higher order.
w := value << (64 - bts)
// If the rhoW consists only of zeros, return the maximum length of bits + 1.
if w == 0 {
return bts + 1
}
return uint8(bits.LeadingZeros64(w) + 1)
}
// x is a hash code.
func encodeSparseHash(hash uint64, p, pPrime uint) (hashCode uint32) {
sparseIndex := uint32(hash >> (64 - pPrime))
sparseRhoW := computeRhoW(hash, uint8(64-pPrime))
return encode(sparseIndex, sparseRhoW, p, pPrime)
}
// k is an encoded hash.
func decodeSparseHash(k uint64, p, pPrime uint) (idx uint64, rhoW uint8) {
var rhoEncodedFlag uint64
if pPrime >= p+RHOW_BITS {
rhoEncodedFlag = uint64(1) << pPrime
} else {
rhoEncodedFlag = uint64(1) << (p + RHOW_BITS)
}
if k&rhoEncodedFlag == 0 {
return k, 0
}
return ((k ^ rhoEncodedFlag) >> RHOW_BITS) << (pPrime - p), uint8(k & RHOW_MASK)
}
func decodeSparseHashForNormal(k uint64, p, pPrime uint) (idx uint64, rhoW uint8) {
var rhoEncodedFlag uint64
if pPrime >= p+RHOW_BITS {
rhoEncodedFlag = uint64(1) << pPrime
} else {
rhoEncodedFlag = uint64(1) << (p + RHOW_BITS)
}
if k&rhoEncodedFlag == 0 {
return k >> (pPrime - p), computeRhoW(k, uint8(pPrime-p))
}
return (k ^ rhoEncodedFlag) >> RHOW_BITS, uint8((k & RHOW_MASK) + uint64(pPrime) - uint64(p))
}
type mergeElem struct {
index uint64
rho uint8
encoded uint64
}
type u64It func() (uint64, bool)
type mergeElemIt func() (mergeElem, bool)
func makeMergeElemIter(p, pPrime uint, input u64It) mergeElemIt {
firstElem := true
var lastIndex uint64
return func() (mergeElem, bool) {
for {
hashCode, ok := input()
if !ok {
return mergeElem{}, false
}
idx, r := decodeSparseHash(hashCode, p, pPrime)
if !firstElem && idx == lastIndex {
// In the case where the tmp_set is being merged with the sparse_list, the tmp_set
// may contain elements that have the same index value. In this case, they will
// have been sorted so the one with the max rho value will come first. We should
// discard all dupes after the first.
continue
}
firstElem = false
lastIndex = idx
return mergeElem{idx, r, hashCode}, true
}
}
}
// The input should be sorted by hashcode.
func makeU64SliceIt(in []uint64) u64It {
idx := 0
return func() (uint64, bool) {
if idx == len(in) {
return 0, false
}
result := in[idx]
idx++
return result, true
}
}
// Both input iterators must be sorted by hashcode.
func merge(p, pPrime uint, sizeEst uint64, it1, it2 u64It) *sparse {
leftIt := makeMergeElemIter(p, pPrime, it1)
rightIt := makeMergeElemIter(p, pPrime, it2)
left, haveLeft := leftIt()
right, haveRight := rightIt()
output := newSparse(sizeEst)
for haveLeft && haveRight {
var toAppend uint64
if left.index < right.index {
toAppend = left.encoded
left, haveLeft = leftIt()
} else if right.index < left.index {
toAppend = right.encoded
right, haveRight = rightIt()
} else { // The indexes are equal. Keep the one with the highest rho value.
if left.rho > right.rho {
toAppend = left.encoded
} else {
toAppend = right.encoded
}
left, haveLeft = leftIt()
right, haveRight = rightIt()
}
output.Add(toAppend)
}
for haveRight {
output.Add(right.encoded)
right, haveRight = rightIt()
}
for haveLeft {
output.Add(left.encoded)
left, haveLeft = leftIt()
}
return output
}
func toNormal(s *sparse, p, pPrime uint) normal {
m := 1 << p
M := newNormal(uint64(m))
it := s.GetIterator()
for {
k, ok := it()
if !ok {
break
}
idx, r := decodeSparseHashForNormal(k, p, pPrime)
val := maxU8(M.Get(idx), r)
M.Set(idx, val)
}
return M
}
func maxU8(x, y uint8) uint8 {
if x >= y {
return x
}
return y
}
func maxU64(x, y uint64) uint64 {
if x >= y {
return x
}
return y
}
func sortHashcodesByIndex(xs []uint64, p, pPrime uint) {
sort.Sort(uint64Sorter{xs, p, pPrime})
}
type uint64Sorter struct {
xs []uint64
p, pPrime uint
}
func (u uint64Sorter) Len() int {
return len(u.xs)
}
func (u uint64Sorter) Less(i, j int) bool {
iIndex, iRho := decodeSparseHash(u.xs[i], u.p, u.pPrime)
jIndex, jRho := decodeSparseHash(u.xs[j], u.p, u.pPrime)
if iIndex != jIndex {
return iIndex < jIndex
}
return iRho > jRho
}
func (u uint64Sorter) Swap(i, j int) {
u.xs[i], u.xs[j] = u.xs[j], u.xs[i]
} | sparseutil.go | 0.61659 | 0.412885 | sparseutil.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.