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 triedb // A node represents a node in the persistent trie used as an index. type node struct { key byte depth int16 count int32 value Value next *node children *node } // createNode creates a new node. Every node must be created using this function // (or other based on this) in order to maintain the invariants. func createNode(key byte, value Value, next *node, children *node) *node { var d int16 var c int32 if value == nil { c = 0 } else { c = 1 } if next != nil { c += next.count } if children != nil { d = 1 + children.depth c += children.count } else { d = 1 } return &node{key, d, c, value, next, children} } // clear returns nil if the node is empty, or the current node if not func (n *node) clear() *node { if n.value == nil && n.next == nil && n.children == nil { return nil } return n } // createLeaf creates a new node with no children and no siblings. func createLeaf(key byte, value Value) *node { return createNode(key, value, nil, nil) } // getKey returns the byte at the current position and the last index for the provided key and position func getKey(key []byte, pos int) (k byte, last int) { last = len(key) - 1 if pos >= last { panic("Position exceeded") } k = key[pos] return } // get returns the value for a key slice, if any. func (n *node) get(key []byte, pos int) Value { k, last := getKey(key, pos) // Refer to next sibling if k > n.key { if n.next != nil { return n.next.get(key, pos) } return nil } // Current node if k == n.key { if pos < last { if n.children != nil { return n.children.get(key, pos+1) } return nil } if pos == last { return n.value } } // It was for a previous sibling return nil } // setNext creates a new node with the provided next sibling pointer if it is different from the current one. func (n *node) setNext(next *node) *node { if n.next == next { return n } return createNode(n.key, n.value, next, n.children) } // setChildren creates a new node with the provided first sibling pointer if it is different from the current one. func (n *node) setChildren(children *node) *node { if n.children == children { return n } return createNode(n.key, n.value, n.next, children) } // createSibling creates a new sibling node. func (n *node) createSibling(key []byte, pos int, value Value) *node { k, last := getKey(key, pos) prev := k < n.key // If no value is provided it's done. if value == nil { if prev { return n } else { return nil } } // Calculate next pointer var next *node if prev { next = n } else { next = nil } // If we are not at the end of the key, create, complete and return an intermediate node if pos < last { return createNode(k, nil, next, nil).set(key, pos, value) } // End of the key, create and return a sibling node. return createNode(k, value, next, nil) } // set creates a new node with the provided value for the provided key slice if it is different from the current one. func (n *node) set(key []byte, pos int, value Value) *node { k, last := getKey(key, pos) // It is for a previous sibling if k < n.key { // We create a previous sibling node if needed return n.createSibling(key, pos, value) } // Next sibling if k > n.key { var next *node if n.next != nil { next = n.next.set(key, pos, value) } else { next = n.createSibling(key, pos, value) } return n.setNext(next).clear() } // Current node if k == n.key { if pos < last { var children *node if n.children != nil { children = n.children } else { if value == nil { return n // Unmodified } children = createNode(key[pos+1], nil, nil, nil) } return n.setChildren(children.set(key, pos+1, value)).clear() } else { // this is the node to change if n.value == value { return n // Unmodified } else { return createNode(n.key, value, n.next, n.children).clear() } } } panic("Unreachable") } // remove clears the value for a key, removing the nodes that are not needed any more. func (n *node) remove(key []byte, pos int) *node { return n.set(key, pos, nil) }
node.go
0.691497
0.472683
node.go
starcoder
package mathx import "math" // Sum returns the sum of values of the provided list. func Sum(ff []float64) float64 { var sum float64 for _, v := range ff { var isInf = math.IsInf(v, 1) || math.IsInf(v, -1) if isInf || math.IsNaN(v) { break } sum += v } return sum } // SumInt returns the sum of values of the provided list. func SumInt(ii []int) int { var sum int for _, v := range ii { sum += v } return sum } // SumArSeq returns the sum of first n elements in the arithmetic sequence a + i×d. // a is the element in the sequence // d is the step in the sequence func SumArSeq(a, d float64, n int) float64 { var nf = float64(n) var k = nf / 2 return nf*a + k*d*(nf-1) } // SumGeomSeq returns the sum of first n elements in the gemetric sequence a×qⁿ func SumGeomSeq(a, q float64, n int) float64 { var nf = float64(n) if q == 1 { return nf * a } var qp = math.Pow(q, nf) return a * (qp - 1) / (q - 1) } // Seq returns the a slice of values from arithmetic sequence [start...end] with step. func Seq(start, end, step float64) []float64 { var n = int((end - start) / step) if n < 0 { panic("infinite sequence") } var vv = make([]float64, n) for i := 0; i < n; i++ { var a = float64(n) vv[i] = start + a*step } return vv } // Grid returns a slice of n values [start...end]. func Grid(start, end float64, n int) []float64 { var step = (start - end) / float64(n) return Seq(start, end, step) } // Tabulate applies provided function to each value of the provided slice // and returns the result in an another slice. func Tabulate(vv []float64, fn func(float64) float64, opts ...Option) []float64 { var tb F2 = func(_, x float64) float64 { return fn(x) } return Scan(0, vv, tb, opts...) } // F2 is a (f64, f64) -> f64 type F2 = func(acc, v float64) float64 // Fold applies provided function: acc2 = fn(acc1, v_i) in v_i -> vv func Fold(acc float64, vv []float64, fn F2) float64 { for _, v := range vv { acc = fn(acc, v) } return acc } // Scan do the same operation, as fold, but it returns intermediate results of applied function. // To avoid allocation you can provide a []float64 buffer using WithBuf option. func Scan(acc float64, vv []float64, fn F2, opts ...Option) []float64 { if len(vv) == 0 { return nil } var cfg config for _, setOpt := range opts { setOpt(&cfg) } var res = cfg.vector var n = len(res) if n == 0 { res = make([]float64, len(vv)) } switch { case n != len(vv): res = scanAppend(acc, vv, res, fn) default: scan(acc, vv, res, fn) } return res } func scan(acc float64, vv, dst []float64, fn F2) { _ = dst[len(vv)-1] for i, v := range vv { acc = fn(acc, v) dst[i] = acc } } func scanAppend(acc float64, vv, dst []float64, fn F2) []float64 { dst = dst[:0] for _, v := range vv { acc = fn(acc, v) dst = append(dst, acc) } return dst }
seq.go
0.756358
0.529568
seq.go
starcoder
package resize import ( "image" "math" "image/color" ) func (r *Resizer) NearestNeighbor(width uint, height uint) (image.Image) { pixelsX := float32(r.img.Bounds().Max.X) / float32(width) pixelsY := float32(r.img.Bounds().Max.Y) / float32(height) newImage := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) for i := 0 ; i < int(width); i++ { for k := 0 ; k < int(height); k++ { pixelWidth := float32(i) * pixelsX pixelHeight := float32(k) * pixelsY if pixelWidth > float32(r.img.Bounds().Max.X) { pixelWidth = float32(r.img.Bounds().Max.X) } if pixelHeight > float32(r.img.Bounds().Max.Y) { pixelHeight = float32(r.img.Bounds().Max.Y) } red, green, blue, alpha := r.img.At(int(pixelWidth), int(pixelHeight)).RGBA() newImage.Set(i, k, color.RGBA{uint8(red / 257), uint8(green / 257), uint8(blue / 257), uint8(alpha / 257)}) } } return newImage } func (resizer *Resizer) Supersample(width uint, height uint) (image.Image){ pixelsX := float32(resizer.img.Bounds().Max.X) / float32(width) pixelsY := float32(resizer.img.Bounds().Max.Y) / float32(height) newImage := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) radiusX := float32(math.Ceil(float64(pixelsX))) / 2 radiusY := float32(math.Ceil(float64(pixelsY))) / 2 arraySize := math.Ceil(float64((radiusY * 2 + 1) * (radiusX * 2 + 1))) var r []uint32 var g []uint32 var b []uint32 var a []uint32 for j := 0 ; j < int(arraySize) ; j++ { r = append(r, 0) g = append(g, 0) b = append(b, 0) a = append(a, 0) } for i := 0 ; i < int(width); i++ { for k := 0 ; k < int(height); k++ { pixelWidth := float32(i) * pixelsX pixelHeight := float32(k) * pixelsY if pixelWidth > float32(resizer.img.Bounds().Max.X) { pixelWidth = float32(resizer.img.Bounds().Max.X) } if pixelHeight > float32(resizer.img.Bounds().Max.Y) { pixelHeight = float32(resizer.img.Bounds().Max.Y) } count := 0 for ii := pixelWidth - radiusX ; ii < pixelWidth + radiusX + 1 ; ii++ { for kk := pixelHeight - radiusY ; kk < pixelHeight + radiusY + 1 ; kk++ { pw := ii ph := kk if pw < 0 { pw = 0 } if pw > float32(resizer.img.Bounds().Max.X) { pw = float32(resizer.img.Bounds().Max.X) } if ph < 0 { ph = 0 } if ph > float32(resizer.img.Bounds().Max.Y) { ph = float32(resizer.img.Bounds().Max.Y) } ri, gi, bi, ai := resizer.img.At(int(pw), int(ph)).RGBA() r[count] = ri g[count] = gi b[count] = bi a[count] = ai count++ } } red := sum(r) / uint32(arraySize) green := sum(g) / uint32(arraySize) blue := sum(b) / uint32(arraySize) alpha := sum(a) / uint32(arraySize) newImage.Set(i, k, color.RGBA{uint8(red / 257), uint8(green / 257), uint8(blue / 257), uint8(alpha / 257)}) } } return newImage } func sum(input []uint32) uint32 { var sum uint32 = 0 for _, i := range input { sum += i } return sum }
algorithmic.go
0.683736
0.492798
algorithmic.go
starcoder
package traverser import ( "fmt" "reflect" ) // New traversal code is derivative of https://gist.github.com/hvoecking/10772475 // MIT License; Copyright (c) 2014 <NAME> - See LICENSE for full license const ( opNoop = iota opSet opUnset opSkip opSplice ) // Traverser is the main type and contains the Map & Node callbacks to be used. // Map will be called each time a Map type is encountered // Node will be called for each traversable element // Accept will be called each time a traversal is made type Traverser struct { Map func(keys []string, key string, data reflect.Value) Node func(keys []string, data reflect.Value) (Op, error) Accept func(keys []string, data reflect.Value) (Op, error) } // Op represents an operation to perform on a value passed to the Node callback. // It is used to skip, mutate and handle error conditions. type Op struct { op int val reflect.Value } // Traverse is the entrypoint for recursive traversal of the given reflect.Value. // reflect.Value is used to support both maps and lists at the root as interface{} is not compatible with []interface{} func (gt *Traverser) Traverse(original reflect.Value) (reflect.Value, error) { if !original.IsValid() { return reflect.Value{}, nil } copy := reflect.New(original.Type()).Elem() _, err := gt.traverse(copy, original, []string{}) return copy, err } func (gt *Traverser) traverse(copy, original reflect.Value, keys []string) (Op, error) { if gt.Accept != nil && len(keys) > 0 { op, _ := gt.Accept(keys, copy) if op.op == opSkip { return Noop() } } switch original.Kind() { case reflect.Ptr: originalValue := original.Elem() if !originalValue.IsValid() { return Noop() } copy.Set(reflect.New(originalValue.Type())) return gt.traverse(copy.Elem(), originalValue, keys) case reflect.Interface: originalValue := original.Elem() if !originalValue.IsValid() { return Noop() } copyValue := reflect.New(originalValue.Type()).Elem() op, err := gt.traverse(copyValue, originalValue, keys) copy.Set(copyValue) return op, err case reflect.Struct: for i := 0; i < original.NumField(); i++ { if original.Field(i).CanSet() { op, err := gt.traverse(copy.Field(i), original.Field(i), append(keys, original.Type().Field(i).Name)) if err != nil { return op, err } } } if gt.Node != nil { return gt.Node(keys, original) } case reflect.Slice: copy.Set(reflect.MakeSlice(original.Type(), original.Len(), original.Cap())) ci := -1 for i := 0; i < original.Len(); i++ { ci++ copyValue := copy.Interface().([]interface{}) op, err := gt.traverse(copy.Index(ci), original.Index(i), append(keys, fmt.Sprintf("%d", i))) if err != nil { return op, err } if op.op == opSet { copyValue[i] = op.val.Interface() copy.Set(reflect.ValueOf(copyValue)) } else if op.op == opUnset { copy.Set(reflect.ValueOf(append(copyValue[:ci], copyValue[ci+1:]...))) ci-- } else if op.op == opSplice { splice, ok := op.val.Interface().([]interface{}) if !ok { return ErrorNoop(fmt.Errorf("only slices can be spliced")) } copyValue = append(copyValue[:ci], append(splice, copyValue[ci+1:]...)...) copy.Set(reflect.ValueOf(copyValue)) ci += len(splice) - 1 } } if gt.Node != nil { return gt.Node(keys, original) } case reflect.Map: copy.Set(reflect.MakeMap(original.Type())) for _, key := range original.MapKeys() { originalValue := original.MapIndex(key) copyValue := reflect.New(originalValue.Type()).Elem() keyString := fmt.Sprintf("%v", key) if gt.Map != nil { gt.Map(keys, keyString, originalValue) } op, err := gt.traverse(copyValue, originalValue, append(keys, keyString)) copy.SetMapIndex(key, copyValue) if err != nil { return op, err } if op.op == opSet || op.op == opUnset { copy.SetMapIndex(key, op.val) } } if gt.Node != nil { return gt.Node(keys, original) } default: copy.Set(original) if gt.Node != nil { return gt.Node(keys, original) } } return Noop() } // Set is a helper function that will return an Op to set the key currently being traversed to the given value func Set(v reflect.Value) (Op, error) { return Op{opSet, v}, nil } // Noop is a helper function that will return an Op that doesn't do anything func Noop() (Op, error) { return Op{opNoop, reflect.Value{}}, nil } // Unset is a helper function that will return an Op that unsets the key currently being traversed func Unset() (Op, error) { return Op{opUnset, reflect.Value{}}, nil } func Splice(v reflect.Value) (Op, error) { return Op{opSplice, v}, nil } // ErrorSet is a helper function that will return an Op that sets the key currently being traversed to the given value and returns an error func ErrorSet(err error, v reflect.Value) (Op, error) { return Op{opSet, v}, err } // ErrorUnset is a helper function that will return an Op that unsets the key currently being traversed and returns an error func ErrorUnset(err error) (Op, error) { return Op{opUnset, reflect.Value{}}, err } // ErrorNoop is a helper function that will return an Op that doesn't do anything but return an error func ErrorNoop(err error) (Op, error) { return Op{opNoop, reflect.Value{}}, err } // Skip is a helper function that will return an Op that will skip processing of the current node func Skip() (Op, error) { return Op{opSkip, reflect.Value{}}, nil }
traverser.go
0.767254
0.41739
traverser.go
starcoder
package fontman var consolasRegular24 font = font{ Height: 37, Description: fontDescription{ Family: "Consolas", Style: "Regular", Size: 24, }, Metricts: fontMetrics{ Ascender: 24, Descender: -9, Height: 37, }, Texture: fontTexture{ Name: "t_consolas_regular_24", Width: 256, Height: 256, }, Chars: []fontChar{ {Char: ' ', Width: 18, X: 1, Y: 24, W: 0, H: 0, OX: 0, OY: 0}, {Char: '!', Width: 18, X: 2, Y: 2, W: 4, H: 22, OX: 7, OY: 22}, {Char: '"', Width: 18, X: 7, Y: 2, W: 11, H: 7, OX: 4, OY: 22}, {Char: '#', Width: 18, X: 19, Y: 4, W: 16, H: 20, OX: 1, OY: 20}, {Char: '$', Width: 18, X: 36, Y: 1, W: 14, H: 27, OX: 2, OY: 23}, {Char: '%', Width: 18, X: 51, Y: 2, W: 18, H: 22, OX: 0, OY: 22}, {Char: '&', Width: 18, X: 70, Y: 2, W: 17, H: 22, OX: 1, OY: 22}, {Char: '\'', Width: 18, X: 88, Y: 2, W: 4, H: 7, OX: 7, OY: 22}, {Char: '(', Width: 18, X: 93, Y: 1, W: 9, H: 29, OX: 4, OY: 23}, {Char: ')', Width: 18, X: 103, Y: 1, W: 9, H: 29, OX: 4, OY: 23}, {Char: '*', Width: 18, X: 113, Y: 2, W: 12, H: 13, OX: 3, OY: 22}, {Char: '+', Width: 18, X: 126, Y: 9, W: 15, H: 14, OX: 2, OY: 15}, {Char: ',', Width: 18, X: 142, Y: 19, W: 8, H: 10, OX: 3, OY: 5}, {Char: '-', Width: 18, X: 151, Y: 15, W: 9, H: 2, OX: 4, OY: 9}, {Char: '.', Width: 18, X: 161, Y: 19, W: 5, H: 5, OX: 6, OY: 5}, {Char: '/', Width: 18, X: 167, Y: 2, W: 14, H: 25, OX: 2, OY: 22}, {Char: '0', Width: 18, X: 182, Y: 4, W: 15, H: 20, OX: 1, OY: 20}, {Char: '1', Width: 18, X: 198, Y: 4, W: 14, H: 20, OX: 2, OY: 20}, {Char: '2', Width: 18, X: 213, Y: 4, W: 13, H: 20, OX: 2, OY: 20}, {Char: '3', Width: 18, X: 227, Y: 4, W: 13, H: 20, OX: 3, OY: 20}, {Char: '4', Width: 18, X: 1, Y: 33, W: 16, H: 20, OX: 1, OY: 20}, {Char: '5', Width: 18, X: 18, Y: 33, W: 13, H: 20, OX: 3, OY: 20}, {Char: '6', Width: 18, X: 32, Y: 33, W: 14, H: 20, OX: 2, OY: 20}, {Char: '7', Width: 18, X: 47, Y: 33, W: 14, H: 20, OX: 2, OY: 20}, {Char: '8', Width: 18, X: 62, Y: 33, W: 14, H: 20, OX: 2, OY: 20}, {Char: '9', Width: 18, X: 77, Y: 33, W: 14, H: 20, OX: 2, OY: 20}, {Char: ':', Width: 18, X: 92, Y: 37, W: 4, H: 16, OX: 6, OY: 16}, {Char: ';', Width: 18, X: 97, Y: 37, W: 8, H: 21, OX: 4, OY: 16}, {Char: '<', Width: 18, X: 106, Y: 35, W: 12, H: 18, OX: 2, OY: 18}, {Char: ':', Width: 18, X: 119, Y: 41, W: 13, H: 7, OX: 2, OY: 12}, {Char: '>', Width: 18, X: 133, Y: 35, W: 12, H: 18, OX: 3, OY: 18}, {Char: '?', Width: 18, X: 146, Y: 31, W: 10, H: 22, OX: 5, OY: 22}, {Char: '@', Width: 18, X: 157, Y: 31, W: 18, H: 28, OX: -1, OY: 22}, {Char: 'A', Width: 18, X: 176, Y: 33, W: 19, H: 20, OX: -1, OY: 20}, {Char: 'B', Width: 18, X: 196, Y: 33, W: 13, H: 20, OX: 2, OY: 20}, {Char: 'C', Width: 18, X: 210, Y: 33, W: 15, H: 20, OX: 1, OY: 20}, {Char: 'D', Width: 18, X: 226, Y: 33, W: 15, H: 20, OX: 2, OY: 20}, {Char: 'E', Width: 18, X: 242, Y: 33, W: 12, H: 20, OX: 3, OY: 20}, {Char: 'F', Width: 18, X: 1, Y: 60, W: 12, H: 20, OX: 3, OY: 20}, {Char: 'G', Width: 18, X: 14, Y: 60, W: 15, H: 20, OX: 1, OY: 20}, {Char: 'H', Width: 18, X: 30, Y: 60, W: 14, H: 20, OX: 2, OY: 20}, {Char: 'I', Width: 18, X: 45, Y: 60, W: 13, H: 20, OX: 2, OY: 20}, {Char: 'J', Width: 18, X: 59, Y: 60, W: 11, H: 20, OX: 3, OY: 20}, {Char: 'K', Width: 18, X: 71, Y: 60, W: 15, H: 20, OX: 2, OY: 20}, {Char: 'L', Width: 18, X: 87, Y: 60, W: 12, H: 20, OX: 4, OY: 20}, {Char: 'M', Width: 18, X: 100, Y: 60, W: 16, H: 20, OX: 1, OY: 20}, {Char: 'N', Width: 18, X: 117, Y: 60, W: 14, H: 20, OX: 2, OY: 20}, {Char: 'O', Width: 18, X: 132, Y: 60, W: 16, H: 20, OX: 1, OY: 20}, {Char: 'P', Width: 18, X: 149, Y: 60, W: 14, H: 20, OX: 2, OY: 20}, {Char: 'Q', Width: 18, X: 164, Y: 60, W: 17, H: 26, OX: 1, OY: 20}, {Char: 'R', Width: 18, X: 182, Y: 60, W: 14, H: 20, OX: 3, OY: 20}, {Char: 'S', Width: 18, X: 197, Y: 60, W: 14, H: 20, OX: 2, OY: 20}, {Char: 'T', Width: 18, X: 212, Y: 60, W: 15, H: 20, OX: 1, OY: 20}, {Char: 'U', Width: 18, X: 228, Y: 60, W: 14, H: 20, OX: 2, OY: 20}, {Char: 'V', Width: 18, X: 1, Y: 90, W: 19, H: 20, OX: 0, OY: 20}, {Char: 'W', Width: 18, X: 21, Y: 90, W: 16, H: 20, OX: 1, OY: 20}, {Char: 'X', Width: 18, X: 38, Y: 90, W: 18, H: 20, OX: 0, OY: 20}, {Char: 'Y', Width: 18, X: 57, Y: 90, W: 17, H: 20, OX: 1, OY: 20}, {Char: 'Z', Width: 18, X: 75, Y: 90, W: 14, H: 20, OX: 2, OY: 20}, {Char: '[', Width: 18, X: 90, Y: 87, W: 8, H: 29, OX: 5, OY: 23}, {Char: '\'', Width: 18, X: 99, Y: 88, W: 14, H: 25, OX: 3, OY: 22}, {Char: ']', Width: 18, X: 114, Y: 87, W: 8, H: 29, OX: 5, OY: 23}, {Char: '^', Width: 18, X: 123, Y: 90, W: 15, H: 10, OX: 1, OY: 20}, {Char: '_', Width: 18, X: 139, Y: 114, W: 18, H: 2, OX: 0, OY: -4}, {Char: '`', Width: 18, X: 158, Y: 87, W: 11, H: 7, OX: 0, OY: 23}, {Char: 'a', Width: 18, X: 170, Y: 94, W: 13, H: 16, OX: 2, OY: 16}, {Char: 'b', Width: 18, X: 184, Y: 88, W: 14, H: 22, OX: 3, OY: 22}, {Char: 'c', Width: 18, X: 199, Y: 94, W: 12, H: 16, OX: 2, OY: 16}, {Char: 'd', Width: 18, X: 212, Y: 88, W: 14, H: 22, OX: 2, OY: 22}, {Char: 'e', Width: 18, X: 227, Y: 94, W: 14, H: 16, OX: 2, OY: 16}, {Char: 'f', Width: 18, X: 1, Y: 117, W: 17, H: 22, OX: 0, OY: 22}, {Char: 'g', Width: 18, X: 19, Y: 123, W: 16, H: 22, OX: 1, OY: 16}, {Char: 'h', Width: 18, X: 36, Y: 117, W: 13, H: 22, OX: 3, OY: 22}, {Char: 'i', Width: 18, X: 50, Y: 117, W: 13, H: 22, OX: 3, OY: 22}, {Char: 'j', Width: 18, X: 64, Y: 117, W: 12, H: 28, OX: 2, OY: 22}, {Char: 'k', Width: 18, X: 77, Y: 117, W: 14, H: 22, OX: 3, OY: 22}, {Char: 'l', Width: 18, X: 92, Y: 117, W: 13, H: 22, OX: 3, OY: 22}, {Char: 'm', Width: 18, X: 106, Y: 123, W: 15, H: 16, OX: 2, OY: 16}, {Char: 'n', Width: 18, X: 122, Y: 123, W: 13, H: 16, OX: 3, OY: 16}, {Char: 'o', Width: 18, X: 136, Y: 123, W: 15, H: 16, OX: 1, OY: 16}, {Char: 'p', Width: 18, X: 152, Y: 123, W: 13, H: 22, OX: 3, OY: 16}, {Char: 'q', Width: 18, X: 166, Y: 123, W: 14, H: 22, OX: 2, OY: 16}, {Char: 'r', Width: 18, X: 181, Y: 123, W: 14, H: 16, OX: 3, OY: 16}, {Char: 's', Width: 18, X: 196, Y: 123, W: 12, H: 16, OX: 3, OY: 16}, {Char: 't', Width: 18, X: 209, Y: 118, W: 14, H: 21, OX: 1, OY: 21}, {Char: 'u', Width: 18, X: 224, Y: 123, W: 13, H: 16, OX: 3, OY: 16}, {Char: 'v', Width: 18, X: 1, Y: 156, W: 17, H: 16, OX: 1, OY: 16}, {Char: 'w', Width: 18, X: 19, Y: 156, W: 17, H: 16, OX: 0, OY: 16}, {Char: 'x', Width: 18, X: 37, Y: 156, W: 16, H: 16, OX: 1, OY: 16}, {Char: 'y', Width: 18, X: 54, Y: 156, W: 17, H: 22, OX: 1, OY: 16}, {Char: 'z', Width: 18, X: 72, Y: 156, W: 13, H: 16, OX: 3, OY: 16}, {Char: '{', Width: 18, X: 86, Y: 149, W: 11, H: 29, OX: 3, OY: 23}, {Char: '|', Width: 18, X: 98, Y: 146, W: 3, H: 32, OX: 8, OY: 26}, {Char: '}', Width: 18, X: 102, Y: 149, W: 11, H: 29, OX: 4, OY: 23}, {Char: '~', Width: 18, X: 114, Y: 160, W: 18, H: 6, OX: 0, OY: 12}, }, }
fontman/consolas_regular_24.go
0.596433
0.710748
consolas_regular_24.go
starcoder
package daemon // Daemon interface is a list of the monerod daemon RPC calls, their inputs and outputs, and examples of each. // Many RPC calls use the daemon's JSON RPC interface while others use their own interfaces, as demonstrated below. type Daemon interface { // GetBlockCount Look up how many blocks are in the longest chain known to the node. GetBlockCount() (*GetBlockCountResponse, error) // OnGetBlockHash Look up a block's hash by its height. OnGetBlockHash(req []uint64) (string, error) // GetBlockTemplate Get a block template on which mining a new block. GetBlockTemplate(req *GetBlockTemplateRequest) (*GetBlockTemplateResponse, error) // SubmitBlock Submit a mined block to the network. SubmitBlock(req []string) (*SubmitBlockResponse, error) // GetLastBlockHeader Block header information for the most recent block is easily retrieved with this method. No inputs are needed. GetLastBlockHeader() (*GetLastBlockHeaderResponse, error) // GetBlockHeaderByHash Block header information can be retrieved using either a block's hash or height. // This method includes a block's hash as an input parameter to retrieve basic information about the block. GetBlockHeaderByHash(req *GetBlockHeaderByHashRequest) (*GetBlockHeaderByHashResponse, error) // GetBlockHeaderByHeight Similar to get_block_header_by_hash above. // This method includes a block's height as an input parameter to retrieve basic information about the block. GetBlockHeaderByHeight(req *GetBlockHeaderByHeightRequest) (*GetBlockHeaderByHeightResponse, error) // GetBlockHeadersRange Similar to get_block_header_by_height above, but for a range of blocks. // This method includes a starting block height and an ending block height as parameters to retrieve basic information about the range of blocks. GetBlockHeadersRange(req *GetBlockHeadersRangeRequest) (*GetBlockHeadersRangeResponse, error) // GetBlock Full block information can be retrieved by either block height or hash, like with the above block header calls. // For full block information, both lookups use the same method, but with different input parameters. GetBlock(req *GetBlockRequest) (*GetBlockResponse, error) // GetConnections Retrieve information about incoming and outgoing connections to your node. GetConnections() (*GetConnectionsResponse, error) // GetInfo Retrieve general information about the state of your node and the network. GetInfo() (*GetInfoResponse, error) // HardForkInfo Look up information regarding hard fork voting and readiness. HardForkInfo() (*HardForkInfoResponse, error) // SetBans Ban another node by IP. SetBans(req *SetBansRequest) (*SetBansResponse, error) // GetBans Get list of banned IPs. GetBans() (*GetBansResponse, error) // FlushTxpool Flush tx ids from transaction pool FlushTxpool(req *FlushTxpoolRequest) (*FlushTxpoolResponse, error) // GetOutputHistogram Get a histogram of output amounts. For all amounts (possibly filtered by parameters), gives the number of outputs on the chain for that amount. // RingCT outputs counts as 0 amount. GetOutputHistogram(req *GetOutputHistogramRequest) (*GetOutputHistogramResponse, error) // GetVersion Give the node current version GetVersion() (*GetVersionResponse, error) // GetCoinbaseTxSum Get the coinbase amount and the fees amount for n last blocks starting at particular height GetCoinbaseTxSum(req *GetCoinbaseTxSumRequest) (*GetCoinbaseTxSumResponse, error) // GetFeeEstimate Gives an estimation on fees per byte. GetFeeEstimate(req *GetFeeEstimateRequest) (*GetFeeEstimateResponse, error) // GetAlternateChains Display alternative chains seen by the node. GetAlternateChains() (*GetAlternateChainsResponse, error) // RelayTx Relay a list of transaction IDs. RelayTx(req *RelayTxRequest) (*RelayTxResponse, error) // SyncInfo Get synchronisation informations SyncInfo() (*SyncInfoResponse, error) // GetTxpoolBacklog Get all transaction pool backlog GetTxpoolBacklog() (*GetTxpoolBacklogResponse, error) // GetOutputDistribution Alias: None. GetOutputDistribution(req *GetOutputDistributionRequest) (*GetOutputDistributionResponse, error) } // MoneroRPC interface for client type MoneroRPC interface { Do(method string, req interface{}, res interface{}) error } type daemon struct { client MoneroRPC } // New creates a new daemon client func New(client MoneroRPC) Daemon { return &daemon{ client: client, } } func (d *daemon) GetBlockCount() (*GetBlockCountResponse, error) { res := new(GetBlockCountResponse) err := d.client.Do("get_block_count", nil, res) return res, err } func (d *daemon) OnGetBlockHash(req []uint64) (string, error) { var res string err := d.client.Do("on_get_block_hash", req, &res) return res, err } func (d *daemon) GetBlockTemplate(req *GetBlockTemplateRequest) (*GetBlockTemplateResponse, error) { res := new(GetBlockTemplateResponse) err := d.client.Do("get_block_template", req, res) return res, err } func (d *daemon) SubmitBlock(req []string) (*SubmitBlockResponse, error) { res := new(SubmitBlockResponse) err := d.client.Do("submit_block", &req, res) return res, err } func (d *daemon) GetLastBlockHeader() (*GetLastBlockHeaderResponse, error) { res := new(GetLastBlockHeaderResponse) err := d.client.Do("get_last_block_header", nil, res) return res, err } func (d *daemon) GetBlockHeaderByHash(req *GetBlockHeaderByHashRequest) (*GetBlockHeaderByHashResponse, error) { res := new(GetBlockHeaderByHashResponse) err := d.client.Do("get_block_header_by_hash", req, res) return res, err } func (d *daemon) GetBlockHeaderByHeight(req *GetBlockHeaderByHeightRequest) (*GetBlockHeaderByHeightResponse, error) { res := new(GetBlockHeaderByHeightResponse) err := d.client.Do("get_block_header_by_height", req, res) return res, err } func (d *daemon) GetBlockHeadersRange(req *GetBlockHeadersRangeRequest) (*GetBlockHeadersRangeResponse, error) { res := new(GetBlockHeadersRangeResponse) err := d.client.Do("get_block_headers_range", req, res) return res, err } func (d *daemon) GetBlock(req *GetBlockRequest) (*GetBlockResponse, error) { res := new(GetBlockResponse) err := d.client.Do("get_block", req, res) return res, err } func (d *daemon) GetConnections() (*GetConnectionsResponse, error) { res := new(GetConnectionsResponse) err := d.client.Do("get_connections", nil, res) return res, err } func (d *daemon) GetInfo() (*GetInfoResponse, error) { res := new(GetInfoResponse) err := d.client.Do("get_info", nil, res) return res, err } func (d *daemon) HardForkInfo() (*HardForkInfoResponse, error) { res := new(HardForkInfoResponse) err := d.client.Do("hard_fork_info", nil, res) return res, err } func (d *daemon) SetBans(req *SetBansRequest) (*SetBansResponse, error) { res := new(SetBansResponse) err := d.client.Do("set_bans", req, res) return res, err } func (d *daemon) GetBans() (*GetBansResponse, error) { res := new(GetBansResponse) err := d.client.Do("get_bans", nil, res) return res, err } func (d *daemon) FlushTxpool(req *FlushTxpoolRequest) (*FlushTxpoolResponse, error) { res := new(FlushTxpoolResponse) err := d.client.Do("flush_txpool", req, res) return res, err } func (d *daemon) GetOutputHistogram(req *GetOutputHistogramRequest) (*GetOutputHistogramResponse, error) { res := new(GetOutputHistogramResponse) err := d.client.Do("get_output_histogram", req, res) return res, err } func (d *daemon) GetVersion() (*GetVersionResponse, error) { res := new(GetVersionResponse) err := d.client.Do("get_version", nil, res) return res, err } func (d *daemon) GetCoinbaseTxSum(req *GetCoinbaseTxSumRequest) (*GetCoinbaseTxSumResponse, error) { res := new(GetCoinbaseTxSumResponse) err := d.client.Do("get_coinbase_tx_sum", req, res) return res, err } func (d *daemon) GetFeeEstimate(req *GetFeeEstimateRequest) (*GetFeeEstimateResponse, error) { res := new(GetFeeEstimateResponse) err := d.client.Do("get_fee_estimate", req, res) return res, err } func (d *daemon) GetAlternateChains() (*GetAlternateChainsResponse, error) { res := new(GetAlternateChainsResponse) err := d.client.Do("get_alternate_chains", nil, res) return res, err } func (d *daemon) RelayTx(req *RelayTxRequest) (*RelayTxResponse, error) { res := new(RelayTxResponse) err := d.client.Do("relay_tx", req, res) return res, err } func (d *daemon) SyncInfo() (*SyncInfoResponse, error) { res := new(SyncInfoResponse) err := d.client.Do("sync_info", nil, res) return res, err } func (d *daemon) GetTxpoolBacklog() (*GetTxpoolBacklogResponse, error) { res := new(GetTxpoolBacklogResponse) err := d.client.Do("get_txpool_backlog", nil, res) return res, err } func (d *daemon) GetOutputDistribution(req *GetOutputDistributionRequest) (*GetOutputDistributionResponse, error) { res := new(GetOutputDistributionResponse) err := d.client.Do("get_output_distribution", req, res) return res, err }
daemon/daemon.go
0.646906
0.421611
daemon.go
starcoder
package goop2 import "fmt" const ( tinyNum float64 = 0.01 ) // Solution stores the solution of an optimization problem and associated // metatdata type Solution struct { Values map[uint64]float64 // The objective for the solution Objective float64 // Whether or not the solution is within the optimality threshold Status OptimizationStatus // The optimality gap returned from the solver. For many solvers, this is // the gap between the best possible solution with integer relaxation and // the best integer solution found so far. // Gap float64 } type OptimizationStatus int // OptimizationStatuses const ( OptimizationStatus_LOADED OptimizationStatus = 1 OptimizationStatus_OPTIMAL = 2 OptimizationStatus_INFEASIBLE = 3 OptimizationStatus_INF_OR_UNBD = 4 OptimizationStatus_UNBOUNDED = 5 OptimizationStatus_CUTOFF = 6 OptimizationStatus_ITERATION_LIMIT = 7 OptimizationStatus_NODE_LIMIT = 8 OptimizationStatus_TIME_LIMIT = 9 OptimizationStatus_SOLUTION_LIMIT = 10 OptimizationStatus_INTERRUPTED = 11 OptimizationStatus_NUMERIC = 12 OptimizationStatus_SUBOPTIMAL = 13 OptimizationStatus_INPROGRESS = 14 OptimizationStatus_USER_OBJ_LIMIT = 15 OptimizationStatus_WORK_LIMIT = 16 ) /* ToMessage Description: Translates the code to the text meaning. This comes from the status codes documentation: https://www.gurobi.com/documentation/9.5/refman/optimization_status_codes.html#sec:StatusCodes */ func (os OptimizationStatus) ToMessage() (string, error) { // Converts each of the statuses to a text message that is human readable. switch os { case OptimizationStatus_LOADED: return "Model is loaded, but no solution information is available.", nil case OptimizationStatus_OPTIMAL: return "Model was solved to optimality (subject to tolerances), and an optimal solution is available.", nil case OptimizationStatus_INFEASIBLE: return "Model was proven to be infeasible.", nil case OptimizationStatus_INF_OR_UNBD: return "Model was proven to be either infeasible or unbounded. To obtain a more definitive conclusion, set the DualReductions parameter to 0 and reoptimize.", nil case OptimizationStatus_UNBOUNDED: return "Model was proven to be unbounded. Important note: an unbounded status indicates the presence of an unbounded ray that allows the objective to improve without limit. It says nothing about whether the model has a feasible solution. If you require information on feasibility, you should set the objective to zero and reoptimize.", nil case OptimizationStatus_CUTOFF: return "Optimal objective for model was proven to be worse than the value specified in the Cutoff parameter. No solution information is available.", nil case OptimizationStatus_ITERATION_LIMIT: return "Optimization terminated because the total number of simplex iterations performed exceeded the value specified in the IterationLimit parameter, or because the total number of barrier iterations exceeded the value specified in the BarIterLimit parameter.", nil case OptimizationStatus_NODE_LIMIT: return "Optimization terminated because the total number of branch-and-cut nodes explored exceeded the value specified in the NodeLimit parameter.", nil case OptimizationStatus_TIME_LIMIT: return "Optimization terminated because the time expended exceeded the value specified in the TimeLimit parameter.", nil case OptimizationStatus_SOLUTION_LIMIT: return "Optimization terminated because the number of solutions found reached the value specified in the SolutionLimit parameter.", nil case OptimizationStatus_INTERRUPTED: return "Optimization was terminated by the user.", nil case OptimizationStatus_NUMERIC: return "Optimization was terminated due to unrecoverable numerical difficulties.", nil case OptimizationStatus_SUBOPTIMAL: return "Unable to satisfy optimality tolerances; a sub-optimal solution is available.", nil case OptimizationStatus_INPROGRESS: return "An asynchronous optimization call was made, but the associated optimization run is not yet complete.", nil case OptimizationStatus_USER_OBJ_LIMIT: return "User specified an objective limit (a bound on either the best objective or the best bound), and that limit has been reached.", nil case OptimizationStatus_WORK_LIMIT: return "Optimization terminated because the work expended exceeded the value specified in the WorkLimit parameter.", nil default: return "", fmt.Errorf("The status with value %v is unrecognized.", os) } } // func newSolution(mipSol solvers.MIPSolution) *Solution { // return &Solution{ // vals: mipSol.GetValues(), // Objective: mipSol.GetObj(), // Optimal: mipSol.GetOptimal(), // Gap: mipSol.GetGap(), // } // } // Value returns the value assigned to the variable in the solution func (s *Solution) Value(v *Var) float64 { return s.Values[v.ID] } // IsOne returns true if the value assigned to the variable is an integer, // and assigned to one. This is a convenience method which should not be // super trusted... func (s *Solution) IsOne(v *Var) bool { return (v.Vtype == Integer || v.Vtype == Binary) && s.Value(v) > tinyNum }
solution.go
0.661267
0.481759
solution.go
starcoder
package settings import ( "encoding/json" "fmt" "testing" "github.com/ingrammicro/cio/api/types" "github.com/ingrammicro/cio/utils" "github.com/stretchr/testify/assert" ) // ListDefinitionsMocked test mocked function func ListDefinitionsMocked(t *testing.T, policyDefinitionsIn []*types.PolicyDefinition) []*types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionsIn) assert.Nil(err, "PolicyDefinitions test data corrupted") // call service cs.On("Get", APIPathPolicyDefinitions).Return(dIn, 200, nil) policyDefinitionsOut, err := ds.ListDefinitions() assert.Nil(err, "Error getting policy definitions") assert.Equal(policyDefinitionsIn, policyDefinitionsOut, "ListDefinitions returned different policy definitions") return policyDefinitionsOut } // ListDefinitionsFailErrMocked test mocked function func ListDefinitionsFailErrMocked( t *testing.T, policyDefinitionsIn []*types.PolicyDefinition, ) []*types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionsIn) assert.Nil(err, "PolicyDefinitions test data corrupted") // call service cs.On("Get", APIPathPolicyDefinitions).Return(dIn, 200, fmt.Errorf("mocked error")) policyDefinitionsOut, err := ds.ListDefinitions() assert.NotNil(err, "We are expecting an error") assert.Nil(policyDefinitionsOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyDefinitionsOut } // ListDefinitionsFailStatusMocked test mocked function func ListDefinitionsFailStatusMocked( t *testing.T, policyDefinitionsIn []*types.PolicyDefinition, ) []*types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionsIn) assert.Nil(err, "PolicyDefinitions test data corrupted") // call service cs.On("Get", APIPathPolicyDefinitions).Return(dIn, 499, nil) policyDefinitionsOut, err := ds.ListDefinitions() assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyDefinitionsOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyDefinitionsOut } // ListDefinitionsFailJSONMocked test mocked function func ListDefinitionsFailJSONMocked( t *testing.T, policyDefinitionsIn []*types.PolicyDefinition, ) []*types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", APIPathPolicyDefinitions).Return(dIn, 200, nil) policyDefinitionsOut, err := ds.ListDefinitions() assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyDefinitionsOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyDefinitionsOut } // GetDefinitionMocked test mocked function func GetDefinitionMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID)).Return(dIn, 200, nil) policyDefinitionOut, err := ds.GetDefinition(policyDefinitionIn.ID) assert.Nil(err, "Error getting policy definition") assert.Equal(*policyDefinitionIn, *policyDefinitionOut, "GetDefinition returned different policy definition") return policyDefinitionOut } // GetDefinitionFailErrMocked test mocked function func GetDefinitionFailErrMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID)). Return(dIn, 200, fmt.Errorf("mocked error")) policyDefinitionOut, err := ds.GetDefinition(policyDefinitionIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyDefinitionOut } // GetDefinitionFailStatusMocked test mocked function func GetDefinitionFailStatusMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID)).Return(dIn, 499, nil) policyDefinitionOut, err := ds.GetDefinition(policyDefinitionIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyDefinitionOut } // GetDefinitionFailJSONMocked test mocked function func GetDefinitionFailJSONMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID)).Return(dIn, 200, nil) policyDefinitionOut, err := ds.GetDefinition(policyDefinitionIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyDefinitionOut } // CreateDefinitionMocked test mocked function func CreateDefinitionMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // to json dOut, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Post", APIPathPolicyDefinitions, mapIn).Return(dOut, 200, nil) policyDefinitionOut, err := ds.CreateDefinition(mapIn) assert.Nil(err, "Error creating policy definition") assert.Equal(policyDefinitionIn, policyDefinitionOut, "CreateDefinition returned different policy definition") return policyDefinitionOut } // CreateDefinitionFailErrMocked test mocked function func CreateDefinitionFailErrMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // to json dOut, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Post", APIPathPolicyDefinitions, mapIn).Return(dOut, 200, fmt.Errorf("mocked error")) policyDefinitionOut, err := ds.CreateDefinition(mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyDefinitionOut } // CreateDefinitionFailStatusMocked test mocked function func CreateDefinitionFailStatusMocked( t *testing.T, policyDefinitionIn *types.PolicyDefinition, ) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // to json dOut, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Post", APIPathPolicyDefinitions, mapIn).Return(dOut, 499, nil) policyDefinitionOut, err := ds.CreateDefinition(mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyDefinitionOut } // CreateDefinitionFailJSONMocked test mocked function func CreateDefinitionFailJSONMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Post", APIPathPolicyDefinitions, mapIn).Return(dIn, 200, nil) policyDefinitionOut, err := ds.CreateDefinition(mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyDefinitionOut } // UpdateDefinitionMocked test mocked function func UpdateDefinitionMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID), mapIn).Return(dIn, 200, nil) policyDefinitionOut, err := ds.UpdateDefinition(policyDefinitionIn.ID, mapIn) assert.Nil(err, "Error parsing policy definition metadata") assert.Equal(*policyDefinitionIn, *policyDefinitionOut, "UpdateDefinition returned different policy definition") return policyDefinitionOut } // UpdateDefinitionFailErrMocked test mocked function func UpdateDefinitionFailErrMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID), mapIn). Return(dIn, 200, fmt.Errorf("mocked error")) policyDefinitionOut, err := ds.UpdateDefinition(policyDefinitionIn.ID, mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyDefinitionOut } // UpdateDefinitionFailStatusMocked test mocked function func UpdateDefinitionFailStatusMocked( t *testing.T, policyDefinitionIn *types.PolicyDefinition, ) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID), mapIn).Return(dIn, 499, nil) policyDefinitionOut, err := ds.UpdateDefinition(policyDefinitionIn.ID, mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyDefinitionOut } // UpdateDefinitionFailJSONMocked test mocked function func UpdateDefinitionFailJSONMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) *types.PolicyDefinition { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Put", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID), mapIn).Return(dIn, 200, nil) policyDefinitionOut, err := ds.UpdateDefinition(policyDefinitionIn.ID, mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyDefinitionOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyDefinitionOut } // DeleteDefinitionMocked test mocked function func DeleteDefinitionMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID)).Return(dIn, 200, nil) err = ds.DeleteDefinition(policyDefinitionIn.ID) assert.Nil(err, "Error deleting policy definition") } // DeleteDefinitionFailErrMocked test mocked function func DeleteDefinitionFailErrMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID)). Return(dIn, 200, fmt.Errorf("mocked error")) err = ds.DeleteDefinition(policyDefinitionIn.ID) assert.NotNil(err, "We are expecting an error") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") } // DeleteDefinitionFailStatusMocked test mocked function func DeleteDefinitionFailStatusMocked(t *testing.T, policyDefinitionIn *types.PolicyDefinition) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyDefinitionIn) assert.Nil(err, "PolicyDefinition test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathPolicyDefinition, policyDefinitionIn.ID)).Return(dIn, 499, nil) err = ds.DeleteDefinition(policyDefinitionIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Contains(err.Error(), "499", "Error should contain http code 499") } // ListDefinitionAssignmentsMocked test mocked function func ListDefinitionAssignmentsMocked( t *testing.T, definitionID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyAssignmentsIn) assert.Nil(err, "PolicyAssignments test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinitionAssignments, definitionID)).Return(dIn, 200, nil) policyAssignmentsOut, err := ds.ListAssignments(definitionID) assert.Nil(err, "Error getting policy definitions") assert.Equal(policyAssignmentsIn, policyAssignmentsOut, "ListAssignments returned different policy definitions") return policyAssignmentsOut } // ListDefinitionAssignmentsFailErrMocked test mocked function func ListDefinitionAssignmentsFailErrMocked( t *testing.T, definitionID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyAssignmentsIn) assert.Nil(err, "PolicyAssignments test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinitionAssignments, definitionID)). Return(dIn, 200, fmt.Errorf("mocked error")) policyAssignmentsOut, err := ds.ListAssignments(definitionID) assert.NotNil(err, "We are expecting an error") assert.Nil(policyAssignmentsOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return policyAssignmentsOut } // ListDefinitionAssignmentsFailStatusMocked test mocked function func ListDefinitionAssignmentsFailStatusMocked( t *testing.T, definitionID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // to json dIn, err := json.Marshal(policyAssignmentsIn) assert.Nil(err, "PolicyAssignments test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinitionAssignments, definitionID)).Return(dIn, 499, nil) policyAssignmentsOut, err := ds.ListAssignments(definitionID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(policyAssignmentsOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return policyAssignmentsOut } // ListDefinitionAssignmentsFailJSONMocked test mocked function func ListDefinitionAssignmentsFailJSONMocked( t *testing.T, definitionID string, policyAssignmentsIn []*types.PolicyAssignment, ) []*types.PolicyAssignment { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewPolicyDefinitionService(cs) assert.Nil(err, "Couldn't load policyDefinition service") assert.NotNil(ds, "PolicyDefinition service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", fmt.Sprintf(APIPathPolicyDefinitionAssignments, definitionID)).Return(dIn, 200, nil) policyAssignmentsOut, err := ds.ListAssignments(definitionID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(policyAssignmentsOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return policyAssignmentsOut }
api/settings/policy_definitions_api_mocked.go
0.723114
0.470128
policy_definitions_api_mocked.go
starcoder
package eval import ( "fmt" ) // Context contains the state used by the engine to execute the DSL. var Context *DSLContext type ( // DSLContext is the data structure that contains the DSL execution state. DSLContext struct { // Stack represents the current execution stack. Stack Stack // Errors contains the DSL execution errors for the current expression set. // Errors is an instance of MultiError. Errors error // roots is the list of DSL roots as registered by all loaded DSLs. roots []Root // dslPackages keeps track of the DSL package import paths so the initiator // may skip any callstack frame that belongs to them when computing error // locations. dslPackages []string } // Stack represents the expression evaluation stack. The stack is appended to // each time the initiator executes an expression source DSL. Stack []Expression ) func init() { Reset() } // Reset resets the eval context, mostly useful for tests. func Reset() { Context = &DSLContext{dslPackages: []string{"goa.design/goa/eval"}} } // Register appends a root expression to the current Context root expressions. // Each root expression may only be registered once. func Register(r Root) error { for _, o := range Context.roots { if r.EvalName() == o.EvalName() { return fmt.Errorf("duplicate DSL %s", r.EvalName()) } } Context.dslPackages = append(Context.dslPackages, r.Packages()...) Context.roots = append(Context.roots, r) return nil } // Current returns current evaluation context, i.e. object being currently built // by DSL. func (s Stack) Current() Expression { if len(s) == 0 { return nil } return s[len(s)-1] } // Error builds the error message from the current context errors. func (c *DSLContext) Error() string { if c.Errors != nil { return c.Errors.Error() } return "" } // Roots orders the DSL roots making sure dependencies are last. It returns an // error if there is a dependency cycle. func (c *DSLContext) Roots() ([]Root, error) { // Flatten dependencies for each root rootDeps := make(map[string][]Root, len(c.roots)) rootByName := make(map[string]Root, len(c.roots)) for _, r := range c.roots { sorted := sortDependencies(c.roots, r, func(r Root) []Root { return r.DependsOn() }) length := len(sorted) for i := 0; i < length/2; i++ { sorted[i], sorted[length-i-1] = sorted[length-i-1], sorted[i] } rootDeps[r.EvalName()] = sorted rootByName[r.EvalName()] = r } // Check for cycles for name, deps := range rootDeps { root := rootByName[name] for otherName, otherdeps := range rootDeps { other := rootByName[otherName] if root.EvalName() == other.EvalName() { continue } dependsOnOther := false for _, dep := range deps { if dep.EvalName() == other.EvalName() { dependsOnOther = true break } } if dependsOnOther { for _, dep := range otherdeps { if dep.EvalName() == root.EvalName() { return nil, fmt.Errorf("dependency cycle: %s and %s depend on each other (directly or not)", root.EvalName(), other.EvalName()) } } } } } // Now sort top level DSLs var sorted []Root for _, r := range c.roots { s := sortDependencies(c.roots, r, func(r Root) []Root { return rootDeps[r.EvalName()] }) for _, s := range s { found := false for _, r := range sorted { if r.EvalName() == s.EvalName() { found = true break } } if !found { sorted = append(sorted, s) } } } return sorted, nil } // Record appends an error to the context Errors field. func (c *DSLContext) Record(err *Error) { if c.Errors == nil { c.Errors = MultiError{err} } else { c.Errors = append(c.Errors.(MultiError), err) } } // sortDependencies sorts the depencies of the given root in the given slice. func sortDependencies(roots []Root, root Root, depFunc func(Root) []Root) []Root { seen := make(map[string]bool, len(roots)) var sorted []Root sortDependenciesR(root, seen, &sorted, depFunc) return sorted } // sortDependenciesR sorts the depencies of the given root in the given slice. func sortDependenciesR(root Root, seen map[string]bool, sorted *[]Root, depFunc func(Root) []Root) { for _, dep := range depFunc(root) { if !seen[dep.EvalName()] { seen[root.EvalName()] = true sortDependenciesR(dep, seen, sorted, depFunc) } } *sorted = append(*sorted, root) }
_vendor-20190311020953/goa.design/goa/eval/context.go
0.65202
0.468183
context.go
starcoder
package gotorch // #cgo CFLAGS: -I ${SRCDIR}/cgotorch // #cgo LDFLAGS: -L ${SRCDIR}/cgotorch -Wl,-rpath ${SRCDIR}/cgotorch -lcgotorch // #cgo LDFLAGS: -L ${SRCDIR}/cgotorch/libtorch/lib -Wl,-rpath ${SRCDIR}/cgotorch/libtorch/lib -lc10 -ltorch -ltorch_cpu // #include "cgotorch.h" import "C" import ( "runtime" "sync" "unsafe" ) var ( tensorFinalizersWG = &sync.WaitGroup{} gcPrepared = false ) func setTensorFinalizer(t *C.Tensor) { // We don't want the following conditional and the finalizer using // different gcPrepared values, so we leverage p and closure here. p := gcPrepared if p { tensorFinalizersWG.Add(1) } runtime.SetFinalizer(t, func(t *C.Tensor) { go func() { C.Tensor_Close(*t) if p { tensorFinalizersWG.Done() } }() }) } // FinishGC should be called right after a train/predict loop func FinishGC() { GC() gcPrepared = false } // GC should be called at the beginning inside a train/predict loop func GC() { runtime.GC() if !gcPrepared { gcPrepared = true return } tensorFinalizersWG.Wait() } func mustNil(err *C.char) { if err != nil { msg := C.GoString(err) C.FreeString(err) panic(msg) } } // Tensor wrappers a pointer to C.Tensor type Tensor struct { T *C.Tensor } // RandN returns a tensor filled with standard normal distribution, torch.randn func RandN(shape []int, requireGrad bool) Tensor { rg := 0 if requireGrad { rg = 1 } var t C.Tensor mustNil(C.RandN((*C.int64_t)(unsafe.Pointer(&shape[0])), C.int64_t(len(shape)), C.int64_t(rg), &t)) setTensorFinalizer(&t) return Tensor{&t} } // Empty returns a tensor filled with random number, torch.empty func Empty(shape []int, requireGrad bool) Tensor { rg := 0 if requireGrad { rg = 1 } var t C.Tensor mustNil(C.Empty((*C.int64_t)(unsafe.Pointer(&shape[0])), C.int64_t(len(shape)), C.int64_t(rg), &t)) setTensorFinalizer(&t) return Tensor{&t} } // Zeros initialization, torch.nn.init.zeros_ func Zeros(a Tensor) Tensor { var t C.Tensor mustNil(C.Zeros_(*a.T, &t)) setTensorFinalizer(&t) return Tensor{&t} } // Uniform initialization, torch.nn.init.uniform_ func Uniform(a Tensor) Tensor { var t C.Tensor mustNil(C.Uniform_(*a.T, &t)) setTensorFinalizer(&t) return Tensor{&t} } // KaimingUniform initialization, torch.nn.init.kaiming_uniform_ func KaimingUniform(input Tensor, a float64, fanMode string, nonLinearity string) Tensor { var t C.Tensor mustNil(C.KaimingUniform_(*input.T, C.double(a), C.CString(fanMode), C.CString(nonLinearity), &t)) setTensorFinalizer(&t) return Tensor{&t} } // String returns the Tensor as a string func (a Tensor) String() string { s := C.Tensor_String(*a.T) r := C.GoString(s) C.FreeString(s) return r } // Print the tensor func (a Tensor) Print() { C.Tensor_Print(*a.T) } // Close the tensor func (a *Tensor) Close() { if a.T != nil { C.Tensor_Close(*a.T) a.T = nil } } // Relu returns relu of the tensor func (a *Tensor) Relu() Tensor { var t C.Tensor mustNil(C.Relu(*a.T, &t)) setTensorFinalizer(&t) return Tensor{&t} } // LeakyRelu returns leaky relu of the tensor according to negativeSlope func (a *Tensor) LeakyRelu(negativeSlope float64) Tensor { var t C.Tensor mustNil(C.LeakyRelu(*a.T, C.double(negativeSlope), &t)) setTensorFinalizer(&t) return Tensor{&t} } // Tanh returns tanh of the current tensor func (a Tensor) Tanh() Tensor { var t C.Tensor mustNil(C.Tanh(*a.T, &t)) setTensorFinalizer(&t) return Tensor{&t} } // Sigmoid returns sigmoid of the current tensor func (a Tensor) Sigmoid() Tensor { var t C.Tensor mustNil(C.Sigmoid(*a.T, &t)) setTensorFinalizer(&t) return Tensor{&t} } // Backward compute the gradient of current tensor func (a Tensor) Backward() { C.Tensor_Backward(*a.T) } // Grad returns a reference of the gradient func (a Tensor) Grad() Tensor { t := C.Tensor_Grad(*a.T) setTensorFinalizer(&t) return Tensor{&t} } // MM multiplies each element of the input two tensors func MM(a, b Tensor) Tensor { var t C.Tensor mustNil(C.MM(*a.T, *b.T, &t)) setTensorFinalizer(&t) return Tensor{&t} } // LeakyRelu returns leaky relu of the tensor according to negativeSlope func LeakyRelu(t Tensor, negativeSlope float64) Tensor { return t.LeakyRelu(negativeSlope) } // Relu returns relu of the tensor func Relu(t Tensor) Tensor { return t.Relu() } // Tanh returns tanh of the current tensor func Tanh(t Tensor) Tensor { return t.Tanh() } // Sigmoid returns sigmoid of the current tensor func Sigmoid(t Tensor) Tensor { return t.Sigmoid() } // Sum returns the sum of all elements in the input tensor func Sum(a Tensor) Tensor { var t C.Tensor mustNil(C.Sum(*a.T, &t)) setTensorFinalizer(&t) return Tensor{&t} } // Conv2d does 2d-convolution func Conv2d(input Tensor, weight Tensor, bias Tensor, stride []int, padding []int, dilation []int, groups int) Tensor { var t C.Tensor if bias.T == nil { mustNil( C.Conv2d( *input.T, *weight.T, nil, (*C.int64_t)(unsafe.Pointer(&stride[0])), C.int64_t(len(stride)), (*C.int64_t)(unsafe.Pointer(&padding[0])), C.int64_t(len(padding)), (*C.int64_t)(unsafe.Pointer(&dilation[0])), C.int64_t(len(dilation)), C.int64_t(groups), &t)) setTensorFinalizer(&t) return Tensor{&t} } mustNil( C.Conv2d( *input.T, *weight.T, *bias.T, (*C.int64_t)(unsafe.Pointer(&stride[0])), C.int64_t(len(stride)), (*C.int64_t)(unsafe.Pointer(&padding[0])), C.int64_t(len(padding)), (*C.int64_t)(unsafe.Pointer(&dilation[0])), C.int64_t(len(dilation)), C.int64_t(groups), &t)) setTensorFinalizer(&t) return Tensor{&t} } // ConvTranspose2d does 2d-fractionally-strided convolution func ConvTranspose2d( input, weight, bias Tensor, stride, padding, outputPadding []int, groups int, dilation []int) Tensor { var cbias, t C.Tensor if bias.T != nil { cbias = *bias.T } mustNil(C.ConvTranspose2d( *input.T, *weight.T, cbias, (*C.int64_t)(unsafe.Pointer(&stride[0])), C.int64_t(len(stride)), (*C.int64_t)(unsafe.Pointer(&padding[0])), C.int64_t(len(padding)), (*C.int64_t)(unsafe.Pointer(&outputPadding[0])), C.int64_t(len(outputPadding)), C.int64_t(groups), (*C.int64_t)(unsafe.Pointer(&dilation[0])), C.int64_t(len(dilation)), &t)) setTensorFinalizer(&t) return Tensor{&t} }
tensor.go
0.697403
0.427935
tensor.go
starcoder
package utilsys import "math/big" // BayesFactor describes something which can alter our prediction // about something by a given factor. It is stateful and only // used for a single actor in a single world. type BayesFactor interface { // Attached is called once to tell the factor the world and actor // it is operating within. Typically the factor will store more // strictly typed representations. Attached(world, actor interface{}) // Factor returns how much information was gained by this factor. // If this factor is not informative, this will return // `big.NewRat(1, 1)`. If this increases the probability of success // by a factor of 2, this returns `big.NewRat(2, 1)`. If it decreases // the odds of success by a factor of 2, this returns `big.NewRat(1, 2)`. Factor() *big.Rat } // BayesFactorBuilder acts as a constructor for BayesFactors, since we need // one BayesFactor per actor. Typically stateless. type BayesFactorBuilder interface { // Build a new BayesFactor not attached yet. Build() BayesFactor } type bayesScorer struct { prior *big.Rat factors []BayesFactor } func (s *bayesScorer) Attached(world, actor interface{}) { for _, factor := range s.factors { factor.Attached(world, actor) } } func (s *bayesScorer) Score() float64 { res := big.NewRat(1, 1).Set(s.prior) for _, factor := range s.factors { res.Mul(res, factor.Factor()) } num := res.Num() denom := res.Denom() resultScore := big.NewFloat(0) resultScore.SetInt(big.NewInt(0).Add(num, denom)) resultScore.Quo(big.NewFloat(0).SetInt(num), resultScore) f, _ := resultScore.Float64() return f } // BayesScorer is a type of ScorerBuilder that assumes that the utility // of the action is 1, but it only succeeds probabilistically. It has // some general chance at success, such as 1 success per 4 failures. It // also has a set of things which alter its odds of success based on the // world, such as "succeeds twice as often when Y is researched" in order // to produce the final probability of succeeds. type BayesScorer struct { prior *big.Rat factors []BayesFactorBuilder } func (s BayesScorer) Build() Scorer { builtFactors := make([]BayesFactor, len(s.factors)) for idx, builder := range s.factors { builtFactors[idx] = builder.Build() } return &bayesScorer{ prior: s.prior, factors: builtFactors, } } // NewBayesScorer produces a ScorerBuilder that has a score of 1 on the action, // but the action only succeeds probabilistically. The estimate of the odds of // success is prior. Note that prior should NOT be interpreted as a fraction, // e.g., 3/5. Instead, it's interpreted such that the numerator is the number of // successes and the denominator is the number of failures. so "3/9" should be // interpreted as 3 successes to 9 failures. A "1/1" prior means 1 success to // 1 failure, aka a 50% chance of success. func NewBayesScorer(prior *big.Rat, factors []BayesFactorBuilder) ScorerBuilder { if prior == nil { panic("prior cannot be nil") } if len(factors) == 0 { panic("factors cannot be empty") } return BayesScorer{ prior: prior, factors: factors, } }
pkg/utilsys/bayes_scorer.go
0.756987
0.443841
bayes_scorer.go
starcoder
package metrics import ( "sync" "time" ) // Meters count events to produce exponentially-weighted moving average rates // at one-, five-, and fifteen-minutes and a mean rate. type Meter interface { Clear() Count() int64 Mark(int64) Rate1() float64 Rate5() float64 Rate15() float64 RateMean() float64 Snapshot() Meter } // GetOrRegisterMeter returns an existing Meter or constructs and registers a // new StandardMeter. func GetOrRegisterMeter(name string, r Registry) Meter { if nil == r { r = DefaultRegistry } return r.GetOrRegister(name, NewMeter).(Meter) } // NewMeter constructs a new StandardMeter and launches a goroutine. func NewMeter() Meter { if UseNilMetrics { return NilMeter{} } m := newStandardMeter() arbiter.Lock() defer arbiter.Unlock() arbiter.meters = append(arbiter.meters, m) if !arbiter.started { arbiter.started = true go arbiter.tick() } return m } // NewMeter constructs and registers a new StandardMeter and launches a // goroutine. func NewRegisteredMeter(name string, r Registry) Meter { c := NewMeter() if nil == r { r = DefaultRegistry } r.Register(name, c) return c } // MeterSnapshot is a read-only copy of another Meter. type MeterSnapshot struct { count int64 rate1, rate5, rate15, rateMean float64 } // Clear panics. func (m *MeterSnapshot) Clear() { panic("Clear called on a MeterSnapshot") } // Count returns the count of events at the time the snapshot was taken. func (m *MeterSnapshot) Count() int64 { return m.count } // Mark panics. func (*MeterSnapshot) Mark(n int64) { panic("Mark called on a MeterSnapshot") } // Rate1 returns the one-minute moving average rate of events per second at the // time the snapshot was taken. func (m *MeterSnapshot) Rate1() float64 { return m.rate1 } // Rate5 returns the five-minute moving average rate of events per second at // the time the snapshot was taken. func (m *MeterSnapshot) Rate5() float64 { return m.rate5 } // Rate15 returns the fifteen-minute moving average rate of events per second // at the time the snapshot was taken. func (m *MeterSnapshot) Rate15() float64 { return m.rate15 } // RateMean returns the meter's mean rate of events per second at the time the // snapshot was taken. func (m *MeterSnapshot) RateMean() float64 { return m.rateMean } // Snapshot returns the snapshot. func (m *MeterSnapshot) Snapshot() Meter { return m } // NilMeter is a no-op Meter. type NilMeter struct{} // Clear is a no-op. func (NilMeter) Clear() {} // Count is a no-op. func (NilMeter) Count() int64 { return 0 } // Mark is a no-op. func (NilMeter) Mark(n int64) {} // Rate1 is a no-op. func (NilMeter) Rate1() float64 { return 0.0 } // Rate5 is a no-op. func (NilMeter) Rate5() float64 { return 0.0 } // Rate15is a no-op. func (NilMeter) Rate15() float64 { return 0.0 } // RateMean is a no-op. func (NilMeter) RateMean() float64 { return 0.0 } // Snapshot is a no-op. func (NilMeter) Snapshot() Meter { return NilMeter{} } // StandardMeter is the standard implementation of a Meter. type StandardMeter struct { lock sync.RWMutex snapshot *MeterSnapshot a1, a5, a15 EWMA startTime time.Time } func newStandardMeter() *StandardMeter { return &StandardMeter{ snapshot: &MeterSnapshot{}, a1: NewEWMA1(), a5: NewEWMA5(), a15: NewEWMA15(), startTime: time.Now(), } } // Clear resets the meter. func (m *StandardMeter) Clear() { m.lock.Lock() defer m.lock.Unlock() m.snapshot = &MeterSnapshot{} m.a1 = NewEWMA1() m.a5 = NewEWMA5() m.a15 = NewEWMA15() m.startTime = time.Now() } // Count returns the number of events recorded. func (m *StandardMeter) Count() int64 { m.lock.RLock() count := m.snapshot.count m.lock.RUnlock() return count } // Mark records the occurance of n events. func (m *StandardMeter) Mark(n int64) { m.lock.Lock() defer m.lock.Unlock() m.snapshot.count += n m.a1.Update(n) m.a5.Update(n) m.a15.Update(n) m.updateSnapshot() } // Rate1 returns the one-minute moving average rate of events per second. func (m *StandardMeter) Rate1() float64 { m.lock.RLock() rate1 := m.snapshot.rate1 m.lock.RUnlock() return rate1 } // Rate5 returns the five-minute moving average rate of events per second. func (m *StandardMeter) Rate5() float64 { m.lock.RLock() rate5 := m.snapshot.rate5 m.lock.RUnlock() return rate5 } // Rate15 returns the fifteen-minute moving average rate of events per second. func (m *StandardMeter) Rate15() float64 { m.lock.RLock() rate15 := m.snapshot.rate15 m.lock.RUnlock() return rate15 } // RateMean returns the meter's mean rate of events per second. func (m *StandardMeter) RateMean() float64 { m.lock.RLock() rateMean := m.snapshot.rateMean m.lock.RUnlock() return rateMean } // Snapshot returns a read-only copy of the meter. func (m *StandardMeter) Snapshot() Meter { m.lock.RLock() snapshot := *m.snapshot m.lock.RUnlock() return &snapshot } func (m *StandardMeter) updateSnapshot() { // should run with write lock held on m.lock snapshot := m.snapshot snapshot.rate1 = m.a1.Rate() snapshot.rate5 = m.a5.Rate() snapshot.rate15 = m.a15.Rate() snapshot.rateMean = float64(snapshot.count) / time.Since(m.startTime).Seconds() } func (m *StandardMeter) tick() { m.lock.Lock() defer m.lock.Unlock() m.a1.Tick() m.a5.Tick() m.a15.Tick() m.updateSnapshot() } type meterArbiter struct { sync.RWMutex started bool meters []*StandardMeter ticker *time.Ticker } var arbiter = meterArbiter{ticker: time.NewTicker(5e9)} // Ticks meters on the scheduled interval func (ma *meterArbiter) tick() { for { select { case <-ma.ticker.C: ma.tickMeters() } } } func (ma *meterArbiter) tickMeters() { ma.RLock() defer ma.RUnlock() for _, meter := range ma.meters { meter.tick() } }
vendor/github.com/launchdarkly/go-metrics/meter.go
0.857619
0.50116
meter.go
starcoder
package nb import ( "github.com/go-voice/voice" ) // g711 are codecs in the ITU-T g711 specification type g711 struct{} func (g711) DecodeBlockSize() int { return 0 } func (g711) DecodedLen(n int) int { return n } func (g711) EncodeBlockSize() int { return 0 } func (g711) EncodedLen(n int) int { return n } func (g711) Format() voice.Format { return voice.Format{Channels: 1, Rate: 8000} } func (g711) Reset() {} // aLaw is an A-Law codec type aLaw struct{ g711 } // ALaw returns a ITU-T G.711 compatible A-law waveform speech coder at 64 kbit/s. func ALaw() Codec { return aLaw{} } func (codec aLaw) Encode(dst []byte, src []int16) error { if err := checkEncodeBounds(codec, dst, src); err != nil { return err } var ( srcLen = len(src) dstLen = len(dst) ) if srcLen == 0 && dstLen == 0 { return nil } for offset, sample := range src { dst[offset] = aLawEncodeTable[(sample>>3)+0x1000] } return nil } func (codec aLaw) Decode(dst []int16, src []byte) error { if err := checkDecodeBounds(codec, dst, src); err != nil { return err } var ( srcLen = len(src) dstLen = len(dst) ) if srcLen == 0 && dstLen == 0 { return nil } for offset, value := range src { dst[offset] = aLawDecodeTable[value] } return nil } // µLaw is an µ-law codec type µLaw struct{ g711 } // MLaw returns a ITU-T G.711 compatible µ-Law waveform speech coder at 64 kbit/s. func MLaw() Codec { return µLaw{} } func (codec µLaw) Encode(dst []byte, src []int16) error { if err := checkEncodeBounds(codec, dst, src); err != nil { return err } var ( srcLen = len(src) dstLen = len(dst) ) if srcLen == 0 && dstLen == 0 { return nil } for offset, sample := range src { dst[offset] = µLawEncodeTable[(sample>>2)+0x2000] } return nil } func (codec µLaw) Decode(dst []int16, src []byte) error { if err := checkDecodeBounds(codec, dst, src); err != nil { return err } var ( srcLen = len(src) dstLen = len(dst) ) if srcLen == 0 && dstLen == 0 { return nil } for offset, value := range src { dst[offset] = µLawDecodeTable[value] } return nil } var ( aLawEncodeTable = mustDecompress([]byte{ 0x1f, 0x8b, 0x08, 0x08, 0xc7, 0x1d, 0x63, 0x5c, 0x02, 0x03, 0x61, 0x6c, 0x61, 0x77, 0x5f, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x00, 0xc5, 0xc1, 0x43, 0x60, 0x18, 0x00, 0x0c, 0x00, 0xc0, 0xd9, 0xb6, 0xcd, 0xce, 0xf6, 0x56, 0x77, 0xab, 0x6d, 0xcc, 0xb6, 0x6d, 0xdb, 0xb6, 0x6d, 0xb3, 0xb6, 0xed, 0xce, 0xb6, 0xbd, 0xe5, 0x91, 0x57, 0x3e, 0x79, 0xe4, 0x91, 0x3b, 0x03, 0x03, 0x5d, 0x2d, 0x94, 0x35, 0x53, 0xd6, 0x5c, 0x59, 0x6b, 0x65, 0x6d, 0x94, 0xb5, 0x54, 0xd6, 0x4a, 0x59, 0x03, 0x65, 0x0d, 0x95, 0xd5, 0x53, 0x56, 0x5f, 0x59, 0x13, 0x65, 0x4d, 0x95, 0x35, 0x52, 0xd6, 0x58, 0x59, 0x77, 0xa1, 0x1e, 0x42, 0x5d, 0x85, 0xba, 0x09, 0xf5, 0x16, 0xea, 0x23, 0xd4, 0x53, 0xa8, 0x97, 0x50, 0x7b, 0xa1, 0x0e, 0x42, 0x6d, 0x85, 0xda, 0x09, 0x75, 0x16, 0xea, 0x22, 0xd4, 0x51, 0xa8, 0x93, 0x50, 0x09, 0x46, 0x49, 0x46, 0x31, 0x46, 0x71, 0x46, 0x19, 0x46, 0x59, 0x46, 0x29, 0x46, 0x69, 0x46, 0x01, 0x46, 0x41, 0x46, 0x3e, 0x46, 0x7e, 0x46, 0x11, 0x46, 0x51, 0x46, 0x21, 0x46, 0x61, 0x46, 0x0d, 0xa2, 0x26, 0x51, 0x8d, 0xa8, 0x4e, 0xd4, 0x21, 0xea, 0x12, 0xb5, 0x88, 0xda, 0x44, 0x05, 0xa2, 0x22, 0x51, 0x8e, 0x28, 0x4f, 0x54, 0x21, 0xaa, 0x12, 0x95, 0x88, 0xca, 0xc4, 0x48, 0x34, 0x0a, 0x0d, 0x47, 0x23, 0xd0, 0x58, 0x34, 0x0e, 0x8d, 0x46, 0x63, 0xd0, 0x40, 0x34, 0x08, 0xf5, 0x47, 0x03, 0xd0, 0x50, 0x34, 0x0c, 0x0d, 0x46, 0x43, 0xd0, 0x4c, 0x30, 0x0b, 0x4c, 0x07, 0x33, 0xc0, 0x5c, 0x30, 0x0f, 0xcc, 0x06, 0x73, 0xc0, 0x44, 0x30, 0x09, 0x8c, 0x07, 0x13, 0xc0, 0x54, 0x30, 0x0d, 0x4c, 0x06, 0x53, 0x80, 0xa5, 0xa5, 0x95, 0x55, 0xdf, 0xbe, 0xfd, 0xfa, 0xd9, 0xda, 0xda, 0xd9, 0x59, 0x5b, 0xdb, 0xd8, 0x18, 0x1b, 0x9b, 0x98, 0x18, 0x1a, 0x1a, 0x19, 0x99, 0x9b, 0x5b, 0x58, 0x98, 0x9a, 0x9a, 0x99, 0x79, 0x7a, 0x7a, 0x79, 0xb9, 0xbb, 0x7b, 0x78, 0xf8, 0xfa, 0xfa, 0xf9, 0x79, 0x7b, 0xfb, 0xf8, 0x38, 0x3a, 0x3a, 0x39, 0xd9, 0xdb, 0x3b, 0x38, 0xb8, 0xba, 0xba, 0xb9, 0x39, 0x3b, 0xbb, 0xb8, 0xa4, 0xa4, 0x24, 0x27, 0xa7, 0xa5, 0xa5, 0xa6, 0x26, 0x24, 0xc4, 0xc7, 0x27, 0x25, 0x25, 0x26, 0xe6, 0xe4, 0x64, 0x67, 0xe7, 0xe5, 0xe5, 0xe6, 0x66, 0x64, 0xa4, 0xa7, 0x67, 0x65, 0x65, 0x66, 0x86, 0x84, 0x04, 0x07, 0x87, 0x85, 0x85, 0x86, 0x06, 0x04, 0xf8, 0xfb, 0x07, 0x05, 0x05, 0x06, 0xc6, 0xc4, 0x44, 0x47, 0xc7, 0xc5, 0xc5, 0xc6, 0x46, 0x44, 0x84, 0x87, 0x47, 0x45, 0x45, 0x46, 0x7e, 0x01, 0x9f, 0xc1, 0x37, 0xf0, 0x15, 0x7c, 0x00, 0xef, 0xc1, 0x27, 0xf0, 0x11, 0xfc, 0x01, 0xbf, 0xc1, 0x3f, 0xf0, 0x17, 0xfc, 0x00, 0xdf, 0xc1, 0x2f, 0xf0, 0x13, 0x3c, 0x41, 0x8f, 0xd1, 0x33, 0xf4, 0x14, 0x3d, 0x40, 0xf7, 0xd1, 0x23, 0xf4, 0x10, 0xbd, 0x41, 0xaf, 0xd1, 0x3b, 0xf4, 0x16, 0xbd, 0x40, 0xcf, 0xd1, 0x2b, 0xf4, 0x12, 0x6d, 0x21, 0x36, 0x13, 0xdb, 0x88, 0xad, 0xc4, 0x06, 0x62, 0x3d, 0xb1, 0x89, 0xd8, 0x48, 0xec, 0x21, 0x76, 0x13, 0xfb, 0x88, 0xbd, 0xc4, 0x0e, 0x62, 0x3b, 0xb1, 0x8b, 0xd8, 0x49, 0x2c, 0x61, 0x2c, 0x66, 0x2c, 0x63, 0x2c, 0x65, 0x2c, 0x60, 0xcc, 0x67, 0x2c, 0x62, 0x2c, 0x64, 0xac, 0x61, 0xac, 0x66, 0xac, 0x63, 0xac, 0x65, 0xac, 0x60, 0x2c, 0x67, 0xac, 0x62, 0xac, 0x64, 0x5c, 0x11, 0xba, 0x2c, 0x74, 0x4d, 0xe8, 0xaa, 0xd0, 0x05, 0xa1, 0xf3, 0x42, 0x97, 0x84, 0x2e, 0x0a, 0xdd, 0x11, 0xba, 0x2d, 0x74, 0x4f, 0xe8, 0xae, 0xd0, 0x0d, 0xa1, 0xeb, 0x42, 0xb7, 0x84, 0x6e, 0x0a, 0x1d, 0x51, 0x76, 0x58, 0xd9, 0x31, 0x65, 0x47, 0x95, 0x1d, 0x50, 0xb6, 0x5f, 0xd9, 0x21, 0x65, 0x07, 0x95, 0x9d, 0x51, 0x76, 0x5a, 0xd9, 0x39, 0x65, 0x67, 0x95, 0x9d, 0x50, 0x76, 0x5c, 0xd9, 0x29, 0x65, 0x27, 0x95, 0xfd, 0x07, 0x99, 0x62, 0x8e, 0x4f, 0x00, 0x20, 0x00, 0x00, }) aLawDecodeTable = [256]int16{ -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016, -20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008, -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88, -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688, -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344, 328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, 72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688, 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848, } aLawToΜLawTable = [256]byte{ 0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d, 0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25, 0x39, 0x3a, 0x37, 0x38, 0x3d, 0x3e, 0x3b, 0x3c, 0x31, 0x32, 0x2f, 0x30, 0x35, 0x36, 0x33, 0x34, 0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d, 0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05, 0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x62, 0x63, 0x60, 0x61, 0x66, 0x67, 0x64, 0x65, 0x5d, 0x5d, 0x5c, 0x5c, 0x5f, 0x5f, 0x5e, 0x5e, 0x74, 0x76, 0x70, 0x72, 0x7c, 0x7e, 0x78, 0x7a, 0x6a, 0x6b, 0x68, 0x69, 0x6e, 0x6f, 0x6c, 0x6d, 0x48, 0x49, 0x46, 0x47, 0x4c, 0x4d, 0x4a, 0x4b, 0x40, 0x41, 0x3f, 0x3f, 0x44, 0x45, 0x42, 0x43, 0x56, 0x57, 0x54, 0x55, 0x5a, 0x5b, 0x58, 0x59, 0x4f, 0x4f, 0x4e, 0x4e, 0x52, 0x53, 0x50, 0x51, 0xaa, 0xab, 0xa8, 0xa9, 0xae, 0xaf, 0xac, 0xad, 0xa2, 0xa3, 0xa0, 0xa1, 0xa6, 0xa7, 0xa4, 0xa5, 0xb9, 0xba, 0xb7, 0xb8, 0xbd, 0xbe, 0xbb, 0xbc, 0xb1, 0xb2, 0xaf, 0xb0, 0xb5, 0xb6, 0xb3, 0xb4, 0x8a, 0x8b, 0x88, 0x89, 0x8e, 0x8f, 0x8c, 0x8d, 0x82, 0x83, 0x80, 0x81, 0x86, 0x87, 0x84, 0x85, 0x9a, 0x9b, 0x98, 0x99, 0x9e, 0x9f, 0x9c, 0x9d, 0x92, 0x93, 0x90, 0x91, 0x96, 0x97, 0x94, 0x95, 0xe2, 0xe3, 0xe0, 0xe1, 0xe6, 0xe7, 0xe4, 0xe5, 0xdd, 0xdd, 0xdc, 0xdc, 0xdf, 0xdf, 0xde, 0xde, 0xf4, 0xf6, 0xf0, 0xf2, 0xfc, 0xfe, 0xf8, 0xfa, 0xea, 0xeb, 0xe8, 0xe9, 0xee, 0xef, 0xec, 0xed, 0xc8, 0xc9, 0xc6, 0xc7, 0xcc, 0xcd, 0xca, 0xcb, 0xc0, 0xc1, 0xbf, 0xbf, 0xc4, 0xc5, 0xc2, 0xc3, 0xd6, 0xd7, 0xd4, 0xd5, 0xda, 0xdb, 0xd8, 0xd9, 0xcf, 0xcf, 0xce, 0xce, 0xd2, 0xd3, 0xd0, 0xd1, } µLawEncodeTable = mustDecompress([]byte{ 0x1f, 0x8b, 0x08, 0x08, 0x27, 0x1d, 0x63, 0x5c, 0x02, 0x03, 0x75, 0x6c, 0x61, 0x77, 0x5f, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x00, 0xed, 0xc1, 0x43, 0x74, 0x18, 0x00, 0x0c, 0x00, 0xd0, 0xce, 0xb6, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, 0xde, 0x6a, 0xb7, 0x6f, 0xb6, 0x6d, 0xdb, 0xb6, 0x6d, 0xdb, 0x36, 0xeb, 0x55, 0x5b, 0x0e, 0x39, 0xe5, 0xd0, 0x1c, 0x72, 0xc8, 0x21, 0xfd, 0xdf, 0xc1, 0x21, 0x56, 0xcc, 0xe2, 0x18, 0x17, 0xd7, 0xb8, 0x78, 0xc6, 0xc5, 0x37, 0x2e, 0x81, 0x71, 0x09, 0x8d, 0x4b, 0x64, 0x5c, 0x62, 0xe3, 0x92, 0x18, 0x97, 0xd4, 0xb8, 0x64, 0xc6, 0x25, 0x37, 0x2e, 0x85, 0x71, 0x29, 0x8d, 0x4b, 0x65, 0x5c, 0x6a, 0x65, 0x69, 0x94, 0xa5, 0x55, 0x96, 0x4e, 0x59, 0x7a, 0x65, 0x19, 0x94, 0x65, 0x54, 0x96, 0x49, 0x59, 0x66, 0x65, 0x59, 0x94, 0x65, 0x55, 0x96, 0x4d, 0x59, 0x76, 0x65, 0x39, 0x94, 0xe5, 0x54, 0x96, 0x4b, 0x59, 0x6e, 0xa1, 0x3c, 0x42, 0x79, 0x85, 0xf2, 0x09, 0xe5, 0x17, 0x2a, 0x20, 0x54, 0x50, 0xa8, 0x90, 0x50, 0x61, 0xa1, 0x22, 0x42, 0x45, 0x85, 0x8a, 0x09, 0x15, 0x17, 0x2a, 0x21, 0x54, 0x52, 0xa8, 0x94, 0x50, 0x69, 0x46, 0x19, 0x46, 0x59, 0x46, 0x39, 0x46, 0x79, 0x46, 0x05, 0x46, 0x45, 0x46, 0x25, 0x46, 0x65, 0x46, 0x15, 0x46, 0x55, 0x46, 0x35, 0x46, 0x75, 0x46, 0x0d, 0x46, 0x4d, 0x46, 0x2d, 0x46, 0x6d, 0xa2, 0x0e, 0x51, 0x97, 0xa8, 0x47, 0xd4, 0x27, 0x1a, 0x10, 0x0d, 0x89, 0x46, 0x44, 0x63, 0xa2, 0x09, 0xd1, 0x94, 0x68, 0x46, 0x34, 0x27, 0x5a, 0x10, 0x2d, 0x89, 0x56, 0x44, 0x6b, 0xd4, 0x06, 0xb5, 0x45, 0xed, 0x50, 0x7b, 0xd4, 0x01, 0x75, 0x44, 0x9d, 0x50, 0x67, 0xd4, 0x05, 0x75, 0x45, 0xdd, 0x50, 0x77, 0xd4, 0x03, 0xf5, 0x44, 0xbd, 0x50, 0x6f, 0xd0, 0x07, 0xf4, 0x05, 0xfd, 0x40, 0x7f, 0x30, 0x00, 0x0c, 0x04, 0x83, 0xc0, 0x60, 0x30, 0x04, 0x0c, 0x05, 0xc3, 0xc0, 0x70, 0x30, 0x02, 0x8c, 0x04, 0xa3, 0x80, 0xa3, 0xa3, 0x93, 0x93, 0xb3, 0xb3, 0x8b, 0x8b, 0xab, 0xab, 0x9b, 0x9b, 0xbb, 0xbb, 0x87, 0x87, 0xa7, 0xa7, 0x97, 0x97, 0xb7, 0xb7, 0x8f, 0x8f, 0xaf, 0xaf, 0x9f, 0x9f, 0xbf, 0xff, 0xbf, 0xe8, 0xe8, 0xa8, 0xa8, 0xc8, 0xc8, 0x88, 0x88, 0xf0, 0xf0, 0xbf, 0x7f, 0xc3, 0xc2, 0x42, 0x43, 0x43, 0x42, 0x82, 0x83, 0x83, 0x82, 0x02, 0x03, 0x03, 0x02, 0xfe, 0xfc, 0xf9, 0xfd, 0xfb, 0x17, 0xf8, 0x09, 0x7e, 0x80, 0xef, 0xe0, 0x1b, 0xf8, 0x0a, 0xbe, 0x80, 0xcf, 0xe0, 0x13, 0xf8, 0x08, 0x3e, 0x80, 0xf7, 0xe0, 0x1d, 0x78, 0x0b, 0xde, 0x80, 0xd7, 0xe0, 0x15, 0x7a, 0x89, 0x5e, 0xa0, 0xe7, 0xe8, 0x19, 0x7a, 0x8a, 0x9e, 0xa0, 0xc7, 0xe8, 0x11, 0x7a, 0x88, 0x1e, 0xa0, 0xfb, 0xe8, 0x1e, 0xba, 0x8b, 0xee, 0xa0, 0xdb, 0xe8, 0x16, 0x71, 0x93, 0xb8, 0x41, 0x5c, 0x27, 0xae, 0x11, 0x57, 0x89, 0x2b, 0xc4, 0x65, 0xe2, 0x12, 0x71, 0x91, 0xb8, 0x40, 0x9c, 0x27, 0xce, 0x11, 0x67, 0x89, 0x33, 0xc4, 0x69, 0xe2, 0x14, 0xe3, 0x24, 0xe3, 0x04, 0xe3, 0x38, 0xe3, 0x18, 0xe3, 0x28, 0xe3, 0x08, 0xe3, 0x30, 0xe3, 0x10, 0xe3, 0x20, 0xe3, 0x00, 0x63, 0x3f, 0x63, 0x1f, 0x63, 0x2f, 0x63, 0x0f, 0x63, 0x37, 0x63, 0x97, 0xd0, 0x4e, 0xa1, 0x1d, 0x42, 0xdb, 0x85, 0xb6, 0x09, 0x6d, 0x15, 0xda, 0x22, 0xb4, 0x59, 0x68, 0x93, 0xd0, 0x46, 0xa1, 0x0d, 0x42, 0xeb, 0x85, 0xd6, 0x09, 0xad, 0x15, 0x5a, 0x23, 0xb4, 0x5a, 0x68, 0x95, 0xb2, 0x95, 0xca, 0x56, 0x28, 0x5b, 0xae, 0x6c, 0x99, 0xb2, 0xa5, 0xca, 0x96, 0x28, 0x5b, 0xac, 0x6c, 0x91, 0xb2, 0x85, 0xca, 0x16, 0x28, 0x9b, 0xaf, 0x6c, 0x9e, 0xb2, 0xb9, 0xca, 0xe6, 0x28, 0x9b, 0xad, 0x6c, 0x96, 0x71, 0x33, 0x8d, 0x9b, 0x61, 0xdc, 0x74, 0xe3, 0xa6, 0x19, 0x37, 0xd5, 0xb8, 0x29, 0xc6, 0x4d, 0x36, 0x6e, 0x92, 0x71, 0x13, 0x8d, 0x9b, 0x60, 0xdc, 0x78, 0xe3, 0xc6, 0x19, 0x37, 0xd6, 0xb8, 0x31, 0xc6, 0x8d, 0x8e, 0x15, 0xb3, 0xff, 0xf1, 0x7f, 0xd2, 0xaf, 0x00, 0x40, 0x00, 0x00, }) µLawDecodeTable = [256]int16{ -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876, -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372, -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876, 844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0, } µLawToAlawTable = [256]byte{ 0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d, 0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25, 0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d, 0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35, 0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d, 0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x6a, 0x68, 0x69, 0x6e, 0x6f, 0x6c, 0x6d, 0x62, 0x63, 0x60, 0x61, 0x66, 0x67, 0x64, 0x65, 0x7a, 0x78, 0x7e, 0x7f, 0x7c, 0x7d, 0x72, 0x73, 0x70, 0x71, 0x76, 0x77, 0x74, 0x75, 0x4b, 0x49, 0x4f, 0x4d, 0x42, 0x43, 0x40, 0x41, 0x46, 0x47, 0x44, 0x45, 0x5a, 0x5b, 0x58, 0x59, 0x5e, 0x5f, 0x5c, 0x5d, 0x52, 0x52, 0x53, 0x53, 0x50, 0x50, 0x51, 0x51, 0x56, 0x56, 0x57, 0x57, 0x54, 0x54, 0x55, 0x55, 0xaa, 0xab, 0xa8, 0xa9, 0xae, 0xaf, 0xac, 0xad, 0xa2, 0xa3, 0xa0, 0xa1, 0xa6, 0xa7, 0xa4, 0xa5, 0xba, 0xbb, 0xb8, 0xb9, 0xbe, 0xbf, 0xbc, 0xbd, 0xb2, 0xb3, 0xb0, 0xb1, 0xb6, 0xb7, 0xb4, 0xb5, 0x8a, 0x8b, 0x88, 0x89, 0x8e, 0x8f, 0x8c, 0x8d, 0x82, 0x83, 0x80, 0x81, 0x86, 0x87, 0x84, 0x9a, 0x9b, 0x98, 0x99, 0x9e, 0x9f, 0x9c, 0x9d, 0x92, 0x93, 0x90, 0x91, 0x96, 0x97, 0x94, 0x95, 0xea, 0xe8, 0xe9, 0xee, 0xef, 0xec, 0xed, 0xe2, 0xe3, 0xe0, 0xe1, 0xe6, 0xe7, 0xe4, 0xe5, 0xfa, 0xf8, 0xfe, 0xff, 0xfc, 0xfd, 0xf2, 0xf3, 0xf0, 0xf1, 0xf6, 0xf7, 0xf4, 0xf5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc2, 0xc3, 0xc0, 0xc1, 0xc6, 0xc7, 0xc4, 0xc5, 0xda, 0xdb, 0xd8, 0xd9, 0xde, 0xdf, 0xdc, 0xdd, 0xd2, 0xd2, 0xd3, 0xd3, 0xd0, 0xd0, 0xd1, 0xd1, 0xd6, 0xd6, 0xd7, 0xd7, 0xd4, 0xd4, 0xd5, 0xd5, } )
nb/g711.go
0.596668
0.498413
g711.go
starcoder
package ode // #define dDOUBLE // #include <ode/ode.h> import "C" // Mass represents object mass properties. type Mass struct { Center Vector3 Inertia Matrix3 Mass float64 } func (m *Mass) toC(c *C.dMass) { c.mass = C.dReal(m.Mass) Vector(m.Center).toC((*C.dReal)(&c.c[0])) Matrix(m.Inertia).toC((*C.dReal)(&c.I[0])) } func (m *Mass) fromC(c *C.dMass) { m.Mass = float64(c.mass) Vector(m.Center).fromC((*C.dReal)(&c.c[0])) Matrix(m.Inertia).fromC((*C.dReal)(&c.I[0])) } // NewMass returns a new Mass instance. func NewMass() *Mass { return &Mass{ Center: NewVector3(), Inertia: NewMatrix3(), } } // Check returns whether the mass's parameter values are valid. func (m *Mass) Check() bool { c := &C.dMass{} m.toC(c) return C.dMassCheck(c) != 0 } // SetZero sets the mass to 0. func (m *Mass) SetZero() { c := &C.dMass{} C.dMassSetZero(c) m.fromC(c) } // SetParams sets the mass parameters. func (m *Mass) SetParams(mass float64, com Vector3, inert Matrix3) { c := &C.dMass{} C.dMassSetParameters(c, C.dReal(mass), C.dReal(com[0]), C.dReal(com[1]), C.dReal(com[2]), C.dReal(inert[0][0]), C.dReal(inert[1][1]), C.dReal(inert[2][2]), C.dReal(inert[0][1]), C.dReal(inert[0][2]), C.dReal(inert[1][3])) m.fromC(c) } // SetSphere sets the mass for a sphere of given properties. func (m *Mass) SetSphere(density, radius float64) { c := &C.dMass{} C.dMassSetSphere(c, C.dReal(density), C.dReal(radius)) m.fromC(c) } // SetSphereTotal sets the mass for a sphere of given properties. func (m *Mass) SetSphereTotal(totalMass, radius float64) { c := &C.dMass{} C.dMassSetSphereTotal(c, C.dReal(totalMass), C.dReal(radius)) m.fromC(c) } // SetCapsule sets the mass for a capsule of given properties. func (m *Mass) SetCapsule(density float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCapsule(c, C.dReal(density), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) } // SetCapsuleTotal sets the mass for a capsule of given properties. func (m *Mass) SetCapsuleTotal(totalMass float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCapsuleTotal(c, C.dReal(totalMass), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) } // SetCylinder sets the mass for a cylinder of given properties. func (m *Mass) SetCylinder(density float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCylinder(c, C.dReal(density), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) } // SetCylinderTotal sets the mass for a cylinder of given properties. func (m *Mass) SetCylinderTotal(totalMass float64, direction int, radius, length float64) { c := &C.dMass{} C.dMassSetCylinderTotal(c, C.dReal(totalMass), C.int(direction), C.dReal(radius), C.dReal(length)) m.fromC(c) } // SetBox sets the mass for a box of given properties. func (m *Mass) SetBox(density float64, lens Vector3) { c := &C.dMass{} C.dMassSetBox(c, C.dReal(density), C.dReal(lens[0]), C.dReal(lens[1]), C.dReal(lens[2])) m.fromC(c) } // SetBoxTotal sets the mass for a box of given properties. func (m *Mass) SetBoxTotal(totalMass float64, lens Vector3) { c := &C.dMass{} C.dMassSetBoxTotal(c, C.dReal(totalMass), C.dReal(lens[0]), C.dReal(lens[1]), C.dReal(lens[2])) m.fromC(c) } // SetTrimesh sets the mass for the given triangle mesh. func (m *Mass) SetTriMesh(density float64, mesh TriMesh) { c := &C.dMass{} C.dMassSetTrimesh(c, C.dReal(density), mesh.c()) m.fromC(c) } // SetTrimeshTotal sets the mass for the given triangle mesh. func (m *Mass) SetTriMeshTotal(totalMass float64, mesh TriMesh) { c := &C.dMass{} C.dMassSetTrimeshTotal(c, C.dReal(totalMass), mesh.c()) m.fromC(c) } // Adjust sets parameters based on the given total mass. func (m *Mass) Adjust(mass float64) { c := &C.dMass{} m.toC(c) C.dMassAdjust(c, C.dReal(mass)) m.fromC(c) } // Translate translates the mass by vec. func (m *Mass) Translate(vec Vector3) { c := &C.dMass{} m.toC(c) C.dMassTranslate(c, C.dReal(vec[0]), C.dReal(vec[1]), C.dReal(vec[2])) m.fromC(c) } // Rotate rotates the mass by rot. func (m *Mass) Rotate(rot Matrix3) { c := &C.dMass{} m.toC(c) C.dMassRotate(c, (*C.dReal)(&rot[0][0])) m.fromC(c) } // Add adds the other mass to this mass. func (m *Mass) Add(other *Mass) { c, oc := &C.dMass{}, &C.dMass{} m.toC(c) other.toC(oc) C.dMassAdd(c, oc) m.fromC(c) }
mass.go
0.717606
0.557604
mass.go
starcoder
package accounting import ( "context" "time" "github.com/btcsuite/btcutil" "github.com/lightninglabs/faraday/fiat" "github.com/lightninglabs/faraday/utils" ) // usdPrice is a function which gets the USD price of bitcoin at a given time. type usdPrice func(timestamp time.Time) (*fiat.USDPrice, error) // satsToMsat converts an amount expressed in sats to msat. func satsToMsat(sats btcutil.Amount) int64 { return int64(sats) * 1000 } // satsToMsat converts an amount expressed in sats to msat, flipping the // sign on the value. func invertedSatsToMsats(sats btcutil.Amount) int64 { return satsToMsat(sats) * -1 } // invertMsat flips the sign value of a msat value. func invertMsat(msat int64) int64 { return msat * -1 } // getConversion is a helper function which queries coincap for a relevant set // of price data and returns a convert function which can be used to get // individual price points from this data. func getConversion(ctx context.Context, startTime, endTime time.Time, disableFiat bool, fiatBackend fiat.PriceBackend, granularity *fiat.Granularity) (usdPrice, error) { // If we don't want fiat values, just return a price which will yield // a zero price and timestamp. if disableFiat { return func(_ time.Time) (*fiat.USDPrice, error) { return &fiat.USDPrice{}, nil }, nil } err := utils.ValidateTimeRange(startTime, endTime) if err != nil { return nil, err } fiatClient, err := fiat.NewPriceSource(fiatBackend, granularity) if err != nil { return nil, err } // Get price data for our relevant period. We get pricing for the whole // period rather than on a per-item level to limit the number of api // calls we need to make to our external data source. prices, err := fiatClient.GetPrices(ctx, startTime, endTime) if err != nil { return nil, err } // Create a wrapper function which can be used to get individual price // points from our set of price data as we create our report. return func(ts time.Time) (*fiat.USDPrice, error) { return fiat.GetPrice(prices, ts) }, nil }
accounting/conversions.go
0.766381
0.423637
conversions.go
starcoder
package data import ( "fmt" "hash/maphash" "math/rand" "github.com/kode4food/ale/types" "github.com/kode4food/ale/types/basic" ) type ( // Bool represents the values True or False Bool bool // Value is the generic interface for all values Value interface { fmt.Stringer Equal(Value) bool } // Values represent a set of Values Values []Value // Name is a Variable name Name string // Names represents a set of Names Names []Name // Named is the generic interface for values that are named Named interface { Name() Name } // Typed is the generic interface for values that are typed Typed interface { Type() types.Type } // Counted interfaces allow a Value to return a count of its items Counted interface { Count() int } // Indexed is the interface for values that have indexed elements Indexed interface { ElementAt(int) (Value, bool) } // Mapped is the interface for Values that have accessible properties Mapped interface { Get(Value) (Value, bool) } // Valuer can return its data as a slice of Values Valuer interface { Values() Values } // Hashed can return a hash code for the value Hashed interface { HashCode() uint64 } ) const ( // True represents the boolean value of True True Bool = true // TrueLiteral represents the literal value of True TrueLiteral = "#t" // False represents the boolean value of false False Bool = false // FalseLiteral represents the literal value of False FalseLiteral = "#f" ) var ( seed = maphash.MakeSeed() nameHash = rand.Uint64() trueHash = rand.Uint64() falseHash = rand.Uint64() ) // Name makes Name Named func (n Name) Name() Name { return n } // Equal compares this Name to another for equality func (n Name) Equal(v Value) bool { if v, ok := v.(Name); ok { return n == v } return false } // String converts this Value into a string func (n Name) String() string { return string(n) } // HashCode returns the hash code for this Name func (n Name) HashCode() uint64 { return nameHash * HashString(string(n)) } // Equal compares this Bool to another for equality func (b Bool) Equal(v Value) bool { if v, ok := v.(Bool); ok { return b == v } return false } // String converts this Value into a string func (b Bool) String() string { if b { return TrueLiteral } return FalseLiteral } // Type returns the Type for this Bool Value func (Bool) Type() types.Type { return basic.Bool } // HashCode returns the hash code for this Bool func (b Bool) HashCode() uint64 { if b { return trueHash } return falseHash } // Truthy evaluates whether a Value is truthy func Truthy(v Value) bool { if v == False || v == Nil { return false } return true } // HashCode returns a hash code for the provided Value. If the Value implements // the Hashed interface, it will call us the HashCode() method. Otherwise, it // will create a hash code from the stringified form of the Value func HashCode(v Value) uint64 { if h, ok := v.(Hashed); ok { return h.HashCode() } return HashString(v.String()) } // HashString returns a hash code for the provided string func HashString(s string) uint64 { var b maphash.Hash b.SetSeed(seed) _, _ = b.WriteString(s) return b.Sum64() }
data/value.go
0.768646
0.450722
value.go
starcoder
package stats import ( "bytes" "context" "encoding/json" "github.com/hscells/cqr" gpipeline "github.com/hscells/groove/pipeline" "github.com/hscells/transmute/backend" "github.com/hscells/transmute/lexer" "github.com/hscells/transmute/parser" tpipeline "github.com/hscells/transmute/pipeline" "github.com/hscells/trecresults" "gopkg.in/olivere/elastic.v5" "io" "log" "runtime" "strconv" "strings" "sync" "time" ) // ElasticsearchStatisticsSource is a way of gathering statistics for a collection using Elasticsearch. type ElasticsearchStatisticsSource struct { client *elastic.Client documentType string index string options SearchOptions parameters map[string]float64 Scroll bool Analyser string AnalyseField string wg sync.WaitGroup } // SearchOptions gets the immutable execute options for the statistics source. func (es *ElasticsearchStatisticsSource) SearchOptions() SearchOptions { return es.options } // Parameters gets the immutable parameters for the statistics source. func (es *ElasticsearchStatisticsSource) Parameters() map[string]float64 { return es.parameters } // TermFrequency is the term frequency in the field. func (es *ElasticsearchStatisticsSource) TermFrequency(term, field, document string) (float64, error) { resp, err := es.client.TermVectors(es.index, es.documentType).Id(document).Do(context.Background()) if err != nil { return 0, err } if tv, ok := resp.TermVectors[field]; ok { return float64(tv.Terms[term].TermFreq), nil } return 0.0, nil } // DocumentFrequency is the document frequency (the number of documents containing the current term). func (es *ElasticsearchStatisticsSource) DocumentFrequency(term string, field string) (float64, error) { resp, err := es.client.TermVectors(es.index, es.documentType). Doc(map[string]string{field: term}). FieldStatistics(false). TermStatistics(true). Offsets(false). Positions(false). Payloads(false). Fields(field). PerFieldAnalyzer(map[string]string{field: ""}). Do(context.Background()) if err != nil { return 0, err } if tv, ok := resp.TermVectors[field]; ok { return float64(tv.Terms[term].DocFreq), nil } return 0.0, nil } // TotalTermFrequency is a sum of total term frequencies (the sum of total term frequencies of each term in this field). func (es *ElasticsearchStatisticsSource) TotalTermFrequency(term, field string) (float64, error) { docField := strings.Replace(field, es.AnalyseField, "", -1) req := es.client.TermVectors(es.index, es.documentType). Doc(map[string]string{field: term}). TermStatistics(true). Offsets(false). Positions(false). Payloads(false) if strings.ContainsRune(term, '*') { req = req.PerFieldAnalyzer(map[string]string{docField: "medline_analyser"}) } resp, err := req.Do(context.Background()) if err != nil { return 0.0, err } if tv, ok := resp.TermVectors[field]; ok { t := strings.ToLower(strings.Replace(strings.Replace(strings.Replace(term, "\"", "", -1), "*", "", -1), "~", "", -1)) return float64(tv.Terms[t].Ttf), nil } return 0.0, nil } // InverseDocumentFrequency is the ratio of of documents in the collection to the number of documents the term appears // in, logarithmically smoothed. func (es *ElasticsearchStatisticsSource) InverseDocumentFrequency(term, field string) (float64, error) { resp1, err := es.client.IndexStats(es.index).Do(context.Background()) if err != nil { return 0.0, err } N := resp1.All.Total.Docs.Count docField := strings.Replace(field, es.AnalyseField, "", -1) req := es.client.TermVectors(es.index, es.documentType). Doc(map[string]string{docField: term}). FieldStatistics(false). TermStatistics(true). Offsets(false). Positions(false). Pretty(false). Payloads(false) if strings.ContainsRune(term, '*') { req = req.PerFieldAnalyzer(map[string]string{docField: "medline_analyser"}) } resp2, err := req.Do(context.Background()) if err != nil { return 0.0, err } if tv, ok := resp2.TermVectors[field]; ok { nt := tv.Terms[term].DocFreq if nt == 0 { return 0.0, nil } return idf(float64(N), float64(nt)), nil } return 0.0, nil } // VocabularySize is the total number of terms in the vocabulary. func (es *ElasticsearchStatisticsSource) VocabularySize(field string) (float64, error) { resp, err := es.client.TermVectors(es.index, es.documentType). Doc(map[string]string{field: ""}). Offsets(false). Positions(false). Realtime(false). Pretty(false). Payloads(false). Fields(field). PerFieldAnalyzer(map[string]string{field: ""}). Do(context.Background()) if err != nil { return 0.0, err } return float64(resp.TermVectors[field].FieldStatistics.SumTtf), nil } // RetrievalSize is the minimum number of documents that contains at least one of the query terms. func (es *ElasticsearchStatisticsSource) RetrievalSize(query cqr.CommonQueryRepresentation) (float64, error) { // Transform the query to an Elasticsearch query. q, err := toElasticsearch(query) if err != nil { return 0.0, err } // Only then can we issue it to Elasticsearch using our API. result, err := es.client.Count(es.index). Query(elastic.NewRawStringQuery(q)). Do(context.Background()) if err != nil { return 0.0, err } return float64(result), nil } // TermVector retrieves the term vector for a document. func (es *ElasticsearchStatisticsSource) TermVector(document string) (TermVector, error) { tv := TermVector{} req := es.client.TermVectors(es.index, es.documentType). Id(document). FieldStatistics(true). TermStatistics(true). Offsets(false). Pretty(false). Positions(false). Payloads(false). Fields("*") resp, err := req.Do(context.Background()) if err != nil { return tv, err } for field, vector := range resp.TermVectors { for term, vec := range vector.Terms { tv = append(tv, TermVectorTerm{ Term: term, Field: field, DocumentFrequency: float64(vec.DocFreq), TermFrequency: float64(vec.TermFreq), TotalTermFrequency: float64(vec.Ttf), }) } } return tv, nil } // ExecuteFast executes an Elasticsearch query and retrieves only the document ids in the fastest possible way. Do not // use this for ranked results as the concurrency of this method does not guarantee order. func (es *ElasticsearchStatisticsSource) ExecuteFast(query gpipeline.Query, options SearchOptions) ([]uint32, error) { // Transform the query to an Elasticsearch query. q, err := toElasticsearch(query.Query) if err != nil { return nil, err } // Set the Limit to how many goroutines can be run. // http://jmoiron.net/blog/limiting-concurrency-in-go/ concurrency := runtime.NumCPU() sem := make(chan bool, concurrency) hits := make([][]uint32, concurrency) log.Println("executing as fast as possible with Elasticsearch", query.Query) for i := 0; i < concurrency; i++ { sem <- true go func(n int) { defer func() { <-sem }() search: hits[n] = []uint32{} // Scroll execute. svc := es.client.Scroll(es.index). FetchSource(false). Pretty(false). Type(es.documentType). KeepAlive("10m"). Slice(elastic.NewSliceQuery().Id(n).Max(concurrency)). SearchSource( elastic.NewSearchSource(). NoStoredFields(). FetchSource(false). Size(options.Size). Slice(elastic.NewSliceQuery().Id(n).Max(concurrency)). TrackScores(false). Query(elastic.NewRawStringQuery(q))) for { result, err := svc.Do(context.Background()) if err == io.EOF { break } if elastic.IsConnErr(err) { log.Println(err) log.Println("retrying...") goto search } if err != nil { log.Println(err) return } for _, hit := range result.Hits.Hits { id, err := strconv.Atoi(hit.Id) if err != nil { log.Println(err) return } hits[n] = append(hits[n], uint32(id)) } log.Printf("%v: %v/%v\n", n, len(hits[n]), result.Hits.TotalHits) } err = svc.Clear(context.Background()) if err != nil { log.Println(err) //panic(err) return } }(i) } // Wait until the last goroutine has read from the semaphore. for i := 0; i < cap(sem); i++ { sem <- true } var results []uint32 for _, hit := range hits { results = append(results, hit...) } log.Printf("done, %v results in total\n", len(results)) return results, nil } // Execute runs the query on Elasticsearch and returns results in trec format. func (es *ElasticsearchStatisticsSource) Execute(query gpipeline.Query, options SearchOptions) (trecresults.ResultList, error) { // Transform the query to an Elasticsearch query. q, err := toElasticsearch(query.Query) if err != nil { return nil, err } // Only then can we issue it to Elasticsearch using our API. if es.Scroll { var hits []*elastic.SearchHit // Scroll execute. svc := es.client.Scroll(es.index). FetchSource(false). Pretty(false). Type(es.documentType). KeepAlive("30m"). SearchSource( elastic.NewSearchSource(). NoStoredFields(). FetchSource(false). Size(options.Size). TrackScores(false). Query(elastic.NewRawStringQuery(q))) for { result, err := svc.Do(context.Background()) if err == io.EOF { break } if err != nil { return nil, err } hits = append(hits, result.Hits.Hits...) } err = svc.Clear(context.Background()) if err != nil { return nil, err } log.Println(len(hits)) // Block until all the channels have completed. results := make(trecresults.ResultList, len(hits)) for i, hit := range hits { results[i] = &trecresults.Result{ Topic: query.Topic, Iteration: "Q0", DocId: hit.Id, Rank: int64(i), Score: *hit.Score, RunName: options.RunName, } } return results, nil } // Regular execute. result, err := es.client.Search(es.index). Index(es.index). Type(es.documentType). Query(elastic.NewRawStringQuery(q)). Size(options.Size). NoStoredFields(). Do(context.Background()) if err != nil { return nil, err } // Construct the results from the Elasticsearch hits. N := len(result.Hits.Hits) results := make(trecresults.ResultList, N) for i, hit := range result.Hits.Hits { results[i] = &trecresults.Result{ Topic: query.Topic, Iteration: "Q0", DocId: hit.Id, Rank: int64(i), Score: *hit.Score, RunName: options.RunName, } } return results, nil } func (es *ElasticsearchStatisticsSource) CollectionSize() (float64, error) { panic("implement me") } // Analyse is a specific Elasticsearch method used in the analyse transformation. func (es *ElasticsearchStatisticsSource) Analyse(text, analyser string) (tokens []string, err error) { res, err := es.client.IndexAnalyze().Index(es.index).Analyzer(analyser).Text(text).Do(context.Background()) if err != nil { return } for _, token := range res.Tokens { tokens = append(tokens, token.Token) } return } // toElasticsearch transforms a cqr query into an Elasticsearch query. func toElasticsearch(query cqr.CommonQueryRepresentation) (string, error) { var result map[string]interface{} // For a Boolean query, it gets a little tricky. // First we need to get the string representation of the cqr. repr, err := backend.NewCQRQuery(query).StringPretty() if err != nil { return "", err } // Then we need to compile it into an Elasticsearch query. p := tpipeline.NewPipeline( parser.NewCQRParser(), backend.NewElasticsearchCompiler(), tpipeline.TransmutePipelineOptions{ LexOptions: lexer.LexOptions{ FormatParenthesis: true, }, RequiresLexing: false, }) esQuery, err := p.Execute(repr) if err != nil { return "", err } // After that, we need to unmarshal it to get the underlying structure. var tmpQuery map[string]interface{} s, err := esQuery.String() if err != nil { return "", err } err = json.Unmarshal(bytes.NewBufferString(s).Bytes(), &tmpQuery) if err != nil { return "", err } result = tmpQuery["query"].(map[string]interface{}) b, err := json.Marshal(result) if err != nil { return "", err } return bytes.NewBuffer(b).String(), nil } // ElasticsearchHosts sets the hosts for the Elasticsearch client. func ElasticsearchHosts(hosts ...string) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { var err error if len(hosts) == 0 { es.client, err = elastic.NewClient(elastic.SetURL("http://localhost:9200")) if err != nil { panic(err) } } else { sniff := true for _, u := range hosts { if strings.Contains(u, "localhost") { sniff = false break } } es.client, err = elastic.NewClient( elastic.SetURL(hosts...), elastic.SetSniff(sniff), elastic.SetHealthcheck(false), elastic.SetHealthcheckTimeout(time.Hour)) if err != nil { panic(err) } } return } } // ElasticsearchDocumentType sets the document type for the Elasticsearch client. func ElasticsearchDocumentType(documentType string) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { es.documentType = documentType return } } // ElasticsearchIndex sets the index for the Elasticsearch client. func ElasticsearchIndex(index string) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { es.index = index return } } // ElasticsearchSearchOptions sets the execute options for the statistic source. func ElasticsearchSearchOptions(options SearchOptions) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { es.options = options return } } // ElasticsearchParameters sets the parameters for the statistic source. func ElasticsearchParameters(params map[string]float64) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { es.parameters = params return } } // ElasticsearchAnalyser sets the analyser for the statistic source. func ElasticsearchAnalyser(analyser string) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { es.Analyser = analyser return } } // ElasticsearchAnalysedField sets the analyser for the statistic source. func ElasticsearchAnalysedField(field string) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { es.AnalyseField = field return } } // ElasticsearchScroll sets the scroll for the statistic source. func ElasticsearchScroll(scroll bool) func(*ElasticsearchStatisticsSource) { return func(es *ElasticsearchStatisticsSource) { es.Scroll = scroll return } } // NewElasticsearchStatisticsSource creates a new ElasticsearchStatisticsSource using functional options. func NewElasticsearchStatisticsSource(options ...func(*ElasticsearchStatisticsSource)) (*ElasticsearchStatisticsSource, error) { es := &ElasticsearchStatisticsSource{} if len(options) == 0 { var err error es.client, err = elastic.NewClient(elastic.SetURL("http://localhost:9200"), elastic.SetSniff(false), elastic.SetHealthcheckTimeout(1*time.Hour)) if err != nil { return nil, err } } else { for _, option := range options { option(es) } } return es, nil }
stats/elasticsearch.go
0.682785
0.40869
elasticsearch.go
starcoder
package main import "log" /** 题目:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-2/ 寻找两个正序数组的中位数 给定两个大小分别为 m 和 n 的正序(从小到大)数组nums1 和nums2。请你找出并返回这两个正序数组的 中位数 。 算法的时间复杂度应该为 O(log (m+n)) 。 示例 1: 输入:nums1 = [1,3], nums2 = [2] 输出:2.00000 解释:合并数组 = [1,2,3] ,中位数 2 示例 2: 输入:nums1 = [1,2], nums2 = [3,4] 输出:2.50000 解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5 提示: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i], nums2[i] <= 106 */ func main() { nums1 := []int{1, 2} nums2 := []int{3, 4} log.Println("寻找两个正序数组的中位数:", findMedianSortedArrays(nums1, nums2)) } // FindMedianSortedArrays 归并排序 func findMedianSortedArrays(nums1, nums2 []int) float64 { var res []int // 归并过程,因为两个数组都是有序的,所以直接合并 m, n := len(nums1), len(nums2) l1, l2 := 0, 0 for l1 < m && l2 < n { if nums1[l1] < nums2[l2] { res = append(res, nums1[l1]) l1++ } else { res = append(res, nums2[l2]) l2++ } } res = append(res, nums1[l1:]...) res = append(res, nums2[l2:]...) length := m + n // 奇数 if length%2 == 1 { return float64(res[length/2]) } // 偶数 mid1 := res[length/2] mid2 := res[length/2-1] return float64(mid1+mid2) / 2.0 } // 二分查找 O(log(m+n)) O(1) func findMedianSortedArrays1(nums1 []int, nums2 []int) float64 { length := len(nums1) + len(nums2) // 奇数 if length%2 == 1 { return float64(getKthElement(nums1, nums2, length/2+1)) } // 偶数 k1, k2 := length/2, length/2+1 return float64(getKthElement(nums1, nums2, k1)+getKthElement(nums1, nums2, k2)) / 2.0 } func getKthElement(nums1, nums2 []int, k int) int { m, n := len(nums1), len(nums2) index1, index2 := 0, 0 for { if m == index1 { return nums2[index2+k-1] } if n == index2 { return nums1[index1+k-1] } if k == 1 { return Min(nums1[0], nums2[0]) } half := k / 2 l1 := Min(index1+half, m) - 1 l2 := Min(index2+half, n) - 1 pivot1, pivot2 := nums1[l1], nums2[l2] if pivot1 <= pivot2 { k -= l1 - index1 + 1 index1 = l1 + 1 } else { k -= l2 - index2 + 1 index2 = l2 + 1 } } } func Min(a, b int) int { if a < b { return a } return b } // findMedianSortedArrays 双指针 O(logmin(m,n))) O(1) func findMedianSortedArrays2(nums1 []int, nums2 []int) float64 { m, n := len(nums1), len(nums2) length := m + n l1, l2 := 0, 0 left, right := 0, 0 // 代表中位数的2个数 // 只需要循环左半部分就可以 for i := 0; i <= length/2; i++ { // 每次更新这2个值 left = right // 这三个条件缺一不可 if l1 < m && (l2 >= n || nums1[l1] < nums2[l2]) { right = nums1[l1] l1++ } else { right = nums2[l2] l2++ } } // 奇数 if length%2 == 1 { return float64(right) } // 偶数 return float64(left+right) / 2.0 }
algorithm/BinarySearch/leetcodeQuestion/findMedianSortedArrays/findMedianSortedArrays.go
0.584271
0.455259
findMedianSortedArrays.go
starcoder
package rui import ( "strconv" "strings" ) // Path is a path interface type Path interface { // Reset erases the Path Reset() // MoveTo begins a new sub-path at the point specified by the given (x, y) coordinates MoveTo(x, y float64) // LineTo adds a straight line to the current sub-path by connecting // the sub-path's last point to the specified (x, y) coordinates LineTo(x, y float64) // ArcTo adds a circular arc to the current sub-path, using the given control points and radius. // The arc is automatically connected to the path's latest point with a straight line, if necessary. // x0, y0 - coordinates of the first control point; // x1, y1 - coordinates of the second control point; // radius - the arc's radius. Must be non-negative. ArcTo(x0, y0, x1, y1, radius float64) // Arc adds a circular arc to the current sub-path. // x, y - coordinates of the arc's center; // radius - the arc's radius. Must be non-negative; // startAngle - the angle at which the arc starts, measured clockwise from the positive // x-axis and expressed in radians. // endAngle - the angle at which the arc ends, measured clockwise from the positive // x-axis and expressed in radians. // clockwise - if true, causes the arc to be drawn clockwise between the start and end angles, // otherwise - counter-clockwise Arc(x, y, radius, startAngle, endAngle float64, clockwise bool) // BezierCurveTo adds a cubic Bézier curve to the current sub-path. The starting point is // the latest point in the current path. // cp0x, cp0y - coordinates of the first control point; // cp1x, cp1y - coordinates of the second control point; // x, y - coordinates of the end point. BezierCurveTo(cp0x, cp0y, cp1x, cp1y, x, y float64) // QuadraticCurveTo adds a quadratic Bézier curve to the current sub-path. // cpx, cpy - coordinates of the control point; // x, y - coordinates of the end point. QuadraticCurveTo(cpx, cpy, x, y float64) // Ellipse adds an elliptical arc to the current sub-path // x, y - coordinates of the ellipse's center; // radiusX - the ellipse's major-axis radius. Must be non-negative; // radiusY - the ellipse's minor-axis radius. Must be non-negative; // rotation - the rotation of the ellipse, expressed in radians; // startAngle - the angle at which the ellipse starts, measured clockwise // from the positive x-axis and expressed in radians; // endAngle - the angle at which the ellipse ends, measured clockwise // from the positive x-axis and expressed in radians. // clockwise - if true, draws the ellipse clockwise, otherwise draws counter-clockwise Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle float64, clockwise bool) // Close adds a straight line from the current point to the start of the current sub-path. // If the shape has already been closed or has only one point, this function does nothing. Close() scriptText() string } type pathData struct { script strings.Builder } // NewPath creates a new empty Path func NewPath() Path { path := new(pathData) path.script.Grow(4096) path.script.WriteString("\nctx.beginPath();") return path } func (path *pathData) Reset() { path.script.Reset() path.script.WriteString("\nctx.beginPath();") } func (path *pathData) MoveTo(x, y float64) { path.script.WriteString("\nctx.moveTo(") path.script.WriteString(strconv.FormatFloat(x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y, 'g', -1, 64)) path.script.WriteString(");") } func (path *pathData) LineTo(x, y float64) { path.script.WriteString("\nctx.lineTo(") path.script.WriteString(strconv.FormatFloat(x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y, 'g', -1, 64)) path.script.WriteString(");") } func (path *pathData) ArcTo(x0, y0, x1, y1, radius float64) { if radius > 0 { path.script.WriteString("\nctx.arcTo(") path.script.WriteString(strconv.FormatFloat(x0, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y0, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(x1, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y1, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(radius, 'g', -1, 64)) path.script.WriteString(");") } } func (path *pathData) Arc(x, y, radius, startAngle, endAngle float64, clockwise bool) { if radius > 0 { path.script.WriteString("\nctx.arc(") path.script.WriteString(strconv.FormatFloat(x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(radius, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(startAngle, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(endAngle, 'g', -1, 64)) if !clockwise { path.script.WriteString(",true);") } else { path.script.WriteString(");") } } } func (path *pathData) BezierCurveTo(cp0x, cp0y, cp1x, cp1y, x, y float64) { path.script.WriteString("\nctx.bezierCurveTo(") path.script.WriteString(strconv.FormatFloat(cp0x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(cp0y, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(cp1x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(cp1y, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y, 'g', -1, 64)) path.script.WriteString(");") } func (path *pathData) QuadraticCurveTo(cpx, cpy, x, y float64) { path.script.WriteString("\nctx.quadraticCurveTo(") path.script.WriteString(strconv.FormatFloat(cpx, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(cpy, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y, 'g', -1, 64)) path.script.WriteString(");") } func (path *pathData) Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle float64, clockwise bool) { if radiusX > 0 && radiusY > 0 { path.script.WriteString("\nctx.ellipse(") path.script.WriteString(strconv.FormatFloat(x, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(y, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(radiusX, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(radiusY, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(rotation, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(startAngle, 'g', -1, 64)) path.script.WriteRune(',') path.script.WriteString(strconv.FormatFloat(endAngle, 'g', -1, 64)) if !clockwise { path.script.WriteString(",true);") } else { path.script.WriteString(");") } } } func (path *pathData) Close() { path.script.WriteString("\nctx.close();") } func (path *pathData) scriptText() string { return path.script.String() }
path.go
0.748076
0.7488
path.go
starcoder
package binheap // Heap provides basic methods: Push, Peak, Pop, Replace top element and PushPop. type Heap[T any] struct { comparator func(x, y T) bool data []T } // EmptyHeap creates empty heap with provided comparator. func EmptyHeap[T any](comparator func(x, y T) bool) Heap[T] { return Heap[T]{ comparator: comparator, } } // FromSlice creates heap, based on provided slice. // Slice could be reordered. func FromSlice[T any](data []T, comparator func(x, y T) bool) Heap[T] { h := Heap[T]{ data: data, comparator: comparator, } n := h.Len() for i := n/2 - 1; i >= 0; i-- { h.down(i, n) } return h } // Push inserts element to heap. func (h *Heap[T]) Push(x T) { h.data = append(h.data, x) h.up(h.Len() - 1) } // Len returns count of elements in heap. func (h *Heap[T]) Len() int { return len(h.data) } // Peak returns top element without deleting. func (h *Heap[T]) Peak() T { return h.data[0] } // Pop returns top element with removing it. func (h *Heap[T]) Pop() T { n := h.Len() - 1 h.swap(0, n) h.down(0, n) result := h.data[n] h.data = h.data[0:n] return result } // PushPop pushes x to the heap and then pops top element. func (h *Heap[T]) PushPop(x T) T { if h.Len() > 0 && h.comparator(h.data[0], x) { x, h.data[0] = h.data[0], x h.down(0, h.Len()) } return x } // Replace extracts the root of the heap, and push a new item. func (h *Heap[T]) Replace(x T) (result T) { result, h.data[0] = h.data[0], x h.fix(0) return } func (h *Heap[T]) fix(i int) (result T) { if !h.down(i, h.Len()) { h.up(i) } return result } func (h *Heap[T]) swap(i, j int) { h.data[i], h.data[j] = h.data[j], h.data[i] } func (h *Heap[T]) up(j int) { for { i := (j - 1) / 2 // parent if i == j || !h.comparator(h.data[j], h.data[i]) { break } h.swap(i, j) j = i } } func (h *Heap[T]) down(i0, n int) bool { i := i0 for { j1 := 2*i + 1 if j1 >= n || j1 < 0 { // j1 < 0 after int overflow break } j := j1 // left child if j2 := j1 + 1; j2 < n && h.comparator(h.data[j2], h.data[j1]) { j = j2 // = 2*i + 2 // right child } if !h.comparator(h.data[j], h.data[i]) { break } h.swap(i, j) i = j } return i > i0 }
binheap/generic.go
0.798344
0.532425
generic.go
starcoder
package jose // IANA registered JOSE headers (https://tools.ietf.org/html/rfc7515#section-4.1) const ( // HeaderAlgorithm identifies: // For JWS: the cryptographic algorithm used to secure the JWS. // For JWE: the cryptographic algorithm used to encrypt or determine the value of the CEK. HeaderAlgorithm = "alg" // string // HeaderEncryption identifies the JWE content encryption algorithm. HeaderEncryption = "enc" // string // HeaderJWKSetURL is a URI that refers to a resource for a set of JSON-encoded public keys, one of which: // For JWS: corresponds to the key used to digitally sign the JWS. // For JWE: corresponds to the public key to which the JWE was encrypted. HeaderJWKSetURL = "jku" // string // HeaderJSONWebKey is: // For JWS: the public key that corresponds to the key used to digitally sign the JWS. // For JWE: the public key to which the JWE was encrypted. HeaderJSONWebKey = "jwk" // JSON // HeaderKeyID is a hint: // For JWS: indicating which key was used to secure the JWS. // For JWE: which references the public key to which the JWE was encrypted. HeaderKeyID = "kid" // string // HeaderSenderKeyID is a hint: // For JWS: not used. // For JWE: which references the (sender) public key used in the JWE key derivation/wrapping to encrypt the CEK. HeaderSenderKeyID = "skid" // string // HeaderX509URL is a URI that refers to a resource for the X.509 public key certificate or certificate chain: // For JWS: corresponding to the key used to digitally sign the JWS. // For JWE: corresponding to the public key to which the JWE was encrypted. HeaderX509URL = "x5u" // HeaderX509CertificateChain contains the X.509 public key certificate or certificate chain: // For JWS: corresponding to the key used to digitally sign the JWS. // For JWE: corresponding to the public key to which the JWE was encrypted. HeaderX509CertificateChain = "x5c" // HeaderX509CertificateDigest (X.509 certificate SHA-1 thumbprint) is a base64url-encoded // SHA-1 thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate: // For JWS: corresponding to the key used to digitally sign the JWS. // For JWE: corresponding to the public key to which the JWE was encrypted. HeaderX509CertificateDigestSha1 = "x5t" // HeaderX509CertificateDigestSha256 (X.509 certificate SHA-256 thumbprint) is a base64url-encoded SHA-256 // thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate: // For JWS: corresponding to the key used to digitally sign the JWS. // For JWE: corresponding to the public key to which the JWE was encrypted. HeaderX509CertificateDigestSha256 = "x5t#S256" // string // HeaderType is: // For JWS: used by JWS applications to declare the media type of this complete JWS. // For JWE: used by JWE applications to declare the media type of this complete JWE. HeaderType = "typ" // string // HeaderContentType is used by JWS applications to declare the media type of: // For JWS: the secured content (the payload). // For JWE: the secured content (the plaintext). HeaderContentType = "cty" // string // HeaderCritical indicates that extensions to: // For JWS: this JWS header specification and/or JWA are being used that MUST be understood and processed. // For JWE: this JWE header specification and/or JWA are being used that MUST be understood and processed. HeaderCritical = "crit" // array // HeaderEPK is used by JWE applications to wrap/unwrap the CEK for a recipient. HeaderEPK = "epk" // JSON ) // Header defined in https://tools.ietf.org/html/rfc7797 const ( // HeaderB64 determines whether the payload is represented in the JWS and the JWS Signing // Input as ASCII(BASE64URL(JWS Payload)) or as the JWS Payload value itself with no encoding performed. HeaderB64Payload = "b64" // bool // A256GCMALG is the default content encryption algorithm value as per // the JWA specification: https://tools.ietf.org/html/rfc7518#section-5.1 A256GCMALG = "A256GCM" // XC20PALG represented XChacha20Poly1305 content encryption algorithm value. XC20PALG = "XC20P" ) // Headers represents JOSE headers. type Headers map[string]interface{} // KeyID gets Key ID from JOSE headers. func (h Headers) KeyID() (string, bool) { return h.stringValue(HeaderKeyID) } // SenderKeyID gets the sender Key ID from Jose headers. func (h Headers) SenderKeyID() (string, bool) { return h.stringValue(HeaderSenderKeyID) } // Algorithm gets Algorithm from JOSE headers. func (h Headers) Algorithm() (string, bool) { return h.stringValue(HeaderAlgorithm) } // Encryption gets content encryption algorithm from JOSE headers. func (h Headers) Encryption() (string, bool) { return h.stringValue(HeaderEncryption) } // Type gets content encryption type from JOSE headers. func (h Headers) Type() (string, bool) { return h.stringValue(HeaderType) } // ContentType gets the payload content type from JOSE headers. func (h Headers) ContentType() (string, bool) { return h.stringValue(HeaderContentType) } func (h Headers) stringValue(key string) (string, bool) { raw, ok := h[key] if !ok { return "", false } str, ok := raw.(string) return str, ok }
pkg/doc/jose/common.go
0.722723
0.457258
common.go
starcoder
package transform import ( "reflect" ) // Rules is a slice where the elements are unary functions like func(*big.Float)json.Number. type Rules []interface{} func (rules Rules) Apply(in interface{}) interface{} { result := rules.apply(reflect.TypeOf(in), reflect.ValueOf(in)) if result.IsValid() { return result.Interface() } return nil } func (rules Rules) apply(target reflect.Type, in reflect.Value) reflect.Value { if !in.IsValid() { return in } // find applicable rule for _, rule := range rules { if in.Type().AssignableTo(reflect.TypeOf(rule).In(0)) { return applyRule(rule, target, in) } } switch in.Kind() { case reflect.Array: return rules.applyArray(in) case reflect.Interface: return rules.applyInterface(target, in) case reflect.Map: return rules.applyMap(in) case reflect.Ptr: return rules.applyPointer(in) case reflect.Slice: return rules.applySlice(in) case reflect.Struct: return rules.applyStruct(in) default: return in } } func (rules Rules) applyArray(in reflect.Value) reflect.Value { result := reflect.New(reflect.ArrayOf(in.Len(), in.Type().Elem())).Elem() for i := 0; i < in.Len(); i++ { newV := rules.apply(in.Type().Elem(), in.Index(i)) result.Index(i).Set(newV) } return result } func (rules Rules) applyInterface(target reflect.Type, in reflect.Value) reflect.Value { if in.IsNil() { return in } return rules.apply(target, in.Elem()) } func (rules Rules) applyMap(in reflect.Value) reflect.Value { if in.IsNil() { return in } result := reflect.MakeMap(in.Type()) for _, k := range in.MapKeys() { newK := rules.apply(in.Type().Key(), k) newV := rules.apply(in.Type().Elem(), in.MapIndex(k)) result.SetMapIndex(newK, newV) } return result } func (rules Rules) applyPointer(in reflect.Value) reflect.Value { if in.IsNil() { return in } ptr := reflect.New(in.Type()).Elem() // create a pointer of the right type ptr.Set(reflect.New(in.Type().Elem())) // create a value for it to point to ptr.Elem().Set(rules.apply(in.Type().Elem(), in.Elem())) return ptr } func (rules Rules) applySlice(in reflect.Value) reflect.Value { if in.IsNil() { return in } result := reflect.MakeSlice(in.Type(), in.Len(), in.Cap()) for i := 0; i < in.Len(); i++ { newV := rules.apply(in.Type().Elem(), in.Index(i)) result.Index(i).Set(newV) } return result } func (rules Rules) applyStruct(in reflect.Value) reflect.Value { result := reflect.New(in.Type()).Elem() for i := 0; i < in.NumField(); i++ { structField := in.Type().Field(i) if structField.PkgPath != "" && !structField.Anonymous { return in // unexported field, cannot safely copy struct } newV := rules.apply(structField.Type, in.Field(i)) result.Field(i).Set(newV) } return result } func applyRule(rule interface{}, target reflect.Type, in reflect.Value) reflect.Value { result := reflect.ValueOf(rule).Call([]reflect.Value{in})[0] if !result.IsValid() && !canBeNil(target) { return in } if result.IsValid() && !result.Type().AssignableTo(target) { return in } return result } // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero. func canBeNil(typ reflect.Type) bool { switch typ.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return true default: return false } }
vendor/github.com/palantir/pkg/transform/transform.go
0.666388
0.477128
transform.go
starcoder
package block import ( "github.com/df-mc/dragonfly/dragonfly/event" "github.com/df-mc/dragonfly/dragonfly/world" "github.com/df-mc/dragonfly/dragonfly/world/sound" "time" ) // Water is a natural fluid that generates abundantly in the world. type Water struct { noNBT empty replaceable // Still makes the water appear as if it is not flowing. Still bool // Depth is the depth of the water. This is a number from 1-8, where 8 is a source block and 1 is the // smallest possible water block. Depth int // Falling specifies if the water is falling. Falling water will always appear as a source block, but its // behaviour differs when it starts spreading. Falling bool } // LiquidDepth returns the depth of the water. func (w Water) LiquidDepth() int { return w.Depth } // SpreadDecay returns 1 - The amount of levels decreased upon spreading. func (Water) SpreadDecay() int { return 1 } // WithDepth returns the water with the depth passed. func (w Water) WithDepth(depth int, falling bool) world.Liquid { w.Depth = depth w.Falling = falling w.Still = false return w } // LiquidFalling returns Water.Falling. func (w Water) LiquidFalling() bool { return w.Falling } // HasLiquidDrops ... func (Water) HasLiquidDrops() bool { return false } // LightDiffusionLevel ... func (Water) LightDiffusionLevel() uint8 { return 2 } // ScheduledTick ... func (w Water) ScheduledTick(pos world.BlockPos, wo *world.World) { if w.Depth == 7 { // Attempt to form new water source blocks. count := 0 pos.Neighbours(func(neighbour world.BlockPos) { if neighbour[1] == pos[1] { if liquid, ok := wo.Liquid(neighbour); ok { if water, ok := liquid.(Water); ok && water.Depth == 8 && !water.Falling { count++ } } } }) if count >= 2 { func() { if canFlowInto(w, wo, pos.Side(world.FaceDown), true) { return } // Only form a new source block if there either is no water below this block, or if the water // below this is not falling (full source block). wo.SetLiquid(pos, Water{Depth: 8, Still: true}) }() } } tickLiquid(w, pos, wo) } // NeighbourUpdateTick ... func (Water) NeighbourUpdateTick(pos, _ world.BlockPos, wo *world.World) { wo.ScheduleBlockUpdate(pos, time.Second/4) } // LiquidType ... func (Water) LiquidType() string { return "water" } // Harden hardens the water if lava flows into it. func (w Water) Harden(pos world.BlockPos, wo *world.World, flownIntoBy *world.BlockPos) bool { if flownIntoBy == nil { return false } if lava, ok := wo.Block(pos.Side(world.FaceUp)).(Lava); ok { ctx := event.C() wo.Handler().HandleLiquidHarden(ctx, pos, w, lava, Stone{}) ctx.Continue(func() { wo.PlaceBlock(pos, Stone{}) wo.PlaySound(pos.Vec3Centre(), sound.Fizz{}) }) return true } else if lava, ok := wo.Block(*flownIntoBy).(Lava); ok { ctx := event.C() wo.Handler().HandleLiquidHarden(ctx, pos, w, lava, Cobblestone{}) ctx.Continue(func() { wo.PlaceBlock(*flownIntoBy, Cobblestone{}) wo.PlaySound(pos.Vec3Centre(), sound.Fizz{}) }) return true } return false } // EncodeBlock ... func (w Water) EncodeBlock() (name string, properties map[string]interface{}) { if w.Depth < 1 || w.Depth > 8 { panic("invalid water depth, must be between 1 and 8") } v := 8 - w.Depth if w.Falling { v += 8 } if w.Still { return "minecraft:water", map[string]interface{}{"liquid_depth": int32(v)} } return "minecraft:flowing_water", map[string]interface{}{"liquid_depth": int32(v)} } // Hash ... func (w Water) Hash() uint64 { return hashWater | (uint64(boolByte(w.Falling)) << 32) | (uint64(boolByte(w.Still)) << 33) | (uint64(w.Depth) << 34) } // allWater returns a list of all water states. func allWater() (b []world.Block) { f := func(still, falling bool) { b = append(b, Water{Still: still, Falling: falling, Depth: 8}) b = append(b, Water{Still: still, Falling: falling, Depth: 7}) b = append(b, Water{Still: still, Falling: falling, Depth: 6}) b = append(b, Water{Still: still, Falling: falling, Depth: 5}) b = append(b, Water{Still: still, Falling: falling, Depth: 4}) b = append(b, Water{Still: still, Falling: falling, Depth: 3}) b = append(b, Water{Still: still, Falling: falling, Depth: 2}) b = append(b, Water{Still: still, Falling: falling, Depth: 1}) } f(true, true) f(true, false) f(false, false) f(false, true) return }
dragonfly/block/water.go
0.68637
0.441492
water.go
starcoder
package redis_wrapper import ( "io" "log" "os" "strings" "time" "github.com/carltd/glib/internal" "github.com/garyburd/redigo/redis" ) const ( redisTag = "redis" ) type hashWrapper interface { // Removes the specified fields from the hash stored at key HashDel(key string, field ...string) error // Determine if a hash field exists HashExists(key, field string) (bool, error) // Get all the fields and values in a hash HashGet(key string, v interface{}) error // Increment the integer value of a hash field by the given number HashIncrBy(key string, field string, value int64) (int64, error) // Increment the float value of a hash field by the given amount HashIncrByFloat(key string, field string, value float64) (float64, error) // Get all fields in hash HashKeys(key string) ([]string, error) // Get the number of fields in a hash HashLen(key string) (uint, error) // Get the values of all given hash fields HashMemberGet(key string, field ...string) (map[string]interface{}, error) // Set multiple hash fields to multiple values HashMemberSet(key string, m map[string]interface{}) error // Set the v to hash, every field be written if the field has no zero value // override - false : field will not be written when the field exists // true : all field will be written HashSet(key string, v interface{}, override bool) error // Get the length of the value of a hash field HashStrLen(key, field string) (int, error) } // GeoItem for Redis Geo functions type GeoItem struct { Lon, Lat, Distance float64 Name, Hash string } type geoWrapper interface { // Add one or more geo spatial items in the geospatial index represented // using a sorted set GeoAdd(key string, items ...*GeoItem) error // Returns longitude and latitude of members of a geospatial index GeoPosition(key string, items ...*GeoItem) error // Returns the distance between two members of a geospatial index GeoDistance(key, item1, item2 string) (float64, error) // Query a sorted set representing a geospatial index to fetch members // matching a given maximum distance from a point GeoRadius(key string, item *GeoItem, radius float64, limit uint) ([]*GeoItem, error) // Returns members of a geospatial index as standard geohash strings GeoHash(key string, names ...string) (map[string]string, error) } type setWrapper interface { // Add one or more members to a set SetAdd(key string, items ...string) error // Get the number of members in a set SetLen(key string) (int, error) // Subtract multiple sets SetDiff(key ...string) ([]string, error) // Subtract multiple sets and store the resulting set in a key SetDiffStore(target string, key ...string) (uint, error) // Intersect multiple sets SetIntersect(key ...string) ([]string, error) // Intersect multiple sets and store the resulting set in a key SetIntersectStore(target string, key ...string) (uint, error) // Determine if a given value is a member of a set SetIsMember(key, item string) (bool, error) // Get all the members in a set SetMembers(key string) ([]string, error) // Move a member from one set to another // true - if the element is moved. // false - if the element is not a member of source and no operation was performed. SetMoveMember(src, target, item string) (bool, error) // Remove and return one or multiple random members from a set SetPopMember(key string, count uint) ([]string, error) // Get one or multiple random members from a set SetRandMember(key string, count uint) ([]string, error) // Remove one or more members from a set SetRemove(key string, items ...string) error // Add multiple sets SetUnion(key ...string) ([]string, error) // Add multiple sets and store the resulting set in a key SetUnionStore(target string, key ...string) (uint, error) // Incrementally iterate Set elements SetScan() // TODO: 需要实现 } // SortSet item type type SortSetItem struct { Member string // used by member score, // @note - the value must be int64 or float64 when used to zadd // @note - the value will be string when returned Score interface{} } type zrangeOption struct { limit, offset int scores bool } type SortSetRangeOption func(opt *zrangeOption) func WithZRange(limit, offset int) SortSetRangeOption { return func(o *zrangeOption) { o.limit = limit o.offset = offset } } func WithZScores() SortSetRangeOption { return func(o *zrangeOption) { o.scores = true } } type sortSetWrapper interface { // Add one or more members to a sorted set, or update its score if it already exists SortSetAdd(key string, items ...*SortSetItem) error // Get the number of members in a sorted set SortSetLen(key string) (int, error) // Remove one or more members from a sorted set SortSetRemove(key string, names ...string) error // Count the members in a sorted set with scores within the given values SortSetCount(key string, minScore, maxScore uint) (uint, error) // Increment the score of a member in a sorted set SortSetIncrBy(key string, item string, val int) (string, error) // Return a range of members in a sorted set, by index SortSetRange(key string, minIndex, maxIndex uint) ([]*SortSetItem, error) // Return a range of members in a sorted set, by score SortSetRangeByScore(key string, minScore, maxScore string, opts ...SortSetRangeOption) ([]*SortSetItem, error) // Determine the index of a member in a sorted set SortSetRank(key, name string) (uint, error) // Remove all members in a sorted set within the given indexes SortSetRemoveRangeByRank(key string, minRank, maxRank int) (uint, error) // Remove all members in a sorted set within the given scores SortSetRemoveRangeByScore(key, minScore, maxScore string) (uint, error) //ZREVRANGE() //ZREVRANGEBYSCORE() //ZREVRANK() //ZSCORE() //ZUNIONSTORE() //ZINTERSTORE() //ZSCAN() //ZRANGEBYLEX() //ZLEXCOUNT() //ZREMRANGEBYLEX() } type stringWrapper interface { APPEND() BITCOUNT() BITOP() BITFIELD() DECR() DECRBY() GET() GETBIT() GETRANGE() GETSET() INCR() INCRBY() INCRBYFLOAT() MGET() MSET() MSETNX() PSETEX() SET() SETBIT() SETEX() SETNX() SETRANGE() STRLEN() } type RedisScriptParam struct { Keys []string Args []interface{} } type scriptWrapper interface { // Check existence of scripts in the script cache. ScriptIsExists(shaValue string) (bool, error) // Execute a Lua script server side ScriptEval(shaValue string, param RedisScriptParam) (interface{}, error) // Load the specified Lua script into the script cache. ScriptLoad(script string) (string, error) } type keyWrapper interface { Delete(key ...string) (int64, error) } type RedisWrapper interface { io.Closer hashWrapper geoWrapper setWrapper keyWrapper sortSetWrapper // TODO stringWrapper scriptWrapper // The returned `redis.Conn` should be closed by manual Raw() redis.Conn } type redisWrapper struct { pool *redis.Pool } func (w *redisWrapper) Raw() redis.Conn { return w.pool.Get() } func (w *redisWrapper) Close() error { return w.pool.Close() } func Open(dsn string) (RedisWrapper, error) { opt, err := internal.ParseRedisDSN(dsn) if err != nil { return nil, err } if !strings.HasPrefix(opt.Url, "redis://") { opt.Url = "redis://" + opt.Url } var pool = &redis.Pool{ MaxIdle: opt.MaxIdle, MaxActive: opt.MaxActive, IdleTimeout: opt.IdleTimeout, Dial: func() (redis.Conn, error) { var conn, err = redis.DialURL( opt.Url, redis.DialConnectTimeout(opt.ConnectTimeout), redis.DialReadTimeout(opt.ReadTimeout), redis.DialWriteTimeout(opt.WriteTimeout), ) if opt.Debug { conn = redis.NewLoggingConn(conn, log.New(os.Stdout, "", log.LstdFlags), "redis") } return conn, err }, TestOnBorrow: func(c redis.Conn, t time.Time) error { if time.Since(t) < opt.TTL { return nil } _, err := c.Do("PING") return err }, Wait: true, } c := pool.Get() if _, err = c.Do("PING"); err != nil { _ = pool.Close() return nil, err } _ = c.Close() return &redisWrapper{pool: pool}, nil }
redis_wrapper/wrapper.go
0.671147
0.452657
wrapper.go
starcoder
package calculator import ( "fmt" "math" "strconv" "strings" ) // Add adds all the other numbers to the first. func Add(a float64, b ...float64) float64 { for _, v := range b { a += v } return a } // Subtract subtracts all the other numbers from the first. func Subtract(a float64, b ...float64) float64 { for _, v := range b { a -= v } return a } // Multiply multiples all the given numbers together. func Multiply(a float64, b ...float64) float64 { for _, v := range b { a *= v } return a } // Divide divides the first number with all the rest. // If any other then the first equals to 0, returns an error. func Divide(a float64, b ...float64) (float64, error) { for _, v := range b { if v == 0 { return 0, fmt.Errorf("divide by 0 is not allowed") } a /= v } return a, nil } // Sqrt takes a number and returns with the square root of it. // If the base is negative, gives an error. func Sqrt(a float64) (float64, error) { if a < 0 { return 0, fmt.Errorf("input have to be positive") } return math.Sqrt(a), nil } // StringHandler receives a string and calls Add, Subtract, Multiply or Divide based on its content. func StringHandler(input string) (ret float64, err error) { operator := strings.IndexAny(input, "+-*/") if operator == -1 { return 0, fmt.Errorf("unrecognized operation") } elements := strings.Split(input, string(input[operator])) if len(elements) != 2 { return 0, fmt.Errorf("not two parts") } a, err := strconv.ParseFloat(strings.TrimSpace(elements[0]), 64) if err != nil { return 0, fmt.Errorf("a: failed parsing float64") } b, err := strconv.ParseFloat(strings.TrimSpace(elements[1]), 64) if err != nil { return 0, fmt.Errorf("b: failed parsing float64") } switch string(input[operator]) { case "+": return Add(a, b), nil case "-": return Subtract(a, b), nil case "*": return Multiply(a, b), nil case "/": ret, err = Divide(a, b) return ret, err } return 0, fmt.Errorf("failed to decide which function to call") }
calculator.go
0.793986
0.441071
calculator.go
starcoder
package medtronic import ( "fmt" "time" ) const ( maxBasal = 34000 // milliUnits maxDuration = 24 * time.Hour ) // TempBasalType represents the temp basal type. type TempBasalType byte //go:generate stringer -type TempBasalType const ( // Absolute represents the pump's use of absolute rates for temporary basals. Absolute TempBasalType = 0 // Percent represents the pump's use of percentage rates for temporary basals. Percent TempBasalType = 1 ) // TempBasalInfo represents a temporary basal setting. type TempBasalInfo struct { Duration time.Duration Type TempBasalType Rate *Insulin `json:",omitempty"` Percent *uint8 `json:",omitempty"` } func decodeTempBasal(data []byte) (TempBasalInfo, error) { if len(data) < 7 || data[0] != 6 { return TempBasalInfo{}, BadResponseError{Command: tempBasal, Data: data} } d := time.Duration(twoByteInt(data[5:7])) * time.Minute tempType := TempBasalType(data[1]) info := TempBasalInfo{Duration: d, Type: tempType} switch tempType { case Absolute: rate := twoByteInsulin(data[3:5], 23) info.Rate = &rate case Percent: percent := data[2] info.Percent = &percent default: return info, BadResponseError{Command: tempBasal, Data: data} } return info, nil } // TempBasal returns the pump's current temporary basal setting. // If none is in effect, it will have a Duration of 0. func (pump *Pump) TempBasal() TempBasalInfo { data := pump.Execute(tempBasal) if pump.Error() != nil { return TempBasalInfo{} } info, err := decodeTempBasal(data) pump.SetError(err) return info } // SetAbsoluteTempBasal sets a temporary basal with the given absolute rate and duration. func (pump *Pump) SetAbsoluteTempBasal(duration time.Duration, rate Insulin) { d := pump.halfHours(duration) r, err := encodeBasalRate("temporary basal", rate, pump.Family()) if err != nil { pump.SetError(err) return } args := append(marshalUint16(r), d) pump.Execute(setAbsoluteTempBasal, args...) } // SetPercentTempBasal sets a temporary basal with the given percent rate and duration. func (pump *Pump) SetPercentTempBasal(duration time.Duration, percent int) { d := pump.halfHours(duration) if percent < 0 || 100 < percent { pump.SetError(fmt.Errorf("percent temporary basal rate (%d) is not between 0 and 100", percent)) return } pump.Execute(setPercentTempBasal, byte(percent), d) } func (pump *Pump) halfHours(duration time.Duration) uint8 { const halfHour = 30 * time.Minute if duration%halfHour != 0 { pump.SetError(fmt.Errorf("duration (%v) is not a multiple of 30 minutes", duration)) return 0 } if duration < 0 { pump.SetError(fmt.Errorf("duration (%v) is negative", duration)) return 0 } if duration > maxDuration { pump.SetError(fmt.Errorf("duration (%v) is too large", duration)) return 0 } return uint8(duration / halfHour) }
tempbasal.go
0.653016
0.457864
tempbasal.go
starcoder
package heap import ( "errors" "math" ) type Heap struct { array []int size int isMax bool } func (obj *Heap) New(isMax bool, array ...int) { obj.isMax = isMax if len(array) > 0 { obj.array = array } else { obj.array = make([]int, 0) } } func (obj *Heap) GetSize() int { return obj.size } func (obj *Heap) SetSize(value int) { obj.size = value } func (obj *Heap) GetArrayLength() int { return len(obj.array) } func (obj *Heap) At(pos int) int { return obj.array[pos] } func (obj *Heap) Set(value int, pos int) (err error) { if len(obj.array) < pos { err = errors.New("pos is bigger than the array size") } else { obj.array[pos] = value } return } func (obj *Heap) Append(value int) { obj.array = append(obj.array, value) } func (obj *Heap) Parent(i int) int { if i%2 == 0 { return i>>1 - 1 } else { return i >> 1 } } func (obj *Heap) Left(i int) int { return (i << 1) + 1 } func (obj *Heap) Right(i int) int { return (i << 1) + 2 } func (a *Heap) Heapify(i int) { var largest int l := a.Left(i) r := a.Right(i) if a.isMax { if l <= a.GetSize()-1 && a.At(l) > a.At(i) { largest = l } else { largest = i } if r <= a.GetSize()-1 && a.At(r) > a.At(largest) { largest = r } } else { if l <= a.GetSize()-1 && a.At(l) < a.At(i) { largest = l } else { largest = i } if r <= a.GetSize()-1 && a.At(r) < a.At(largest) { largest = r } } if largest != i { tmp := a.At(i) a.Set(a.At(largest), i) a.Set(tmp, largest) a.Heapify(largest) } } func (a *Heap) BuildHeap() { a.SetSize(a.GetArrayLength()) for i := a.GetArrayLength() / 2; i >= 0; i-- { a.Heapify(i) } } func (a *Heap) RootNode() int { return a.At(0) } func (a *Heap) ExtractRoot() (max int, err error) { if a.GetSize() < 1 { err = errors.New("Heap Underflow") return } else { max = a.At(0) a.Set(a.At(a.GetSize()), 0) a.SetSize(a.GetSize() - 1) a.Heapify(0) return } } func (a *Heap) IncreaseKey(i int, key int) (err error) { if a.isMax { if key < a.At(i) { return errors.New("New key is smaller than the current key") } } else { if key > a.At(i) { return errors.New("New key is bigger than the current key") } } a.Set(key, i) for i > 1 && a.At(a.Parent(i)) < a.At(i) { tmp := a.At(i) a.Set(a.At(a.Parent(i)), i) a.Set(tmp, a.Parent(i)) i = a.Parent(i) } return } func (a *Heap) MaxHeapInsert(key int) { a.Append(math.MinInt32) a.SetSize(a.GetSize() + 1) a.IncreaseKey(a.GetSize()-1, key) }
go/heap/heap.go
0.503418
0.403097
heap.go
starcoder
package system import ( "github.com/stretchr/testify/require" "github.com/clearblade/cbtest" "github.com/clearblade/cbtest/config" "github.com/clearblade/cbtest/provider" ) // Import imports the system given by merging the base system given by // `systemPath` and the extra files given by each of the `extraPaths`. // Panics on failure. func Import(t cbtest.T, systemPath string, extraPaths ...string) *EphemeralSystem { t.Helper() system, err := ImportE(t, systemPath, extraPaths...) require.NoError(t, err) return system } // ImportE imports the system given by merging the base system given by // `systemPath` and the extra files given by each of the `extraPaths`. // Returns error on failure. func ImportE(t cbtest.T, systemPath string, extraPaths ...string) (*EphemeralSystem, error) { t.Helper() config, err := config.ObtainConfig(t) if err != nil { return nil, err } return ImportWithConfigE(t, config, systemPath, extraPaths...) } // ImportWithConfig imports the system given by merging the base system // given by `systemPath` and the extra files given by each of the `extraPaths` // into the platform instance given by the config. // Panics on error. func ImportWithConfig(t cbtest.T, provider provider.Config, systemPath string, extraPaths ...string) *EphemeralSystem { t.Helper() system, err := ImportWithConfigE(t, provider, systemPath, extraPaths...) require.NoError(t, err) return system } // ImportWithConfigE imports the system given by merging the base system // given by `systemPath` and the extra files given by each of the `extraPaths` // into the platform instance given by the config. // Returns error on failure. func ImportWithConfigE(t cbtest.T, provider provider.Config, systemPath string, extraPaths ...string) (*EphemeralSystem, error) { t.Helper() return runImportWorkflow(t, provider, &defaultImportSteps{ path: systemPath, extra: extraPaths, }) } // runImportWorkflow is an unexported function that runs the import workflow. func runImportWorkflow(t cbtest.T, provider provider.Config, steps importSteps) (*EphemeralSystem, error) { t.Helper() var err error config := provider.Config(t) systemPath := steps.Path() extraPaths := steps.Extra() // make sure the system is actually a system err = steps.CheckSystem(systemPath) if err != nil { return nil, err } // our imported system root will be at a temporary directory tempdir, tempcleanup := steps.MakeTempDir() // the system paths that are gonna be merged into the temporary directory mergePaths := make([]string, 0, 1+len(extraPaths)) mergePaths = append(mergePaths, systemPath) mergePaths = append(mergePaths, extraPaths...) t.Log("Merging system folders...") err = steps.MergeFolders(tempdir, mergePaths...) if err != nil { steps.Cleanup(tempdir) tempcleanup() return nil, err } t.Log("Registering developer...") err = steps.RegisterDeveloper(t, config) if err != nil { steps.Cleanup(tempdir) tempcleanup() return nil, err } t.Log("Importing system into platform...") systemKey, systemSecret, err := steps.DoImport(t, config, tempdir) if err != nil { steps.Cleanup(tempdir) tempcleanup() return nil, err } system := newImportedSystem(config, tempdir) system.config.SystemKey = systemKey system.config.SystemSecret = systemSecret t.Log("Import successful") t.Logf("Platform URL: %s", system.PlatformURL()) t.Logf("Messaging URL: %s", system.MessagingURL()) t.Logf("System key: %s", system.SystemKey()) t.Logf("System URL: %s", system.RemoteURL()) return system, nil }
modules/system/import.go
0.778818
0.44342
import.go
starcoder
package elements import ( "github.com/fileformats/graphics/jt/model" "errors" ) // Late Loaded Property Atom Element is a property atom type used to reference an associated piece of atomic // data in a separate addressable segment of the JT file. The connotation derives from the associated data being // stored in a separate addressable segment of the JT file, and thus a JT file reader can be structured to support // the best practice of delaying the loading/reading of the associated data until it is actually needed. type LateLoadedPropertyAtom struct { BasePropertyAtom // Version Number is the version identifier for this data collection VersionNumber uint8 // Segment ID is the globally unique identifier for the associated data segment in the JT file SegmentId model.GUID // Segment Type defines a broad classification of the associated data segment contents SegmentType int32 // Object ID is the identifier for the payload. Other objects referencing this particular // payload will do so using the Object ID PayloadObjectId int32 // Reserved data field that is guaranteed to always be greater than or equal to 1 Reserved int32 } func (n LateLoadedPropertyAtom) GUID() model.GUID { return model.LateLoadedPropertyAtomElement } func (n *LateLoadedPropertyAtom) Read(c *model.Context) error { c.LogGroup("LateLoadedPropertyAtom") defer c.LogGroupEnd() if err := (&n.BasePropertyAtom).Read(c); err != nil { return err } if c.Version.GreaterEqThan(model.V9) { if c.Version.GreaterEqThan(model.V10) { n.VersionNumber = c.Data.UInt8() } else { n.VersionNumber = uint8(c.Data.Int16()) } if n.VersionNumber != 1 { return errors.New("Invalid version number") } c.Log("VersionNumber: %d", n.VersionNumber) } c.Data.Unpack(&n.SegmentId) c.Log("SegmentId: %s (%s)", n.SegmentId, n.SegmentId.Name()) n.SegmentType = c.Data.Int32() c.Log("SegmentType: %d", n.SegmentType) if c.Version.GreaterEqThan(model.V9) { n.PayloadObjectId = c.Data.Int32() c.Log("PayloadObjectId: %d", n.PayloadObjectId) n.Reserved = c.Data.Int32() c.Log("Reserved: %d", n.Reserved) } return c.Data.GetError() } func (n *LateLoadedPropertyAtom) Value() interface{} { return n.PayloadObjectId } func (n *LateLoadedPropertyAtom) GetPropertyAtom() *BasePropertyAtom { return &n.BasePropertyAtom } func (n *LateLoadedPropertyAtom) BaseElement() *JTElement { return &n.JTElement }
jt/segments/elements/LateLoadedPropertyAtom.go
0.739705
0.463748
LateLoadedPropertyAtom.go
starcoder
package resample import ( "math" ) /* * The Lanczos kernel function L(x, a). */ func lanczosKernel(x float64, a float64) float64 { /* * Calculate the sections of the Lanczos kernel. */ if x == 0 { return 1.0 } else if (-a < x) && (x < a) { piX := math.Pi * x piXa := piX / a piXsquared := piX * piX xSin := math.Sin(piX) xaSin := math.Sin(piXa) prodSins := xSin * xaSin arg := a * prodSins result := arg / piXsquared return result } else { return 0.0 } } /* * The Lanczos interpolation function S(s, x, a). */ func lanczosInterpolate(s []float64, x float64, a uint16) float64 { floorX := math.Floor(x) idx := int(floorX) idxInc := idx + 1 aInt := int(a) lBound := idxInc - aInt uBound := idxInc + aInt n := len(s) aFloat := float64(a) sum := float64(0.0) /* * Calculate the Lanczos sum. */ for i := lBound; i < uBound; i++ { /* * Check if we are still within the bounds of the slice. */ if (i >= 0) && (i < n) { iFloat := float64(i) diff := x - iFloat fac := s[i] val := lanczosKernel(diff, aFloat) sum += fac * val } } return sum } /* * Resample time series data from a source to a target sampling rate using the * Lanczos resampling method. */ func Time(samples []float64, sourceRate uint32, targetRate uint32) []float64 { inputLength := len(samples) inputLengthFloat := float64(inputLength) sourceRateFloat := float64(sourceRate) targetRateFloat := float64(targetRate) expansion := targetRateFloat / sourceRateFloat outputLengthFloat := inputLengthFloat * expansion outputLengthFloor := math.Floor(outputLengthFloat) outputLength := int(outputLengthFloor) /* * If we exactly hit the last sample, do not expand the sequence. */ if outputLengthFloor == outputLengthFloat { outputLength-- } outputBuffer := make([]float64, outputLength) dx := sourceRateFloat / targetRateFloat /* * Calculate output samples using Lanczos interpolation. */ for i, _ := range outputBuffer { iFloat := float64(i) x := iFloat * dx val := lanczosInterpolate(samples, x, 3) outputBuffer[i] = val } return outputBuffer } /* * Resample frequency domain data to a different number of target bins using * the Lanczos resampling method. */ func Frequency(bins []complex128, numTargetBins uint32) []complex128 { numSourceBins := len(bins) sourceReal := make([]float64, numSourceBins) sourceImag := make([]float64, numSourceBins) /* * Extract real and imaginary sequences from complex sequence. */ for i, elem := range bins { elemReal := real(elem) sourceReal[i] = elemReal elemImag := imag(elem) sourceImag[i] = elemImag } targetBins := make([]complex128, numTargetBins) numSourceBinsFloat := float64(numSourceBins) numTargetBinsFloat := float64(numTargetBins) dx := numSourceBinsFloat / numTargetBinsFloat /* * Calculate output samples using Lanczos interpolation. */ for i, _ := range targetBins { iFloat := float64(i) x := iFloat * dx targetReal := lanczosInterpolate(sourceReal, x, 3) targetImag := lanczosInterpolate(sourceImag, x, 3) targetComplex := complex(targetReal, targetImag) targetBins[i] = targetComplex } return targetBins } /* * Oversample the source signal by a factor and write the result into the * target buffer. */ func Oversample(source []float64, target []float64, factor uint32) { factorFloat := float64(factor) dx := 1.0 / factorFloat /* * Calculate output samples using Lanczos interpolation. */ for i, _ := range target { iFloat := float64(i) x := iFloat * dx val := lanczosInterpolate(source, x, 3) target[i] = val } }
resample/resample.go
0.772702
0.523603
resample.go
starcoder
package navmeshv2 import ( "github.com/g3n/engine/math32" ) const ( CollisionTerrain = iota CollisionObject ) type CollisionFlag byte func (f CollisionFlag) IsTerrain() bool { return f == CollisionTerrain } func (f CollisionFlag) IsObject() bool { return f == CollisionObject } type Collision struct { VectorLocal *math32.Vector3 VectorGlobal *math32.Vector3 ContactEdge RtNavmeshEdge Region Flag CollisionFlag } func FindTerrainCollisions(currentPosition, nextPosition RtNavmeshPosition, currentCell, nextCell RtNavmeshCellQuad) (bool, Collision) { collisions := make([]Collision, 0) line1 := LineSegment{ A: currentPosition.Offset, B: nextPosition.Offset, } if currentPosition.Region.ID == nextPosition.Region.ID { if currentCell.Index == nextCell.Index { return false, Collision{} } for _, edge := range currentCell.Edges { if intersects, vIntersection := line1.Intersects(edge.GetLine()); intersects { if edge.GetFlag().IsBlocked() { collisions = append(collisions, Collision{ VectorLocal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), VectorGlobal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), ContactEdge: edge, Region: currentPosition.Region, }) } } } for _, edge := range nextCell.Edges { if intersects, vIntersection := line1.Intersects(edge.GetLine()); intersects { if edge.GetFlag().IsBlocked() { collisions = append(collisions, Collision{ VectorLocal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), VectorGlobal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), ContactEdge: edge, Region: nextPosition.Region, }) } } } } else { vCurGlobal := currentPosition.GetGlobalCoordinates() vNextGlobal := nextPosition.GetGlobalCoordinates() line1 = LineSegment{ A: vCurGlobal, B: vNextGlobal, } for _, edge := range currentCell.Edges { a := RtNavmeshPosition{ Cell: &currentCell, Instance: nil, Region: currentPosition.Region, Offset: edge.GetLine().A, } b := RtNavmeshPosition{ Cell: &currentCell, Instance: nil, Region: currentPosition.Region, Offset: edge.GetLine().B, } line2 := LineSegment{ A: a.GetGlobalCoordinates(), B: b.GetGlobalCoordinates(), } if intersects, vIntersection := line1.Intersects(line2); intersects { if edge.GetFlag().IsBlocked() { collisions = append(collisions, Collision{ VectorLocal: math32.NewVector3(float32(int(vIntersection.X)%int(RegionWidth)), 0, float32(int(vIntersection.Y)%int(RegionHeight))), VectorGlobal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), ContactEdge: edge, Region: currentPosition.Region, }) } } } for _, edge := range nextCell.Edges { a := RtNavmeshPosition{ Cell: &currentCell, Instance: nil, Region: currentPosition.Region, Offset: edge.GetLine().A, } b := RtNavmeshPosition{ Cell: &currentCell, Instance: nil, Region: currentPosition.Region, Offset: edge.GetLine().B, } line2 := LineSegment{ A: a.GetGlobalCoordinates(), B: b.GetGlobalCoordinates(), } if intersects, vIntersection := line1.Intersects(line2); intersects { if edge.GetFlag().IsBlocked() { collisions = append(collisions, Collision{ VectorLocal: math32.NewVector3(float32(int(vIntersection.X)%int(RegionWidth)), 0, float32(int(vIntersection.Y)%int(RegionHeight))), VectorGlobal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), ContactEdge: edge, Region: nextPosition.Region, }) } } } } collision, err := FindNearestCollision(currentPosition.Offset, collisions) if err != nil { return false, Collision{} } else { return true, collision } } func FindObjectCollisions(currentPosition, nextPosition RtNavmeshPosition, currentObjects, nextObjects []RtNavmeshInstObj) (bool, Collision, bool, *math32.Vector3) { collides1, coll1, inObject1, objPos1 := FindCollisionsInObjects(currentPosition, nextPosition, currentObjects) collides2, coll2, inObject2, objPos2 := FindCollisionsInObjects(currentPosition, nextPosition, nextObjects) if collides1 && collides2 { distance1 := currentPosition.Offset.DistanceToSquared(coll1.VectorGlobal) distance2 := currentPosition.Offset.DistanceToSquared(coll2.VectorGlobal) if distance1 <= distance2 { return true, coll1, inObject1, coll1.VectorGlobal } else { return true, coll2, inObject2, coll2.VectorGlobal } } else if collides1 { return true, coll1, inObject1, coll1.VectorGlobal } else if collides2 { return true, coll2, inObject2, coll2.VectorGlobal } else if inObject1 { return false, Collision{}, inObject1, objPos1 } else if inObject2 { return false, Collision{}, inObject2, objPos2 } else { return false, Collision{}, false, nil } } func FindCollisionsInObjects(cur, next RtNavmeshPosition, objects []RtNavmeshInstObj) (bool, Collision, bool, *math32.Vector3) { inObj := false inObj2 := false var objPos *math32.Vector3 for _, object := range objects { vCurLocal := cur.Offset.Clone().ApplyMatrix4(object.GetWorldToLocal()) vNextLocal := next.Offset.Clone().ApplyMatrix4(object.GetWorldToLocal()) curInObject := object.Object.IsPositionInObjectCell(vCurLocal) nextInObject := object.Object.IsPositionInObjectCell(vNextLocal) if !curInObject && !nextInObject { // skip continue } line1 := LineSegment{ A: vCurLocal.Clone(), B: vNextLocal.Clone(), } gCollisions := make([]Collision, 0) iCollisions := make([]Collision, 0) for _, gEdge := range object.Object.GlobalEdges { line2 := gEdge.GetLine() if intersects, vIntersection := line1.Intersects(line2); intersects { if gEdge.GetFlag().IsBlocked() || (curInObject && gEdge.GetFlag().IsBridge()) { gCollisions = append(gCollisions, Collision{ VectorLocal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), VectorGlobal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y).ApplyMatrix4(object.GetLocalToWorld()), ContactEdge: &gEdge, Region: object.Region, }) } else { inObj = true } } } for _, iEdge := range object.Object.InternalEdges { line2 := iEdge.GetLine() if intersects, vIntersection := line1.Intersects(line2); intersects { if iEdge.GetFlag().IsBlocked() { iCollisions = append(iCollisions, Collision{ VectorLocal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y), VectorGlobal: math32.NewVector3(vIntersection.X, 0, vIntersection.Y).ApplyMatrix4(object.GetLocalToWorld()), ContactEdge: &iEdge, Region: object.Region, }) } else { inObj2 = true } } } filteredGlobalCollisions := make([]Collision, 0) for _, collision := range gCollisions { flag := collision.ContactEdge.GetFlag() if curInObject && flag.IsBridge() { filteredGlobalCollisions = append(filteredGlobalCollisions, collision) } } finalCollisions := make([]Collision, 0) nearestGlobalCollision, err1 := FindNearestCollision(vCurLocal, filteredGlobalCollisions) nearestLocalCollision, err2 := FindNearestCollision(vCurLocal, iCollisions) if err1 == nil { finalCollisions = append(finalCollisions, nearestGlobalCollision) } if err2 == nil { finalCollisions = append(finalCollisions, nearestLocalCollision) } finalCollision, err3 := FindNearestCollision(vCurLocal, finalCollisions) if inObj || inObj2 { _, height := object.Object.FindHeight(vNextLocal) objPos = vNextLocal objPos.Y = height objPos.ApplyMatrix4(object.LocalToWorld) } if err3 == ErrEmptyCollisionList { // no collision! continue } return true, finalCollision, inObj || inObj2, objPos } return false, Collision{}, inObj || inObj2, objPos } func FindNearestCollision(localPosition *math32.Vector3, collisions []Collision) (Collision, error) { delta := math32.Inf(1) var nearestCollision Collision if len(collisions) == 0 { return nearestCollision, ErrEmptyCollisionList } for _, collision := range collisions { if distance := localPosition.DistanceToSquared(collision.VectorLocal); distance <= delta { delta = distance nearestCollision = collision } } return nearestCollision, nil }
navmeshv2/collision.go
0.605099
0.54468
collision.go
starcoder
package schemax /* definitionFlags is an unsigned 8-bit integer that describes zero or more perceived values that only manifest visually when TRUE. Such verisimilitude is revealed by the presence of the indicated definitionFlags value's "label" name, such as `SINGLE-VALUE`. The actual value "TRUE" is never actually seen in textual format. */ type definitionFlags uint8 const ( Obsolete definitionFlags = 1 << iota // 1 SingleValue // 2 Collective // 4 NoUserModification // 8 HumanReadable // 16 (applies only to *LDAPSyntax instances) ) func (r definitionFlags) IsZero() bool { return uint8(r) == 0 } /* is returns a boolean value indicative of whether the specified value is enabled within the receiver instance. */ func (r definitionFlags) is(o definitionFlags) bool { return r.enabled(o) } /* String is a stringer method that returns the name(s) definitionFlags receiver in question, whether it represents multiple boolean flags or only one. If only a specific definitionFlags string is desired (if enabled), use definitionFlags.<Name>() (e.g: definitionFlags.Obsolete()). */ func (r definitionFlags) String() (val string) { // Look for so-called "pure" // boolean values first ... switch r { case NoUserModification: return `NO-USER-MODIFICATION` case SingleValue: return `SINGLE-VALUE` case Obsolete: return `OBSOLETE` case Collective: return `COLLECTIVE` case HumanReadable: return `HUMAN-READABLE` } // Assume multiple boolean bits // are set concurrently ... strs := []definitionFlags{ Obsolete, Collective, SingleValue, HumanReadable, NoUserModification, } vals := make([]string, 0) for _, v := range strs { if r.enabled(v) { vals = append(vals, v.String()) } } if len(vals) != 0 { val = join(vals, ` `) } return } /* Obsolete returns the `OBSOLETE` flag if the appropriate bits are set within the receiver instance. */ func (r definitionFlags) Obsolete() string { if r.enabled(Obsolete) { return r.String() } return `` } /* SingleValue returns the `SINGLE-VALUE` flag if the appropriate bits are set within the receiver instance. */ func (r definitionFlags) SingleValue() string { if r.enabled(SingleValue) { return r.String() } return `` } /* Collective returns the `COLLECTIVE` flag if the appropriate bits are set within the receiver instance. */ func (r definitionFlags) Collective() string { if r.enabled(Collective) { return r.String() } return `` } /* HumanReadable returns the `HUMAN-READABLE` flag if the appropriate bits are set within the receiver instance. Note this would only apply to *LDAPSyntax instances bearing this type. */ func (r definitionFlags) HumanReadable() string { if r.enabled(HumanReadable) { return r.String() } return `` } /* NoUserModification returns the `NO-USER-MODIFICATION` flag if the appropriate bits are set within the receiver instance. */ func (r definitionFlags) NoUserModification() string { if r.enabled(NoUserModification) { return r.String() } return `` } /* Unset removes the specified definitionFlags bits from the receiver instance of definitionFlags, thereby "disabling" the provided option. */ func (r *definitionFlags) Unset(o definitionFlags) { r.unset(o) } /* Set adds the specified definitionFlags bits to the receiver instance of definitionFlags, thereby "enabling" the provided option. */ func (r *definitionFlags) Set(o definitionFlags) { r.set(o) } func (r *definitionFlags) set(o definitionFlags) { *r = *r ^ o } func (b *definitionFlags) unset(o definitionFlags) { *b = *b &^ o } func (r definitionFlags) enabled(o definitionFlags) bool { return r&o != 0 } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *DITStructureRule) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r DITStructureRule) Obsolete() bool { return r.flags.is(Obsolete) } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *DITContentRule) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r DITContentRule) Obsolete() bool { return r.flags.is(Obsolete) } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *MatchingRuleUse) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r MatchingRuleUse) Obsolete() bool { return r.flags.is(Obsolete) } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *MatchingRule) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r MatchingRule) Obsolete() bool { return r.flags.is(Obsolete) } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *LDAPSyntax) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r LDAPSyntax) Obsolete() bool { return r.flags.is(Obsolete) } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *ObjectClass) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r ObjectClass) Obsolete() bool { return r.flags.is(Obsolete) } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *AttributeType) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r AttributeType) Obsolete() bool { return r.flags.is(Obsolete) } /* setdefinitionFlags is a private method used by reflect to set boolean values. */ func (r *NameForm) setdefinitionFlags(b definitionFlags) { r.flags.set(b) } /* Obsolete returns a boolean value that reflects whether the receiver instance is marked OBSOLETE. */ func (r NameForm) Obsolete() bool { return r.flags.is(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *AttributeType) SetObsolete() { r.flags.set(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *ObjectClass) SetObsolete() { r.flags.set(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *MatchingRule) SetObsolete() { r.flags.set(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *MatchingRuleUse) SetObsolete() { r.flags.set(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *DITStructureRule) SetObsolete() { r.flags.set(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *DITContentRule) SetObsolete() { r.flags.set(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *NameForm) SetObsolete() { r.flags.set(Obsolete) } /* SetObsolete marks the receiver as OBSOLETE. */ func (r *LDAPSyntax) SetObsolete() { r.flags.set(Obsolete) } /* SetHumanReadable marks the LDAPSyntax receiver as HumanReadable. */ func (r *LDAPSyntax) SetHumanReadable() { r.flags.set(HumanReadable) } /* HumanReadable returns a boolean value indicative of whether the receiver describes a HUMAN-READABLE attribute type, typically manifesting as the X-NOT-HUMAN-READABLE ldapSyntax extension. */ func (r *AttributeType) HumanReadable() bool { return r.flags.is(HumanReadable) } /* SetCollective marks the receiver as COLLECTIVE. */ func (r *AttributeType) SetCollective() { r.flags.set(Collective) } /* Collective returns a boolean value indicative of whether the receiver describes a COLLECTIVE attribute type. */ func (r *AttributeType) Collective() bool { return r.flags.is(Collective) } /* SetCollective marks the receiver as NO-USER-MODIFICATION. */ func (r *AttributeType) SetNoUserModification() { r.flags.set(NoUserModification) } /* NoUserModification returns a boolean value indicative of whether the receiver describes a NO-USER-MODIFICATION attribute type. */ func (r *AttributeType) NoUserModification() bool { return r.flags.is(NoUserModification) } /* SetSingleValue marks the receiver as SINGLE-VALUE. */ func (r *AttributeType) SetSingleValue() { r.flags.set(SingleValue) } /* SingleValue returns a boolean value indicative of whether the receiver describes a SINGLE-VALUE attribute type. */ func (r *AttributeType) SingleValue() bool { return r.flags.is(SingleValue) } func validateFlag(b definitionFlags) (err error) { if b.is(Collective) && b.is(SingleValue) { return raise(invalidFlag, "Cannot have single-valued collective attribute") } return }
flags.go
0.883626
0.516595
flags.go
starcoder
package de32 import ( "github.com/ziutek/matrix/matrix32" "math/rand" "time" ) type args struct { a, b, c matrix32.Dense // three vectors for crossover f, cr float32 // differential weight and crossover probability } type Agent struct { x matrix32.Dense in chan args // to send three vectors for crossovera out chan float32 // to obtain actual cost value for this agent rnd *rand.Rand } func newAgent(min, max []float32, newcost func() Cost) *Agent { a := new(Agent) a.x = matrix32.MakeDense(1, len(min)) a.in = make(chan args, 1) a.out = make(chan float32, 1) a.rnd = rand.New(rand.NewSource(time.Now().UnixNano())) // Place this agent in random place on the initial area. x := a.x.Elems() for i, m := range min { x[i] = m + (max[i]-m)*a.rnd.Float32() } // Run crossover loop go a.crossoverLoop(newcost) return a } func (a *Agent) X() []float32 { return a.x.Elems() } // Returns random cut points for crossover func (a *Agent) cutpoints(cr float32) (start, stop int) { n := a.x.NumCol() l := 1 for l < n && a.rnd.Float32() < cr { l++ } // now l <= n start = a.rnd.Intn(n) stop = (start + l) % (n + 1) return } func perturb(u matrix32.Dense, in args, start, stop int) { v := u.Cols(start, stop) v.Sub(in.b.Cols(start, stop), in.c.Cols(start, stop), in.f) v.AddTo(in.a.Cols(start, stop), 1) } // Crossover loop func (a *Agent) crossoverLoop(newcost func() Cost) { u := matrix32.MakeDense(a.x.Size()) n := u.NumCol() cost := newcost() costX := cost.Cost(a.x.Elems()) for in := range a.in { if !in.a.IsValid() { return } start, stop := a.cutpoints(in.cr) // Crossover: // u = a + f * (b + c) for elements between start and stop // u = x for remaining elements if start < stop { u.Cols(0, start).Copy(a.x.Cols(0, start)) perturb(u, in, start, stop) u.Cols(stop, n).Copy(a.x.Cols(stop, n)) } else { stop++ // because it is modulo (n+1) perturb(u, in, 0, stop) u.Cols(stop, start).Copy(a.x.Cols(stop, start)) perturb(u, in, start, n) } // Selection if costU := cost.Cost(u.Elems()); costU <= costX { a.x, u = u, a.x costX = costU } // Return new cost a.out <- costX } }
de32/agent.go
0.632957
0.41253
agent.go
starcoder
package clang // #include "./clang-c/Documentation.h" // #include "./clang-c/Index.h" // #include "go-clang.h" import "C" import ( "reflect" "unsafe" ) /* A cursor representing some element in the abstract syntax tree for a translation unit. The cursor abstraction unifies the different kinds of entities in a program--declaration, statements, expressions, references to declarations, etc.--under a single "cursor" abstraction with a common set of operations. Common operation for a cursor include: getting the physical location in a source file where the cursor points, getting the name associated with a cursor, and retrieving cursors for any child nodes of a particular cursor. Cursors can be produced in two specific ways. clang_getTranslationUnitCursor() produces a cursor for a translation unit, from which one can use clang_visitChildren() to explore the rest of the translation unit. clang_getCursor() maps from a physical source location to the entity that resides at that location, allowing one to map from the source code into the AST. */ type Cursor struct { c C.CXCursor } // Given a cursor that represents a documentable entity (e.g., declaration), return the associated parsed comment as a CXComment_FullComment AST node. func (c Cursor) ParsedComment() Comment { return Comment{C.clang_Cursor_getParsedComment(c.c)} } // Retrieve the NULL cursor, which represents no entity. func NewNullCursor() Cursor { return Cursor{C.clang_getNullCursor()} } // Determine whether two cursors are equivalent. func (c Cursor) Equal(c2 Cursor) bool { o := C.clang_equalCursors(c.c, c2.c) return o != C.uint(0) } // Returns non-zero if \p cursor is null. func (c Cursor) IsNull() bool { o := C.clang_Cursor_isNull(c.c) return o != C.int(0) } // Compute a hash value for the given cursor. func (c Cursor) HashCursor() uint32 { return uint32(C.clang_hashCursor(c.c)) } // Retrieve the kind of the given cursor. func (c Cursor) Kind() CursorKind { return CursorKind(C.clang_getCursorKind(c.c)) } /* Determine whether the given declaration is invalid. A declaration is invalid if it could not be parsed successfully. Returns non-zero if the cursor represents a declaration and it is invalid, otherwise NULL. */ func (c Cursor) IsInvalidDeclaration() bool { o := C.clang_isInvalidDeclaration(c.c) return o != C.uint(0) } // Determine whether the given cursor has any attributes. func (c Cursor) HasAttrs() bool { o := C.clang_Cursor_hasAttrs(c.c) return o != C.uint(0) } // Determine the linkage of the entity referred to by a given cursor. func (c Cursor) Linkage() LinkageKind { return LinkageKind(C.clang_getCursorLinkage(c.c)) } /* Describe the visibility of the entity referred to by a cursor. This returns the default visibility if not explicitly specified by a visibility attribute. The default visibility may be changed by commandline arguments. Parameter cursor The cursor to query. Returns The visibility of the cursor. */ func (c Cursor) Visibility() VisibilityKind { return VisibilityKind(C.clang_getCursorVisibility(c.c)) } /* Determine the availability of the entity that this cursor refers to, taking the current target platform into account. Parameter cursor The cursor to query. Returns The availability of the cursor. */ func (c Cursor) Availability() AvailabilityKind { return AvailabilityKind(C.clang_getCursorAvailability(c.c)) } // Determine the "language" of the entity referred to by a given cursor. func (c Cursor) Language() LanguageKind { return LanguageKind(C.clang_getCursorLanguage(c.c)) } // Determine the "thread-local storage (TLS) kind" of the declaration referred to by a cursor. func (c Cursor) TLSKind() TLSKind { return TLSKind(C.clang_getCursorTLSKind(c.c)) } // Returns the translation unit that a cursor originated from. func (c Cursor) TranslationUnit() TranslationUnit { return TranslationUnit{C.clang_Cursor_getTranslationUnit(c.c)} } /* Determine the semantic parent of the given cursor. The semantic parent of a cursor is the cursor that semantically contains the given \p cursor. For many declarations, the lexical and semantic parents are equivalent (the lexical parent is returned by clang_getCursorLexicalParent()). They diverge when declarations or definitions are provided out-of-line. For example: \code class C { void f(); }; void C::f() { } \endcode In the out-of-line definition of C::f, the semantic parent is the class C, of which this function is a member. The lexical parent is the place where the declaration actually occurs in the source code; in this case, the definition occurs in the translation unit. In general, the lexical parent for a given entity can change without affecting the semantics of the program, and the lexical parent of different declarations of the same entity may be different. Changing the semantic parent of a declaration, on the other hand, can have a major impact on semantics, and redeclarations of a particular entity should all have the same semantic context. In the example above, both declarations of C::f have C as their semantic context, while the lexical context of the first C::f is C and the lexical context of the second C::f is the translation unit. For global declarations, the semantic parent is the translation unit. */ func (c Cursor) SemanticParent() Cursor { return Cursor{C.clang_getCursorSemanticParent(c.c)} } /* Determine the lexical parent of the given cursor. The lexical parent of a cursor is the cursor in which the given \p cursor was actually written. For many declarations, the lexical and semantic parents are equivalent (the semantic parent is returned by clang_getCursorSemanticParent()). They diverge when declarations or definitions are provided out-of-line. For example: \code class C { void f(); }; void C::f() { } \endcode In the out-of-line definition of C::f, the semantic parent is the class C, of which this function is a member. The lexical parent is the place where the declaration actually occurs in the source code; in this case, the definition occurs in the translation unit. In general, the lexical parent for a given entity can change without affecting the semantics of the program, and the lexical parent of different declarations of the same entity may be different. Changing the semantic parent of a declaration, on the other hand, can have a major impact on semantics, and redeclarations of a particular entity should all have the same semantic context. In the example above, both declarations of C::f have C as their semantic context, while the lexical context of the first C::f is C and the lexical context of the second C::f is the translation unit. For declarations written in the global scope, the lexical parent is the translation unit. */ func (c Cursor) LexicalParent() Cursor { return Cursor{C.clang_getCursorLexicalParent(c.c)} } /* Determine the set of methods that are overridden by the given method. In both Objective-C and C++, a method (aka virtual member function, in C++) can override a virtual method in a base class. For Objective-C, a method is said to override any method in the class's base class, its protocols, or its categories' protocols, that has the same selector and is of the same kind (class or instance). If no such method exists, the search continues to the class's superclass, its protocols, and its categories, and so on. A method from an Objective-C implementation is considered to override the same methods as its corresponding method in the interface. For C++, a virtual member function overrides any virtual member function with the same signature that occurs in its base classes. With multiple inheritance, a virtual member function can override several virtual member functions coming from different base classes. In all cases, this function determines the immediate overridden method, rather than all of the overridden methods. For example, if a method is originally declared in a class A, then overridden in B (which in inherits from A) and also in C (which inherited from B), then the only overridden method returned from this function when invoked on C's method will be B's method. The client may then invoke this function again, given the previously-found overridden methods, to map out the complete method-override set. Parameter cursor A cursor representing an Objective-C or C++ method. This routine will compute the set of methods that this method overrides. Parameter overridden A pointer whose pointee will be replaced with a pointer to an array of cursors, representing the set of overridden methods. If there are no overridden methods, the pointee will be set to NULL. The pointee must be freed via a call to clang_disposeOverriddenCursors(). Parameter num_overridden A pointer to the number of overridden functions, will be set to the number of overridden functions in the array pointed to by \p overridden. */ func (c Cursor) OverriddenCursors() []Cursor { var cp_overridden *C.CXCursor var overridden []Cursor var numOverridden C.uint C.clang_getOverriddenCursors(c.c, &cp_overridden, &numOverridden) gos_overridden := (*reflect.SliceHeader)(unsafe.Pointer(&overridden)) gos_overridden.Cap = int(numOverridden) gos_overridden.Len = int(numOverridden) gos_overridden.Data = uintptr(unsafe.Pointer(cp_overridden)) return overridden } // Free the set of overridden cursors returned by \c clang_getOverriddenCursors(). func Dispose(overridden []Cursor) { gos_overridden := (*reflect.SliceHeader)(unsafe.Pointer(&overridden)) cp_overridden := (*C.CXCursor)(unsafe.Pointer(gos_overridden.Data)) C.clang_disposeOverriddenCursors(cp_overridden) } // Retrieve the file that is included by the given inclusion directive cursor. func (c Cursor) IncludedFile() File { return File{C.clang_getIncludedFile(c.c)} } /* Retrieve the physical location of the source constructor referenced by the given cursor. The location of a declaration is typically the location of the name of that declaration, where the name of that declaration would occur if it is unnamed, or some keyword that introduces that particular declaration. The location of a reference is where that reference occurs within the source code. */ func (c Cursor) Location() SourceLocation { return SourceLocation{C.clang_getCursorLocation(c.c)} } /* Retrieve the physical extent of the source construct referenced by the given cursor. The extent of a cursor starts with the file/line/column pointing at the first character within the source construct that the cursor refers to and ends with the last character within that source construct. For a declaration, the extent covers the declaration itself. For a reference, the extent covers the location of the reference (e.g., where the referenced entity was actually used). */ func (c Cursor) Extent() SourceRange { return SourceRange{C.clang_getCursorExtent(c.c)} } // Retrieve the type of a CXCursor (if any). func (c Cursor) Type() Type { return Type{C.clang_getCursorType(c.c)} } /* Retrieve the underlying type of a typedef declaration. If the cursor does not reference a typedef declaration, an invalid type is returned. */ func (c Cursor) TypedefDeclUnderlyingType() Type { return Type{C.clang_getTypedefDeclUnderlyingType(c.c)} } /* Retrieve the integer type of an enum declaration. If the cursor does not reference an enum declaration, an invalid type is returned. */ func (c Cursor) EnumDeclIntegerType() Type { return Type{C.clang_getEnumDeclIntegerType(c.c)} } /* Retrieve the integer value of an enum constant declaration as a signed long long. If the cursor does not reference an enum constant declaration, LLONG_MIN is returned. Since this is also potentially a valid constant value, the kind of the cursor must be verified before calling this function. */ func (c Cursor) EnumConstantDeclValue() int64 { return int64(C.clang_getEnumConstantDeclValue(c.c)) } /* Retrieve the integer value of an enum constant declaration as an unsigned long long. If the cursor does not reference an enum constant declaration, ULLONG_MAX is returned. Since this is also potentially a valid constant value, the kind of the cursor must be verified before calling this function. */ func (c Cursor) EnumConstantDeclUnsignedValue() uint64 { return uint64(C.clang_getEnumConstantDeclUnsignedValue(c.c)) } /* Retrieve the bit width of a bit field declaration as an integer. If a cursor that is not a bit field declaration is passed in, -1 is returned. */ func (c Cursor) FieldDeclBitWidth() int32 { return int32(C.clang_getFieldDeclBitWidth(c.c)) } /* Retrieve the number of non-variadic arguments associated with a given cursor. The number of arguments can be determined for calls as well as for declarations of functions or methods. For other cursors -1 is returned. */ func (c Cursor) NumArguments() int32 { return int32(C.clang_Cursor_getNumArguments(c.c)) } /* Retrieve the argument cursor of a function or method. The argument cursor can be determined for calls as well as for declarations of functions or methods. For other cursors and for invalid indices, an invalid cursor is returned. */ func (c Cursor) Argument(i uint32) Cursor { return Cursor{C.clang_Cursor_getArgument(c.c, C.uint(i))} } /* Returns the number of template args of a function decl representing a template specialization. If the argument cursor cannot be converted into a template function declaration, -1 is returned. For example, for the following declaration and specialization: template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo<float, -7, true>(); The value 3 would be returned from this call. */ func (c Cursor) NumTemplateArguments() int32 { return int32(C.clang_Cursor_getNumTemplateArguments(c.c)) } /* Retrieve the kind of the I'th template argument of the CXCursor C. If the argument CXCursor does not represent a FunctionDecl, an invalid template argument kind is returned. For example, for the following declaration and specialization: template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo<float, -7, true>(); For I = 0, 1, and 2, Type, Integral, and Integral will be returned, respectively. */ func (c Cursor) TemplateArgumentKind(i uint32) TemplateArgumentKind { return TemplateArgumentKind(C.clang_Cursor_getTemplateArgumentKind(c.c, C.uint(i))) } /* Retrieve a CXType representing the type of a TemplateArgument of a function decl representing a template specialization. If the argument CXCursor does not represent a FunctionDecl whose I'th template argument has a kind of CXTemplateArgKind_Integral, an invalid type is returned. For example, for the following declaration and specialization: template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo<float, -7, true>(); If called with I = 0, "float", will be returned. Invalid types will be returned for I == 1 or 2. */ func (c Cursor) TemplateArgumentType(i uint32) Type { return Type{C.clang_Cursor_getTemplateArgumentType(c.c, C.uint(i))} } /* Retrieve the value of an Integral TemplateArgument (of a function decl representing a template specialization) as a signed long long. It is undefined to call this function on a CXCursor that does not represent a FunctionDecl or whose I'th template argument is not an integral value. For example, for the following declaration and specialization: template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo<float, -7, true>(); If called with I = 1 or 2, -7 or true will be returned, respectively. For I == 0, this function's behavior is undefined. */ func (c Cursor) TemplateArgumentValue(i uint32) int64 { return int64(C.clang_Cursor_getTemplateArgumentValue(c.c, C.uint(i))) } /* Retrieve the value of an Integral TemplateArgument (of a function decl representing a template specialization) as an unsigned long long. It is undefined to call this function on a CXCursor that does not represent a FunctionDecl or whose I'th template argument is not an integral value. For example, for the following declaration and specialization: template <typename T, int kInt, bool kBool> void foo() { ... } template <> void foo<float, 2147483649, true>(); If called with I = 1 or 2, 2147483649 or true will be returned, respectively. For I == 0, this function's behavior is undefined. */ func (c Cursor) TemplateArgumentUnsignedValue(i uint32) uint64 { return uint64(C.clang_Cursor_getTemplateArgumentUnsignedValue(c.c, C.uint(i))) } // Determine whether a CXCursor that is a macro, is function like. func (c Cursor) IsMacroFunctionLike() bool { o := C.clang_Cursor_isMacroFunctionLike(c.c) return o != C.uint(0) } // Determine whether a CXCursor that is a macro, is a builtin one. func (c Cursor) IsMacroBuiltin() bool { o := C.clang_Cursor_isMacroBuiltin(c.c) return o != C.uint(0) } // Determine whether a CXCursor that is a function declaration, is an inline declaration. func (c Cursor) IsFunctionInlined() bool { o := C.clang_Cursor_isFunctionInlined(c.c) return o != C.uint(0) } // Returns the Objective-C type encoding for the specified declaration. func (c Cursor) DeclObjCTypeEncoding() string { o := cxstring{C.clang_getDeclObjCTypeEncoding(c.c)} defer o.Dispose() return o.String() } /* Retrieve the return type associated with a given cursor. This only returns a valid type if the cursor refers to a function or method. */ func (c Cursor) ResultType() Type { return Type{C.clang_getCursorResultType(c.c)} } /* Retrieve the exception specification type associated with a given cursor. This is a value of type CXCursor_ExceptionSpecificationKind. This only returns a valid result if the cursor refers to a function or method. */ func (c Cursor) ExceptionSpecificationType() int32 { return int32(C.clang_getCursorExceptionSpecificationType(c.c)) } /* Return the offset of the field represented by the Cursor. If the cursor is not a field declaration, -1 is returned. If the cursor semantic parent is not a record field declaration, CXTypeLayoutError_Invalid is returned. If the field's type declaration is an incomplete type, CXTypeLayoutError_Incomplete is returned. If the field's type declaration is a dependent type, CXTypeLayoutError_Dependent is returned. If the field's name S is not found, CXTypeLayoutError_InvalidFieldName is returned. */ func (c Cursor) OffsetOfField() int64 { return int64(C.clang_Cursor_getOffsetOfField(c.c)) } // Determine whether the given cursor represents an anonymous record declaration. func (c Cursor) IsAnonymous() bool { o := C.clang_Cursor_isAnonymous(c.c) return o != C.uint(0) } // Returns non-zero if the cursor specifies a Record member that is a bitfield. func (c Cursor) IsBitField() bool { o := C.clang_Cursor_isBitField(c.c) return o != C.uint(0) } // Returns 1 if the base class specified by the cursor with kind CX_CXXBaseSpecifier is virtual. func (c Cursor) IsVirtualBase() bool { o := C.clang_isVirtualBase(c.c) return o != C.uint(0) } /* Returns the access control level for the referenced object. If the cursor refers to a C++ declaration, its access control level within its parent scope is returned. Otherwise, if the cursor refers to a base specifier or access specifier, the specifier itself is returned. */ func (c Cursor) AccessSpecifier() AccessSpecifier { return AccessSpecifier(C.clang_getCXXAccessSpecifier(c.c)) } /* Returns the storage class for a function or variable declaration. If the passed in Cursor is not a function or variable declaration, CX_SC_Invalid is returned else the storage class. */ func (c Cursor) StorageClass() StorageClass { return StorageClass(C.clang_Cursor_getStorageClass(c.c)) } /* Determine the number of overloaded declarations referenced by a CXCursor_OverloadedDeclRef cursor. Parameter cursor The cursor whose overloaded declarations are being queried. Returns The number of overloaded declarations referenced by cursor. If it is not a CXCursor_OverloadedDeclRef cursor, returns 0. */ func (c Cursor) NumOverloadedDecls() uint32 { return uint32(C.clang_getNumOverloadedDecls(c.c)) } /* Retrieve a cursor for one of the overloaded declarations referenced by a CXCursor_OverloadedDeclRef cursor. Parameter cursor The cursor whose overloaded declarations are being queried. Parameter index The zero-based index into the set of overloaded declarations in the cursor. Returns A cursor representing the declaration referenced by the given cursor at the specified index. If the cursor does not have an associated set of overloaded declarations, or if the index is out of bounds, returns clang_getNullCursor(); */ func (c Cursor) OverloadedDecl(index uint32) Cursor { return Cursor{C.clang_getOverloadedDecl(c.c, C.uint(index))} } /* For cursors representing an iboutletcollection attribute, this function returns the collection element type. */ func (c Cursor) IBOutletCollectionType() Type { return Type{C.clang_getIBOutletCollectionType(c.c)} } /* Retrieve a Unified Symbol Resolution (USR) for the entity referenced by the given cursor. A Unified Symbol Resolution (USR) is a string that identifies a particular entity (function, class, variable, etc.) within a program. USRs can be compared across translation units to determine, e.g., when references in one translation refer to an entity defined in another translation unit. */ func (c Cursor) USR() string { o := cxstring{C.clang_getCursorUSR(c.c)} defer o.Dispose() return o.String() } // Retrieve a name for the entity referenced by this cursor. func (c Cursor) Spelling() string { o := cxstring{C.clang_getCursorSpelling(c.c)} defer o.Dispose() return o.String() } /* Retrieve a range for a piece that forms the cursors spelling name. Most of the times there is only one range for the complete spelling but for Objective-C methods and Objective-C message expressions, there are multiple pieces for each selector identifier. Parameter pieceIndex the index of the spelling name piece. If this is greater than the actual number of pieces, it will return a NULL (invalid) range. Parameter options Reserved. */ func (c Cursor) SpellingNameRange(pieceIndex uint32, options uint32) SourceRange { return SourceRange{C.clang_Cursor_getSpellingNameRange(c.c, C.uint(pieceIndex), C.uint(options))} } /* Retrieve the default policy for the cursor. The policy should be released after use with \c clang_PrintingPolicy_dispose. */ func (c Cursor) PrintingPolicy() PrintingPolicy { return PrintingPolicy{C.clang_getCursorPrintingPolicy(c.c)} } /* Pretty print declarations. Parameter Cursor The cursor representing a declaration. Parameter Policy The policy to control the entities being printed. If NULL, a default policy is used. Returns The pretty printed declaration or the empty string for other cursors. */ func (c Cursor) PrettyPrinted(policy PrintingPolicy) string { o := cxstring{C.clang_getCursorPrettyPrinted(c.c, policy.c)} defer o.Dispose() return o.String() } /* Retrieve the display name for the entity referenced by this cursor. The display name contains extra information that helps identify the cursor, such as the parameters of a function or template or the arguments of a class template specialization. */ func (c Cursor) DisplayName() string { o := cxstring{C.clang_getCursorDisplayName(c.c)} defer o.Dispose() return o.String() } /* For a cursor that is a reference, retrieve a cursor representing the entity that it references. Reference cursors refer to other entities in the AST. For example, an Objective-C superclass reference cursor refers to an Objective-C class. This function produces the cursor for the Objective-C class from the cursor for the superclass reference. If the input cursor is a declaration or definition, it returns that declaration or definition unchanged. Otherwise, returns the NULL cursor. */ func (c Cursor) Referenced() Cursor { return Cursor{C.clang_getCursorReferenced(c.c)} } /* For a cursor that is either a reference to or a declaration of some entity, retrieve a cursor that describes the definition of that entity. Some entities can be declared multiple times within a translation unit, but only one of those declarations can also be a definition. For example, given: \code int f(int, int); int g(int x, int y) { return f(x, y); } int f(int a, int b) { return a + b; } int f(int, int); \endcode there are three declarations of the function "f", but only the second one is a definition. The clang_getCursorDefinition() function will take any cursor pointing to a declaration of "f" (the first or fourth lines of the example) or a cursor referenced that uses "f" (the call to "f' inside "g") and will return a declaration cursor pointing to the definition (the second "f" declaration). If given a cursor for which there is no corresponding definition, e.g., because there is no definition of that entity within this translation unit, returns a NULL cursor. */ func (c Cursor) Definition() Cursor { return Cursor{C.clang_getCursorDefinition(c.c)} } // Determine whether the declaration pointed to by this cursor is also a definition of that entity. func (c Cursor) IsCursorDefinition() bool { o := C.clang_isCursorDefinition(c.c) return o != C.uint(0) } /* Retrieve the canonical cursor corresponding to the given cursor. In the C family of languages, many kinds of entities can be declared several times within a single translation unit. For example, a structure type can be forward-declared (possibly multiple times) and later defined: \code struct X; struct X; struct X { int member; }; \endcode The declarations and the definition of X are represented by three different cursors, all of which are declarations of the same underlying entity. One of these cursor is considered the "canonical" cursor, which is effectively the representative for the underlying entity. One can determine if two cursors are declarations of the same underlying entity by comparing their canonical cursors. Returns The canonical cursor for the entity referred to by the given cursor. */ func (c Cursor) CanonicalCursor() Cursor { return Cursor{C.clang_getCanonicalCursor(c.c)} } /* If the cursor points to a selector identifier in an Objective-C method or message expression, this returns the selector index. After getting a cursor with #clang_getCursor, this can be called to determine if the location points to a selector identifier. Returns The selector index if the cursor is an Objective-C method or message expression and the cursor is pointing to a selector identifier, or -1 otherwise. */ func (c Cursor) SelectorIndex() int32 { return int32(C.clang_Cursor_getObjCSelectorIndex(c.c)) } /* Given a cursor pointing to a C++ method call or an Objective-C message, returns non-zero if the method/message is "dynamic", meaning: For a C++ method: the call is virtual. For an Objective-C message: the receiver is an object instance, not 'super' or a specific class. If the method/message is "static" or the cursor does not point to a method/message, it will return zero. */ func (c Cursor) IsDynamicCall() bool { o := C.clang_Cursor_isDynamicCall(c.c) return o != C.int(0) } // Given a cursor pointing to an Objective-C message or property reference, or C++ method call, returns the CXType of the receiver. func (c Cursor) ReceiverType() Type { return Type{C.clang_Cursor_getReceiverType(c.c)} } /* Given a cursor that represents a property declaration, return the associated property attributes. The bits are formed from CXObjCPropertyAttrKind. Parameter reserved Reserved for future use, pass 0. */ func (c Cursor) PropertyAttributes(reserved uint32) uint32 { return uint32(C.clang_Cursor_getObjCPropertyAttributes(c.c, C.uint(reserved))) } // Given a cursor that represents an Objective-C method or parameter declaration, return the associated Objective-C qualifiers for the return type or the parameter respectively. The bits are formed from CXObjCDeclQualifierKind. func (c Cursor) DeclQualifiers() uint32 { return uint32(C.clang_Cursor_getObjCDeclQualifiers(c.c)) } // Given a cursor that represents an Objective-C method or property declaration, return non-zero if the declaration was affected by "\@optional". Returns zero if the cursor is not such a declaration or it is "\@required". func (c Cursor) IsObjCOptional() bool { o := C.clang_Cursor_isObjCOptional(c.c) return o != C.uint(0) } // Returns non-zero if the given cursor is a variadic function or method. func (c Cursor) IsVariadic() bool { o := C.clang_Cursor_isVariadic(c.c) return o != C.uint(0) } /* Returns non-zero if the given cursor points to a symbol marked with external_source_symbol attribute. Parameter language If non-NULL, and the attribute is present, will be set to the 'language' string from the attribute. Parameter definedIn If non-NULL, and the attribute is present, will be set to the 'definedIn' string from the attribute. Parameter isGenerated If non-NULL, and the attribute is present, will be set to non-zero if the 'generated_declaration' is set in the attribute. */ func (c Cursor) IsExternalSymbol() (string, string, uint32, bool) { var language cxstring defer language.Dispose() var definedIn cxstring defer definedIn.Dispose() var isGenerated C.uint o := C.clang_Cursor_isExternalSymbol(c.c, &language.c, &definedIn.c, &isGenerated) return language.String(), definedIn.String(), uint32(isGenerated), o != C.uint(0) } // Given a cursor that represents a declaration, return the associated comment's source range. The range may include multiple consecutive comments with whitespace in between. func (c Cursor) CommentRange() SourceRange { return SourceRange{C.clang_Cursor_getCommentRange(c.c)} } // Given a cursor that represents a declaration, return the associated comment text, including comment markers. func (c Cursor) RawCommentText() string { o := cxstring{C.clang_Cursor_getRawCommentText(c.c)} defer o.Dispose() return o.String() } // Given a cursor that represents a documentable entity (e.g., declaration), return the associated \paragraph; otherwise return the first paragraph. func (c Cursor) BriefCommentText() string { o := cxstring{C.clang_Cursor_getBriefCommentText(c.c)} defer o.Dispose() return o.String() } // Retrieve the CXString representing the mangled name of the cursor. func (c Cursor) Mangling() string { o := cxstring{C.clang_Cursor_getMangling(c.c)} defer o.Dispose() return o.String() } // Retrieve the CXStrings representing the mangled symbols of the C++ constructor or destructor at the cursor. func (c Cursor) CXXManglings() *StringSet { o := C.clang_Cursor_getCXXManglings(c.c) var gop_o *StringSet if o != nil { gop_o = &StringSet{*o} } return gop_o } // Retrieve the CXStrings representing the mangled symbols of the ObjC class interface or implementation at the cursor. func (c Cursor) ObjCManglings() *StringSet { o := C.clang_Cursor_getObjCManglings(c.c) var gop_o *StringSet if o != nil { gop_o = &StringSet{*o} } return gop_o } // Given a CXCursor_ModuleImportDecl cursor, return the associated module. func (c Cursor) Module() Module { return Module{C.clang_Cursor_getModule(c.c)} } // Determine if a C++ constructor is a converting constructor. func (c Cursor) CXXConstructor_IsConvertingConstructor() bool { o := C.clang_CXXConstructor_isConvertingConstructor(c.c) return o != C.uint(0) } // Determine if a C++ constructor is a copy constructor. func (c Cursor) CXXConstructor_IsCopyConstructor() bool { o := C.clang_CXXConstructor_isCopyConstructor(c.c) return o != C.uint(0) } // Determine if a C++ constructor is the default constructor. func (c Cursor) CXXConstructor_IsDefaultConstructor() bool { o := C.clang_CXXConstructor_isDefaultConstructor(c.c) return o != C.uint(0) } // Determine if a C++ constructor is a move constructor. func (c Cursor) CXXConstructor_IsMoveConstructor() bool { o := C.clang_CXXConstructor_isMoveConstructor(c.c) return o != C.uint(0) } // Determine if a C++ field is declared 'mutable'. func (c Cursor) CXXField_IsMutable() bool { o := C.clang_CXXField_isMutable(c.c) return o != C.uint(0) } // Determine if a C++ method is declared '= default'. func (c Cursor) CXXMethod_IsDefaulted() bool { o := C.clang_CXXMethod_isDefaulted(c.c) return o != C.uint(0) } // Determine if a C++ member function or member function template is pure virtual. func (c Cursor) CXXMethod_IsPureVirtual() bool { o := C.clang_CXXMethod_isPureVirtual(c.c) return o != C.uint(0) } // Determine if a C++ member function or member function template is declared 'static'. func (c Cursor) CXXMethod_IsStatic() bool { o := C.clang_CXXMethod_isStatic(c.c) return o != C.uint(0) } // Determine if a C++ member function or member function template is explicitly declared 'virtual' or if it overrides a virtual method from one of the base classes. func (c Cursor) CXXMethod_IsVirtual() bool { o := C.clang_CXXMethod_isVirtual(c.c) return o != C.uint(0) } // Determine if a C++ record is abstract, i.e. whether a class or struct has a pure virtual member function. func (c Cursor) CXXRecord_IsAbstract() bool { o := C.clang_CXXRecord_isAbstract(c.c) return o != C.uint(0) } // Determine if an enum declaration refers to a scoped enum. func (c Cursor) EnumDecl_IsScoped() bool { o := C.clang_EnumDecl_isScoped(c.c) return o != C.uint(0) } // Determine if a C++ member function or member function template is declared 'const'. func (c Cursor) CXXMethod_IsConst() bool { o := C.clang_CXXMethod_isConst(c.c) return o != C.uint(0) } /* Given a cursor that represents a template, determine the cursor kind of the specializations would be generated by instantiating the template. This routine can be used to determine what flavor of function template, class template, or class template partial specialization is stored in the cursor. For example, it can describe whether a class template cursor is declared with "struct", "class" or "union". Parameter C The cursor to query. This cursor should represent a template declaration. Returns The cursor kind of the specializations that would be generated by instantiating the template \p C. If \p C is not a template, returns CXCursor_NoDeclFound. */ func (c Cursor) TemplateCursorKind() CursorKind { return CursorKind(C.clang_getTemplateCursorKind(c.c)) } /* Given a cursor that may represent a specialization or instantiation of a template, retrieve the cursor that represents the template that it specializes or from which it was instantiated. This routine determines the template involved both for explicit specializations of templates and for implicit instantiations of the template, both of which are referred to as "specializations". For a class template specialization (e.g., std::vector<bool>), this routine will return either the primary template (std::vector) or, if the specialization was instantiated from a class template partial specialization, the class template partial specialization. For a class template partial specialization and a function template specialization (including instantiations), this this routine will return the specialized template. For members of a class template (e.g., member functions, member classes, or static data members), returns the specialized or instantiated member. Although not strictly "templates" in the C++ language, members of class templates have the same notions of specializations and instantiations that templates do, so this routine treats them similarly. Parameter C A cursor that may be a specialization of a template or a member of a template. Returns If the given cursor is a specialization or instantiation of a template or a member thereof, the template or member that it specializes or from which it was instantiated. Otherwise, returns a NULL cursor. */ func (c Cursor) SpecializedCursorTemplate() Cursor { return Cursor{C.clang_getSpecializedCursorTemplate(c.c)} } /* Given a cursor that references something else, return the source range covering that reference. Parameter C A cursor pointing to a member reference, a declaration reference, or an operator call. Parameter NameFlags A bitset with three independent flags: CXNameRange_WantQualifier, CXNameRange_WantTemplateArgs, and CXNameRange_WantSinglePiece. Parameter PieceIndex For contiguous names or when passing the flag CXNameRange_WantSinglePiece, only one piece with index 0 is available. When the CXNameRange_WantSinglePiece flag is not passed for a non-contiguous names, this index can be used to retrieve the individual pieces of the name. See also CXNameRange_WantSinglePiece. Returns The piece of the name pointed to by the given cursor. If there is no name, or if the PieceIndex is out-of-range, a null-cursor will be returned. */ func (c Cursor) ReferenceNameRange(nameFlags uint32, pieceIndex uint32) SourceRange { return SourceRange{C.clang_getCursorReferenceNameRange(c.c, C.uint(nameFlags), C.uint(pieceIndex))} } func (c Cursor) DefinitionSpellingAndExtent() (string, string, uint32, uint32, uint32, uint32) { var startBuf *C.char defer C.free(unsafe.Pointer(startBuf)) var endBuf *C.char defer C.free(unsafe.Pointer(endBuf)) var startLine C.uint var startColumn C.uint var endLine C.uint var endColumn C.uint C.clang_getDefinitionSpellingAndExtent(c.c, &startBuf, &endBuf, &startLine, &startColumn, &endLine, &endColumn) return C.GoString(startBuf), C.GoString(endBuf), uint32(startLine), uint32(startColumn), uint32(endLine), uint32(endColumn) } /* Retrieve a completion string for an arbitrary declaration or macro definition cursor. Parameter cursor The cursor to query. Returns A non-context-sensitive completion string for declaration and macro definition cursors, or NULL for other kinds of cursors. */ func (c Cursor) CompletionString() CompletionString { return CompletionString{C.clang_getCursorCompletionString(c.c)} } // If cursor is a statement declaration tries to evaluate the statement and if its variable, tries to evaluate its initializer, into its corresponding type. func (c Cursor) Evaluate() EvalResult { return EvalResult{C.clang_Cursor_Evaluate(c.c)} } /* Find references of a declaration in a specific file. Parameter cursor pointing to a declaration or a reference of one. Parameter file to search for references. Parameter visitor callback that will receive pairs of CXCursor/CXSourceRange for each reference found. The CXSourceRange will point inside the file; if the reference is inside a macro (and not a macro argument) the CXSourceRange will be invalid. Returns one of the CXResult enumerators. */ func (c Cursor) FindReferencesInFile(file File, visitor CursorAndRangeVisitor) Result { return Result(C.clang_findReferencesInFile(c.c, file.c, visitor.c)) } func (c Cursor) Xdata() int32 { return int32(c.c.xdata) }
clang/cursor_gen.go
0.755457
0.410284
cursor_gen.go
starcoder
package prx import ( "reflect" "strings" "time" "github.com/mb0/xelf/bfr" "github.com/mb0/xelf/cor" "github.com/mb0/xelf/lit" "github.com/mb0/xelf/typ" ) // Reflect returns the xelf type for the interface value v or an error. func Reflect(v interface{}) (typ.Type, error) { return ReflectType(reflect.TypeOf(v)) } // ReflectType returns the xelf type for the reflect type t or an error. func ReflectType(t reflect.Type) (res typ.Type, err error) { nfos := make(infoMap) return reflectType(t, nfos) } var ( refLit = reflect.TypeOf((*lit.Lit)(nil)).Elem() refBool = reflect.TypeOf(false) refInt = reflect.TypeOf(int64(0)) refReal = reflect.TypeOf(float64(0)) refStr = reflect.TypeOf("") refRaw = reflect.TypeOf([]byte(nil)) refUUID = reflect.TypeOf([16]byte{}) refSpan = reflect.TypeOf(time.Second) refTime = reflect.TypeOf(time.Time{}) refList = reflect.TypeOf((*lit.List)(nil)) refDict = reflect.TypeOf((*lit.Dict)(nil)) refSecs = reflect.TypeOf((*lit.MarkSpan)(nil)) refBits = reflect.TypeOf((*lit.MarkBits)(nil)) refEnum = reflect.TypeOf((*lit.MarkEnum)(nil)) refType = reflect.TypeOf(typ.Void) refEl = reflect.TypeOf((*interface { WriteBfr(*bfr.Ctx) error String() string Typ() typ.Type })(nil)).Elem() ) type fields = struct { *typ.Info Idx [][]int } type infoMap = map[reflect.Type]*fields func getConstInfo(t reflect.Type, cs []typ.Const) *typ.Info { return &typ.Info{ Ref: t.String(), Consts: cs, } } func reflectType(t reflect.Type, nfos infoMap) (res typ.Type, err error) { var ptr bool if ptr = t.Kind() == reflect.Ptr; ptr { t = t.Elem() } switch t.Kind() { case reflect.Bool: res = typ.Bool case reflect.Int64: if isRef(t, refSecs) { res = typ.Span break } if isRef(t, refEnum) { cs := reflect.Zero(t).Interface().(lit.MarkEnum).Enums() res = typ.Type{typ.KindBits, getConstInfo(t, typ.Constants(cs))} break } fallthrough case reflect.Int, reflect.Int32: res = typ.Int case reflect.Uint64: if isRef(t, refBits) { cs := reflect.Zero(t).Interface().(lit.MarkBits).Bits() res = typ.Type{typ.KindBits, getConstInfo(t, typ.Constants(cs))} break } fallthrough case reflect.Uint, reflect.Uint32: res = typ.Int case reflect.Float32, reflect.Float64: res = typ.Real case reflect.String: if isRef(t, refEnum) { cs := reflect.Zero(t).Interface().(lit.MarkEnum).Enums() res = typ.Type{typ.KindBits, getConstInfo(t, typ.Constants(cs))} break } res = typ.Str case reflect.Struct: if isRef(t, refTime) { res = typ.Time break } if isRef(t, refType) { res = typ.Typ break } if isRef(t, refDict.Elem()) { if !ptr { return typ.Void, typ.ErrInvalid } return typ.Dict(typ.Any), nil } nfo, _, err := reflectFields(t, nfos) if err != nil { return typ.Void, err } k := typ.KindRec if tn := t.Name(); tn != "" { if c := tn[0]; c >= 'A' && c <= 'Z' { k = typ.KindObj nfo.Ref = t.String() } } res = typ.Type{Kind: k, Info: nfo} case reflect.Array: if isRef(t, refUUID) { res = typ.UUID } case reflect.Map: if !isRef(t.Key(), refStr) { return typ.Void, cor.Error("dict key must be string type") } et, err := reflectType(t.Elem(), nfos) if err != nil { return typ.Void, err } res = typ.Dict(et) case reflect.Slice: if isRef(t, refRaw) { res = typ.Raw break } if isRef(t, refList) { return typ.Idxr(typ.Any), nil } if t.Name() == "Dyn" && isRef(t, refEl) { res = typ.Dyn break } et, err := reflectType(t.Elem(), nfos) if err != nil { return typ.Void, err } res = typ.List(et) case reflect.Interface: return typ.Any, nil } if res.IsZero() { return typ.Void, typ.ErrInvalid } if ptr { return typ.Opt(res), nil } return res, nil } func isRef(t reflect.Type, ref reflect.Type) bool { return t == ref || t.ConvertibleTo(ref) } func reflectFields(t reflect.Type, nfos infoMap) (*typ.Info, [][]int, error) { nfo := nfos[t] if nfo != nil { return nfo.Info, nfo.Idx, nil } nfo = &fields{Info: new(typ.Info)} nfos[t] = nfo fs := make([]typ.Param, 0, 16) idx := make([][]int, 0, 16) err := collectFields(t, nil, func(name, _ string, et reflect.Type, i []int) error { ft, err := reflectType(et, nfos) if err != nil { return err } fs = append(fs, typ.Param{name, ft}) var copy []int idx = append(idx, append(copy, i...)) return nil }) if err != nil { return nil, nil, err } nfo.Params = fs nfo.Idx = idx return nfo.Info, idx, nil } type fidx struct { name string idx []int } func fieldIndices(t reflect.Type, fs []typ.Param) ([][]int, error) { m := make(map[string]fidx, len(fs)+8) err := collectFields(t, nil, func(name, key string, _ reflect.Type, idx []int) error { var copy []int m[key] = fidx{name, append(copy, idx...)} return nil }) if err != nil { return nil, err } res := make([][]int, 0, len(fs)) for _, f := range fs { fi, ok := m[f.Key()] if !ok { return nil, cor.Errorf("field %s not found", f.Key()) } res = append(res, fi.idx) } return res, nil } type fieldCollector = func(name, key string, t reflect.Type, idx []int) error func collectFields(t reflect.Type, idx []int, col fieldCollector) error { n := t.NumField() for i := 0; i < n; i++ { f := t.Field(i) if f.Name != "" && !f.Anonymous { if c := f.Name[0]; c < 'A' || c > 'Z' { continue } } var key string var opt bool // check for a json struct tag first tag := strings.Split(f.Tag.Get("json"), ",") if len(tag) > 0 && tag[0] != "" { key = tag[0] if key == "-" { // skip ignored fields continue } // we found a key check if optional field for _, t := range tag[1:] { if opt = t == "omitempty"; opt { break } } } // collect embedded only if we have no key set by json tag explicitly if key == "" && f.Anonymous { et := f.Type if et.Kind() == reflect.Ptr { et = et.Elem() } err := collectFields(et, append(idx, i), col) if err != nil { return err } continue } name := f.Name // use simple capitalization if key does not match the lowercase name if key != "" && key != cor.LastKey(name) { name = cor.Cased(key) } if key == "" { key = cor.LastKey(name) } if opt { // append a question mark to optional fields name += "?" } err := col(name, key, f.Type, append(idx, i)) if err != nil { return err } } return nil }
prx/reflect.go
0.541894
0.451024
reflect.go
starcoder
package openapi import ( "encoding/json" ) // DispatchRate struct for DispatchRate type DispatchRate struct { DispatchThrottlingRateInMsg *int32 `json:"dispatchThrottlingRateInMsg,omitempty"` DispatchThrottlingRateInByte *int64 `json:"dispatchThrottlingRateInByte,omitempty"` RelativeToPublishRate *bool `json:"relativeToPublishRate,omitempty"` RatePeriodInSecond *int32 `json:"ratePeriodInSecond,omitempty"` } // NewDispatchRate instantiates a new DispatchRate 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 NewDispatchRate() *DispatchRate { this := DispatchRate{} return &this } // NewDispatchRateWithDefaults instantiates a new DispatchRate 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 NewDispatchRateWithDefaults() *DispatchRate { this := DispatchRate{} return &this } // GetDispatchThrottlingRateInMsg returns the DispatchThrottlingRateInMsg field value if set, zero value otherwise. func (o *DispatchRate) GetDispatchThrottlingRateInMsg() int32 { if o == nil || o.DispatchThrottlingRateInMsg == nil { var ret int32 return ret } return *o.DispatchThrottlingRateInMsg } // GetDispatchThrottlingRateInMsgOk returns a tuple with the DispatchThrottlingRateInMsg field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DispatchRate) GetDispatchThrottlingRateInMsgOk() (*int32, bool) { if o == nil || o.DispatchThrottlingRateInMsg == nil { return nil, false } return o.DispatchThrottlingRateInMsg, true } // HasDispatchThrottlingRateInMsg returns a boolean if a field has been set. func (o *DispatchRate) HasDispatchThrottlingRateInMsg() bool { if o != nil && o.DispatchThrottlingRateInMsg != nil { return true } return false } // SetDispatchThrottlingRateInMsg gets a reference to the given int32 and assigns it to the DispatchThrottlingRateInMsg field. func (o *DispatchRate) SetDispatchThrottlingRateInMsg(v int32) { o.DispatchThrottlingRateInMsg = &v } // GetDispatchThrottlingRateInByte returns the DispatchThrottlingRateInByte field value if set, zero value otherwise. func (o *DispatchRate) GetDispatchThrottlingRateInByte() int64 { if o == nil || o.DispatchThrottlingRateInByte == nil { var ret int64 return ret } return *o.DispatchThrottlingRateInByte } // GetDispatchThrottlingRateInByteOk returns a tuple with the DispatchThrottlingRateInByte field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DispatchRate) GetDispatchThrottlingRateInByteOk() (*int64, bool) { if o == nil || o.DispatchThrottlingRateInByte == nil { return nil, false } return o.DispatchThrottlingRateInByte, true } // HasDispatchThrottlingRateInByte returns a boolean if a field has been set. func (o *DispatchRate) HasDispatchThrottlingRateInByte() bool { if o != nil && o.DispatchThrottlingRateInByte != nil { return true } return false } // SetDispatchThrottlingRateInByte gets a reference to the given int64 and assigns it to the DispatchThrottlingRateInByte field. func (o *DispatchRate) SetDispatchThrottlingRateInByte(v int64) { o.DispatchThrottlingRateInByte = &v } // GetRelativeToPublishRate returns the RelativeToPublishRate field value if set, zero value otherwise. func (o *DispatchRate) GetRelativeToPublishRate() bool { if o == nil || o.RelativeToPublishRate == nil { var ret bool return ret } return *o.RelativeToPublishRate } // GetRelativeToPublishRateOk returns a tuple with the RelativeToPublishRate field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DispatchRate) GetRelativeToPublishRateOk() (*bool, bool) { if o == nil || o.RelativeToPublishRate == nil { return nil, false } return o.RelativeToPublishRate, true } // HasRelativeToPublishRate returns a boolean if a field has been set. func (o *DispatchRate) HasRelativeToPublishRate() bool { if o != nil && o.RelativeToPublishRate != nil { return true } return false } // SetRelativeToPublishRate gets a reference to the given bool and assigns it to the RelativeToPublishRate field. func (o *DispatchRate) SetRelativeToPublishRate(v bool) { o.RelativeToPublishRate = &v } // GetRatePeriodInSecond returns the RatePeriodInSecond field value if set, zero value otherwise. func (o *DispatchRate) GetRatePeriodInSecond() int32 { if o == nil || o.RatePeriodInSecond == nil { var ret int32 return ret } return *o.RatePeriodInSecond } // GetRatePeriodInSecondOk returns a tuple with the RatePeriodInSecond field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *DispatchRate) GetRatePeriodInSecondOk() (*int32, bool) { if o == nil || o.RatePeriodInSecond == nil { return nil, false } return o.RatePeriodInSecond, true } // HasRatePeriodInSecond returns a boolean if a field has been set. func (o *DispatchRate) HasRatePeriodInSecond() bool { if o != nil && o.RatePeriodInSecond != nil { return true } return false } // SetRatePeriodInSecond gets a reference to the given int32 and assigns it to the RatePeriodInSecond field. func (o *DispatchRate) SetRatePeriodInSecond(v int32) { o.RatePeriodInSecond = &v } func (o DispatchRate) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.DispatchThrottlingRateInMsg != nil { toSerialize["dispatchThrottlingRateInMsg"] = o.DispatchThrottlingRateInMsg } if o.DispatchThrottlingRateInByte != nil { toSerialize["dispatchThrottlingRateInByte"] = o.DispatchThrottlingRateInByte } if o.RelativeToPublishRate != nil { toSerialize["relativeToPublishRate"] = o.RelativeToPublishRate } if o.RatePeriodInSecond != nil { toSerialize["ratePeriodInSecond"] = o.RatePeriodInSecond } return json.Marshal(toSerialize) } type NullableDispatchRate struct { value *DispatchRate isSet bool } func (v NullableDispatchRate) Get() *DispatchRate { return v.value } func (v *NullableDispatchRate) Set(val *DispatchRate) { v.value = val v.isSet = true } func (v NullableDispatchRate) IsSet() bool { return v.isSet } func (v *NullableDispatchRate) Unset() { v.value = nil v.isSet = false } func NewNullableDispatchRate(val *DispatchRate) *NullableDispatchRate { return &NullableDispatchRate{value: val, isSet: true} } func (v NullableDispatchRate) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableDispatchRate) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
openapi/model_dispatch_rate.go
0.743727
0.5119
model_dispatch_rate.go
starcoder
package domain import ( "fmt" "math" apperrors "github.com/miguelramirez93/quasar_fire_operation/shared/app_errors" "github.com/miguelramirez93/quasar_fire_operation/shared/models" "github.com/miguelramirez93/quasar_fire_operation/shared/utils/numbers" valueobjects "github.com/miguelramirez93/quasar_fire_operation/shared/value_objects" ) type Radar struct { models.RadarProps } func NewRadar(satellitesData []*models.Satellite) Radar { return Radar{ models.RadarProps{ Satellites: satellitesData, }, } } func (rd *Radar) GetLocation(distances ...float32) (x, y float32) { if len(distances) > (len(rd.Satellites)) { panic(apperrors.ErrNumOfDistances.Error()) } r1 := distances[0] r2 := distances[1] r3 := distances[2] x1 := rd.Satellites[0].Coordenates.X y1 := rd.Satellites[0].Coordenates.Y x2 := rd.Satellites[1].Coordenates.X y2 := rd.Satellites[1].Coordenates.Y x3 := rd.Satellites[2].Coordenates.X y3 := rd.Satellites[2].Coordenates.Y //Calculate emisor coordenates with the intersection of the 3 circles that distances and coordenates build. // A = (-2x1 + 2x2) A := float32((-2 * x1) + (2 * x2)) //B = (-2y1 + 2y2) B := float32((-2 * y1) + (2 * y2)) //C = (r1^2) - (r2^2) - (x1^2) + (x2^2) - (y1^2) + (y2^2) C := (r1 * r1) - (r2 * r2) - float32(x1*x1) + float32(x2*x2) - float32(y1*y1) + float32(y2*y2) //D = (-2x2 + 2x3) D := float32((-2 * x2) + (2 * x3)) //E = (-2y2 + 2y3) E := float32((-2 * y2) + (2 * y3)) //F = (r2^2) - (r3^2) - (x2^2) + (x3^2) - (y2^2) + (y3^2) F := float32(math.Pow(float64(r2), 2)) - float32(math.Pow(float64(r3), 2)) - float32(math.Pow(float64(x2), 2)) + float32(math.Pow(float64(x3), 2)) - float32(math.Pow(float64(y2), 2)) + float32(math.Pow(float64(y3), 2)) // Formula: x= (CE - FB) / (EA - BD) x = ((C * E) - (F * B)) / ((E * A) - (B * D)) // Formula: y= (CD - AF) / (BD - AE) y = ((C * D) - (A * F)) / ((B * D) - (A * E)) //check if data is consistent resultCoordenates := valueobjects.CoordinatePair{ X: valueobjects.Coordinate(x), Y: valueobjects.Coordinate(y), } checkResultPointDistance(&resultCoordenates, valueobjects.CoordinatePair{ X: x1, Y: y1, }, r1) checkResultPointDistance(&resultCoordenates, valueobjects.CoordinatePair{ X: x2, Y: y2, }, r2) checkResultPointDistance(&resultCoordenates, valueobjects.CoordinatePair{ X: x3, Y: y3, }, r3) return numbers.RoundDecimals(x, 1), numbers.RoundDecimals(y, 1) } func checkResultPointDistance(sourceCoordenates *valueobjects.CoordinatePair, pointToCehck valueobjects.CoordinatePair, distance float32) { distanceToX1Y1 := sourceCoordenates.CalculateDistanceTo(pointToCehck) if math.Round(float64(distanceToX1Y1)) != math.Round(float64(distance)) { panic(fmt.Sprintf("Point (%f,%f) is not consistent with distance %f", pointToCehck.X, pointToCehck.Y, distance)) } }
domain/radar.go
0.707607
0.467757
radar.go
starcoder
package faker import ( "regexp" "strings" ) const digits = "0123456789" const lowerLetters = "abcdefghijklmnopqrstuvwxyz" const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" const charset = digits + lowerLetters + upperLetters // StringWithSize will build a random string of length size. func StringWithSize(size int) string { return stringWithSize(size, charset) } // String will build a random string of length between 1 and 8. func String() string { return StringWithSize(IntInRange(1, 8)) } // DigitsWithSize will build a random string of only digits of length size. func DigitsWithSize(size int) string { return stringWithSize(size, digits) } // Digits will build a random string of only digits of length between 1 and 8. func Digits() string { return DigitsWithSize(IntInRange(1, 8)) } // LettersWithSize will build a random string of only letters of length size. func LettersWithSize(size int) string { return stringWithSize(size, lowerLetters+upperLetters) } // Letters will build a random string of only letters of length between 1 and 8. func Letters() string { return LettersWithSize(IntInRange(1, 8)) } // Lexify will replace all occurrences of "?" in str with a random letter. func Lexify(str string) string { return replaceChar(str, "?", func() string { return LettersWithSize(1) }) } // Numerify will replace all occurrences of "?" in str with a random digit. func Numerify(str string) string { return replaceChar(str, "?", func() string { return DigitsWithSize(1) }) } // Parameterize replaces special characters in str so that it may be used as part of a 'pretty' URL. func Parameterize(str string) string { notAlphaNumRegExp := regexp.MustCompile("[^A-Za-z0-9]+") firstLastDashRegexp := regexp.MustCompile("^-|-$") parameterizeString := notAlphaNumRegExp.ReplaceAllString(str, "-") parameterizeString = firstLastDashRegexp.ReplaceAllString(parameterizeString, "") return strings.ToLower(parameterizeString) } // Pick returns a random string among those passed as parameters. func Pick(pool ...string) string { if len(pool) == 0 { return "" } i := IntInRange(0, len(pool)-1) return pool[i] } // Private functions func stringWithSize(size int, charset string) string { b := make([]byte, size) for i := range b { b[i] = charset[random.Intn(len(charset))] } return string(b) } func replaceChar(str, chr string, fn func() string) string { r := str count := strings.Count(str, chr) for i := 0; i < count; i++ { r = strings.Replace(r, chr, fn(), 1) } return r } // Builder functions func stringWithSizeBuilder(params ...string) (interface{}, error) { size, err := paramsToInt(params...) if err != nil { return nil, err } return StringWithSize(size), nil } func stringBuilder(params ...string) (interface{}, error) { return String(), nil } func digitsWithSizeBuilder(params ...string) (interface{}, error) { size, err := paramsToInt(params...) if err != nil { return nil, err } return DigitsWithSize(size), nil } func digitsBuilder(params ...string) (interface{}, error) { return Digits(), nil } func lettersWithSizeBuilder(params ...string) (interface{}, error) { size, err := paramsToInt(params...) if err != nil { return nil, err } return LettersWithSize(size), nil } func lettersBuilder(params ...string) (interface{}, error) { return Letters(), nil } func lexifyBuilder(params ...string) (interface{}, error) { if len(params) != 1 { return nil, parametersError(nil) } return Lexify(params[0]), nil } func numerifyBuilder(params ...string) (interface{}, error) { if len(params) != 1 { return nil, parametersError(nil) } return Numerify(params[0]), nil } func parameterizeBuilder(params ...string) (interface{}, error) { if len(params) != 1 { return nil, parametersError(nil) } return Parameterize(params[0]), nil } func pickBuilder(params ...string) (interface{}, error) { return Pick(params...), nil }
string.go
0.710226
0.512998
string.go
starcoder
package dataframe import ( "context" ) // ApplyDataFrameFn is used by the Apply function when used with DataFrames. // vals contains the values for the current row. The keys contain ints (index of Series) and strings (name of Series). // The returned map must only contain what values you intend to update. The key can be a string (name of Series) or int (index of Series). // If nil is returned, the existing values for the row are unchanged. type ApplyDataFrameFn func(vals map[interface{}]interface{}, row, nRows int) map[interface{}]interface{} // ApplySeriesFn is used by the Apply function when used with Series. // val contains the value of the current row. The returned value is the updated value. type ApplySeriesFn func(val interface{}, row, nRows int) interface{} // Apply will call fn for each row in the Series or DataFrame and replace the existing value with the new // value returned by fn. When sdf is a DataFrame, fn must be of type ApplyDataFrameFn. When sdf is a Series, fn must be of type ApplySeriesFn. func Apply(ctx context.Context, sdf interface{}, fn interface{}, opts ...FilterOptions) (interface{}, error) { switch typ := sdf.(type) { case Series: var x ApplySeriesFn switch v := fn.(type) { case func(val interface{}, row, nRows int) interface{}: x = ApplySeriesFn(v) default: x = fn.(ApplySeriesFn) } s, err := applySeries(ctx, typ, x, opts...) if s == nil { return nil, err } return s, err case *DataFrame: var x ApplyDataFrameFn switch v := fn.(type) { case func(vals map[interface{}]interface{}, row, nRows int) map[interface{}]interface{}: x = ApplyDataFrameFn(v) default: x = fn.(ApplyDataFrameFn) } df, err := applyDataFrame(ctx, typ, x, opts...) if df == nil { return nil, err } return df, err default: panic("sdf must be a Series or DataFrame") } return nil, nil } func applySeries(ctx context.Context, s Series, fn ApplySeriesFn, opts ...FilterOptions) (Series, error) { if fn == nil { panic("fn is required") } if len(opts) == 0 { opts = append(opts, FilterOptions{}) } if !opts[0].DontLock { s.Lock() defer s.Unlock() } nRows := s.NRows(dontLock) var ns Series if !opts[0].InPlace { x, ok := s.(NewSerieser) if !ok { panic("s must implement NewSerieser interface if InPlace is false") } // Create a New Series ns = x.NewSeries(s.Name(dontLock), &SeriesInit{Capacity: nRows}) } iterator := s.ValuesIterator(ValuesOptions{InitialRow: 0, Step: 1, DontReadLock: true}) for { if err := ctx.Err(); err != nil { return nil, err } row, val, nRows := iterator() if row == nil { break } newVal := fn(val, *row, nRows) if opts[0].InPlace { s.Update(*row, newVal, dontLock) } else { ns.Append(newVal, dontLock) } } if !opts[0].InPlace { return ns, nil } return nil, nil } func applyDataFrame(ctx context.Context, df *DataFrame, fn ApplyDataFrameFn, opts ...FilterOptions) (*DataFrame, error) { if fn == nil { panic("fn is required") } if len(opts) == 0 { opts = append(opts, FilterOptions{}) } if !opts[0].DontLock { df.Lock() defer df.Unlock() } nRows := df.n var ndf *DataFrame if !opts[0].InPlace { // Create all series seriess := []Series{} for i := range df.Series { s := df.Series[i] x, ok := s.(NewSerieser) if !ok { panic("all Series in DataFrame must implement NewSerieser interface if InPlace is false") } seriess = append(seriess, x.NewSeries(df.Series[i].Name(dontLock), &SeriesInit{Capacity: nRows})) } // Create a new dataframe ndf = NewDataFrame(seriess...) } iterator := df.ValuesIterator(ValuesOptions{InitialRow: 0, Step: 1, DontReadLock: true}) for { if err := ctx.Err(); err != nil { return nil, err } row, vals, nRows := iterator() if row == nil { break } newVals := fn(vals, *row, nRows) if opts[0].InPlace { if newVals != nil { df.UpdateRow(*row, &dontLock, newVals) } } else { if newVals != nil { ndf.Append(&dontLock, newVals) } else { ndf.Append(&dontLock, vals) } } } if !opts[0].InPlace { return ndf, nil } return nil, nil }
apply.go
0.627152
0.556821
apply.go
starcoder
package ids import ( "bytes" "math/bits" ) // NumBits is the number of bits this patricia tree manages const NumBits = 256 // BitsPerByte is the number of bits per byte const BitsPerByte = 8 // EqualSubset takes in two indices and two ids and returns if the ids are // equal from bit start to bit end (non-inclusive). Bit indices are defined as: // [7 6 5 4 3 2 1 0] [15 14 13 12 11 10 9 8] ... [255 254 253 252 251 250 249 248] // Where index 7 is the MSB of byte 0. func EqualSubset(start, stop int, id1, id2 ID) bool { stop-- if start > stop || stop < 0 { return true } if stop >= NumBits { return false } startIndex := start / BitsPerByte stopIndex := stop / BitsPerByte // If there is a series of bytes between the first byte and the last byte, they must be equal if startIndex+1 < stopIndex && !bytes.Equal(id1[startIndex+1:stopIndex], id2[startIndex+1:stopIndex]) { return false } startBit := uint(start % BitsPerByte) // Index in the byte that the first bit is at stopBit := uint(stop % BitsPerByte) // Index in the byte that the last bit is at startMask := -1 << startBit // 111...0... The number of 0s is equal to startBit stopMask := (1 << (stopBit + 1)) - 1 // 000...1... The number of 1s is equal to stopBit+1 if startIndex == stopIndex { // If we are looking at the same byte, both masks need to be applied mask := startMask & stopMask // The index here could be startIndex or stopIndex, as they are equal b1 := mask & int(id1[startIndex]) b2 := mask & int(id2[startIndex]) return b1 == b2 } start1 := startMask & int(id1[startIndex]) start2 := startMask & int(id2[startIndex]) stop1 := stopMask & int(id1[stopIndex]) stop2 := stopMask & int(id2[stopIndex]) return start1 == start2 && stop1 == stop2 } // FirstDifferenceSubset takes in two indices and two ids and returns the index // of the first difference between the ids inside bit start to bit end // (non-inclusive). Bit indices are defined above func FirstDifferenceSubset(start, stop int, id1, id2 ID) (int, bool) { stop-- if start > stop || stop < 0 || stop >= NumBits { return 0, false } startIndex := start / BitsPerByte stopIndex := stop / BitsPerByte startBit := uint(start % BitsPerByte) // Index in the byte that the first bit is at stopBit := uint(stop % BitsPerByte) // Index in the byte that the last bit is at startMask := -1 << startBit // 111...0... The number of 0s is equal to startBit stopMask := (1 << (stopBit + 1)) - 1 // 000...1... The number of 1s is equal to stopBit+1 if startIndex == stopIndex { // If we are looking at the same byte, both masks need to be applied mask := startMask & stopMask // The index here could be startIndex or stopIndex, as they are equal b1 := mask & int(id1[startIndex]) b2 := mask & int(id2[startIndex]) if b1 == b2 { return 0, false } bd := b1 ^ b2 return bits.TrailingZeros8(uint8(bd)) + startIndex*BitsPerByte, true } // Check the first byte, may have some bits masked start1 := startMask & int(id1[startIndex]) start2 := startMask & int(id2[startIndex]) if start1 != start2 { bd := start1 ^ start2 return bits.TrailingZeros8(uint8(bd)) + startIndex*BitsPerByte, true } // Check all the interior bits for i := startIndex + 1; i < stopIndex; i++ { b1 := int(id1[i]) b2 := int(id2[i]) if b1 != b2 { bd := b1 ^ b2 return bits.TrailingZeros8(uint8(bd)) + i*BitsPerByte, true } } // Check the last byte, may have some bits masked stop1 := stopMask & int(id1[stopIndex]) stop2 := stopMask & int(id2[stopIndex]) if stop1 != stop2 { bd := stop1 ^ stop2 return bits.TrailingZeros8(uint8(bd)) + stopIndex*BitsPerByte, true } // No difference was found return 0, false }
ids/bits.go
0.729327
0.542015
bits.go
starcoder
package pwr import ( "fmt" "io" "log" "github.com/go-errors/errors" "github.com/itchio/wharf/wire" ) // A Compressor can compress a stream given a quality setting type Compressor interface { Apply(writer io.Writer, quality int32) (io.Writer, error) } // A Decompressor can decompress a stream with a given algorithm type Decompressor interface { Apply(reader io.Reader) (io.Reader, error) } var compressors map[CompressionAlgorithm]Compressor var decompressors map[CompressionAlgorithm]Decompressor func init() { compressors = make(map[CompressionAlgorithm]Compressor) decompressors = make(map[CompressionAlgorithm]Decompressor) } // RegisterCompressor lets wharf know how to compress a stream for a given algorithm func RegisterCompressor(a CompressionAlgorithm, c Compressor) { if compressors[a] != nil { log.Printf("RegisterCompressor: overwriting current compressor for %s\n", a) } compressors[a] = c } // RegisterDecompressor lets wharf know how to decompress a stream for a given algorithm func RegisterDecompressor(a CompressionAlgorithm, d Decompressor) { if decompressors[a] != nil { log.Printf("RegisterCompressor: overwriting current decompressor for %s\n", a) } decompressors[a] = d } // ToString returns a human-readable description of given compression settings func (cs *CompressionSettings) ToString() string { return fmt.Sprintf("%s-q%d", cs.Algorithm.String(), cs.Quality) } // CompressWire wraps a wire.WriteContext into a compressor, according to given settings, // so that any messages written through the returned WriteContext will first be compressed. func CompressWire(ctx *wire.WriteContext, compression *CompressionSettings) (*wire.WriteContext, error) { if compression == nil { return nil, errors.Wrap(fmt.Errorf("no compression specified"), 1) } if compression.Algorithm == CompressionAlgorithm_NONE { return ctx, nil } compressor := compressors[compression.Algorithm] if compressor == nil { return nil, errors.Wrap(fmt.Errorf("no compressor registered for %s", compression.Algorithm.String()), 1) } compressedWriter, err := compressor.Apply(ctx.Writer(), compression.Quality) if err != nil { return nil, errors.Wrap(err, 1) } return wire.NewWriteContext(compressedWriter), nil } // DecompressWire wraps a wire.ReadContext into a decompressor, according to the given settings, // so that any messages read through the returned ReadContext will first be decompressed. func DecompressWire(ctx *wire.ReadContext, compression *CompressionSettings) (*wire.ReadContext, error) { if compression == nil { return nil, errors.Wrap(fmt.Errorf("no compression specified"), 1) } if compression.Algorithm == CompressionAlgorithm_NONE { return ctx, nil } decompressor := decompressors[compression.Algorithm] if decompressor == nil { return nil, errors.Wrap(fmt.Errorf("no decompressor registered for %s", compression.Algorithm.String()), 1) } compressedReader, err := decompressor.Apply(ctx.Reader()) if err != nil { return nil, errors.Wrap(err, 1) } return wire.NewReadContext(compressedReader), nil }
pwr/compression.go
0.774583
0.422147
compression.go
starcoder
package options import ( "time" ) // FindOptions represent all possible options to the find() function. type FindOptions struct { AllowPartialResults *bool // If true, allows partial results to be returned if some shards are down. BatchSize *int32 // Specifies the number of documents to return in every batch. Collation *Collation // Specifies a collation to be used Comment *string // Specifies a string to help trace the operation through the database. CursorType *CursorType // Specifies the type of cursor to use Hint interface{} // Specifies the index to use. Limit *int64 // Sets a limit on the number of results to return. Max interface{} // Sets an exclusive upper bound for a specific index MaxAwaitTime *time.Duration // Specifies the maximum amount of time for the server to wait on new documents. MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run. Min interface{} // Specifies the inclusive lower bound for a specific index. NoCursorTimeout *bool // If true, prevents cursors from timing out after an inactivity period. OplogReplay *bool // Adds an option for internal use only and should not be set. Projection interface{} // Limits the fields returned for all documents. ReturnKey *bool // If true, only returns index keys for all result documents. ShowRecordID *bool // If true, a $recordId field with the record identifier will be added to the returned documents. Skip *int64 // Specifies the number of documents to skip before returning Snapshot *bool // If true, prevents the cursor from returning a document more than once because of an intervening write operation. Sort interface{} // Specifies the order in which to return results. } // Find creates a new FindOptions instance. func Find() *FindOptions { return &FindOptions{} } // SetAllowPartialResults sets whether partial results can be returned if some shards are down. // For server versions < 3.2, this defaults to false. func (f *FindOptions) SetAllowPartialResults(b bool) *FindOptions { f.AllowPartialResults = &b return f } // SetBatchSize sets the number of documents to return in each batch. func (f *FindOptions) SetBatchSize(i int32) *FindOptions { f.BatchSize = &i return f } // SetCollation specifies a Collation to use for the Find operation. // Valid for server versions >= 3.4 func (f *FindOptions) SetCollation(collation *Collation) *FindOptions { f.Collation = collation return f } // SetComment specifies a string to help trace the operation through the database. func (f *FindOptions) SetComment(comment string) *FindOptions { f.Comment = &comment return f } // SetCursorType specifes the type of cursor to use. func (f *FindOptions) SetCursorType(ct CursorType) *FindOptions { f.CursorType = &ct return f } // SetHint specifies the index to use. func (f *FindOptions) SetHint(hint interface{}) *FindOptions { f.Hint = hint return f } // SetLimit specifies a limit on the number of results. // A negative limit implies that only 1 batch should be returned. func (f *FindOptions) SetLimit(i int64) *FindOptions { f.Limit = &i return f } // SetMax specifies an exclusive upper bound for a specific index. func (f *FindOptions) SetMax(max interface{}) *FindOptions { f.Max = max return f } // SetMaxAwaitTime specifies the max amount of time for the server to wait on new documents. // If the cursor type is not TailableAwait, this option is ignored. // For server versions < 3.2, this option is ignored. func (f *FindOptions) SetMaxAwaitTime(d time.Duration) *FindOptions { f.MaxAwaitTime = &d return f } // SetMaxTime specifies the max time to allow the query to run. func (f *FindOptions) SetMaxTime(d time.Duration) *FindOptions { f.MaxTime = &d return f } // SetMin specifies the inclusive lower bound for a specific index. func (f *FindOptions) SetMin(min interface{}) *FindOptions { f.Min = min return f } // SetNoCursorTimeout specifies whether or not cursors should time out after a period of inactivity. // For server versions < 3.2, this defaults to false. func (f *FindOptions) SetNoCursorTimeout(b bool) *FindOptions { f.NoCursorTimeout = &b return f } // SetOplogReplay adds an option for internal use only and should not be set. // For server versions < 3.2, this defaults to false. func (f *FindOptions) SetOplogReplay(b bool) *FindOptions { f.OplogReplay = &b return f } // SetProjection adds an option to limit the fields returned for all documents. func (f *FindOptions) SetProjection(projection interface{}) *FindOptions { f.Projection = projection return f } // SetReturnKey adds an option to only return index keys for all result documents. func (f *FindOptions) SetReturnKey(b bool) *FindOptions { f.ReturnKey = &b return f } // SetShowRecordID adds an option to determine whether to return the record identifier for each document. // If true, a $recordId field will be added to each returned document. func (f *FindOptions) SetShowRecordID(b bool) *FindOptions { f.ShowRecordID = &b return f } // SetSkip specifies the number of documents to skip before returning. // For server versions < 3.2, this defaults to 0. func (f *FindOptions) SetSkip(i int64) *FindOptions { f.Skip = &i return f } // SetSnapshot prevents the cursor from returning a document more than once because of an intervening write operation. func (f *FindOptions) SetSnapshot(b bool) *FindOptions { f.Snapshot = &b return f } // SetSort specifies the order in which to return documents. func (f *FindOptions) SetSort(sort interface{}) *FindOptions { f.Sort = sort return f } // MergeFindOptions combines the argued FindOptions into a single FindOptions in a last-one-wins fashion func MergeFindOptions(opts ...*FindOptions) *FindOptions { fo := Find() for _, opt := range opts { if opt == nil { continue } if opt.AllowPartialResults != nil { fo.AllowPartialResults = opt.AllowPartialResults } if opt.BatchSize != nil { fo.BatchSize = opt.BatchSize } if opt.Collation != nil { fo.Collation = opt.Collation } if opt.Comment != nil { fo.Comment = opt.Comment } if opt.CursorType != nil { fo.CursorType = opt.CursorType } if opt.Hint != nil { fo.Hint = opt.Hint } if opt.Limit != nil { fo.Limit = opt.Limit } if opt.Max != nil { fo.Max = opt.Max } if opt.MaxAwaitTime != nil { fo.MaxAwaitTime = opt.MaxAwaitTime } if opt.MaxTime != nil { fo.MaxTime = opt.MaxTime } if opt.Min != nil { fo.Min = opt.Min } if opt.NoCursorTimeout != nil { fo.NoCursorTimeout = opt.NoCursorTimeout } if opt.OplogReplay != nil { fo.OplogReplay = opt.OplogReplay } if opt.Projection != nil { fo.Projection = opt.Projection } if opt.ReturnKey != nil { fo.ReturnKey = opt.ReturnKey } if opt.ShowRecordID != nil { fo.ShowRecordID = opt.ShowRecordID } if opt.Skip != nil { fo.Skip = opt.Skip } if opt.Snapshot != nil { fo.Snapshot = opt.Snapshot } if opt.Sort != nil { fo.Sort = opt.Sort } } return fo } // FindOneOptions represent all possible options to the findOne() function. type FindOneOptions struct { AllowPartialResults *bool // If true, allows partial results to be returned if some shards are down. BatchSize *int32 // Specifies the number of documents to return in every batch. Collation *Collation // Specifies a collation to be used Comment *string // Specifies a string to help trace the operation through the database. CursorType *CursorType // Specifies the type of cursor to use Hint interface{} // Specifies the index to use. Max interface{} // Sets an exclusive upper bound for a specific index MaxAwaitTime *time.Duration // Specifies the maximum amount of time for the server to wait on new documents. MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run. Min interface{} // Specifies the inclusive lower bound for a specific index. NoCursorTimeout *bool // If true, prevents cursors from timing out after an inactivity period. OplogReplay *bool // Adds an option for internal use only and should not be set. Projection interface{} // Limits the fields returned for all documents. ReturnKey *bool // If true, only returns index keys for all result documents. ShowRecordID *bool // If true, a $recordId field with the record identifier will be added to the returned documents. Skip *int64 // Specifies the number of documents to skip before returning Snapshot *bool // If true, prevents the cursor from returning a document more than once because of an intervening write operation. Sort interface{} // Specifies the order in which to return results. } // FindOne creates a new FindOneOptions instance. func FindOne() *FindOneOptions { return &FindOneOptions{} } // SetAllowPartialResults sets whether partial results can be returned if some shards are down. func (f *FindOneOptions) SetAllowPartialResults(b bool) *FindOneOptions { f.AllowPartialResults = &b return f } // SetBatchSize sets the number of documents to return in each batch. func (f *FindOneOptions) SetBatchSize(i int32) *FindOneOptions { f.BatchSize = &i return f } // SetCollation specifies a Collation to use for the Find operation. func (f *FindOneOptions) SetCollation(collation *Collation) *FindOneOptions { f.Collation = collation return f } // SetComment specifies a string to help trace the operation through the database. func (f *FindOneOptions) SetComment(comment string) *FindOneOptions { f.Comment = &comment return f } // SetCursorType specifes the type of cursor to use. func (f *FindOneOptions) SetCursorType(ct CursorType) *FindOneOptions { f.CursorType = &ct return f } // SetHint specifies the index to use. func (f *FindOneOptions) SetHint(hint interface{}) *FindOneOptions { f.Hint = hint return f } // SetMax specifies an exclusive upper bound for a specific index. func (f *FindOneOptions) SetMax(max interface{}) *FindOneOptions { f.Max = max return f } // SetMaxAwaitTime specifies the max amount of time for the server to wait on new documents. // For server versions < 3.2, this option is ignored. func (f *FindOneOptions) SetMaxAwaitTime(d time.Duration) *FindOneOptions { f.MaxAwaitTime = &d return f } // SetMaxTime specifies the max time to allow the query to run. func (f *FindOneOptions) SetMaxTime(d time.Duration) *FindOneOptions { f.MaxTime = &d return f } // SetMin specifies the inclusive lower bound for a specific index. func (f *FindOneOptions) SetMin(min interface{}) *FindOneOptions { f.Min = min return f } // SetNoCursorTimeout specifies whether or not cursors should time out after a period of inactivity. func (f *FindOneOptions) SetNoCursorTimeout(b bool) *FindOneOptions { f.NoCursorTimeout = &b return f } // SetOplogReplay adds an option for internal use only and should not be set. func (f *FindOneOptions) SetOplogReplay(b bool) *FindOneOptions { f.OplogReplay = &b return f } // SetProjection adds an option to limit the fields returned for all documents. func (f *FindOneOptions) SetProjection(projection interface{}) *FindOneOptions { f.Projection = projection return f } // SetReturnKey adds an option to only return index keys for all result documents. func (f *FindOneOptions) SetReturnKey(b bool) *FindOneOptions { f.ReturnKey = &b return f } // SetShowRecordID adds an option to determine whether to return the record identifier for each document. // If true, a $recordId field will be added to each returned document. func (f *FindOneOptions) SetShowRecordID(b bool) *FindOneOptions { f.ShowRecordID = &b return f } // SetSkip specifies the number of documents to skip before returning. func (f *FindOneOptions) SetSkip(i int64) *FindOneOptions { f.Skip = &i return f } // SetSnapshot prevents the cursor from returning a document more than once because of an intervening write operation. func (f *FindOneOptions) SetSnapshot(b bool) *FindOneOptions { f.Snapshot = &b return f } // SetSort specifies the order in which to return documents. func (f *FindOneOptions) SetSort(sort interface{}) *FindOneOptions { f.Sort = sort return f } // MergeFindOneOptions combines the argued FindOneOptions into a single FindOneOptions in a last-one-wins fashion func MergeFindOneOptions(opts ...*FindOneOptions) *FindOneOptions { fo := FindOne() for _, opt := range opts { if opt == nil { continue } if opt.AllowPartialResults != nil { fo.AllowPartialResults = opt.AllowPartialResults } if opt.BatchSize != nil { fo.BatchSize = opt.BatchSize } if opt.Collation != nil { fo.Collation = opt.Collation } if opt.Comment != nil { fo.Comment = opt.Comment } if opt.CursorType != nil { fo.CursorType = opt.CursorType } if opt.Hint != nil { fo.Hint = opt.Hint } if opt.Max != nil { fo.Max = opt.Max } if opt.MaxAwaitTime != nil { fo.MaxAwaitTime = opt.MaxAwaitTime } if opt.MaxTime != nil { fo.MaxTime = opt.MaxTime } if opt.Min != nil { fo.Min = opt.Min } if opt.NoCursorTimeout != nil { fo.NoCursorTimeout = opt.NoCursorTimeout } if opt.OplogReplay != nil { fo.OplogReplay = opt.OplogReplay } if opt.Projection != nil { fo.Projection = opt.Projection } if opt.ReturnKey != nil { fo.ReturnKey = opt.ReturnKey } if opt.ShowRecordID != nil { fo.ShowRecordID = opt.ShowRecordID } if opt.Skip != nil { fo.Skip = opt.Skip } if opt.Snapshot != nil { fo.Snapshot = opt.Snapshot } if opt.Sort != nil { fo.Sort = opt.Sort } } return fo } // FindOneAndReplaceOptions represent all possible options to the findOne() function. type FindOneAndReplaceOptions struct { BypassDocumentValidation *bool // If true, allows the write to opt out of document-level validation. Collation *Collation // Specifies a collation to be used MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run. Projection interface{} // Limits the fields returned for all documents. ReturnDocument *ReturnDocument // Specifies whether the original or updated document should be returned. Sort interface{} // Specifies the order in which to return results. Upsert *bool // If true, creates a a new document if no document matches the query. } // FindOneAndReplace creates a new FindOneAndReplaceOptions instance. func FindOneAndReplace() *FindOneAndReplaceOptions { return &FindOneAndReplaceOptions{} } // SetBypassDocumentValidation specifies whether or not the write should opt out of document-level validation. // Valid for server versions >= 3.2. For servers < 3.2, this option is ignored. func (f *FindOneAndReplaceOptions) SetBypassDocumentValidation(b bool) *FindOneAndReplaceOptions { f.BypassDocumentValidation = &b return f } // SetCollation specifies a Collation to use for the Find operation. func (f *FindOneAndReplaceOptions) SetCollation(collation *Collation) *FindOneAndReplaceOptions { f.Collation = collation return f } // SetMaxTime specifies the max time to allow the query to run. func (f *FindOneAndReplaceOptions) SetMaxTime(d time.Duration) *FindOneAndReplaceOptions { f.MaxTime = &d return f } // SetProjection adds an option to limit the fields returned for all documents. func (f *FindOneAndReplaceOptions) SetProjection(projection interface{}) *FindOneAndReplaceOptions { f.Projection = projection return f } // SetReturnDocument specifies whether the original or updated document should be returned. // If set to Before, the original document will be returned. If set to After, the updated document // will be returned. func (f *FindOneAndReplaceOptions) SetReturnDocument(rd ReturnDocument) *FindOneAndReplaceOptions { f.ReturnDocument = &rd return f } // SetSort specifies the order in which to return documents. func (f *FindOneAndReplaceOptions) SetSort(sort interface{}) *FindOneAndReplaceOptions { f.Sort = sort return f } // SetUpsert specifies if a new document should be created if no document matches the query. func (f *FindOneAndReplaceOptions) SetUpsert(b bool) *FindOneAndReplaceOptions { f.Upsert = &b return f } // MergeFindOneAndReplaceOptions combines the argued FindOneAndReplaceOptions into a single FindOneAndReplaceOptions in a last-one-wins fashion func MergeFindOneAndReplaceOptions(opts ...*FindOneAndReplaceOptions) *FindOneAndReplaceOptions { fo := FindOneAndReplace() for _, opt := range opts { if opt == nil { continue } if opt.BypassDocumentValidation != nil { fo.BypassDocumentValidation = opt.BypassDocumentValidation } if opt.Collation != nil { fo.Collation = opt.Collation } if opt.MaxTime != nil { fo.MaxTime = opt.MaxTime } if opt.Projection != nil { fo.Projection = opt.Projection } if opt.ReturnDocument != nil { fo.ReturnDocument = opt.ReturnDocument } if opt.Sort != nil { fo.Sort = opt.Sort } if opt.Upsert != nil { fo.Upsert = opt.Upsert } } return fo } // FindOneAndUpdateOptions represent all possible options to the findOne() function. type FindOneAndUpdateOptions struct { ArrayFilters *ArrayFilters // A set of filters specifying to which array elements an update should apply. BypassDocumentValidation *bool // If true, allows the write to opt out of document-level validation. Collation *Collation // Specifies a collation to be used MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run. Projection interface{} // Limits the fields returned for all documents. ReturnDocument *ReturnDocument // Specifies whether the original or updated document should be returned. Sort interface{} // Specifies the order in which to return results. Upsert *bool // If true, creates a a new document if no document matches the query. } // FindOneAndUpdate creates a new FindOneAndUpdateOptions instance. func FindOneAndUpdate() *FindOneAndUpdateOptions { return &FindOneAndUpdateOptions{} } // SetBypassDocumentValidation sets filters that specify to which array elements an update should apply. func (f *FindOneAndUpdateOptions) SetBypassDocumentValidation(b bool) *FindOneAndUpdateOptions { f.BypassDocumentValidation = &b return f } // SetArrayFilters specifies a set of filters, which func (f *FindOneAndUpdateOptions) SetArrayFilters(filters ArrayFilters) *FindOneAndUpdateOptions { f.ArrayFilters = &filters return f } // SetCollation specifies a Collation to use for the Find operation. func (f *FindOneAndUpdateOptions) SetCollation(collation *Collation) *FindOneAndUpdateOptions { f.Collation = collation return f } // SetMaxTime specifies the max time to allow the query to run. func (f *FindOneAndUpdateOptions) SetMaxTime(d time.Duration) *FindOneAndUpdateOptions { f.MaxTime = &d return f } // SetProjection adds an option to limit the fields returned for all documents. func (f *FindOneAndUpdateOptions) SetProjection(projection interface{}) *FindOneAndUpdateOptions { f.Projection = projection return f } // SetReturnDocument specifies whether the original or updated document should be returned. // If set to Before, the original document will be returned. If set to After, the updated document // will be returned. func (f *FindOneAndUpdateOptions) SetReturnDocument(rd ReturnDocument) *FindOneAndUpdateOptions { f.ReturnDocument = &rd return f } // SetSort specifies the order in which to return documents. func (f *FindOneAndUpdateOptions) SetSort(sort interface{}) *FindOneAndUpdateOptions { f.Sort = sort return f } // SetUpsert specifies if a new document should be created if no document matches the query. func (f *FindOneAndUpdateOptions) SetUpsert(b bool) *FindOneAndUpdateOptions { f.Upsert = &b return f } // MergeFindOneAndUpdateOptions combines the argued FindOneAndUpdateOptions into a single FindOneAndUpdateOptions in a last-one-wins fashion func MergeFindOneAndUpdateOptions(opts ...*FindOneAndUpdateOptions) *FindOneAndUpdateOptions { fo := FindOneAndUpdate() for _, opt := range opts { if opt == nil { continue } if opt.ArrayFilters != nil { fo.ArrayFilters = opt.ArrayFilters } if opt.BypassDocumentValidation != nil { fo.BypassDocumentValidation = opt.BypassDocumentValidation } if opt.Collation != nil { fo.Collation = opt.Collation } if opt.MaxTime != nil { fo.MaxTime = opt.MaxTime } if opt.Projection != nil { fo.Projection = opt.Projection } if opt.ReturnDocument != nil { fo.ReturnDocument = opt.ReturnDocument } if opt.Sort != nil { fo.Sort = opt.Sort } if opt.Upsert != nil { fo.Upsert = opt.Upsert } } return fo } // FindOneAndDeleteOptions represent all possible options to the findOne() function. type FindOneAndDeleteOptions struct { Collation *Collation // Specifies a collation to be used MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run. Projection interface{} // Limits the fields returned for all documents. Sort interface{} // Specifies the order in which to return results. } // FindOneAndDelete creates a new FindOneAndDeleteOptions instance. func FindOneAndDelete() *FindOneAndDeleteOptions { return &FindOneAndDeleteOptions{} } // SetCollation specifies a Collation to use for the Find operation. // Valid for server versions >= 3.4 func (f *FindOneAndDeleteOptions) SetCollation(collation *Collation) *FindOneAndDeleteOptions { f.Collation = collation return f } // SetMaxTime specifies the max time to allow the query to run. func (f *FindOneAndDeleteOptions) SetMaxTime(d time.Duration) *FindOneAndDeleteOptions { f.MaxTime = &d return f } // SetProjection adds an option to limit the fields returned for all documents. func (f *FindOneAndDeleteOptions) SetProjection(projection interface{}) *FindOneAndDeleteOptions { f.Projection = projection return f } // SetSort specifies the order in which to return documents. func (f *FindOneAndDeleteOptions) SetSort(sort interface{}) *FindOneAndDeleteOptions { f.Sort = sort return f } // MergeFindOneAndDeleteOptions combines the argued FindOneAndDeleteOptions into a single FindOneAndDeleteOptions in a last-one-wins fashion func MergeFindOneAndDeleteOptions(opts ...*FindOneAndDeleteOptions) *FindOneAndDeleteOptions { fo := FindOneAndDelete() for _, opt := range opts { if opt == nil { continue } if opt.Collation != nil { fo.Collation = opt.Collation } if opt.MaxTime != nil { fo.MaxTime = opt.MaxTime } if opt.Projection != nil { fo.Projection = opt.Projection } if opt.Sort != nil { fo.Sort = opt.Sort } } return fo }
vendor/github.com/mongodb/mongo-go-driver/mongo/options/findoptions.go
0.681515
0.409929
findoptions.go
starcoder
package iiif import ( "image" "strconv" "strings" ) // A RegionType tells us what a Region is representing so we know how to apply // the x/y/w/h values type RegionType int const ( // RTNone means we didn't find a valid region string RTNone RegionType = iota // RTFull means we ignore x/y/w/h and use the whole image RTFull // RTPercent means we interpret x/y/w/h as percentages of the image size RTPercent // RTPixel means we interpret x/y/w/h as precise coordinates within the image RTPixel // RTSquare means a square region where w/h are the image's shortest dimension RTSquare ) // Region represents the part of the image we'll manipulate. It can be thought // of as the cropping rectangle. type Region struct { Type RegionType X, Y, W, H float64 } // StringToRegion takes a string representing a region, as seen in a IIIF URL, // and fills in the values based on the string's format. func StringToRegion(p string) Region { if p == "full" { return Region{Type: RTFull} } if p == "square" { return Region{Type: RTSquare} } r := Region{Type: RTPixel} if len(p) > 4 && p[0:4] == "pct:" { r.Type = RTPercent p = p[4:] } vals := strings.Split(p, ",") if len(vals) < 4 { return Region{Type: RTNone} } r.X, _ = strconv.ParseFloat(vals[0], 64) r.Y, _ = strconv.ParseFloat(vals[1], 64) r.W, _ = strconv.ParseFloat(vals[2], 64) r.H, _ = strconv.ParseFloat(vals[3], 64) return r } // Valid checks for (a) a known region type, and then (b) verifies that the // values are valid for the given type. There is no attempt to check for // per-image correctness, just general validity. func (r Region) Valid() bool { switch r.Type { case RTNone: return false case RTFull, RTSquare: return true } if r.W <= 0 || r.H <= 0 || r.X < 0 || r.Y < 0 { return false } if r.Type == RTPercent && (r.X+r.W > 100 || r.Y+r.H > 100) { return false } return true } // GetCrop determines the cropped area that this region represents given an // image width and height func (r Region) GetCrop(w, h int) image.Rectangle { crop := image.Rect(0, 0, w, h) switch r.Type { case RTSquare: if w < h { top := (h - w) / 2 crop = image.Rect(0, top, w, w+top) } else if h < w { left := (w - h) / 2 crop = image.Rect(left, 0, h+left, h) } case RTPixel: crop = image.Rect(int(r.X), int(r.Y), int(r.X+r.W), int(r.Y+r.H)) case RTPercent: crop = image.Rect( int(r.X*float64(w)/100.0), int(r.Y*float64(h)/100.0), int((r.X+r.W)*float64(w)/100.0), int((r.Y+r.H)*float64(h)/100.0), ) } return crop }
src/iiif/region.go
0.721939
0.633155
region.go
starcoder
package geogoth // LineString ... type LineString struct { Coords [][]float64 } // NewLineString creates LineString func NewLineString(coords [][]float64) LineString { return LineString{ Coords: coords, } } // Coordinates returns array of longitude, latitude of the LineString func (l LineString) Coordinates() interface{} { return l.Coords // longitude (Y), latitude (X) } // GetCoordinates returns array of longitude, latitude of LineString // coordnum - index of coordinate arr func (l LineString) GetCoordinates(coordnum int) (float64, float64) { coords := (l.Coordinates()).([][]float64) lon := coords[coordnum][0] lat := coords[coordnum][1] return lon, lat // longitude (Y), latitude (X) } // Type returns type of the LineString (LineString) func (l LineString) Type() string { return "LineString" } // Length returns length of the LineString func (l LineString) Length() float64 { return LineStringLength(&l) } // DistanceTo returns distance between two geo objects func (l LineString) DistanceTo(f Feature) float64 { var distance float64 switch f.Type() { case "Point": point := f.(*Point) distance = DistancePointLinstring(point, &l) case "MultiPoint": mpoint := f.(*MultiPoint) distance = DistanceMultipointLinestring(mpoint, &l) case "LineString": lstr := f.(*LineString) distance = DistanceLineStringLineString(&l, lstr) case "MultiLineString": mlinestr := f.(*MultiLineString) distance = DistanceLineStringMultiLineString(&l, mlinestr) case "Polygon": pol := f.(*Polygon) distance = DistanceLineStringPolygon(&l, pol) case "MultiPolygon": mpol := f.(*MultiPolygon) distance = DistanceLineStringMultiPolygon(&l, mpol) } return distance } // IntersectsWith returns true if geoObject intersects with Feature func (l LineString) IntersectsWith(f Feature) bool { var intersection bool switch f.Type() { case "Point": // point := f.(*Point) case "MultiPoint": // mpoint := f.(*MultiPoint) case "LineString": // lstr := f.(*LineString) case "MultiLineString": // mlinestr := f.(*MultiLineString) case "Polygon": // polygon := f.(*Polygon) case "MultiPolygon": // mpolyg := f.(*MultiPolygon) } return intersection }
linestring.go
0.879289
0.47098
linestring.go
starcoder
package mesh import ( "log" "math" "alvin.com/GoCarver/geom" "alvin.com/GoCarver/hmap" ) // gridRow: Rows of vertices form a grid; each square in that grid form 2 triangles. // row i+1: +---+---+---+-- - // | /| /| /| // | / | / | / | // |/ |/ |/ | // row i: +---+---+---+-- - // Note: The mesh is layed out over a regular grid. N+1 x-coordinates are stored within a single // array in the mesh since they are shared by all vertices. (See TriangleMesh below.) type gridRow struct { y float64 // y-coordinate for this entire row z []float64 // Z-coordinates for N+1 vertices along the x-axis. normals []geom.Vec3 // 2*N precomputed unit normals for each triangle formed by row i and i+1 } // TriangleMesh is a regular NxM triangle mesh representing the height map built from // a scalar height map (interface codeSampler). type TriangleMesh struct { xyBox Footprint // The mesh footprint. zMin, zMax float64 // Z extents rows []gridRow // Rows along the y-axis. x []float64 // X-coordinate for N+1 vertices along the x-axis. } // triangleArray implements interface TriangleIterator type triangleArray struct { triangles []meshTriangle iteratorIndex int } var _ TriangleIterator = (*triangleArray)(nil) // NewTriangleMesh creates and returns a new triangle mesh generated from the min/max corners // of the grid and a sampler. The number of vertices along x and y in the grid is determined // by the number of samples that the sampler generate in these directions. (See interface // iSampler.) A grid point is generated for each sample. func NewTriangleMesh( pMin geom.Pt2, pMax geom.Pt2, zBlack, zWhite float64, sampler hmap.ScalarGridSampler) *TriangleMesh { if pMin.X == pMax.X || pMin.Y == pMax.Y { return nil } mesh := &TriangleMesh{} mesh.xyBox = NewFootprint(pMin, pMax) mesh.buildMesh(zBlack, zWhite, sampler) mesh.zMin = math.Min(zBlack, zWhite) mesh.zMax = math.Max(zBlack, zWhite) return mesh } // GetZExtents returns the mesh z-extents. func (t *TriangleMesh) GetZExtents() (zMin, zMax float64) { zMin, zMax = t.zMin, t.zMax return } // GetNumTriangles returns the number of triangles in the mesh as pair of numbers (nX, nY) // where nX is the number of triangles along X and nY is the number of triangle rows along Y. func (t *TriangleMesh) GetNumTriangles() (nX int, nY int) { nY = len(t.rows) - 1 nX = 0 if nY > 0 { nX = 2 * (len(t.x) - 1) } return } // GetMeshFootprint returns the footprint for the entire mesh. func (t *TriangleMesh) GetMeshFootprint() Footprint { return t.xyBox } // GetTriangle returns the triangle at index (iX, iY) where 0 <= iX < nX and // 0 <= iY < nY. Triangle counts nX and nY are returned by GetNumTriangles. func (t *TriangleMesh) GetTriangle(iX, iY int) Triangle { nX, nY := t.GetNumTriangles() if iX < 0 || iX >= nX || iY < 0 || iY >= nY { log.Fatal("Triangle indices out of range") return &meshTriangle{} } trg := &meshTriangle{} trg.normal = t.rows[iY].normals[iX] // Vertices and triangles are layed out as follows in the grid: // nY+1 +---+ // | /| // T0 | / | T1 // |/ | // nY +---+ // nV nV+1 iT := iX & 0x01 iV := iX / 2 xLeft := t.x[iV] xRight := t.x[iV+1] yBottom := t.rows[iY].y yTop := t.rows[iY+1].y if iT == 0 { trg.vertices[0] = geom.NewPt3(xLeft, yBottom, t.rows[iY].z[iV]) trg.vertices[1] = geom.NewPt3(xLeft, yTop, t.rows[iY+1].z[iV]) trg.vertices[2] = geom.NewPt3(xRight, yTop, t.rows[iY+1].z[iV+1]) } else { trg.vertices[0] = geom.NewPt3(xLeft, yBottom, t.rows[iY].z[iV]) trg.vertices[1] = geom.NewPt3(xRight, yTop, t.rows[iY+1].z[iV+1]) trg.vertices[2] = geom.NewPt3(xRight, yBottom, t.rows[iY].z[iV+1]) } return trg } // GetFootprintForTriangle returns the footprint for triangle at indices (iX, iY). func (t *TriangleMesh) GetFootprintForTriangle(iX, iY int) Footprint { nX, nY := t.GetNumTriangles() if iX < 0 || iX >= nX || iY < 0 || iY >= nY { log.Fatal("Triangle indices out of range") return Footprint{} } // Vertices and triangles are layed out as follows in the grid: // nY+1 +---+ // | | // | | // | | // nY +---+ // nV nV+1 f := Footprint{} nV := iX / 2 f.PMin.X = t.x[nV] f.PMin.Y = t.rows[iY].y f.PMax.X = t.x[nV+1] f.PMax.Y = t.rows[iY+1].y return f } // GetTrianglesUnderFootprint gathers all the mesh triangles that are covered by the given footprint // into an iterator. The footprint is considered to be a closed set when looking for the triangles. // That is, triangles whose boundaries abut with the footprint are considered to be covered by the // footprint. This function may return an empty iterator. func (t *TriangleMesh) GetTrianglesUnderFootprint(f Footprint) TriangleIterator { iMinRow, iMaxRow := t.findRowsForFootprint(f) if iMinRow < 0 { return &triangleArray{} } iMinCol, iMaxCol := t.findColumnsForFootprint(f) if iMinCol < 0 { return &triangleArray{} } // TODO: check footprints that lie entirely on one side of diagonal between triangles. numTriangles := 2 * (iMaxRow - iMinRow) * (iMaxCol - iMinCol) // fmt.Printf("Num triangles: %d\n", numTriangles) ta := &triangleArray{ triangles: make([]meshTriangle, numTriangles), iteratorIndex: 0, } n := 0 for ic := iMinCol; ic < iMaxCol; ic++ { for ir := iMinRow; ir < iMaxRow; ir++ { row0 := &t.rows[ir] row1 := &t.rows[ir+1] ta.triangles[n].vertices[0] = geom.NewPt3(t.x[ic], row0.y, row0.z[ic]) ta.triangles[n].vertices[1] = geom.NewPt3(t.x[ic], row1.y, row1.z[ic]) ta.triangles[n].vertices[2] = geom.NewPt3(t.x[ic+1], row1.y, row1.z[ic+1]) ta.triangles[n].normal = row0.normals[2*ic] n++ ta.triangles[n].vertices[0] = geom.NewPt3(t.x[ic], row0.y, row0.z[ic]) ta.triangles[n].vertices[1] = geom.NewPt3(t.x[ic+1], row1.y, row1.z[ic+1]) ta.triangles[n].vertices[2] = geom.NewPt3(t.x[ic+1], row0.y, row0.z[ic+1]) ta.triangles[n].normal = row0.normals[2*ic+1] n++ } } return ta } // Find the rows that overlap with the given footprint. Returns indices iMinRow, iMaxRow // such that the footprint fits entirely within the y-coordinates of each row. Returns // iMinRow == iMaxRow == -1 if the footprint doesn't overlap the mesh at all. func (t *TriangleMesh) findRowsForFootprint(f Footprint) (iMinRow, iMaxRow int) { // Check for empty mesh. if len(t.rows) == 0 { return -1, -1 } // Check for footprint trivially above or below mesh's y-boundaries. if f.PMax.Y < t.xyBox.PMin.Y || f.PMin.Y > t.xyBox.PMax.Y { return -1, -1 } // Index to top row of vertices. iTopRow := len(t.rows) - 1 // Find the first row that is just below or level with the footprint. iMinRow = 0 for { if iMinRow == iTopRow-1 { break // Reached top-most limit for iMinRow. } if f.PMin.Y <= t.rows[iMinRow+1].y { break } iMinRow++ } // Now look for the first row that is strictly above the footprint. iMaxRow = iMinRow + 1 for { if iMaxRow == iTopRow { break // Reached top-most row. } if t.rows[iMaxRow].y > f.PMax.Y { break } iMaxRow++ } // fmt.Printf("Print min/max rows: %d - %d\n", iMinRow, iMaxRow) return } // Find the columns that overlap with the given footprint. Returns indices iMinCol, iMaxCol // such that the footprint fits entirely with the x-coordinates of each column. Returns // iMinCol == iMaxCol == -1 if the footprint doesn't overlap the mesh at all. func (t *TriangleMesh) findColumnsForFootprint(f Footprint) (iMinCol, iMaxCol int) { // Check for empty mesh. if len(t.rows) == 0 { return -1, -1 } // Check for footprint trivially to the left or right of mesh's y-boundaries. if f.PMax.X < t.xyBox.PMin.X || f.PMin.X > t.xyBox.PMax.X { return -1, -1 } // Index to last column of x-coordinates. iLastCol := len(t.x) - 1 // Find the first column that is just to the left or even with the footprint. iMinCol = 0 for { if iMinCol == iLastCol-1 { break // Reached right-most limit for iMinCol. } if f.PMin.X <= t.x[iMinCol+1] { break } iMinCol++ } // Now look for the first column that is strictly to the right of the footprint. iMaxCol = iMinCol + 1 for { if iMaxCol == iLastCol { break // Reached right-most column. } if t.x[iMaxCol] > f.PMax.X { break } iMaxCol++ } // fmt.Printf("Min.max column: %d, %d\n", iMinCol, iMaxCol) return } func (t *TriangleMesh) buildMesh(zBlack, zWhite float64, sampler hmap.ScalarGridSampler) { pMin := t.xyBox.PMin pMax := t.xyBox.PMax numGridRows := sampler.GetNumSamplesFromY0ToY1(pMin.Y, pMax.Y) numVerticesPerRow := sampler.GetNumSamplesFromX0ToX1(pMin.X, pMax.X) if numGridRows <= 1 { numGridRows = 2 } if numVerticesPerRow <= 1 { numVerticesPerRow = 2 } // Fill x-coordinates array. t.x = make([]float64, numVerticesPerRow) for i := range t.x { x := 0.0 switch i { case 0: x = pMin.X case numVerticesPerRow - 1: x = pMax.X default: t := float64(i) / float64(numVerticesPerRow-1) x = (1.0-t)*pMin.X + t*pMax.X } t.x[i] = x } // fmt.Printf("x-coordinates: %v\n", t.x) // Fill rows. t.rows = make([]gridRow, numGridRows) for i := range t.rows { yRow := 0.0 switch i { case 0: yRow = pMin.Y case numGridRows - 1: yRow = pMax.Y default: t := float64(i) / float64(numGridRows-1) yRow = (1-t)*pMin.Y + t*pMax.Y } t.rows[i].y = yRow t.populateVerticesForRow(i, zBlack, zWhite, sampler) if i > 0 { t.populateNormalsForRow(i - 1) } } } // Allocate and fill the array of z-coordinates for grid row with index rowIndex. func (t *TriangleMesh) populateVerticesForRow( rowIndex int, zBlack, zWhite float64, sampler hmap.ScalarGridSampler) { numVertices := len(t.x) y := t.rows[rowIndex].y t.rows[rowIndex].z = make([]float64, numVertices) for i := range t.x { x := t.x[i] uv := geom.NewPt2(x, y) z := sampler.At(uv) z = (1.0-z)*zBlack + z*zWhite t.rows[rowIndex].z[i] = z } } // Allocate and fill the array of triangle normals for grid row with index rowIndex. // Pre-condition: z-coordinates for rows at index rowIndex and rowIndex+1 must be populated. func (t *TriangleMesh) populateNormalsForRow(rowIndex int) { if rowIndex >= len(t.rows)-1 { log.Fatal("Index rowIndex out of range") return } // xk xl x-coordinates xk and xl // yj +---+ row of vertices at y = yj // | /| // | / | grid cell with 2 triangles // |/ | // yi +---+ row of vertices at y = yi yi := t.rows[rowIndex].y yj := t.rows[rowIndex+1].y zi := t.rows[rowIndex].z zj := t.rows[rowIndex+1].z // There are two normal vectors (two triangles) per grid cell. Each cell // consists of four vertices, two from each row. numVertices := len(t.x) numNormals := (numVertices - 1) * 2 t.rows[rowIndex].normals = make([]geom.Vec3, numNormals) for k := 0; k < numVertices-1; k++ { xk := t.x[k] xl := t.x[k+1] p0 := geom.NewPt3(xk, yi, zi[k]) p1 := geom.NewPt3(xk, yj, zj[k]) p2 := geom.NewPt3(xl, yj, zj[k+1]) // fmt.Printf("Normal: p0=%v, p1=%v, p2=%v", p0, p1, p2) w1 := p1.Sub(p0) w2 := p2.Sub(p0) n1 := w2.Cross(w1) t.rows[rowIndex].normals[2*k] = n1.Norm() // fmt.Printf(" - w1=%v, w2=%v", w1, w2) p2 = geom.NewPt3(xl, yi, zi[k+1]) w1 = p2.Sub(p0) n2 := w1.Cross(w2) t.rows[rowIndex].normals[2*k+1] = n2.Norm() // fmt.Printf(" - n1=%v, n2=%v\n", n1, n2) } } // GetTriangleCount implements interface TriangleIterator. func (t *triangleArray) GetTriangleCount() int { return len(t.triangles) } // Next implements interface TriangleIterator. func (t *triangleArray) Next() Triangle { if t.iteratorIndex >= t.GetTriangleCount() { return nil } retVal := &t.triangles[t.iteratorIndex] t.iteratorIndex++ return retVal }
mesh/triangle_mesh.go
0.761804
0.578984
triangle_mesh.go
starcoder
package manifests // Type of resource const ( // service mesh resource SERVICE_MESH = iota // native Kubernetes resource K8s // native Meshery resource MESHERY ) // Json Paths type JsonPath []string type Component struct { Schemas []string Definitions []string } type Config struct { Name string // Name of the service mesh,or k8 or meshery MeshVersion string Filter CrdFilter //json path filters ModifyDefSchema func(*string, *string) //takes in definition and schema, does some manipulation on them and returns the new def and schema } /* How to customize these filters (These comments to be updated if the behavior changes in future)- There are only two types of filters used internally by kubeopenapi-jsonschema which is being used here- filter(input filter) and output filter. The filters described below are an abstraction over those filters. 1. RootFilter- is used at two places (a) For fetching the crd names or api resources on which we will iterate over, first we apply the root filter to get the objects we are interested in and then the NameFilter is applied as output filter to take out just the names from selected objects. (b) [this will be discussed after ItrFilter] 2. NameFilter- As explained above, it is used as an --o-filter to extract only the names after RootFilter(1(a)) has been applied. 3. ItrFilter- This is an incomplete filter, intentionally left incomplete. Before getting version and group with VersionFilter and GroupFilter, we want to obtain only the object we are interested in, in a given iteration. Crdnames or ApiResource names which are obtained by NameFilter are iterated over and used within,lets call it X. ItrFilter filters out the object which has some given field set to X. A complete filter might look something like "$.a.b[?(@.c==X)]". Since X is obtained at runtime, we pass ItrFilter such that it can be later appended with "==X)]". So you can use this filter to find objects where we can get versions and groups based on X. Hence ItrFilter in this example can be passed as "$.a.b[?(@.c". All filters except this and ItrSpecFilter are complete. 4. GroupFilter- After ItrFilter gives us the object with the group and version of the crd/resource we are interested in with this iteration, GroupFilter is used as output filter to only extract the group. 5. VersionFilter- After ItrFilter gives us the object with the group and version of the crd/resource we are interested in with this iteration, GroupFilter is used as output filter to only extract the version. 6. ItrSpecFilter- Functionally is same as ItrFilter but instead of group and version, it is used to get openapi spec/schema. 7. GField- The GroupFilter returns a json which has group in it. The key name which is used to signify group will be passed here. For eg: "group" 8. VField- The GroupFilter returns a json which has version in it. The key name which is used to signify version will be passed here. For eg: "version", "name","version-name" 9. OnlyRes- In some cases we dont want to compute crdnames/api-resources at runtime as we already have them. Pass those names as an array here to skip that step. 10. IsJson- The file on which to apply all these filters is, by default expected to be YAML. Set this to true if a JSON is passed instead. (These are the only two supported formats) 11. SpecFilter- When SpecFilter is passed, it is applied as output filter after ItrSpec filter. 1(b) If SpecFilter is not passed, then before the ItrSpecFilter the rootfilter will be applied by default and then the ItrSpec filter will be applied as output filter. */ type CrdFilter struct { RootFilter JsonPath NameFilter JsonPath GroupFilter JsonPath VersionFilter JsonPath SpecFilter JsonPath ItrFilter string ItrSpecFilter string VField string GField string IsJson bool OnlyRes []string }
utils/manifests/definitions.go
0.533154
0.476336
definitions.go
starcoder
package engine import ( "fmt" "reflect" "time" ) type Assertion struct { name string nodeType NodeType parent *Assertion children []*Assertion details []Detail result Result Logger Logger } type Detail struct { Name string Message string RecordTime time.Time } func NewAssertion(name string, nodeType NodeType, parent *Assertion, logger Logger) *Assertion { assertion := &Assertion{ name: name, nodeType: nodeType, result: NOTRUN, parent: parent, children: make([]*Assertion, 0), details: make([]Detail, 0), Logger: logger, } if assertion.parent != nil { assertion.parent.children = append(assertion.parent.children, assertion) } return assertion } func (a *Assertion) AssertEquals(expected interface{}, actual interface{}, title string) { if reflect.TypeOf(expected).Kind() != reflect.TypeOf(actual).Kind() { a.details = append(a.details, Detail{ Name: "Assert", Message: fmt.Sprintf("%s expected %T(%v), but actual was %T(%v)", title, expected, expected, actual, actual), RecordTime: time.Now(), }) a.fail() return } switch reflect.TypeOf(expected).Kind() { case reflect.Array, reflect.Slice: expectedRV := reflect.ValueOf(expected) actualRV := reflect.ValueOf(actual) if expectedRV.Len() != actualRV.Len() { a.details = append(a.details, Detail{ Name: "Assert", Message: fmt.Sprintf("%s expected %T(%v), but actual was %T(%v)", title, expected, expected, actual, actual), RecordTime: time.Now(), }) a.fail() return } for i := 0; i < expectedRV.Len(); i++ { if expectedRV.Index(i).CanInterface() { if expectedRV.Index(i).Interface() != actualRV.Index(i).Interface() { a.details = append(a.details, Detail{ Name: "Assert", Message: fmt.Sprintf("%s expected %T(%v), but actual was %T(%v)", title, expected, expected, actual, actual), RecordTime: time.Now(), }) a.fail() return } } else { a.details = append(a.details, Detail{ Name: "Assert", Message: "cannot be compared", RecordTime: time.Now(), }) a.fail() return } } default: if expected != actual { a.details = append(a.details, Detail{ Name: "Assert", Message: fmt.Sprintf("%s expected %T(%v), but actual was %T(%v)", title, expected, expected, actual, actual), RecordTime: time.Now(), }) a.fail() } } } func (a *Assertion) AssertNotEquals(expected interface{}, actual interface{}, title string) { if reflect.TypeOf(expected).Kind() != reflect.TypeOf(actual).Kind() { return } switch reflect.TypeOf(expected).Kind() { case reflect.Array, reflect.Slice: expectedRV := reflect.ValueOf(expected) actualRV := reflect.ValueOf(actual) if expectedRV.Len() != actualRV.Len() { return } for i := 0; i < expectedRV.Len(); i++ { if expectedRV.Index(i).CanInterface() { if expectedRV.Index(i).Interface() != actualRV.Index(i).Interface() { return } } else { a.details = append(a.details, Detail{ Name: "Assert", Message: "cannot be compared", RecordTime: time.Now(), }) a.fail() } } a.details = append(a.details, Detail{ Name: "Assert", Message: fmt.Sprintf("%s expected not %T(%v), but actual was %T(%v)", title, expected, expected, actual, actual), RecordTime: time.Now(), }) a.fail() default: if expected == actual { a.details = append(a.details, Detail{ Name: "Assert", Message: fmt.Sprintf("%s expected not %T(%v), but actual was %T(%v)", title, expected, expected, actual, actual), RecordTime: time.Now(), }) a.fail() } } } func (a *Assertion) AssertFail(title string) { a.details = append(a.details, Detail{ Name: "Assert", Message: fmt.Sprintf("Fail, because %s", title), RecordTime: time.Now(), }) a.fail() } func (a *Assertion) fail() { if a.parent != nil { a.parent.fail() } a.result = FAIL } func (a *Assertion) Result() Result { return a.result } func (a *Assertion) AddDetail(name string, message string, args ...interface{}) { a.details = append(a.details, Detail{Name: name, Message: fmt.Sprintf(message, args...), RecordTime: time.Now()}) } func (a *Assertion) GetDetails() []Detail { return a.details }
engine/assertion.go
0.529263
0.621756
assertion.go
starcoder
// Package queue implements a singly-linked list with queue behaviors. package queue import ( "fmt" coll "github.com/maguerrido/collection" ) // node of a Queue. type node struct { // value stored in the node. value interface{} // next points to the next node. // If the node is the back node, then points to nil. next *node } // clear sets the properties of the node to its zero values. // Time complexity: O(1). func (n *node) clear() { n.value, n.next = nil, nil } // Queue represents a singly-linked list. // The zero value for Queue is an empty Queue ready to use. type Queue struct { // front points to the front (first) node in the queue. // back points to the back (last) node in the queue. front, back *node // len is the current length (number of nodes). len int } // New returns a new Queue ready to use. // Time complexity: O(1). func New() *Queue { return new(Queue) } // NewBySlice returns a new Queue with the values stored in the slice keeping its order. // Time complexity: O(n), where n is the current length of the slice. func NewBySlice(values []interface{}) *Queue { q := New() for _, v := range values { q.Push(v) } return q } // Clone returns a new cloned Queue. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) Clone() *Queue { clone := New() for n := q.front; n != nil; n = n.next { clone.Push(n.value) } return clone } // Do gets the front value and performs all the procedures, then repeats it with the rest of the values. // The queue will be empty. // Time complexity: O(n*p), where n is the current length of the queue and p is the number of procedures. func (q *Queue) Do(procedures ...func(v interface{})) { for !q.IsEmpty() { v := q.Get() for _, procedure := range procedures { procedure(v) } } } // Equals compares this queue with the 'other' queue and returns true if they are equal. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) Equals(other *Queue) bool { if q.len != other.len { return false } for i, j := q.front, other.front; i != nil; i, j = i.next, j.next { if i.value != j.value { return false } } return true } // EqualsByComparator compares this queue with the 'other' queue and returns true if they are equal. // The comparison between values is defined by the parameter 'equals'. // The function 'equals' must return true if 'v1' equals 'v2'. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) EqualsByComparator(other *Queue, equals func(v1, v2 interface{}) bool) bool { if q.len != other.len { return false } for i, j := q.front, other.front; i != nil; i, j = i.next, j.next { if !equals(i.value, j.value) { return false } } return true } // Get returns the front value and removes it from the queue. // If the queue is empty, then returns nil. // Time complexity: O(1). func (q *Queue) Get() interface{} { if q.IsEmpty() { return nil } n, v := q.front, q.front.value if q.back == n { q.back = nil } q.front = n.next n.clear() q.len-- return v } // GetIf returns all first values that meet the condition defined by the 'condition' parameter. These values will be //removed from the queue. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) GetIf(condition func(v interface{}) bool) []interface{} { values := make([]interface{}, 0) for n := q.front; n != nil; { if condition(n.value) { values = append(values, q.Get()) n = q.front } else { return values } } return values } // IsEmpty returns true if the queue has no values. // Time complexity: O(1). func (q *Queue) IsEmpty() bool { return q.len == 0 } func (q *Queue) Iterator() coll.Iterator { return &iterator{ q: q, prev: nil, this: nil, index: -1, lastCommand: -1, lastHasNext: false, } } // Len returns the current length of the queue. // Time complexity: O(1). func (q *Queue) Len() int { return q.len } // Peek returns the front value. // If the queue is empty, then returns nil. // Time complexity: O(1). func (q *Queue) Peek() interface{} { if q.IsEmpty() { return nil } return q.front.value } // Push inserts the value 'v' at the back of the queue. // Time complexity: O(1). func (q *Queue) Push(v interface{}) { n := &node{value: v, next: nil} if q.IsEmpty() { q.front = n } else { q.back.next = n } q.back = n q.len++ } // RemoveAll sets the properties of the queue to its zero values. // Time complexity: O(1). func (q *Queue) RemoveAll() { q.front, q.back, q.len = nil, nil, 0 } func (q *Queue) removeNode(prev, n *node) { if q.front == n { if q.back == n { q.front, q.back = nil, nil } else { q.front = n.next } } else if q.back == n { q.back = prev prev.next = nil } else { prev.next = n.next } n.clear() q.len-- } // Search returns the index (zero based) of the first match of the value 'v'. // If the value 'v' does not belong to the queue, then returns -1. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) Search(v interface{}) int { for n, i := q.front, 0; n != nil; n, i = n.next, i+1 { if n.value == v { return i } } return -1 } // SearchByComparator returns the index (zero based) of the first match of the value 'v'. // If the value 'v' does not belong to the queue, then returns -1. // The comparison between values is defined by the parameter 'equals'. // The function 'equals' must return true if 'v1' equals 'v2'. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) SearchByComparator(v interface{}, equals func(v1, v2 interface{}) bool) int { for n, i := q.front, 0; n != nil; n, i = n.next, i+1 { if equals(n.value, v) { return i } } return -1 } // Slice returns a new slice with the values stored in the queue keeping its order. // The queue retains its original state. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) Slice() []interface{} { values := make([]interface{}, 0, q.len) for n := q.front; n != nil; n = n.next { values = append(values, n.value) } return values } // String returns a representation of the queue as a string. // Queue implements the fmt.Stringer interface. // Time complexity: O(n), where n is the current length of the queue. func (q *Queue) String() string { if q.IsEmpty() { return "[]" } n := q.front str := "[" for ; n.next != nil; n = n.next { str += fmt.Sprintf("%v ", n.value) } return str + fmt.Sprintf("%v]", n.value) } type iterator struct { q *Queue prev, this *node index int lastCommand int lastHasNext bool } const ( iteratorCommandHasNext = 0 iteratorCommandNext = 1 iteratorCommandRemove = 2 ) func (i *iterator) ForEach(action func(v *interface{})) { if action != nil { for e := i.q.front; e != nil; e = e.next { action(&e.value) } } } func (i *iterator) HasNext() bool { i.lastCommand = iteratorCommandHasNext i.lastHasNext = i.index < i.q.len-1 return i.lastHasNext } func (i *iterator) Next() (interface{}, error) { if i.lastCommand != iteratorCommandHasNext { return nil, fmt.Errorf(coll.ErrorIteratorNext) } else if !i.lastHasNext { return nil, fmt.Errorf(coll.ErrorIteratorHasNext) } if i.this == nil { i.this = i.q.front } else { i.prev = i.this i.this = i.this.next } i.index++ i.lastCommand = iteratorCommandNext return i.this.value, nil } func (i *iterator) Remove() error { if !i.lastHasNext { return fmt.Errorf(coll.ErrorIteratorHasNext) } else if i.lastCommand != iteratorCommandNext { return fmt.Errorf(coll.ErrorIteratorRemove) } i.q.removeNode(i.prev, i.this) i.this = i.prev i.index-- i.lastCommand = iteratorCommandRemove return nil }
queue/queue.go
0.843541
0.452838
queue.go
starcoder
// Package counter implements counters that keeps track of their recent values // over different periods of time. // Example: // c := counter.New() // c.Incr(n) // ... // delta1h := c.Delta1h() // delta10m := c.Delta10m() // delta1m := c.Delta1m() // and: // rate1h := c.Rate1h() // rate10m := c.Rate10m() // rate1m := c.Rate1m() package counter import ( "sync" "time" "v.io/x/ref/services/stats" ) var ( // TimeNow is used for testing. TimeNow = time.Now ) const ( hour = 0 tenminutes = 1 minute = 2 ) // Counter is a counter that keeps track of its recent values over a given // period of time, and with a given resolution. Use New() to instantiate. type Counter struct { mu sync.RWMutex ts [3]*timeseries lastUpdate time.Time } // New returns a new Counter. func New() *Counter { now := TimeNow() c := &Counter{} c.ts[hour] = newTimeSeries(now, time.Hour, time.Minute) c.ts[tenminutes] = newTimeSeries(now, 10*time.Minute, 10*time.Second) c.ts[minute] = newTimeSeries(now, time.Minute, time.Second) return c } func (c *Counter) advance() time.Time { now := TimeNow() for _, ts := range c.ts { ts.advanceTime(now) } return now } // Value returns the current value of the counter. func (c *Counter) Value() int64 { c.mu.RLock() defer c.mu.RUnlock() return c.ts[minute].headValue() } // LastUpdate returns the last update time of the counter. func (c *Counter) LastUpdate() time.Time { c.mu.RLock() defer c.mu.RUnlock() return c.lastUpdate } // Set updates the current value of the counter. func (c *Counter) Set(value int64) { c.mu.Lock() defer c.mu.Unlock() c.lastUpdate = c.advance() for _, ts := range c.ts { ts.set(value) } } // Incr increments the current value of the counter by 'delta'. func (c *Counter) Incr(delta int64) { c.mu.Lock() defer c.mu.Unlock() c.lastUpdate = c.advance() for _, ts := range c.ts { ts.incr(delta) } } // Delta1h returns the delta for the last hour. func (c *Counter) Delta1h() int64 { c.mu.RLock() defer c.mu.RUnlock() c.advance() return c.ts[hour].delta() } // Delta10m returns the delta for the last 10 minutes. func (c *Counter) Delta10m() int64 { c.mu.RLock() defer c.mu.RUnlock() c.advance() return c.ts[tenminutes].delta() } // Delta1m returns the delta for the last minute. func (c *Counter) Delta1m() int64 { c.mu.RLock() defer c.mu.RUnlock() c.advance() return c.ts[minute].delta() } // Rate1h returns the rate of change of the counter in the last hour. func (c *Counter) Rate1h() float64 { c.mu.RLock() defer c.mu.RUnlock() c.advance() return c.ts[hour].rate() } // Rate10m returns the rate of change of the counter in the last 10 minutes. func (c *Counter) Rate10m() float64 { c.mu.RLock() defer c.mu.RUnlock() c.advance() return c.ts[tenminutes].rate() } // Rate1m returns the rate of change of the counter in the last minute. func (c *Counter) Rate1m() float64 { c.mu.RLock() defer c.mu.RUnlock() c.advance() return c.ts[minute].rate() } // TimeSeries1h returns the time series data in the last hour. func (c *Counter) TimeSeries1h() stats.TimeSeries { return c.timeseries(c.ts[hour]) } // TimeSeries10m returns the time series data in the last 10 minutes. func (c *Counter) TimeSeries10m() stats.TimeSeries { return c.timeseries(c.ts[tenminutes]) } // TimeSeries1m returns the time series data in the last minute. func (c *Counter) TimeSeries1m() stats.TimeSeries { return c.timeseries(c.ts[minute]) } func (c *Counter) timeseries(ts *timeseries) stats.TimeSeries { c.mu.RLock() defer c.mu.RUnlock() return stats.TimeSeries{ Values: ts.values(), Resolution: ts.resolution, StartTime: ts.tailTime(), } } // Reset resets the counter to an empty state. func (c *Counter) Reset() { c.mu.Lock() defer c.mu.Unlock() now := TimeNow() for _, ts := range c.ts { ts.reset(now) } }
x/ref/lib/stats/counter/counter.go
0.852091
0.405566
counter.go
starcoder
package evaluator import ( "fmt" "ghostlang.org/x/ghost/ast" "ghostlang.org/x/ghost/object" "ghostlang.org/x/ghost/value" ) type Evaluator func(node ast.Node, scope *object.Scope) object.Object // Evaluate is the heart of our evaluator. It switches off between the various // AST node types and evaluates each accordingly and returns its value. func Evaluate(node ast.Node, scope *object.Scope) object.Object { switch node := node.(type) { case *ast.Program: return evaluateProgram(node, scope) case *ast.Assign: return evaluateAssign(node, scope) case *ast.Block: return evaluateBlock(node, scope) case *ast.Boolean: return evaluateBoolean(node, scope) case *ast.Break: return evaluateBreak(node, scope) case *ast.Call: return evaluateCall(node, scope) case *ast.Class: return evaluateClass(node, scope) case *ast.Compound: return evaluateCompound(node, scope) case *ast.Continue: return evaluateContinue(node, scope) case *ast.Expression: return Evaluate(node.Expression, scope) case *ast.For: return evaluateFor(node, scope) case *ast.ForIn: return evaluateForIn(node, scope) case *ast.Function: return evaluateFunction(node, scope) case *ast.Identifier: return evaluateIdentifier(node, scope) case *ast.If: return evaluateIf(node, scope) case *ast.Import: return evaluateImport(node, scope) case *ast.ImportFrom: return evaluateImportFrom(node, scope) case *ast.Index: return evaluateIndex(node, scope) case *ast.Infix: return evaluateInfix(node, scope) case *ast.List: return evaluateList(node, scope) case *ast.Map: return evaluateMap(node, scope) case *ast.Method: return evaluateMethod(node, scope) case *ast.Null: return evaluateNull(node, scope) case *ast.Number: return evaluateNumber(node, scope) case *ast.Prefix: return evaluatePrefix(node, scope) case *ast.Property: return evaluateProperty(node, scope) case *ast.Return: return evaluateReturn(node, scope) case *ast.String: return evaluateString(node, scope) case *ast.Switch: return evaluateSwitch(node, scope) case *ast.Ternary: return evaluateTernary(node, scope) case *ast.This: return evaluateThis(node, scope) case *ast.While: return evaluateWhile(node, scope) } return nil } // ============================================================================= // Helper functions // toBooleanValue converts the passed native boolean value into a boolean // object. func toBooleanValue(input bool) *object.Boolean { if input { return value.TRUE } return value.FALSE } // isError determines if the referenced object is an error. func isError(obj object.Object) bool { if obj != nil { return obj.Type() == object.ERROR } return false } // isTerminator determines if the referenced object is an error, break, or continue. func isTerminator(obj object.Object) bool { if obj != nil { return obj.Type() == object.ERROR || obj.Type() == object.BREAK || obj.Type() == object.CONTINUE } return false } // isTruthy determines if the referenced value is of a truthy value. func isTruthy(value object.Object) bool { switch value := value.(type) { case *object.Null: return false case *object.Boolean: return value.Value case *object.String: return len(value.Value) > 0 default: return true } } // newError returns a new error object. func newError(format string, a ...interface{}) *object.Error { return &object.Error{Message: fmt.Sprintf(format, a...)} }
src/evaluator/evaluator.go
0.746971
0.489442
evaluator.go
starcoder
package rbtree const ( red = false black = true ) // Compare compares two values. Returns 0 if a==b, negative if a < b, and // positive a > b. type Compare func(a, b interface{}) int // RedBlackTree is a red-black tree. type RedBlackTree struct { // Compare is used to compare values in the red-black tree for ordering. Compare root *node size int } // New constructs an empty red-black tree. func New(compare Compare) *RedBlackTree { return &RedBlackTree{Compare: compare} } // Size returns the size of the red-black tree in constant time. func (r *RedBlackTree) Size() int { return r.size } // Max returns the maximum value in the tree. func (r *RedBlackTree) Max() interface{} { if r.root == nil { return nil } return r.root.max().value } // Min returns the minimum value in the tree. func (r *RedBlackTree) Min() interface{} { if r.root == nil { return nil } return r.root.min().value } type node struct { value interface{} left, right, parent *node color bool } func (n *node) sibling() *node { if n == n.parent.left { return n.parent.right } return n.parent.left } func (n *node) max() *node { for n.right != nil { n = n.right } return n } func (n *node) min() *node { for n.left != nil { n = n.left } return n } func (n *node) defcolor() bool { if n == nil { return black } return n.color } func (r *RedBlackTree) replace(src, dest *node) { if src.parent == nil { r.root = dest } else { if src == src.parent.left { src.parent.left = dest } else { src.parent.right = dest } } if dest != nil { dest.parent = src.parent } } func (r *RedBlackTree) rotateLeft(src *node) { dest := src.right r.replace(src, dest) src.right = dest.left if dest.left != nil { dest.left.parent = src } dest.left = src src.parent = dest } func (r *RedBlackTree) rotateRight(src *node) { dest := src.left r.replace(src, dest) src.left = dest.right if dest.right != nil { dest.right.parent = src } dest.right = src src.parent = dest }
rbtree.go
0.822403
0.404596
rbtree.go
starcoder
package template import ( "fmt" "github.com/pkg/errors" "reflect" "strings" "text/template/parse" ) var ( zero reflect.Value errorType = reflect.TypeOf((*error)(nil)).Elem() ) // Data represent a data source, which contains the value used in template. template will find value in it. type Data interface { Value(string) interface{} } // Template is a object parsed from template-string type Template struct { raw string nodes []parse.Node } // New create a new template from a string func New(s string) (*Template, error) { t := &Template{ raw: s, } sets, err := parse.Parse("default", t.raw, "", "", builtins) if err != nil { return nil, err } t.nodes = sets["default"].Root.Nodes return t, nil } // String return the original template string func (t *Template) String() string { return t.raw } // Execute return the golang value which the template represented func (t *Template) Execute(data Data) (interface{}, error) { switch len(t.nodes) { case 0: return t.raw, nil case 1: switch n := t.nodes[0].(type) { case *parse.ActionNode: v, err := evalAction(n, data) // execute the value from the template if err != nil { return nil, err } return v.Interface(), nil case *parse.TextNode: return n.String(), nil default: return nil, errors.Errorf("unvalid node type %d", n.Type()) } default: // having multiple node in text, means it must be a string value, such as "{{ .a }}{{ .b }}" can not return a single golang value, it must be a string. s := "" for _, node := range t.nodes { switch n := node.(type) { case *parse.ActionNode: v, err := evalAction(n, data) if err != nil { return nil, err } s = fmt.Sprintf("%s%v", s, v.Interface()) case *parse.TextNode: s = fmt.Sprintf("%s%s", s, n.String()) default: return nil, errors.Errorf("unvalid node type %d", n.Type()) } } return s, nil } } // Parse a template string directlly, it is same to call New() and then Execute(). func Parse(s string, data Data) (interface{}, error) { tmp, err := New(s) if err != nil { return nil, err } return tmp.Execute(data) } func evalAction(action *parse.ActionNode, data Data) (value reflect.Value, err error) { return evalPipeline(action.Pipe, data) } // evalPipeline returns the value acquired by evaluating a pipeline. If the // pipeline has a variable declaration, the variable will be pushed on the // stack. Callers should therefore pop the stack after they are finished // executing commands depending on the pipeline value. func evalPipeline(pipe *parse.PipeNode, data Data) (value reflect.Value, err error) { if pipe == nil { return value, errors.New("pipenode is nil") } for _, cmd := range pipe.Cmds { value, err = evalCommand(cmd, data, value) // previous value is this one's final arg. if err != nil { return value, errors.Wrap(err, "fail to eval command") } if value.Kind() == reflect.Interface && value.Type().NumMethod() == 0 { value = reflect.ValueOf(value.Interface()) // lovely! } } return value, nil } func evalCommand(cmd *parse.CommandNode, data Data, final reflect.Value) (reflect.Value, error) { firstWord := cmd.Args[0] switch n := firstWord.(type) { case *parse.FieldNode: return evalFieldNode(firstWord.(*parse.FieldNode), data, cmd.Args, final) case *parse.ChainNode: return evalChainNode(n, data, cmd.Args, final) case *parse.IdentifierNode: // Must be a function. return evalFunction(n, data, cmd, cmd.Args, final) case *parse.PipeNode: // Parenthesized pipeline. The arguments are all inside the pipeline; final is ignored. return evalPipeline(n, data) } // firstWord is not a function, so it can not having argument, check here. if len(cmd.Args) > 1 || final.IsValid() { return zero, errors.Errorf("can not give argument to non-function %s", firstWord) } switch word := firstWord.(type) { case *parse.BoolNode: return reflect.ValueOf(word.True), nil case *parse.NumberNode: return idealConstant(word) case *parse.StringNode: return reflect.ValueOf(word.Text), nil case *parse.TextNode: return reflect.ValueOf(word.String()), nil case *parse.NilNode: return zero, errors.New("nil is not a command") } return zero, errors.Errorf("can't evaluate command %q", firstWord) } func evalFieldNode(field *parse.FieldNode, data Data, args []parse.Node, final reflect.Value) (reflect.Value, error) { return evalFieldChain(field, data, field.Ident, args, final, zero) } func evalChainNode(chain *parse.ChainNode, data Data, args []parse.Node, final reflect.Value) (reflect.Value, error) { if len(chain.Field) == 0 { return zero, errors.New("internal error: no fields in evalChainNode") } if chain.Node.Type() == parse.NodeNil { return zero, errors.Errorf("indirection through explicit nil in %s", chain) } // (pipe).Field1.Field2 has pipe as .Node, fields as .Field. Eval the pipeline, then the fields. pipe, err := evalArg(chain.Node, data, nil) if err != nil { return zero, err } return evalFieldChain(chain, data, chain.Field, args, final, pipe) } // evalFieldChain evaluates .X.Y.Z possibly followed by arguments. // receiver is the value being walked along the chain. func evalFieldChain(node parse.Node, data Data, ident []string, args []parse.Node, final, receiver reflect.Value) (reflect.Value, error) { n, from := len(ident), 0 if n == 0 { return zero, errors.New("no field defined in fieldNode") } if !receiver.IsValid() { if tmp := data.Value(ident[0]); tmp != nil { receiver = reflect.ValueOf(tmp) } else { return zero, errors.Errorf("value %s not found or is nil", ident[0]) } // TODO can not return it directlly, it may be a function if n == 1 { // check if it's a function if receiver.IsValid() && receiver.Type().Kind() == reflect.Func { return evalCall(receiver, args, data, ident[0], final) } return receiver, nil } from = 1 } var err error for i := from; i < n-1; i++ { receiver, err = evalField(node, data, ident[i], nil, zero, receiver) if err != nil { return zero, err } } // Now if it's a method, it gets the arguments. return evalField(node, data, ident[n-1], args, final, receiver) } // evalField evaluates an expression like (.Field) or (.Field arg1 arg2). // The 'final' argument represents the return value from the preceding // value of the pipeline, if any. func evalField(node parse.Node, data Data, fieldName string, args []parse.Node, final, receiver reflect.Value) (reflect.Value, error) { if !receiver.IsValid() { return zero, errors.New("unvalid receiver value") } typ := receiver.Type() receiver, _ = indirect(receiver) // Unless it's an interface, need to get to a value of type *T to guarantee // we see all methods of T and *T. ptr := receiver if ptr.Kind() != reflect.Interface && ptr.CanAddr() { ptr = ptr.Addr() } if method := ptr.MethodByName(fieldName); method.IsValid() { return evalCall(method, args, data, fieldName, final) } hasArgs := len(args) > 1 || final.IsValid() // It's not a method; must be a field of a struct or an element of a map. The receiver must not be nil. receiver, isNil := indirect(receiver) if isNil { return zero, errors.Errorf("nil pointer evaluating %s.%s", typ, fieldName) } switch receiver.Kind() { case reflect.Struct: tField, ok := receiver.Type().FieldByName(fieldName) if ok { field := receiver.FieldByIndex(tField.Index) if tField.PkgPath != "" { // field is unexported return zero, errors.Errorf("%s is an unexported field of struct type %s", fieldName, typ) } // If it's a function, we must call it. if hasArgs { return zero, errors.Errorf("%s has arguments but cannot be invoked as function", fieldName) } return field, nil } return zero, errors.Errorf("%s is not a field of struct type %s", fieldName, typ) case reflect.Map: // If it's a map, attempt to use the field name as a key. nameVal := reflect.ValueOf(fieldName) if nameVal.Type().AssignableTo(receiver.Type().Key()) { if hasArgs { return zero, errors.Errorf("%s is not a method but has arguments", fieldName) } result := receiver.MapIndex(nameVal) if !result.IsValid() { return zero, errors.Errorf("map has no entry for key %q", fieldName) } return result, nil } } return zero, errors.Errorf("can't evaluate field %s in type %s", fieldName, typ) } func evalFunction(node *parse.IdentifierNode, data Data, cmd parse.Node, args []parse.Node, final reflect.Value) (reflect.Value, error) { name := node.Ident function, ok := builtins[name] if !ok { return zero, errors.Errorf("%q is not a defined function", name) } return evalCall(reflect.ValueOf(function), args, data, name, final) } func evalArg(n parse.Node, data Data, typ reflect.Type) (reflect.Value, error) { switch arg := n.(type) { case *parse.NilNode: if canBeNil(typ) { return reflect.Zero(typ), nil } return zero, errors.Errorf("cannot assign nil to %s", typ) case *parse.FieldNode: tmp, err := evalFieldNode(arg, data, []parse.Node{n}, zero) if err != nil { return zero, err } return validateType(tmp, typ) case *parse.PipeNode: tmp, err := evalPipeline(arg, data) if err != nil { return zero, err } return validateType(tmp, typ) case *parse.IdentifierNode: tmp, err := evalFunction(arg, data, arg, nil, zero) if err != nil { return zero, err } return validateType(tmp, typ) case *parse.ChainNode: tmp, err := evalChainNode(arg, data, nil, zero) if err != nil { return zero, err } return validateType(tmp, typ) } switch typ.Kind() { case reflect.Bool: return evalBool(typ, n) case reflect.Complex64, reflect.Complex128: return evalComplex(typ, n) case reflect.Float32, reflect.Float64: return evalFloat(typ, n) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return evalInteger(typ, n) case reflect.Interface: if typ.NumMethod() == 0 { return evalEmptyInterface(n, data) } case reflect.String: return evalString(typ, n) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return evalUnsignedInteger(typ, n) } return zero, errors.Errorf("can't handle %s for arg of type %s", n, typ) } func evalBool(typ reflect.Type, n parse.Node) (reflect.Value, error) { if n, ok := n.(*parse.BoolNode); ok { value := reflect.New(typ).Elem() value.SetBool(n.True) return value, nil } return zero, errors.Errorf("expected bool; found %s", n) } func evalString(typ reflect.Type, n parse.Node) (reflect.Value, error) { if n, ok := n.(*parse.StringNode); ok { value := reflect.New(typ).Elem() value.SetString(n.Text) return value, nil } return zero, errors.Errorf("expected string; found %s", n) } func evalInteger(typ reflect.Type, n parse.Node) (reflect.Value, error) { if n, ok := n.(*parse.NumberNode); ok && n.IsInt { value := reflect.New(typ).Elem() value.SetInt(n.Int64) return value, nil } return zero, errors.Errorf("expected integer; found %s", n) } func evalUnsignedInteger(typ reflect.Type, n parse.Node) (reflect.Value, error) { if n, ok := n.(*parse.NumberNode); ok && n.IsUint { value := reflect.New(typ).Elem() value.SetUint(n.Uint64) return value, nil } return zero, errors.Errorf("expected unsigned integer; found %s", n) } func evalFloat(typ reflect.Type, n parse.Node) (reflect.Value, error) { if n, ok := n.(*parse.NumberNode); ok && n.IsFloat { value := reflect.New(typ).Elem() value.SetFloat(n.Float64) return value, nil } return zero, errors.Errorf("expected float; found %s", n) } func evalComplex(typ reflect.Type, n parse.Node) (reflect.Value, error) { if n, ok := n.(*parse.NumberNode); ok && n.IsComplex { value := reflect.New(typ).Elem() value.SetComplex(n.Complex128) return value, nil } return zero, errors.Errorf("expected complex; found %s", n) } func evalEmptyInterface(n parse.Node, data Data) (reflect.Value, error) { switch n := n.(type) { case *parse.BoolNode: return reflect.ValueOf(n.True), nil case *parse.FieldNode: return evalFieldNode(n, data, nil, zero) case *parse.IdentifierNode: return evalFunction(n, data, n, nil, zero) case *parse.NilNode: // NilNode is handled in evalArg, the only place that calls here. return zero, errors.Errorf("evalEmptyInterface: nil (can't happen)") case *parse.NumberNode: return idealConstant(n) case *parse.StringNode: return reflect.ValueOf(n.Text), nil case *parse.PipeNode: return evalPipeline(n, data) } return zero, errors.Errorf("can't handle assignment of %s to empty interface argument", n) } // evalCall executes a function or method call. If it's a method, fun already has the receiver bound, so // it looks just like a function call. The arg list, if non-nil, includes (in the manner of the shell), arg[0] // as the function itself. func evalCall(fun reflect.Value, args []parse.Node, data Data, name string, final reflect.Value) (reflect.Value, error) { var err error if args != nil { args = args[1:] // Zeroth arg is function name/node; not passed to function. } typ := fun.Type() numIn := len(args) if final.IsValid() { numIn++ } numFixed := len(args) if typ.IsVariadic() { numFixed = typ.NumIn() - 1 // last arg is the variadic one. if numIn < numFixed { return zero, errors.Errorf("wrong number of args for %s: want at least %d got %d", name, typ.NumIn()-1, len(args)) } } else if numIn < typ.NumIn()-1 || !typ.IsVariadic() && numIn != typ.NumIn() { return zero, errors.Errorf("wrong number of args for %s: want %d got %d", name, typ.NumIn(), len(args)) } if !goodFunc(typ) { // TODO: This could still be a confusing error; maybe goodFunc should provide info. return zero, errors.Errorf("can't call method/function %q with %d results", name, typ.NumOut()) } // Build the arg list. argv := make([]reflect.Value, numIn) // Args must be evaluated. Fixed args first. i := 0 for ; i < numFixed && i < len(args); i++ { argv[i], err = evalArg(args[i], data, typ.In(i)) if err != nil { return zero, err } } // Now the ... args. if typ.IsVariadic() { argType := typ.In(typ.NumIn() - 1).Elem() // Argument is a slice. for ; i < len(args); i++ { argv[i], err = evalArg(args[i], data, argType) if err != nil { return zero, err } } } // Add final value if necessary. if final.IsValid() { t := typ.In(typ.NumIn() - 1) if typ.IsVariadic() { if numIn-1 < numFixed { // The added final argument corresponds to a fixed parameter of the function. // Validate against the type of the actual parameter. t = typ.In(numIn - 1) } else { // The added final argument corresponds to the variadic part. // Validate against the type of the elements of the variadic slice. t = t.Elem() } } argv[i], err = validateType(final, t) if err != nil { return zero, err } } result := fun.Call(argv) // If we have an error that is not nil, stop execution and return that error to the caller. if len(result) == 2 && !result[1].IsNil() { return zero, errors.Errorf("error calling %s: %s", name, result[1].Interface().(error)) } return result[0], nil } // idealConstant is called to return the value of a number in a context where // we don't know the type. In that case, the syntax of the number tells us // its type, and we use Go rules to resolve. Note there is no such thing as // a uint ideal constant in this situation - the value must be of int type. func idealConstant(constant *parse.NumberNode) (reflect.Value, error) { // These are ideal constants but we don't know the type // and we have no context. (If it was a method argument, // we'd know what we need.) The syntax guides us to some extent. switch { case constant.IsComplex: return reflect.ValueOf(constant.Complex128), nil // incontrovertible. case constant.IsFloat && !isHexConstant(constant.Text) && strings.IndexAny(constant.Text, ".eE") >= 0: return reflect.ValueOf(constant.Float64), nil case constant.IsInt: n := int(constant.Int64) if int64(n) != constant.Int64 { return zero, errors.Errorf("%s overflows int", constant.Text) } return reflect.ValueOf(n), nil case constant.IsUint: return zero, errors.Errorf("%s overflows int", constant.Text) } return zero, nil } // indirect returns the item at the end of indirection, and a bool to indicate if it's nil. // We indirect through pointers and empty interfaces (only) because // non-empty interfaces have methods we might need. func indirect(v reflect.Value) (rv reflect.Value, isNil bool) { for ; v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface; v = v.Elem() { if v.IsNil() { return v, true } if v.Kind() == reflect.Interface && v.NumMethod() > 0 { break } } return v, false } // canBeNil reports whether an untyped nil can be assigned to the type. See reflect.Zero. func canBeNil(typ reflect.Type) bool { switch typ.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return true } return false } // validateType guarantees that the value is valid and assignable to the type. func validateType(value reflect.Value, typ reflect.Type) (reflect.Value, error) { if !value.IsValid() { if typ == nil || canBeNil(typ) { // An untyped nil interface{}. Accept as a proper nil value. return reflect.Zero(typ), nil } return zero, errors.Errorf("invalid value; expected %s", typ) } if typ != nil && !value.Type().AssignableTo(typ) { if value.Kind() == reflect.Interface && !value.IsNil() { value = value.Elem() if value.Type().AssignableTo(typ) { return value, nil } // fallthrough } // Does one dereference or indirection work? We could do more, as we // do with method receivers, but that gets messy and method receivers // are much more constrained, so it makes more sense there than here. // Besides, one is almost always all you need. switch { case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ): value = value.Elem() if !value.IsValid() { return zero, errors.Errorf("dereference of nil pointer of type %s", typ) } case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr(): value = value.Addr() default: return zero, errors.Errorf("wrong type for value; expected %s; got %s", typ, value.Type()) } } return value, nil } func isHexConstant(s string) bool { return len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') }
template/template.go
0.586049
0.42656
template.go
starcoder
package topo import ( "gonum.org/v1/gonum/graph" "gonum.org/v1/gonum/graph/internal/ordered" "gonum.org/v1/gonum/graph/internal/set" ) // Builder is a pure topological graph construction type. type Builder interface { AddNode(graph.Node) SetEdge(graph.Edge) } // CliqueGraph builds the clique graph of g in dst using Clique and CliqueGraphEdge // nodes and edges. The nodes returned by calls to Nodes on the nodes and edges of // the constructed graph are the cliques and the common nodes between cliques // respectively. The dst graph is not cleared. func CliqueGraph(dst Builder, g graph.Undirected) { cliques := BronKerbosch(g) // Construct a consistent view of cliques in g. Sorting costs // us a little, but not as much as the cliques themselves. for _, c := range cliques { ordered.ByID(c) } ordered.BySliceIDs(cliques) cliqueNodes := make(cliqueNodeSets, len(cliques)) for id, c := range cliques { s := set.NewNodesSize(len(c)) for _, n := range c { s.Add(n) } ns := &nodeSet{Clique: Clique{id: int64(id), nodes: c}, nodes: s} dst.AddNode(ns.Clique) for _, n := range c { nid := n.ID() cliqueNodes[nid] = append(cliqueNodes[nid], ns) } } for _, cliques := range cliqueNodes { for i, uc := range cliques { for _, vc := range cliques[i+1:] { // Retain the nodes that contribute to the // edge between the cliques. var edgeNodes []graph.Node switch 1 { case len(uc.Clique.nodes): edgeNodes = []graph.Node{uc.Clique.nodes[0]} case len(vc.Clique.nodes): edgeNodes = []graph.Node{vc.Clique.nodes[0]} default: for _, n := range set.IntersectionOfNodes(uc.nodes, vc.nodes) { edgeNodes = append(edgeNodes, n) } ordered.ByID(edgeNodes) } dst.SetEdge(CliqueGraphEdge{from: uc.Clique, to: vc.Clique, nodes: edgeNodes}) } } } } type cliqueNodeSets map[int64][]*nodeSet type nodeSet struct { Clique nodes set.Nodes } // Clique is a node in a clique graph. type Clique struct { id int64 nodes []graph.Node } // ID returns the node ID. func (n Clique) ID() int64 { return n.id } // Nodes returns the nodes in the clique. func (n Clique) Nodes() []graph.Node { return n.nodes } // CliqueGraphEdge is an edge in a clique graph. type CliqueGraphEdge struct { from, to Clique nodes []graph.Node } // From returns the from node of the edge. func (e CliqueGraphEdge) From() graph.Node { return e.from } // To returns the to node of the edge. func (e CliqueGraphEdge) To() graph.Node { return e.to } // ReversedEdge returns a new CliqueGraphEdge with // the edge end points swapped. The nodes of the // new edge are shared with the receiver. func (e CliqueGraphEdge) ReversedEdge() graph.Edge { e.from, e.to = e.to, e.from; return e } // Nodes returns the common nodes in the cliques of the underlying graph // corresponding to the from and to nodes in the clique graph. func (e CliqueGraphEdge) Nodes() []graph.Node { return e.nodes }
graph/topo/clique_graph.go
0.731922
0.564879
clique_graph.go
starcoder
package math3 import ( "math" "github.com/golang/glog" ) type EulerChangeCallback func() type Euler struct { x float64 y float64 z float64 Order EulerOrder OnChangeCallback EulerChangeCallback } func NewEuler() *Euler { return &Euler{ 0, 0, 0, EulerDefaultOrder, EulerEmptyCallback, } } type EulerOrder string const ( XYZ EulerOrder = "XYZ" YZX = "YZX" ZXY = "ZXY" XZY = "XZY" YXZ = "YXZ" ZYX = "ZYX" CurrentOrder = "current" ) var EulerRotationOrders = []EulerOrder{XYZ, YZX, ZXY, XZY, YXZ, ZYX} const EulerDefaultOrder = XYZ func (e *Euler) GetX() float64 { return e.x } func (e *Euler) SetX(value float64) { e.x = value e.OnChangeCallback() } func (e *Euler) GetY() float64 { return e.y } func (e *Euler) SetY(value float64) { e.y = value e.OnChangeCallback() } func (e *Euler) GetZ() float64 { return e.z } func (e *Euler) SetZ(value float64) { e.z = value e.OnChangeCallback() } func (e *Euler) GetOder() EulerOrder { return e.Order } func (e *Euler) SetOrder(value EulerOrder) { e.Order = value e.OnChangeCallback() } func (e *Euler) Set(x, y, z float64, order EulerOrder) *Euler { e.x = x e.y = y e.z = z if order != CurrentOrder { e.Order = order } e.OnChangeCallback() return e } func (e *Euler) Clone() *Euler { return NewEuler().Copy(e) } func (e *Euler) Copy(src *Euler) *Euler { e.x = src.x e.y = src.y e.z = src.z e.Order = src.Order e.OnChangeCallback() return e } func (e *Euler) SetFromRotationMatrix( m *Matrix4, order EulerOrder, update bool) *Euler { // assumes the upper 3x3 of m is a pure rotation matrix (i.E, unscaled) te := m.Elements m11 := te[0] m12 := te[4] m13 := te[8] m21 := te[1] m22 := te[5] m23 := te[9] m31 := te[2] m32 := te[6] m33 := te[10] if order == CurrentOrder { order = e.Order } if order == XYZ { e.y = math.Asin(Clamp(m13, -1, 1)) if math.Abs(m13) < 0.99999 { e.x = math.Atan2(-m23, m33) e.z = math.Atan2(-m12, m11) } else { e.x = math.Atan2(m32, m22) e.z = 0 } } else if order == YXZ { e.x = math.Asin(-Clamp(m23, -1, 1)) if math.Abs(m23) < 0.99999 { e.y = math.Atan2(m13, m33) e.z = math.Atan2(m21, m22) } else { e.y = math.Atan2(-m31, m11) e.z = 0 } } else if order == ZXY { e.x = math.Asin(Clamp(m32, -1, 1)) if math.Abs(m32) < 0.99999 { e.y = math.Atan2(-m31, m33) e.z = math.Atan2(-m12, m22) } else { e.y = 0 e.z = math.Atan2(m21, m11) } } else if order == ZYX { e.y = math.Asin(-Clamp(m31, -1, 1)) if math.Abs(m31) < 0.99999 { e.x = math.Atan2(m32, m33) e.z = math.Atan2(m21, m11) } else { e.x = 0 e.z = math.Atan2(-m12, m22) } } else if order == YZX { e.z = math.Asin(Clamp(m21, -1, 1)) if math.Abs(m21) < 0.99999 { e.x = math.Atan2(-m23, m22) e.y = math.Atan2(-m31, m11) } else { e.x = 0 e.y = math.Atan2(m13, m33) } } else if order == XZY { e.z = math.Asin(-Clamp(m12, -1, 1)) if math.Abs(m12) < 0.99999 { e.x = math.Atan2(m32, m22) e.y = math.Atan2(m13, m11) } else { e.x = math.Atan2(-m23, m33) e.y = 0 } } else { glog.Warningf("three.Euler: SetFromRotationMatrix() given unsupported order: %s", string(order)) } e.Order = order if update != false { e.OnChangeCallback() } return e } func (e *Euler) SetFromQuaternion( q *Quaternion, order EulerOrder, update bool) *Euler { matrix := NewMatrix4() matrix.MakeRotationFromQuaternion(q) return e.SetFromRotationMatrix(matrix, order, update) } func (e *Euler) SetFromVector3(v *Vector3, order EulerOrder) *Euler { return e.Set(v.X, v.Y, v.Z, order) } func (e *Euler) Reorder(newOrder EulerOrder) *Euler { // WARNING: e discards revolution information -bhouston q := NewQuaternion() q.SetFromEuler(e, false) return e.SetFromQuaternion(q, newOrder, false) } func (e *Euler) Equals(other *Euler) bool { return (e.x == other.x) && (e.y == other.y) && (e.z == other.z) && (e.Order == other.Order) } func (e *Euler) FromArray(array []float64, order EulerOrder) *Euler { e.x = array[0] e.y = array[1] e.z = array[2] if order == CurrentOrder { e.Order = order } e.OnChangeCallback() return e } func (e *Euler) ToArray(array []float64, offset int) ([]float64, EulerOrder) { if array == nil { array = make([]float64, offset+3) } array[offset] = e.x array[offset+1] = e.y array[offset+2] = e.z return array, e.Order } func (e *Euler) ToVector3(target *Vector3) *Vector3 { if target == nil { target = NewVector3() } return target.Set(e.x, e.y, e.z) } func (e *Euler) OnChange(callback EulerChangeCallback) *Euler { e.OnChangeCallback = callback return e } func EulerEmptyCallback() {}
math3/euler.go
0.785226
0.491273
euler.go
starcoder
package cluster import ( ddbRaft "github.com/armPelionEdge/devicedb/raft" ) type ClusterStateDeltaType int const ( DeltaNodeAdd ClusterStateDeltaType = iota DeltaNodeRemove ClusterStateDeltaType = iota DeltaNodeLoseToken ClusterStateDeltaType = iota DeltaNodeGainToken ClusterStateDeltaType = iota DeltaNodeGainPartitionReplicaOwnership ClusterStateDeltaType = iota DeltaNodeLosePartitionReplicaOwnership ClusterStateDeltaType = iota DeltaNodeLosePartitionReplica ClusterStateDeltaType = iota DeltaNodeGainPartitionReplica ClusterStateDeltaType = iota DeltaSiteAdded ClusterStateDeltaType = iota DeltaSiteRemoved ClusterStateDeltaType = iota DeltaRelayAdded ClusterStateDeltaType = iota DeltaRelayRemoved ClusterStateDeltaType = iota DeltaRelayMoved ClusterStateDeltaType = iota ) type ClusterStateDeltaRange []ClusterStateDelta func (r ClusterStateDeltaRange) Len() int { return len(r) } func (r ClusterStateDeltaRange) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r ClusterStateDeltaRange) Less(i, j int) bool { if r[i].Type != r[j].Type { return r[i].Type < r[j].Type } switch r[i].Type { case DeltaNodeAdd: return r[i].Delta.(NodeAdd).NodeID < r[j].Delta.(NodeAdd).NodeID case DeltaNodeRemove: return r[i].Delta.(NodeRemove).NodeID < r[j].Delta.(NodeRemove).NodeID case DeltaNodeLoseToken: if r[i].Delta.(NodeLoseToken).NodeID != r[j].Delta.(NodeLoseToken).NodeID { return r[i].Delta.(NodeLoseToken).NodeID < r[j].Delta.(NodeLoseToken).NodeID } return r[i].Delta.(NodeLoseToken).Token < r[j].Delta.(NodeLoseToken).Token case DeltaNodeGainToken: if r[i].Delta.(NodeGainToken).NodeID != r[j].Delta.(NodeGainToken).NodeID { return r[i].Delta.(NodeGainToken).NodeID < r[j].Delta.(NodeGainToken).NodeID } return r[i].Delta.(NodeGainToken).Token < r[j].Delta.(NodeGainToken).Token case DeltaNodeGainPartitionReplicaOwnership: if r[i].Delta.(NodeGainPartitionReplicaOwnership).NodeID != r[j].Delta.(NodeGainPartitionReplicaOwnership).NodeID { return r[i].Delta.(NodeGainPartitionReplicaOwnership).NodeID < r[j].Delta.(NodeGainPartitionReplicaOwnership).NodeID } if r[i].Delta.(NodeGainPartitionReplicaOwnership).Partition != r[j].Delta.(NodeGainPartitionReplicaOwnership).Partition { return r[i].Delta.(NodeGainPartitionReplicaOwnership).Partition < r[j].Delta.(NodeGainPartitionReplicaOwnership).Partition } return r[i].Delta.(NodeGainPartitionReplicaOwnership).Replica < r[j].Delta.(NodeGainPartitionReplicaOwnership).Replica case DeltaNodeLosePartitionReplicaOwnership: if r[i].Delta.(NodeLosePartitionReplicaOwnership).NodeID != r[j].Delta.(NodeLosePartitionReplicaOwnership).NodeID { return r[i].Delta.(NodeLosePartitionReplicaOwnership).NodeID < r[j].Delta.(NodeLosePartitionReplicaOwnership).NodeID } if r[i].Delta.(NodeLosePartitionReplicaOwnership).Partition != r[j].Delta.(NodeLosePartitionReplicaOwnership).Partition { return r[i].Delta.(NodeLosePartitionReplicaOwnership).Partition < r[j].Delta.(NodeLosePartitionReplicaOwnership).Partition } return r[i].Delta.(NodeLosePartitionReplicaOwnership).Replica < r[j].Delta.(NodeLosePartitionReplicaOwnership).Replica case DeltaNodeGainPartitionReplica: if r[i].Delta.(NodeGainPartitionReplica).NodeID != r[j].Delta.(NodeGainPartitionReplica).NodeID { return r[i].Delta.(NodeGainPartitionReplica).NodeID < r[j].Delta.(NodeGainPartitionReplica).NodeID } if r[i].Delta.(NodeGainPartitionReplica).Partition != r[j].Delta.(NodeGainPartitionReplica).Partition { return r[i].Delta.(NodeGainPartitionReplica).Partition < r[j].Delta.(NodeGainPartitionReplica).Partition } return r[i].Delta.(NodeGainPartitionReplica).Replica < r[j].Delta.(NodeGainPartitionReplica).Replica case DeltaNodeLosePartitionReplica: if r[i].Delta.(NodeLosePartitionReplica).NodeID != r[j].Delta.(NodeLosePartitionReplica).NodeID { return r[i].Delta.(NodeLosePartitionReplica).NodeID < r[j].Delta.(NodeLosePartitionReplica).NodeID } if r[i].Delta.(NodeLosePartitionReplica).Partition != r[j].Delta.(NodeLosePartitionReplica).Partition { return r[i].Delta.(NodeLosePartitionReplica).Partition < r[j].Delta.(NodeLosePartitionReplica).Partition } return r[i].Delta.(NodeLosePartitionReplica).Replica < r[j].Delta.(NodeLosePartitionReplica).Replica case DeltaSiteAdded: return r[i].Delta.(SiteAdded).SiteID < r[j].Delta.(SiteAdded).SiteID case DeltaSiteRemoved: return r[i].Delta.(SiteRemoved).SiteID < r[j].Delta.(SiteRemoved).SiteID case DeltaRelayAdded: return r[i].Delta.(RelayAdded).RelayID < r[j].Delta.(RelayAdded).RelayID case DeltaRelayRemoved: return r[i].Delta.(RelayRemoved).RelayID < r[j].Delta.(RelayRemoved).RelayID case DeltaRelayMoved: if r[i].Delta.(RelayMoved).RelayID != r[j].Delta.(RelayMoved).RelayID { return r[i].Delta.(RelayMoved).RelayID < r[j].Delta.(RelayMoved).RelayID } return r[i].Delta.(RelayMoved).SiteID < r[j].Delta.(RelayMoved).SiteID } return false } type ClusterStateDelta struct { Type ClusterStateDeltaType Delta interface{} } type NodeAdd struct { NodeID uint64 NodeConfig NodeConfig } type NodeRemove struct { NodeID uint64 } type NodeAddress struct { NodeID uint64 Address ddbRaft.PeerAddress } type NodeGainToken struct { NodeID uint64 Token uint64 } type NodeLoseToken struct { NodeID uint64 Token uint64 } type NodeGainPartitionReplicaOwnership struct { NodeID uint64 Partition uint64 Replica uint64 } type NodeLosePartitionReplicaOwnership struct { NodeID uint64 Partition uint64 Replica uint64 } type NodeGainPartitionReplica struct { NodeID uint64 Partition uint64 Replica uint64 } type NodeLosePartitionReplica struct { NodeID uint64 Partition uint64 Replica uint64 } type SiteAdded struct { SiteID string } type SiteRemoved struct { SiteID string } type RelayAdded struct { RelayID string } type RelayRemoved struct { RelayID string } type RelayMoved struct { RelayID string SiteID string }
vendor/github.com/armPelionEdge/devicedb/cluster/delta.go
0.52342
0.712495
delta.go
starcoder
package go2linq // Reimplementing LINQ to Objects: Part 15 – Union // https://codeblog.jonskeet.uk/2010/12/30/reimplementing-linq-to-objects-part-15-union/ // https://docs.microsoft.com/dotnet/api/system.linq.enumerable.union // Union produces the set union of two sequences by using reflect.DeepEqual as equality comparer. // 'first' and 'second' must not be based on the same Enumerator, otherwise use UnionSelf instead. func Union[Source any](first, second Enumerator[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } return UnionEq(first, second, nil) } // UnionMust is like Union but panics in case of error. func UnionMust[Source any](first, second Enumerator[Source]) Enumerator[Source] { r, err := Union(first, second) if err != nil { panic(err) } return r } // UnionSelf produces the set union of two sequences by using reflect.DeepEqual as equality comparer. // 'first' and 'second' may be based on the same Enumerator. // 'first' must have real Reset method. 'second' is enumerated immediately. func UnionSelf[Source any](first, second Enumerator[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } sl2 := Slice(second) first.Reset() return Union(first, NewOnSliceEn(sl2...)) } // UnionSelfMust is like UnionSelf but panics in case of error. func UnionSelfMust[Source any](first, second Enumerator[Source]) Enumerator[Source] { r, err := UnionSelf(first, second) if err != nil { panic(err) } return r } // UnionEq produces the set union of two sequences by using a specified Equaler to compare values. // If 'eq' is nil reflect.DeepEqual is used. // 'first' and 'second' must not be based on the same Enumerator, otherwise use UnionEqSelf instead. func UnionEq[Source any](first, second Enumerator[Source], eq Equaler[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } return DistinctEq(ConcatMust(first, second), eq) } // UnionEqMust is like UnionEq but panics in case of error. func UnionEqMust[Source any](first, second Enumerator[Source], eq Equaler[Source]) Enumerator[Source] { r, err := UnionEq(first, second, eq) if err != nil { panic(err) } return r } // UnionEqSelf produces the set union of two sequences by using a specified Equaler. // If 'eq' is nil reflect.DeepEqual is used. // 'first' and 'second' may be based on the same Enumerator. // 'first' must have real Reset method. 'second' is enumerated immediately. func UnionEqSelf[Source any](first, second Enumerator[Source], eq Equaler[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } sl2 := Slice(second) first.Reset() return UnionEq(first, NewOnSliceEn(sl2...), eq) } // UnionEqSelfMust is like UnionEqSelf but panics in case of error. func UnionEqSelfMust[Source any](first, second Enumerator[Source], eq Equaler[Source]) Enumerator[Source] { r, err := UnionEqSelf(first, second, eq) if err != nil { panic(err) } return r } // UnionCmp produces the set union of two sequences by using a specified Comparer. // (See DistinctCmp function.) // 'first' and 'second' must not be based on the same Enumerator, otherwise use UnionCmpSelf instead. func UnionCmp[Source any](first, second Enumerator[Source], comparer Comparer[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } if comparer == nil { return nil, ErrNilComparer } return DistinctCmp(ConcatMust(first, second), comparer) } // UnionCmpMust is like UnionCmp but panics in case of error. func UnionCmpMust[Source any](first, second Enumerator[Source], comparer Comparer[Source]) Enumerator[Source] { r, err := UnionCmp(first, second, comparer) if err != nil { panic(err) } return r } // UnionCmpSelf produces the set union of two sequences by using a specified Comparer. // (See DistinctCmp function.) // 'first' and 'second' may be based on the same Enumerator. // 'first' must have real Reset method. 'second' is enumerated immediately. func UnionCmpSelf[Source any](first, second Enumerator[Source], comparer Comparer[Source]) (Enumerator[Source], error) { if first == nil || second == nil { return nil, ErrNilSource } if comparer == nil { return nil, ErrNilComparer } sl2 := Slice(second) first.Reset() return UnionCmp(first, NewOnSliceEn(sl2...), comparer) } // UnionCmpSelfMust is like UnionCmpSelf but panics in case of error. func UnionCmpSelfMust[Source any](first, second Enumerator[Source], comparer Comparer[Source]) Enumerator[Source] { r, err := UnionCmpSelf(first, second, comparer) if err != nil { panic(err) } return r }
union.go
0.879425
0.472623
union.go
starcoder
Package command contains the commands used by vtctldclient. It is intended only for use in vtctldclient's main package and entrypoint. The rest of this documentation is intended for maintainers. Commands are grouped into files by the types of resources they interact with ( e.g. GetTablet, CreateTablet, DeleteTablet, GetTablets) or by what they do (e.g. PlannedReparentShard, EmergencyReparentShard, InitShardPrimary). Please add the command to the appropriate existing file, alphabetically, or create a new grouping if one does not exist. The root command lives in root.go, and commands must attach themselves to this during an init function in order to be reachable from the CLI. root.go also contains the global variables available to any subcommand that are managed by the root command's pre- and post-run functions. Commands must not attempt to manage these, as that may conflict with Root's post-run cleanup actions. All commands should, at a minimum, use the commandCtx rather than creating their own context.Background to start, as it contains root tracing spans that would be lost. Commands should not keep their logic in an anonymous function on the cobra.Command struct, but instead in a separate function that is assigned to RunE. Commands should strive to keep declaration, function definition, and flag initialization located as closely together as possible, to make the code easier to follow and understand (the global variables declared near Root are the exception here, not the rule). Commands should also prevent individual flag names from polluting the package namespace. A good pattern we have found is to do the following: package command // (imports ...) var ( CreateTablet = &cobra.Command{ Use: "CreateTablet [options] --keyspace=<keyspace> --shard=<shard-range> <tablet-alias> <tablet-type>", Args: cobra.ExactArgs(2), RunE: commandCreateTablet, } GetTablet = &cobra.Command{ Use: "GetTablet <tablet-alias>", Args: cobra.ExactArgs(1), RunE: commandGetTablet, } ) var createTabletOptions = struct { Opt1 string Opt2 bool Keyspace string Shard string }{} func commandCreateTablet(cmd *cobra.Command, args []string) error { aliasStr := cmd.Flags().Args(0) tabletTypeStr := cmd.Flags().Args(1) // do stuff with: // - client // - commandCtx // - createTabletOptions // - aliasStr // - tabletTypeStr return nil } // GetTablet takes no flags, so it needs no anonymous struct to store them func commandGetTablet(cmd *cobra.Command, args []string) error { aliasStr := cmd.Flags().Arg(0) // do stuff with: // - client // - commandCtx // - aliasStr return nil } // finally, hook up all the commands in this file to Root, and add any flags // to each of those commands func init() { CreateTablet.Flags().StringVar(&createTabletOptions.Opt1, "opt1", "default", "help") CreateTablet.Flags().BoolVar(&createTabletOptions.Opt2, "opt2", false, "help") CreateTablet.Flags().StringVarP(&createTabletOptions.Keyspace, "keyspace", "k", "keyspace of tablet") CreateTablet.MarkFlagRequired("keyspace") CreateTablet.Flags().StringVarP(&createTabletOptions.Shard, "shard", "s", "shard range of tablet") CreateTablet.MarkFlagRequired("shard") Root.AddCommand(CreateTablet) Root.AddCommand(GetTablet) } A note on RunE and SilenceUsage: We prefer using RunE over Run for the entrypoint to our subcommands, because it allows us return errors back up to the vtctldclient main function and do error handling, logging, and exit-code management once, in one place, rather than on a per-command basis. However, cobra treats errors returned from a command's RunE as usage errors, and therefore will print the command's full usage text to stderr when RunE returns non-nil, in addition to propagating that error back up to the result of the root command's Execute() method. This is decidedly not what we want. There is no plan to address this in cobra v1. [1] The suggested workaround for this issue is to set SilenceUsage: true, either on the root command or on every subcommand individually. This also does not work for vtctldclient, because not every flag can be parsed during pflag.Parse time, and for certain flags (mutually exclusive options, optional flags that require other flags to be set with them, etc) we do additional parsing and validation of flags in an individual subcommand. We want errors during this phase to be treated as usage errors, so setting SilenceUsage=true before this point would not cause usage text to be printed for us. So, for us, we want to individually set cmd.SilenceUsage = true at *particular points* in each command, dependending on whether that command needs to do an additional parse & validation pass. In most cases, the command does not need to post-validate its options, and can set cmd.SilencUsage = true as their first line. We feel, though, that a line that reads "SilenceUsage = true" to be potentially confusing in how it reads. A maintainer without sufficient context may read this and say "Silence usage? We don't want that" and remove the lines, so we provide a wrapper function that communicates intent, cli.FinishedParsing, that each subcommand should call when they have transitioned from the parsing & validation phase of their entrypoint to the actual logic. [1]: https://github.com/spf13/cobra/issues/340 */ package command
go/cmd/vtctldclient/command/doc.go
0.558327
0.539165
doc.go
starcoder
package dlx /* Dancing Links (Algorithm X) data struct. | | | | - columns 0 - columns 1 - columns 2 - ......... - columns i - | | | | - node(row)- node - node - node - | | | | - node(row)- node - | | - node(row)- node - node - | | | - node(row)- node - node - | | | */ type Column struct { Node Index int // index of the column Size int // size of node of the column } type Node struct { Col *Column // column of the node Row *Node // first node of the row of the node Up, Down, Left, Right *Node // up, down, left, right of the node } // X holds the matrix-like columns and solution. type X struct { Cols []Column Sol Solution } type Solution []*Node // NewX returns Dlx data struct with columns initialized. func NewX(size int) *X { ret := &X{} ret.Cols = make([]Column, size+1) // use column 0 as head it := &ret.Cols[0] // head.column = head it.Col = it // head.left = last it.Left = &ret.Cols[size].Node // last.right = head ret.Cols[size].Right = &it.Node for i := 1; i < len(ret.Cols); i++ { curr := &ret.Cols[i] // curr index = i curr.Index = i // curr column = curr curr.Col = curr // curr up = curr curr.Up = &curr.Node // curr down = curr curr.Down = &curr.Node // curr left = prev curr.Left = &it.Node // prev.right = curr it.Right = &curr.Node // prev column = curr column it = curr } return ret } // AddRow adds a new row that contains multiple node associated with certain columns // colIndexes: associated column indexes (excluded head index 0) func (x *X) AddRow(colIndexes []int) { row := make([]Node, len(colIndexes)) for i, ci := range colIndexes { col := &x.Cols[ci] nd := &row[i] col.Size++ nd.Col = col nd.Row = &row[0] nd.Up = col.Up nd.Down = &col.Node nd.Left = &row[circularShiftLeft(i, len(colIndexes))] nd.Right = &row[circularShiftRight(i, len(colIndexes))] nd.Up.Down = nd nd.Down.Up = nd nd.Right.Left = nd nd.Left.Right = nd } } func circularShiftLeft(curr int, length int) int { left := curr - 1 if left < 0 { return length - 1 } return left } func circularShiftRight(curr int, length int) int { right := curr + 1 if right >= length { return 0 } return right } func cover(col *Column) { col.Right.Left = col.Left col.Left.Right = col.Right for i := col.Down; i != &col.Node; i = i.Down { for j := i.Right; j != i; j = j.Right { j.Down.Up = j.Up j.Up.Down = j.Down j.Col.Size-- } } } func uncover(col *Column) { for i := col.Up; i != &col.Node; i = i.Up { for j := i.Left; j != i; j = j.Left { j.Down.Up = j j.Up.Down = j j.Col.Size++ } } col.Right.Left = &col.Node col.Left.Right = &col.Node } // Search runs Algorithm X. // Search Passes solution through f() when a completed solution found, Algorithm X will continue for next solution if f() returns false. // Search ends normally, or the f() returns true. func (x *X) Search(f func(Solution) bool) bool { head := &x.Cols[0] hrc := head.Right.Col if hrc == head { // circular search completed, the solution cache in x.sol return f(x.Sol) } // find the column has minimum size, it improves overall performance by compare with linear iterator it := hrc min := it.Size for { hrc = hrc.Right.Col if hrc == head { break } if hrc.Size < min { it = hrc min = hrc.Size } } ret := false cover(it) x.Sol = append(x.Sol, nil) oLen := len(x.Sol) for j := it.Down; j != &it.Node; j = j.Down { if ret { break } x.Sol[oLen-1] = j for i := j.Right; i != j; i = i.Right { cover(i.Col) } ret = x.Search(f) j = x.Sol[oLen-1] it = j.Col for i := j.Left; i != j; i = i.Left { uncover(i.Col) } } x.Sol = x.Sol[:oLen-1] uncover(it) return ret }
dlx/dlx.go
0.633637
0.623291
dlx.go
starcoder
package katamari import ( "errors" "github.com/benitogf/katamari/key" ) // Apply filter function // type for functions will serve as filters // key: the key to filter // data: the data received or about to be sent // returns // data: to be stored or sent to the client // error: will prevent data to pass the filter type Apply func(key string, data []byte) ([]byte, error) // ApplyDelete callback function type ApplyDelete func(key string) error // Notify after a write is done type Notify func(key string) type hook struct { path string apply ApplyDelete } // Filter path -> match type filter struct { path string apply Apply } type watch struct { path string apply Notify } // Router group of filters type router []filter type hooks []hook type watchers []watch // Filters read and write type filters struct { Write router Read router Delete hooks After watchers } // DeleteFilter add a filter that runs before sending a read result func (app *Server) DeleteFilter(path string, apply ApplyDelete) { app.filters.Delete = append(app.filters.Delete, hook{ path: path, apply: apply, }) } // https://github.com/golang/go/issues/11862 // WriteFilter add a filter that triggers on write func (app *Server) WriteFilter(path string, apply Apply) { app.filters.Write = append(app.filters.Write, filter{ path: path, apply: apply, }) } // AfterFilter add a filter that triggers after a successful write func (app *Server) AfterFilter(path string, apply Notify) { app.filters.After = append(app.filters.After, watch{ path: path, apply: apply, }) } // ReadFilter add a filter that runs before sending a read result func (app *Server) ReadFilter(path string, apply Apply) { app.filters.Read = append(app.filters.Read, filter{ path: path, apply: apply, }) } // NoopHook open noop hook func NoopHook(index string) error { return nil } // NoopFilter open noop filter func NoopFilter(index string, data []byte) ([]byte, error) { return data, nil } // OpenFilter open noop read and write filters func (app *Server) OpenFilter(name string) { app.WriteFilter(name, NoopFilter) app.ReadFilter(name, NoopFilter) app.DeleteFilter(name, NoopHook) } func (r watchers) check(path string) { match := -1 for i, filter := range r { if filter.path == path || key.Match(filter.path, path) { match = i break } } if match == -1 { return } r[match].apply(path) } func (r hooks) check(path string, static bool) error { match := -1 for i, filter := range r { if filter.path == path || key.Match(filter.path, path) { match = i break } } if match == -1 && !static { return nil } if match == -1 && static { return errors.New("route not defined, static mode, key:" + path) } return r[match].apply(path) } func (r router) checkStatic(path string, static bool) error { match := -1 for i, filter := range r { if filter.path == path || key.Match(filter.path, path) { match = i break } } if match == -1 && !static { return nil } if match == -1 && static { return errors.New("route not defined, static mode, key:" + path) } return nil } func (r router) check(path string, data []byte, static bool) ([]byte, error) { match := -1 for i, filter := range r { if filter.path == path || key.Match(filter.path, path) { match = i break } } if match == -1 && !static { return data, nil } if match == -1 && static { return nil, errors.New("route not defined, static mode, key:" + path) } return r[match].apply(path, data) }
filters.go
0.663451
0.418043
filters.go
starcoder
package record import ( "unsafe" store_pb "github.com/genzai-io/sliced/proto/store" ) const maxItems = 256 // max items per node const nBits = 8 // 1, 2, 4, 8 - match nNodes with the correct nBits const nNodes = 256 // 2, 4, 16, 256 - match nNodes with the correct nBits type cellT struct { id store_pb.RecordID extra uint64 data unsafe.Pointer } type nodeT struct { branch bool items []cellT nodes []*nodeT } // RecordTree is a RecordID prefix tree type Tree struct { len int root *nodeT } // Insert inserts an item into the tree. Items are ordered by it's cell. // The extra param is a simple user context value. func (tr *Tree) Insert(cell store_pb.RecordID, data unsafe.Pointer, extra uint64) { if tr.root == nil { tr.root = new(nodeT) } tr.insert(tr.root, cell, data, extra, 128-nBits) tr.len++ } func (tr *Tree) insert(n *nodeT, cell store_pb.RecordID, data unsafe.Pointer, extra uint64, bits uint) { if !n.branch { if bits == 0 || len(n.items) < maxItems { i := tr.find(n, cell) n.items = append(n.items, cellT{}) copy(n.items[i+1:], n.items[i:len(n.items)-1]) n.items[i] = cellT{id: cell, extra: extra, data: data} return } tr.split(n, bits) tr.insert(n, cell, data, extra, bits) return } var i int if bits > 64 { i = int(cell.Epoch >> (128 - bits) & (nNodes - 1)) } else { i = int(cell.Seq >> (bits) & (nNodes - 1)) } for i >= len(n.nodes) { n.nodes = append(n.nodes, nil) } if n.nodes[i] == nil { n.nodes[i] = new(nodeT) } tr.insert(n.nodes[i], cell, data, extra, bits-nBits) } // Len returns the number of items in the tree. func (tr *Tree) Len() int { return tr.len } func (tr *Tree) split(n *nodeT, bits uint) { n.branch = true for i := 0; i < len(n.items); i++ { tr.insert(n, n.items[i].id, n.items[i].data, n.items[i].extra, bits) } n.items = nil } func (tr *Tree) find(n *nodeT, cell store_pb.RecordID) int { i, j := 0, len(n.items) for i < j { h := i + (j-i)/2 if !(IsLess(cell, n.items[h].id)) { i = h + 1 } else { j = h } } return i } // Remove removes an item from the tree based on it's cell and data values. func (tr *Tree) Remove(cell store_pb.RecordID, data unsafe.Pointer) { if tr.root == nil { return } if tr.remove(tr.root, cell, data, 128-nBits) { tr.len-- } } func (tr *Tree) remove(n *nodeT, cell store_pb.RecordID, data unsafe.Pointer, bits uint) bool { if !n.branch { i := tr.find(n, cell) - 1 for ; i >= 0; i-- { if n.items[i].id != cell { break } if n.items[i].data == data { n.items[i] = cellT{} copy(n.items[i:len(n.items)-1], n.items[i+1:]) n.items = n.items[:len(n.items)-1] return true } } return false } var i int if bits > 64 { i = int(cell.Epoch >> (128 - bits) & (nNodes - 1)) } else { i = int(cell.Seq >> (bits) & (nNodes - 1)) } if i >= len(n.nodes) || n.nodes[i] == nil || !tr.remove(n.nodes[i], cell, data, bits-nBits) { return false } if !n.nodes[i].branch && len(n.nodes[i].items) == 0 { n.nodes[i] = nil for i := 0; i < len(n.nodes); i++ { if n.nodes[i] != nil { return true } } n.branch = false } return true } // Scan iterates over the entire tree. Return false from the iter function to stop. func (tr *Tree) Scan(iter func(cell store_pb.RecordID, data unsafe.Pointer, extra uint64) bool) { if tr.root == nil { return } tr.scan(tr.root, iter) } func (tr *Tree) scan(n *nodeT, iter func(cell store_pb.RecordID, data unsafe.Pointer, extra uint64) bool) bool { if !n.branch { for i := 0; i < len(n.items); i++ { if !iter(n.items[i].id, n.items[i].data, n.items[i].extra) { return false } } } else { for i := 0; i < len(n.nodes); i++ { if n.nodes[i] != nil { if !tr.scan(n.nodes[i], iter) { return false } } } } return true } // Range iterates over the three start with the cell param. func (tr *Tree) Range(cell store_pb.RecordID, iter func(cell store_pb.RecordID, key unsafe.Pointer, extra uint64) bool) { if tr.root == nil { return } tr._range(tr.root, cell, 128-nBits, iter) } func (tr *Tree) _range(n *nodeT, cell store_pb.RecordID, bits uint, iter func(cell store_pb.RecordID, data unsafe.Pointer, extra uint64) bool) (hit, ok bool) { if !n.branch { hit = true i := tr.find(n, cell) - 1 for ; i >= 0; i-- { if IsLess(n.items[i].id, cell) { break } } i++ for ; i < len(n.items); i++ { if !iter(n.items[i].id, n.items[i].data, n.items[i].extra) { return hit, false } } return hit, true } var i int if bits > 64 { i = int(cell.Epoch >> (128 - bits) & (nNodes - 1)) } else { i = int(cell.Seq >> (bits) & (nNodes - 1)) } if i >= len(n.nodes) || n.nodes[i] == nil { return hit, true } for ; i < len(n.nodes); i++ { if n.nodes[i] != nil { if hit { if !tr.scan(n.nodes[i], iter) { return hit, false } } else { hit, ok = tr._range(n.nodes[i], cell, bits-nBits, iter) if !ok { return hit, false } } } } return hit, true }
app/record/tree.go
0.557364
0.437763
tree.go
starcoder
package ydbsql import ( "context" ) // Compose returns a new Trace which has functional fields composed // both from t and x. func (t Trace) Compose(x Trace) (ret Trace) { switch { case t.OnDial == nil: ret.OnDial = x.OnDial case x.OnDial == nil: ret.OnDial = t.OnDial default: h1 := t.OnDial h2 := x.OnDial ret.OnDial = func(d DialStartInfo) func(DialDoneInfo) { r1 := h1(d) r2 := h2(d) switch { case r1 == nil: return r2 case r2 == nil: return r1 default: return func(d DialDoneInfo) { r1(d) r2(d) } } } } return ret } type traceContextKey struct{} // WithTrace returns context which has associated Trace with it. func WithTrace(ctx context.Context, t Trace) context.Context { return context.WithValue(ctx, traceContextKey{}, ContextTrace(ctx).Compose(t), ) } // ContextTrace returns Trace associated with ctx. // If there is no Trace associated with ctx then zero value // of Trace is returned. func ContextTrace(ctx context.Context) Trace { t, _ := ctx.Value(traceContextKey{}).(Trace) return t } func (t Trace) onDial(ctx context.Context, d DialStartInfo) func(DialDoneInfo) { c := ContextTrace(ctx) var fn func(DialStartInfo) func(DialDoneInfo) switch { case t.OnDial == nil: fn = c.OnDial case c.OnDial == nil: fn = t.OnDial default: h1 := t.OnDial h2 := c.OnDial fn = func(d DialStartInfo) func(DialDoneInfo) { r1 := h1(d) r2 := h2(d) switch { case r1 == nil: return r2 case r2 == nil: return r1 default: return func(d DialDoneInfo) { r1(d) r2(d) } } } } if fn == nil { return func(DialDoneInfo) { return } } res := fn(d) if res == nil { return func(DialDoneInfo) { return } } return res } func traceOnDial(ctx context.Context, t Trace, c context.Context) func(context.Context, error) { var p DialStartInfo p.Context = c res := t.onDial(ctx, p) return func(c context.Context, e error) { var p DialDoneInfo p.Context = c p.Error = e res(p) } }
ydbsql/trace_gtrace.go
0.605333
0.432782
trace_gtrace.go
starcoder
package pending_review import "time" // Review contains teh essentials of a submission type Review struct { ReviewerName string SubmittedAt time.Time HTMLURL string } // Reviews summarizes all the reviews of a given pull request type Reviews struct { Count int // Total number of comments, requested changes, and approvals ValidApprovals int // Counted by head commit approvals from official community reviewers and the Conan team TeamApproval bool // At least one approval from the Conan team Approvals []string // List of users who have approved the pull request on the head commit Blockers []string // List of Conan team members who have requested changes on the head commit LastReview *Review `json:",omitempty"` // Snapshot of the last review } // IsApproved when the conditions for merging are meet as per https://github.com/conan-io/conan-center-index/blob/master/docs/review_process.md func (r *Reviews) IsApproved() bool { return r.TeamApproval && r.ValidApprovals >= 3 && len(r.Blockers) == 0 } // ProcessReviewComments interprets the all the reviews to extract a summary based on the requirements of CCI func ProcessReviewComments(reviews []*PullRequestReview, sha string) Reviews { summary := Reviews{ Count: len(reviews), TeamApproval: false, } if len := len(reviews); len > 0 { lastReview := reviews[len-1] summary.LastReview = &Review{ ReviewerName: lastReview.GetUser().GetLogin(), SubmittedAt: lastReview.GetSubmittedAt(), HTMLURL: lastReview.GetHTMLURL(), } } for _, review := range reviews { onBranchHead := sha == review.GetCommitID() reviewerName := review.GetUser().GetLogin() isTeamMember := isTeamMember(reviewerName) isMember := isTeamMember || isCommunityMember(reviewerName) switch review.GetState() { // Either as indicated by the reviewer or by updates from the GitHub API case "CHANGES_REQUESTED": if isTeamMember { summary.Blockers, _ = appendUnique(summary.Blockers, reviewerName) } removed := false summary.Approvals, removed = removeUnique(summary.Approvals, reviewerName) if removed && isMember { // If a reviewer retracted their reivew, the count needs to be adjusted summary.ValidApprovals = summary.ValidApprovals - 1 } case "APPROVED": summary.Blockers, _ = removeUnique(summary.Blockers, reviewerName) if !onBranchHead { break // If the approval is on anything other than the HEAD it's not counted by @conan-center-bot } new := false summary.Approvals, new = appendUnique(summary.Approvals, reviewerName) if !new { // Duplicate review (usually an accident) break } if isTeamMember { summary.TeamApproval = true } if isMember { summary.ValidApprovals = summary.ValidApprovals + 1 } case "DISMISSED": summary.Blockers, _ = removeUnique(summary.Blockers, reviewerName) case "COMMENTED": // Out-dated Approvals are transformed into comments https://github.com/conan-io/conan-center-index/pull/3855#issuecomment-770120073 // TODO: Figure out how GitHub knows what they were! default: } } return summary } func isTeamMember(reviewerName string) bool { switch reviewerName { // As defined by https://github.com/conan-io/conan-center-index/blob/master/docs/review_process.md#official-reviewers case "memsharded", "lasote", "danimtb", "jgsogo", "czoido", "solvingj", "SSE4", "uilianries": return true default: return false } } func isCommunityMember(reviewerName string) bool { switch reviewerName { // As defined by https://github.com/conan-io/conan-center-index/issues/2857 // and https://github.com/conan-io/conan-center-index/blob/master/docs/review_process.md#community-reviewers case "madebr", "SpaceIm", "ericLemanissier", "prince-chrismc", "Croydon", "intelligide", "theirix", "gocarlos", "mathbunnyru", "ericriff": return true default: return false } } func appendUnique(slice []string, elem string) ([]string, bool) { for _, e := range slice { if e == elem { return slice, false } } return append(slice, elem), true } func removeUnique(slice []string, elem string) ([]string, bool) { for i, e := range slice { if e == elem { return append(slice[:i], slice[i+1:]...), true } } return slice, false }
pkg/pending_review/review.go
0.530723
0.472014
review.go
starcoder
package dateparse import ( "strings" "time" ) var ( sunday = `воскресенье|sunday` monday = `понедельник|monday` tuesday = `вторник|tuesday` wednesday = `среду|среда|wednesday` thursday = `четверг|thursday` friday = `пятницу|пятница|friday` saturday = `субботу|суббота|saturday` weeks = strings.Join([]string{ sunday, monday, tuesday, wednesday, thursday, friday, saturday, }, "|") ) var ( shortSunday = `вс|воскр|sun` shortMonday = `пн|пнд|понед|mon` shortTuesday = `вт|thu` shortWednesday = `ср|wed` shortThursday = `чт|thu` shortFriday = `пт|fri` shortSaturday = `сб|sat` shortWeeks = strings.Join([]string{ shortSunday, shortMonday, shortTuesday, shortWednesday, shortThursday, shortFriday, shortSaturday, }, "|") ) func parseWeekDay(s string, opts Opts) time.Time { date := getDate(opts.Now.Year(), opts.Now.Month(), opts.Now.Day(), opts.TodayEndHour, 0, 0, opts) if weakDay := parseWeekDays(s); weakDay < 7 { v := weakDay - int(date.Weekday()) if v < 0 { date = date.Add(time.Duration(v)*24*time.Hour + 7*24*time.Hour) } else { date = date.Add(time.Duration(v) * 24 * time.Hour) } } return date } func parseWeekDays(s string) int { switch { case strings.Contains(strings.Join([]string{sunday, shortSunday}, "|"), s): return 0 case strings.Contains(strings.Join([]string{monday, shortMonday}, "|"), s): return 1 case strings.Contains(strings.Join([]string{tuesday, shortTuesday}, "|"), s): return 2 case strings.Contains(strings.Join([]string{wednesday, shortWednesday}, "|"), s): return 3 case strings.Contains(strings.Join([]string{thursday, shortThursday}, "|"), s): return 4 case strings.Contains(strings.Join([]string{friday, shortFriday}, "|"), s): return 5 case strings.Contains(strings.Join([]string{saturday, shortSaturday}, "|"), s): return 6 } return 7 } func calculateWeekDuration(m []string, opts Opts, weekPosition int) (time.Time, string) { timePosition := weekPosition + 1 if weekPosition < 0 { weekPosition = len(m) - 1 timePosition = weekPosition - 2 } date := parseWeekDay(m[weekPosition], opts) switch { case strings.Contains(durPrefix, m[weekPosition-1]): date = date.Add(24 * 7 * time.Hour) } if len(m) > 3 { switch { case strings.Contains(morning, m[timePosition]) && m[timePosition] != "": if date.Weekday() == opts.Now.Weekday() && opts.Now.Hour() > 10 { date = date.Add(24 * 7 * time.Hour) } return getDate(date.Year(), date.Month(), date.Day(), 10, 0, 0, opts), m[0] case strings.Contains(evening, m[timePosition]) && m[timePosition] != "": return date, m[0] case strings.Contains(noon, m[timePosition]) && m[timePosition] != "": return getDate(date.Year(), date.Month(), date.Day(), 12, 0, 0, opts), m[0] case strings.Contains(midnight, m[timePosition]) && m[timePosition] != "": return getDate(date.Year(), date.Month(), date.Day(), 0, 0, 0, opts), m[0] } } if date.Before(opts.Now) { date = date.Add(7 * 24 * time.Hour) } return date, m[0] }
week.go
0.523177
0.485844
week.go
starcoder
package lexer import ( "github.com/domterion/yapl/token" ) // A struct to represent and hold data for the Lexer type Lexer struct { input string position int // The current position in the input, a pointer to current char readPosition int // The current reading position in the input, current char + 1 ch byte // Current char being examined } // Instantiates a new lexer with the given input func New(input string) *Lexer { l := &Lexer{input: input} l.readChar() return l } // Reads the next char then advances the read position // If we reach the end of the input then it sets the current char to 0 or NUL indicating the EOF or we havent reached anything // If not then it sets the current char to the next char func (l *Lexer) readChar() { if l.readPosition >= len(l.input) { // 0 is the ASCII code for NUL l.ch = 0 } else { // Sets the current char to the char at the read position l.ch = l.input[l.readPosition] } l.position = l.readPosition l.readPosition += 1 } // Examines the current char and return a token that matches that char then we advance the char func (l *Lexer) NextToken() token.Token { var tok token.Token l.skipWhitespace() switch l.ch { case '=': // Lets look into the future to make sense of the code! if l.peekChar() == '=' { ch := l.ch l.readChar() tok = token.Token{Type: token.EQ, Literal: string(ch) + string(l.ch)} } else { tok = newToken(token.ASSIGN, l.ch) } case '+': tok = newToken(token.PLUS, l.ch) case '-': tok = newToken(token.MINUS, l.ch) case '!': // We can look into the future without going 88 MPH if l.peekChar() == '=' { ch := l.ch l.readChar() tok = token.Token{Type: token.NOT_EQ, Literal: string(ch) + string(l.ch)} } else { tok = newToken(token.BANG, l.ch) } case '/': tok = newToken(token.SLASH, l.ch) case '*': tok = newToken(token.ASTERISK, l.ch) case '<': tok = newToken(token.LT, l.ch) case '>': tok = newToken(token.GT, l.ch) case ';': tok = newToken(token.SEMICOLON, l.ch) case ',': tok = newToken(token.COMMA, l.ch) case '(': tok = newToken(token.LPAREN, l.ch) case ')': tok = newToken(token.RPAREN, l.ch) case '{': tok = newToken(token.LBRACE, l.ch) case '}': tok = newToken(token.RBRACE, l.ch) case 0: tok.Literal = "" tok.Type = token.EOF default: if isLetter(l.ch) { tok.Literal = l.readIdentifier() tok.Type = token.LookupIdent(tok.Literal) // Early returns because we already advanced the char above and dont need to do it again return tok } else if isDigit(l.ch) { tok.Type = token.INT tok.Literal = l.readNumber() // Same reason for early return as above return tok } else { // We dont know how to handle it therefore the char is illegal tok = newToken(token.ILLEGAL, l.ch) } } // Advance the char since we have no examined the current l.readChar() return tok } // Reads an identifier andd advances the lexers position till it finds a non number (!0-9) char func (l *Lexer) readNumber() string { position := l.position for isDigit(l.ch) { l.readChar() } return l.input[position:l.position] } // Reads an identifier and advances the lexers position till it finds a non letter char func (l *Lexer) readIdentifier() string { position := l.position for isLetter(l.ch) { l.readChar() } return l.input[position:l.position] } // This isnt Python, whitespace means nothing to us. func (l *Lexer) skipWhitespace() { for l.ch == ' ' || l.ch == '\t' || l.ch == '\n' || l.ch == '\r' { l.readChar() } } // A helper function to check if a char is a number or not func isDigit(ch byte) bool { return '0' <= ch && ch <= '9' } // A helper function to check if a char is a letter or not func isLetter(ch byte) bool { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' } // A helper function to help with token creation func newToken(tokenType token.TokenType, ch byte) token.Token { return token.Token{Type: tokenType, Literal: string(ch)} } // A helper function that peeks at the next char without advancing position func (l *Lexer) peekChar() byte { if l.readPosition >= len(l.input) { return 0 } else { return l.input[l.readPosition] } }
lexer/lexer.go
0.627267
0.416975
lexer.go
starcoder
package yacht // funcMap maps categories to functions which calculate results for a given category. // interface type is used since the different functions have different signatures. var funcMap = map[string]interface{}{ "Ones": nOfNumber, "Twos": nOfNumber, "Threes": nOfNumber, "Fours": nOfNumber, "Fives": nOfNumber, "Sixes": nOfNumber, "Full House": fullHouse, "Four of a Kind": fourOfAKind, "Little Straight": straight, "Big Straight": straight, "Choice": choice, "Yacht": yacht, } // get the counts for each of the thrown values func getCounts(dice []int) map[int]int { counts := make(map[int]int) for _, v := range dice { counts[v]++ } return counts } // calculate score for selected number n func nOfNumber(n int, dice []int) (score int) { for _, v := range dice { if v == n { score += n } } return score } // calculate score for "full house" func fullHouse(dice []int) (score int) { for v, n := range getCounts(dice) { if n < 2 || 3 < n { return 0 } score += n * v } return score } // calculate score for "4 of a kind" func fourOfAKind(dice []int) (score int) { for v, n := range getCounts(dice) { if n >= 4 { score = 4 * v } } return score } // calculate score for straigt, set "start" to 1 for a little straigt func straight(dice []int, start int) (score int) { if len(getCounts(dice)) != 5 { return 0 } min, max := dice[0], dice[0] for i := 0; i < len(dice); i++ { if dice[i] < min { min = dice[i] } if dice[i] > max { max = dice[i] } } if min == start && max-min == 4 { return 30 } return 0 } // just count all numbers func choice(dice []int) (score int) { for _, v := range dice { score += v } return score } // yacht: all numbers equal give score 50 func yacht(dice []int) int { v := dice[0] for i := 0; i < len(dice); i++ { if dice[i] != v { return 0 } } return 50 } // Score returns results for a throw of dice func Score(dice []int, category string) (score int) { switch category { case "ones": score = funcMap["Ones"].(func(int, []int) int)(1, dice) case "twos": score = funcMap["Twos"].(func(int, []int) int)(2, dice) case "threes": score = funcMap["Threes"].(func(int, []int) int)(3, dice) case "fours": score = funcMap["Fours"].(func(int, []int) int)(4, dice) case "fives": score = funcMap["Fives"].(func(int, []int) int)(5, dice) case "sixes": score = funcMap["Sixes"].(func(int, []int) int)(6, dice) case "full house": score = funcMap["Full House"].(func([]int) int)(dice) case "four of a kind": score = funcMap["Four of a Kind"].(func([]int) int)(dice) case "little straight": score = funcMap["Little Straight"].(func([]int, int) int)(dice, 1) case "big straight": score = funcMap["Big Straight"].(func([]int, int) int)(dice, 2) case "choice": score = funcMap["Choice"].(func([]int) int)(dice) case "yacht": score = funcMap["Yacht"].(func([]int) int)(dice) default: score = 0 } return score }
yacht/yacht.go
0.638948
0.495056
yacht.go
starcoder
package main import ( "fmt" "math" "sort" ) func sumAgg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } sum := 0.0 for _, v := range vs { sum += v } return sum, nil } func avgAgg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } sum := 0.0 for _, v := range vs { sum += v } return sum / float64(len(vs)), nil } func maxAgg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } max := math.Inf(-1) for _, v := range vs { if v > max { max = v } } return max, nil } func minAgg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } min := math.Inf(1) for _, v := range vs { if v < min { min = v } } return min, nil } func medianAgg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } return quantile(vs, 0.5), nil } func q95Agg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } return quantile(vs, 0.95), nil } func q99Agg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } return quantile(vs, 0.99), nil } func q999Agg(metrics []*float64) (float64, error) { vs := removeNulls(metrics) if len(vs) == 0 { return 0, fmt.Errorf("only null values returned") } return quantile(vs, 0.999), nil } func nullcntAgg(metrics []*float64) (float64, error) { cnt := 0 for _, v := range metrics { if v == nil { cnt++ } } return float64(cnt), nil } func nullpctAgg(metrics []*float64) (float64, error) { cnt := 0 for _, v := range metrics { if v == nil { cnt++ } } return float64(cnt) / float64(len(metrics)), nil } func flattenMetrics(ms metrics) []*float64 { size := 0 for _, m := range ms { size += len(m.Datapoints) } vals := make([]*float64, 0, size) for _, m := range ms { for _, d := range m.Datapoints { vals = append(vals, d.Value) } } return vals } func removeNulls(vs []*float64) []float64 { xs := make([]float64, 0, len(vs)) for _, v := range vs { if v != nil { xs = append(xs, *v) } } return xs } func quantile(vs []float64, q float64) float64 { sort.Float64s(vs) return vs[int(float64(len(vs))*q)] }
aggregations.go
0.619701
0.431944
aggregations.go
starcoder
package copypasta import ( "bytes" "math" "regexp" "sort" "strconv" "strings" ) /* 其他无法分类的算法 三维 n 皇后 https://oeis.org/A068940 Maximal number of chess queens that can be placed on a 3-dimensional chessboard of order n so that no two queens attack each other Smallest positive integer k such that n = +-1+-2+-...+-k for some choice of +'s and -'s https://oeis.org/A140358 相关题目 https://codeforces.com/problemset/problem/1278/B Numbers n such that n is the substring identical to the least significant bits of its base 2 representation. https://oeis.org/A181891 https://oeis.org/A181929 前缀 https://oeis.org/A038102 子串 Maximal number of regions obtained by joining n points around a circle by straight lines. Also number of regions in 4-space formed by n-1 hyperplanes. a(n) = n*(n-1)*(n*n-5*n+18)/24+1 https://oeis.org/A000127 https://oeis.org/A001069 Log2*(n) (version 2): take log_2 of n this many times to get a number < 2 https://oeis.org/A211667 Number of iterations sqrt(sqrt(sqrt(...(n)...))) such that the result is < 2 a(n) = 1, 2, 3, 4, 5, ... for n = 2^1, 2^2, 2^4, 2^8, 2^16, ..., i.e., n = 2, 4, 16, 256, 65536, ... = https://oeis.org/A001146 https://oeis.org/A002024 n appears n times; a(n) = floor(sqrt(2n) + 1/2) https://www.zhihu.com/question/25045244 找规律 https://codeforces.com/problemset/problem/1034/B 长度为 n 的所有二进制串,最多能划分出的 11 的个数之和 https://oeis.org/A045883 相关题目 https://codeforces.com/contest/1511/problem/E 4 汉诺塔 http://oeis.org/A007664 Reve's puzzle: number of moves needed to solve the Towers of Hanoi puzzle with 4 pegs and n disks, according to the Frame-Stewart algorithm https://www.acwing.com/problem/content/description/98/ 麻将 2021·昆明 https://ac.nowcoder.com/acm/contest/12548/K */ func miscCollection() { // debug 用 toArray := func(a []int) (res [100]int) { for i, v := range a { res[i] = v } return } // 预处理 log 的整数部分 logInit := func() { const mx int = 1e6 log := [mx + 1]int{} // log[0] 未定义,请勿访问 for i := 2; i <= mx; i++ { log[i] = log[i>>1] + 1 } } // 找环 // 1<=next[i]<=n // 相关题目 https://atcoder.jp/contests/abc167/tasks/abc167_d // EXTRA: 周期追逐 https://codeforces.com/problemset/problem/547/A getCycle := func(next []int, n, st int) (beforeCycle, cycle []int) { vis := make([]int8, n+1) for v := st; vis[v] < 2; v = next[v] { if vis[v] == 1 { cycle = append(cycle, v) } vis[v]++ } for v := st; vis[v] == 1; v = next[v] { beforeCycle = append(beforeCycle, v) } return } // max record pos // 相关题目(这也是一道好题)https://codeforces.com/problemset/problem/1381/B recordPos := func(a []int) []int { pos := []int{0} for i, v := range a { if v > a[pos[len(pos)-1]] { pos = append(pos, i) } } //pos = append(pos, len(a)) return pos } // 小结论:把 n 用 m 等分,得到 m-n%m 个 n/m 和 n%m 个 n/m+1 // 相关题目 https://codeforces.com/problemset/problem/663/A partition := func(n, m int) (q, cntQ, cntQ1 int) { // m must > 0 return n / m, m - n%m, n % m } // 用堆求前 k 小 smallK := func(a []int, k int) []int { k++ q := hp{} // 最大堆 for _, v := range a { if q.Len() < k || v < q.IntSlice[0] { q.push(v) } if q.Len() > k { q.pop() // 不断弹出更大的元素,留下的就是较小的 } } return q.IntSlice // 注意返回的不是有序数组 } // floatStr must contain a . // all decimal part must have same length // floatToInt("3.000100", 1e6) => 3000100 // "3.0001" is not allowed floatToInt := func(floatStr string, shift10 int) int { splits := strings.SplitN(floatStr, ".", 2) i, _ := strconv.Atoi(splits[0]) d, _ := strconv.Atoi(splits[1]) return i*shift10 + d } // floatToRat("1.2", 1e1) => (6, 5) // https://www.luogu.com.cn/problem/UVA10555 floatToRat := func(floatStr string, shift10 int) (m, n int) { m = floatToInt(floatStr, shift10) n = shift10 var g int // g := gcd(m, n) m /= g n /= g return } isInt := func(x float64) bool { const eps = 1e-8 return math.Abs(x-math.Round(x)) < eps } // 适用于需要频繁读取 a 中元素到一个 map 中的情况 // 调用 quickHashMapRead(a) 后 // 原来的类似 cnt[a[i]]++ 的操作,可以让 cnt 由 map[int]int 改为 make([]int, len(rk)) // 若需要访问 a[i] 原有元素,可以访问 origin[a[i]] // 这样后续操作就与 map 无关了 quickHashMapRead := func(a []int) ([]int, int) { origin := make([]int, len(a)) rk := map[int]int{} for i, v := range a { if _, has := rk[v]; !has { rk[v] = len(rk) origin[rk[v]] = v } a[i] = rk[v] } return origin, len(rk) } // 括号拼接 // 代码来源 https://codeforces.com/gym/101341/problem/A // 类似题目 https://atcoder.jp/contests/abc167/tasks/abc167_f // https://codeforces.com/problemset/problem/1203/F1 concatBrackets := func(ss [][]byte) (ids []int) { type pair struct{ x, y, i int } d := 0 var ls, rs []pair for i, s := range ss { l, r := 0, 0 for _, b := range s { if b == '(' { l++ } else if l > 0 { l-- } else { r++ } } if r < l { ls = append(ls, pair{r, l, i}) } else { rs = append(rs, pair{l, r, i}) } d += l - r } sort.Slice(ls, func(i, j int) bool { return ls[i].x < ls[j].x }) sort.Slice(rs, func(i, j int) bool { return rs[i].x < rs[j].x }) f := func(ps []pair) []int { _ids := []int{} s := 0 for _, p := range ps { if s < p.x { return nil } s += p.y - p.x _ids = append(_ids, p.i) } return _ids } idsL := f(ls) idsR := f(rs) if d != 0 || idsL == nil || idsR == nil { return } for _, id := range idsL { ids = append(ids, id) } for i := len(idsR) - 1; i >= 0; i-- { ids = append(ids, idsR[i]) } return } sliceToStr := func(a []int) []byte { b := bytes.Buffer{} b.WriteByte('{') for i, v := range a { if i > 0 { b.WriteByte(',') } b.WriteString(strconv.Itoa(v)) } b.WriteString("}\n") return b.Bytes() } getMapRangeValues := func(m map[int]int, l, r int) (a []int) { for i := l; i <= r; i++ { v, ok := m[i] if !ok { v = -1 } a = append(a, v) } return } // 螺旋矩阵 Spiral Matrix // https://ac.nowcoder.com/acm/contest/6489/C // 另:只考虑枚举顺序 LC54 https://leetcode-cn.com/problems/spiral-matrix/ genSpiralMatrix := func(n, m int) [][]int { mat := make([][]int, n) for i := range mat { mat[i] = make([]int, m) for j := range mat[i] { // 如果从 1 开始这里可以不要,下面的 != -1 改成 > 0 mat[i][j] = -1 } } type pair struct{ x, y int } dir4 := [4]pair{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} // 右下左上 x, y, di := 0, 0, 0 //pos := make([]pair, n*m+1) for i := 0; i < n*m; i++ { // 从 0 到 n*m-1 mat[x][y] = i //pos[i] = pair{x, y} d := dir4[di&3] if xx, yy := x+d.x, y+d.y; xx < 0 || xx >= n || yy < 0 || yy >= m || mat[xx][yy] != -1 { di++ } d = dir4[di&3] x += d.x y += d.y } return mat } // 01 矩阵,每个 1 位置向四个方向延伸连续 1 的最远距离 // https://codingcompetitions.withgoogle.com/kickstart/round/0000000000436140/000000000068c509 max1dir4 := func(a [][]int) (ls, rs, us, ds [][]int) { n, m := len(a), len(a[0]) ls, rs = make([][]int, n), make([][]int, n) for i, row := range a { ls[i] = make([]int, m) for j, v := range row { if v == 0 { continue } if j == 0 || row[j-1] == 0 { ls[i][j] = j } else { ls[i][j] = ls[i][j-1] } } rs[i] = make([]int, m) for j := m - 1; j >= 0; j-- { if row[j] == 0 { continue } if j == m-1 || row[j+1] == 0 { rs[i][j] = j } else { rs[i][j] = rs[i][j+1] } } } us, ds = make([][]int, n), make([][]int, n) for i := range us { us[i] = make([]int, m) ds[i] = make([]int, m) } for j := 0; j < m; j++ { for i, row := range a { if row[j] == 0 { continue } if i == 0 || a[i-1][j] == 0 { us[i][j] = i } else { us[i][j] = us[i-1][j] } } for i := n - 1; i >= 0; i-- { if a[i][j] == 0 { continue } if i == n-1 || a[i+1][j] == 0 { ds[i][j] = i } else { ds[i][j] = ds[i+1][j] } } } return } // a 是环形,合并相邻元素 (v,w) 的时候删除 w,在 a 上不断循环合并直至没有可以合并的相邻元素 // 相关题目 https://codeforces.com/problemset/problem/1483/B loopMergeOnRing := func(a []int, canMerge func(v, w int) bool) []int { n := len(a) r := make([]int, n) for i := 0; i < n-1; i++ { r[i] = i + 1 } ans := []int{} q := []int{} for i, v := range a { if canMerge(v, a[r[i]]) { q = append(q, i) } } del := make([]bool, n) for len(q) > 0 { i := q[0] q = q[1:] if del[i] { continue } if !del[r[i]] { ans = append(ans, r[i]) // +1 del[r[i]] = true } r[i] = r[r[i]] if canMerge(a[i], a[r[i]]) { q = append(q, i) } } return ans } // 最小栈,支持动态 push pop,查询栈中最小元素 // 思路是用另一个栈,同步 push pop,处理 push 时压入 min(当前元素,栈顶元素),注意栈为空的时候直接压入元素 // https://ac.nowcoder.com/acm/contest/1055/A // https://blog.nowcoder.net/n/ceb3214b89594af481ef9b794c75a929 _ = []interface{}{ toArray, logInit, getCycle, recordPos, partition, smallK, floatToRat, isInt, quickHashMapRead, concatBrackets, sliceToStr, getMapRangeValues, genSpiralMatrix, max1dir4, loopMergeOnRing, } } // b 是 a 的一个排列(允许有重复元素) // 返回 b 中各个元素在 a 中的下标(重复的元素顺序保持一致) // 可用于求从 a 变到 b 需要的相邻位元素交换的最小次数,即返回结果的逆序对个数 // LC周赛239C https://leetcode-cn.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/ func mapPos(a, b []int) []int { pos := map[int][]int{} for i, v := range a { pos[v] = append(pos[v], i) } ids := make([]int, len(b)) for i, v := range b { ids[i] = pos[v][0] pos[v] = pos[v][1:] } return ids } // 逆序对 // LC 面试题 51 https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/ // EXTRA: LC 327 https://leetcode-cn.com/problems/count-of-range-sum/ // LC 493 https://leetcode-cn.com/problems/reverse-pairs/ // 一张关于归并排序的好图 https://www.cnblogs.com/chengxiao/p/6194356.html func mergeCount(a []int) int64 { n := len(a) if n <= 1 { return 0 } left := append([]int(nil), a[:n/2]...) right := append([]int(nil), a[n/2:]...) cnt := mergeCount(left) + mergeCount(right) l, r := 0, 0 for i := range a { // 归并排序的同时计算逆序对 if l < len(left) && (r == len(right) || left[l] <= right[r]) { a[i] = left[l] l++ } else { cnt += int64(n/2 - l) a[i] = right[r] r++ } } return cnt } // 状压 N 皇后 // LC51 https://leetcode-cn.com/problems/n-queens/ // LC52 https://leetcode-cn.com/problems/n-queens-ii/ func totalNQueens(n int) (ans int) { var f func(row, columns, diagonals1, diagonals2 int) f = func(row, columns, diagonals1, diagonals2 int) { if row == 1 { ans++ return } availablePositions := (1<<n - 1) &^ (columns | diagonals1 | diagonals2) for availablePositions > 0 { position := availablePositions & -availablePositions f(row+1, columns|position, (diagonals1|position)<<1, (diagonals2|position)>>1) availablePositions &^= position // 移除该比特位 } } f(0, 0, 0, 0) return } // 格雷码 https://oeis.org/A003188 https://oeis.org/A014550 // https://en.wikipedia.org/wiki/Gray_code // LC89 https://leetcode-cn.com/problems/gray-code/ // 转换 https://codeforces.com/problemset/problem/1419/E func grayCode(length int) []int { ans := make([]int, 1<<length) for i := range ans { ans[i] = i ^ i>>1 } return ans } // 输入两个无重复元素的序列,返回通过交换相邻元素,从 a 到 b 所需的最小交换次数 // 保证 a b 包含相同的元素 func countSwap(a, b []int) int { // 可能要事先 copy 一份 a // 暴力法 ans := 0 for _, tar := range b { for i, v := range a { if v == tar { ans += i a = append(a[:i], a[i+1:]...) break } } } return ans } // 输入一个仅包含 () 的括号串,返回右括号个数不少于左括号个数的非空子串个数 func countValidSubstring(s string) (ans int) { cnt := map[int]int{0: 1} leSum := 1 // less equal than v v := 0 for _, b := range s { if b == '(' { leSum -= cnt[v] v-- } else { v++ leSum += cnt[v] } ans += leSum cnt[v]++ leSum++ } return } // 负二进制数相加 // LC1073/周赛139C https://leetcode-cn.com/problems/adding-two-negabinary-numbers/ https://leetcode-cn.com/contest/weekly-contest-139/ func addNegabinary(a1, a2 []int) []int { if len(a1) < len(a2) { a1, a2 = a2, a1 } for i, j := len(a1)-1, len(a2)-1; j >= 0; { a1[i] += a2[j] i-- j-- } ans := append(make([]int, 2), a1...) for i := len(ans) - 1; i >= 0; i-- { if ans[i] >= 2 { ans[i] -= 2 if ans[i-1] >= 1 { ans[i-1]-- } else { ans[i-1]++ ans[i-2]++ } } } for i, v := range ans { if v != 0 { return ans[i:] } } return []int{0} } // 负二进制转换 // LC1017/周赛130B https://leetcode-cn.com/problems/convert-to-base-2/ https://leetcode-cn.com/contest/weekly-contest-130/ func toNegabinary(n int) (res string) { if n == 0 { return "0" } for ; n != 0; n = -(n >> 1) { res = string(byte('0'+n&1)) + res } return } // 分数转小数 // https://en.wikipedia.org/wiki/Repeating_decimal // Period of decimal representation of 1/n, or 0 if 1/n terminates https://oeis.org/A051626 // The periodic part of the decimal expansion of 1/n https://oeis.org/A036275 // 例如 (2, -3) => ("-0.", "6") // b must not be zero // LC166 https://leetcode-cn.com/problems/fraction-to-recurring-decimal/ // WF1990 https://www.luogu.com.cn/problem/UVA202 func fractionToDecimal(a, b int64) (beforeCycle, cycle []byte) { if a == 0 { return []byte{'0'}, nil } var res []byte if a < 0 && b > 0 || a > 0 && b < 0 { res = []byte{'-'} } if a < 0 { a = -a } if b < 0 { b = -b } res = append(res, strconv.FormatInt(a/b, 10)...) r := a % b if r == 0 { return res, nil } res = append(res, '.') posMap := map[int64]int{} for r != 0 { if pos, ok := posMap[r]; ok { return res[:pos], res[pos:] } posMap[r] = len(res) r *= 10 res = append(res, '0'+byte(r/b)) r %= b } return res, nil } // 小数转分数 // decimal like "2.15(376)", which means "2.15376376376..." // https://zh.wikipedia.org/wiki/%E5%BE%AA%E7%8E%AF%E5%B0%8F%E6%95%B0#%E5%8C%96%E7%82%BA%E5%88%86%E6%95%B8%E7%9A%84%E6%96%B9%E6%B3%95 func decimalToFraction(decimal string) (a, b int64) { r := regexp.MustCompile(`(?P<integerPart>\d+)\.?(?P<nonRepeatingPart>\d*)\(?(?P<repeatingPart>\d*)\)?`) match := r.FindStringSubmatch(decimal) integerPart, nonRepeatingPart, repeatingPart := match[1], match[2], match[3] intPartNum, _ := strconv.ParseInt(integerPart, 10, 64) if repeatingPart == "" { repeatingPart = "0" } b, _ = strconv.ParseInt(strings.Repeat("9", len(repeatingPart))+strings.Repeat("0", len(nonRepeatingPart)), 10, 64) a, _ = strconv.ParseInt(nonRepeatingPart+repeatingPart, 10, 64) if nonRepeatingPart != "" { v, _ := strconv.ParseInt(nonRepeatingPart, 10, 64) a -= v } a += intPartNum * b // 后续需要用 gcd 化简 // 或者用 return big.NewRat(a, b) return } // 表达式计算(无括号) // LC227 https://leetcode-cn.com/problems/basic-calculator-ii/ func calculate(s string) (ans int) { s = strings.ReplaceAll(s, " ", "") v, sign, stack := 0, '+', []int{} for i, b := range s { if '0' <= b && b <= '9' { v = v*10 + int(b-'0') if i+1 < len(s) { continue } } switch sign { case '+': stack = append(stack, v) case '-': stack = append(stack, -v) case '*': w := stack[len(stack)-1] stack = stack[:len(stack)-1] stack = append(stack, w*v) default: // '/' w := stack[len(stack)-1] stack = stack[:len(stack)-1] stack = append(stack, w/v) } v = 0 sign = b } for _, v := range stack { ans += v } return } // 倒序思想 // 来源自被删除的 C 题 https://ac.nowcoder.com/acm/contest/view-submission?submissionId=45798625 // 有一个大小为 n*m 的网格图,和一个长为 n*m 的目标位置列表,每个位置表示网格图中的一个格点且互不相同 // 网格图初始为空 // 按照此列表的顺序,一个士兵从网格图边缘的任意位置进入并到达目标位置,到达后该士兵停留在此格点,下一个士兵开始进入网格图 // 每个士兵会尽可能地避免经过有士兵的格点 // 输出每个士兵必须经过的士兵数之和 // n, m <= 500 // 思路: // 将问题转化成从最后一个士兵开始倒着退出网格 // 对于一个填满的网格图,每个士兵到边缘的最短路径就是离他最近的边缘的距离 // 当一个士兵退出网格后,BFS 地更新他周围的士兵到边缘的最短路径(空格点为 0,有人的格点为 1) // 复杂度 O((n+m)*min(n,m)^2) func minMustPassSum(n, m int, targetCells [][2]int) int { min := func(a, b int) int { if a < b { return a } return b } dis := make([][]int, n) filled := make([][]int, n) // 格子是否有人 inQ := make([][]bool, n) for i := range dis { dis[i] = make([]int, m) filled[i] = make([]int, m) for j := range dis[i] { dis[i][j] = min(min(i, n-1-i), min(j, m-1-j)) filled[i][j] = 1 } inQ[i] = make([]bool, m) } ans := 0 type pair struct{ x, y int } dir4 := []pair{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} for i := len(targetCells) - 1; i >= 0; i-- { p := targetCells[i] x, y := p[0], p[1] //x-- //y-- ans += dis[x][y] filled[x][y] = 0 q := []pair{{x, y}} for len(q) > 0 { p := q[0] q = q[1:] x, y := p.x, p.y inQ[x][y] = false for _, d := range dir4 { if xx, yy := x+d.x, y+d.y; 0 <= xx && xx < n && 0 <= yy && yy < m && dis[x][y]+filled[x][y] < dis[xx][yy] { dis[xx][yy] = dis[x][y] + filled[x][y] if !inQ[xx][yy] { inQ[xx][yy] = true q = append(q, pair{xx, yy}) } } } } } return ans } // 马走日从 (0,0) 到 (x,y) 所需最小步数 // LC1197/双周赛9B https://leetcode-cn.com/contest/biweekly-contest-9/problems/minimum-knight-moves/ func minKnightMoves(x, y int) int { abs := func(x int) int { if x < 0 { return -x } return x } max := func(a, b int) int { if a > b { return a } return b } x, y = abs(x), abs(y) if x+y == 1 { return 3 } ans := max(max((x+1)/2, (y+1)/2), (x+y+2)/3) ans += (ans ^ x ^ y) & 1 return ans } // 判断 6 个矩形是否为长方体的 6 个面 // NEERC04 https://www.luogu.com.cn/problem/UVA1587 func isCuboid(rect [][2]int) bool { for i, r := range rect { if r[0] > r[1] { rect[i] = [2]int{r[1], r[0]} } } sort.Slice(rect, func(i, j int) bool { a, b := rect[i], rect[j]; return a[0] < b[0] || a[0] == b[0] && a[1] < b[1] }) for i := 0; i < 6; i += 2 { if rect[i] != rect[i+1] { // NOTE: [2] return false } } y0, y2 := rect[0][1], rect[2][1] return rect[2][0] == rect[0][0] && (rect[4] == [2]int{y0, y2} || rect[4] == [2]int{y2, y0}) } // 约瑟夫问题 // 思路:用递推公式,自底向上计算 // https://zh.wikipedia.org/wiki/%E7%BA%A6%E7%91%9F%E5%A4%AB%E6%96%AF%E9%97%AE%E9%A2%98 // https://oi-wiki.org/misc/josephus/ 注意当 k 较小时,存在 O(klogn) 的做法 // 相关题目 https://leetcode-cn.com/problems/find-the-winner-of-the-circular-game/ // https://codeforces.com/gym/101955/problem/K func josephusProblem(n, k int) int { cur := 0 for i := 2; i <= n; i++ { cur = (cur + k) % i } return cur + 1 // 1-index } // 均分纸牌 https://www.luogu.com.cn/problem/P1031 // 环形 https://www.luogu.com.cn/problem/P2512 https://www.luogu.com.cn/problem/P4016 // 二维环形 https://www.acwing.com/problem/content/107/ func minMoveToAllSameInCircle(a []int) (ans int) { // int64 abs := func(x int) int { if x < 0 { return -x } return x } n := len(a) avg := 0 for _, v := range a { avg += v } if avg%n != 0 { return -1 } avg /= n sum := make([]int, n) sum[0] = a[0] - avg for i := 1; i < n; i++ { sum[i] = sum[i-1] + a[i] - avg } sort.Ints(sum) // 或者快速选择 mid := sum[n/2] for _, v := range sum { ans += abs(v - mid) } return }
copypasta/misc.go
0.644449
0.617801
misc.go
starcoder
package set import ( "sort" "github.com/juju/errors" "gopkg.in/juju/names.v2" ) // Tags represents the Set data structure, it implements tagSet // and contains names.Tags. type Tags map[names.Tag]bool // NewTags creates and initializes a Tags and populates it with // inital values as specified in the parameters. func NewTags(initial ...names.Tag) Tags { result := make(Tags) for _, value := range initial { result.Add(value) } return result } // NewTagsFromStrings creates and initializes a Tags and populates it // by using names.ParseTag on the initial values specified in the parameters. func NewTagsFromStrings(initial ...string) (Tags, error) { result := make(Tags) for _, value := range initial { tag, err := names.ParseTag(value) if err != nil { return result, errors.Trace(err) } result.Add(tag) } return result, nil } // Size returns the number of elements in the set. func (t Tags) Size() int { return len(t) } // IsEmpty is true for empty or uninitialized sets. func (t Tags) IsEmpty() bool { return len(t) == 0 } // Add puts a value into the set. func (t Tags) Add(value names.Tag) { if t == nil { panic("uninitalised set") } t[value] = true } // Remove takes a value out of the set. If value wasn't in the set to start // with, this method silently succeeds. func (t Tags) Remove(value names.Tag) { delete(t, value) } // Contains returns true if the value is in the set, and false otherwise. func (t Tags) Contains(value names.Tag) bool { _, exists := t[value] return exists } // Values returns an unordered slice containing all the values in the set. func (t Tags) Values() []names.Tag { result := make([]names.Tag, len(t)) i := 0 for key := range t { result[i] = key i++ } return result } // stringValues returns a list of strings that represent a names.Tag // Used internally by the SortedValues method. func (t Tags) stringValues() []string { result := make([]string, t.Size()) i := 0 for key := range t { result[i] = key.String() i++ } return result } // SortedValues returns an ordered slice containing all the values in the set. func (t Tags) SortedValues() []names.Tag { values := t.stringValues() sort.Strings(values) result := make([]names.Tag, len(values)) for i, value := range values { // We already know only good strings can live in the Tags set // so we can safely ignore the error here. tag, _ := names.ParseTag(value) result[i] = tag } return result } // Union returns a new Tags representing a union of the elments in the // method target and the parameter. func (t Tags) Union(other Tags) Tags { result := make(Tags) // Use the internal map rather than going through the friendlier functions // to avoid extra allocation of slices. for value := range t { result[value] = true } for value := range other { result[value] = true } return result } // Intersection returns a new Tags representing a intersection of the elments in the // method target and the parameter. func (t Tags) Intersection(other Tags) Tags { result := make(Tags) // Use the internal map rather than going through the friendlier functions // to avoid extra allocation of slices. for value := range t { if other.Contains(value) { result[value] = true } } return result } // Difference returns a new Tags representing all the values in the // target that are not in the parameter. func (t Tags) Difference(other Tags) Tags { result := make(Tags) // Use the internal map rather than going through the friendlier functions // to avoid extra allocation of slices. for value := range t { if !other.Contains(value) { result[value] = true } } return result }
vendor/github.com/juju/utils/set/tags.go
0.777849
0.542379
tags.go
starcoder
package core import ( "fmt" "hash/fnv" "strings" "github.com/raviqqe/hamt" ) // StringType represents a string in the language. type StringType string // Eval evaluates a value into a WHNF. func (s StringType) eval() Value { return s } // NewString creates a string in the language from one in Go. func NewString(s string) StringType { return StringType(s) } func (s StringType) assign(i, v Value) Value { n, err := checkIndex(i) if err != nil { return err } rs := []rune(string(s)) if int(n) > len(rs) { return OutOfRangeError() } s, err = EvalString(v) if err != nil { return err } cs := []rune(string(s)) if len(cs) != 1 { return ValueError("cannot assign non-character to string") } rs[int(n)-1] = cs[0] return StringType(rs) } func (s StringType) index(v Value) Value { n, err := checkIndex(v) if err != nil { return err } i := int(n) rs := []rune(string(s)) if i > len(rs) { return OutOfRangeError() } return NewString(string(rs[i-1 : i])) } func (s StringType) insert(v Value, t Value) Value { n, err := checkIndex(v) if err != nil { return err } i := int(n) - 1 if i > len(s) { return OutOfRangeError() } ss, err := EvalString(t) if err != nil { return err } return s[:i] + ss + s[i:] } func (s StringType) merge(vs ...Value) Value { vs = append([]Value{s}, vs...) for _, t := range vs { go EvalPure(t) } ss := make([]string, 0, len(vs)) for _, t := range vs { s, err := EvalString(t) if err != nil { return err } ss = append(ss, string(s)) } return NewString(strings.Join(ss, "")) } func (s StringType) delete(v Value) Value { n, err := checkIndex(v) i := int(n) - 1 if err != nil { return err } else if i >= len(s) { return OutOfRangeError() } return s[:i] + s[i+1:] } func (s StringType) toList() Value { if s == "" { return EmptyList } rs := []rune(string(s)) return cons( NewString(string(rs[0])), PApp(ToList, NewString(string(rs[1:])))) } func (s StringType) compare(c comparable) int { return strings.Compare(string(s), string(c.(StringType))) } func (StringType) ordered() {} func (s StringType) string() Value { return s } func (s StringType) quoted() Value { return NewString(fmt.Sprintf("%#v", string(s))) } func (s StringType) size() Value { return NewNumber(float64(len([]rune(string(s))))) } func (s StringType) include(v Value) Value { ss, ok := v.(StringType) if !ok { return NotStringError(v) } return NewBoolean(strings.Contains(string(s), string(ss))) } // Hash hashes a string. func (s StringType) Hash() uint32 { h := fnv.New32() if _, err := h.Write([]byte(string(s))); err != nil { panic(err) } return h.Sum32() } // Equal checks equality of strings. func (s StringType) Equal(e hamt.Entry) bool { if t, ok := e.(StringType); ok { return s == t } return false }
src/lib/core/string.go
0.704567
0.406862
string.go
starcoder
package exp type bitwise struct { lhs Expression rhs interface{} op BitwiseOperation } func NewBitwiseExpression(op BitwiseOperation, lhs Expression, rhs interface{}) BitwiseExpression { return bitwise{op: op, lhs: lhs, rhs: rhs} } func (b bitwise) Clone() Expression { return NewBitwiseExpression(b.op, b.lhs.Clone(), b.rhs) } func (b bitwise) RHS() interface{} { return b.rhs } func (b bitwise) LHS() Expression { return b.lhs } func (b bitwise) Op() BitwiseOperation { return b.op } func (b bitwise) Expression() Expression { return b } func (b bitwise) As(val interface{}) AliasedExpression { return NewAliasExpression(b, val) } func (b bitwise) Eq(val interface{}) BooleanExpression { return eq(b, val) } func (b bitwise) Neq(val interface{}) BooleanExpression { return neq(b, val) } func (b bitwise) Gt(val interface{}) BooleanExpression { return gt(b, val) } func (b bitwise) Gte(val interface{}) BooleanExpression { return gte(b, val) } func (b bitwise) Lt(val interface{}) BooleanExpression { return lt(b, val) } func (b bitwise) Lte(val interface{}) BooleanExpression { return lte(b, val) } func (b bitwise) Asc() OrderedExpression { return asc(b) } func (b bitwise) Desc() OrderedExpression { return desc(b) } func (b bitwise) Like(i interface{}) BooleanExpression { return like(b, i) } func (b bitwise) NotLike(i interface{}) BooleanExpression { return notLike(b, i) } func (b bitwise) ILike(i interface{}) BooleanExpression { return iLike(b, i) } func (b bitwise) NotILike(i interface{}) BooleanExpression { return notILike(b, i) } func (b bitwise) RegexpLike(val interface{}) BooleanExpression { return regexpLike(b, val) } func (b bitwise) RegexpNotLike(val interface{}) BooleanExpression { return regexpNotLike(b, val) } func (b bitwise) RegexpILike(val interface{}) BooleanExpression { return regexpILike(b, val) } func (b bitwise) RegexpNotILike(val interface{}) BooleanExpression { return regexpNotILike(b, val) } func (b bitwise) In(i ...interface{}) BooleanExpression { return in(b, i...) } func (b bitwise) NotIn(i ...interface{}) BooleanExpression { return notIn(b, i...) } func (b bitwise) Is(i interface{}) BooleanExpression { return is(b, i) } func (b bitwise) IsNot(i interface{}) BooleanExpression { return isNot(b, i) } func (b bitwise) IsNull() BooleanExpression { return is(b, nil) } func (b bitwise) IsNotNull() BooleanExpression { return isNot(b, nil) } func (b bitwise) IsTrue() BooleanExpression { return is(b, true) } func (b bitwise) IsNotTrue() BooleanExpression { return isNot(b, true) } func (b bitwise) IsFalse() BooleanExpression { return is(b, false) } func (b bitwise) IsNotFalse() BooleanExpression { return isNot(b, false) } func (b bitwise) Distinct() SQLFunctionExpression { return NewSQLFunctionExpression("DISTINCT", b) } func (b bitwise) Between(val RangeVal) RangeExpression { return between(b, val) } func (b bitwise) NotBetween(val RangeVal) RangeExpression { return notBetween(b, val) } // used internally to create a Bitwise Inversion BitwiseExpression func bitwiseInversion(rhs Expression) BitwiseExpression { return NewBitwiseExpression(BitwiseInversionOp, nil, rhs) } // used internally to create a Bitwise OR BitwiseExpression func bitwiseOr(lhs Expression, rhs interface{}) BitwiseExpression { return NewBitwiseExpression(BitwiseOrOp, lhs, rhs) } // used internally to create a Bitwise AND BitwiseExpression func bitwiseAnd(lhs Expression, rhs interface{}) BitwiseExpression { return NewBitwiseExpression(BitwiseAndOp, lhs, rhs) } // used internally to create a Bitwise XOR BitwiseExpression func bitwiseXor(lhs Expression, rhs interface{}) BitwiseExpression { return NewBitwiseExpression(BitwiseXorOp, lhs, rhs) } // used internally to create a Bitwise LEFT SHIFT BitwiseExpression func bitwiseLeftShift(lhs Expression, rhs interface{}) BitwiseExpression { return NewBitwiseExpression(BitwiseLeftShiftOp, lhs, rhs) } // used internally to create a Bitwise RIGHT SHIFT BitwiseExpression func bitwiseRightShift(lhs Expression, rhs interface{}) BitwiseExpression { return NewBitwiseExpression(BitwiseRightShiftOp, lhs, rhs) }
exp/bitwise.go
0.805938
0.420481
bitwise.go
starcoder
package reporting import ( "fmt" "sort" "strings" ) type Table struct { // title for the entire table title string // rows contains the captions for each row rows []string // rowWidth is the length of the longest row caption rowWidth int // cols contains the captions for each column cols []string // colWidths contains the width required for each column, indexed by caption colWidths map[string]int // cells is the content for each cell, arranged per row, then per column cells map[string]map[string]string } func NewTable(title string) *Table { return &Table{ title: title, cells: make(map[string]map[string]string), rowWidth: len(title), colWidths: make(map[string]int), } } // Rows returns a slice containing the captions of all the rows of the table // A new slice is returned to avoid violations of encapsulation func (t *Table) Rows() []string { var result []string result = append(result, t.rows...) return result } // AddRow adds the specified row to the table if it doesn't already exist func (t *Table) AddRow(row string) { if t.indexOfRow(row) == -1 { t.rows = append(t.rows, row) if len(row) > t.rowWidth { t.rowWidth = len(row) } } } // SortRows allows rows to be sorted by caption func (t *Table) SortRows(less func(top string, bottom string) bool) { sort.Slice(t.rows, func(i, j int) bool { return less(t.rows[i], t.rows[j]) }) } // Columns returns a slice containing the captions of all the columns of the table // A new slice is returned to avoid violations of encapsulation func (t *Table) Columns() []string { var result []string result = append(result, t.cols...) return result } // AddColumn adds the specified column to the table if it doesn't already exist func (t *Table) AddColumn(col string) { index := t.indexOfColumn(col) if index == -1 { t.cols = append(t.cols, col) t.colWidths[col] = len(col) } } // SortColumns allows columns to be sorted by caption func (t *Table) SortColumns(less func(left string, right string) bool) { sort.Slice(t.cols, func(i, j int) bool { return less(t.cols[i], t.cols[j]) }) } // SetCell sets the content of a given cell of the table func (t *Table) SetCell(row string, col string, cell string) { t.AddColumn(col) t.AddRow(row) rowCells := t.getRowCells(row) rowCells[col] = cell if len(cell) > t.colWidths[col] { t.colWidths[col] = len(cell) } } func (t *Table) WriteTo(buffer *strings.Builder) { buffer.WriteString(t.renderHeader()) buffer.WriteString(t.renderDivider()) for _, r := range t.rows { buffer.WriteString(t.renderRow(r)) } } func (t *Table) getRowCells(row string) map[string]string { if m, ok := t.cells[row]; ok { return m } result := make(map[string]string) t.cells[row] = result return result } func (t *Table) renderHeader() string { var result strings.Builder result.WriteString(fmt.Sprintf("| %*s |", -t.rowWidth, t.title)) for _, c := range t.cols { result.WriteString(fmt.Sprintf(" %*s |", -t.colWidths[c], c)) } result.WriteString("\n") return result.String() } func (t *Table) renderDivider() string { var result strings.Builder result.WriteString("|") for i := -2; i < t.rowWidth; i++ { result.WriteRune('-') } result.WriteRune('|') for _, c := range t.cols { width := t.colWidths[c] for i := -2; i < width; i++ { result.WriteRune('-') } result.WriteRune('|') } result.WriteString("\n") return result.String() } func (t *Table) renderRow(row string) string { var result strings.Builder cells := t.getRowCells(row) result.WriteString(fmt.Sprintf("| %*s |", -t.rowWidth, row)) for _, c := range t.cols { content := cells[c] result.WriteString(fmt.Sprintf(" %*s |", -t.colWidths[c], content)) } result.WriteString("\n") return result.String() } func (t *Table) indexOfRow(row string) int { for i, r := range t.rows { if r == row { return i } } return -1 } func (t *Table) indexOfColumn(col string) int { for i, c := range t.cols { if c == col { return i } } return -1 }
v2/tools/generator/internal/reporting/table.go
0.770983
0.563498
table.go
starcoder
package idmapper // Forked from https://github.com/plar/go-adaptive-radix-tree // Callback function type for tree traversal. type Callback func(key Key, value Value) error // RadixTree is an Adaptive Radix Tree implementation for our internal Mapper. type RadixTree struct { root *artNode size int } // NewRadixTree creates a new adaptive radix tree. func NewRadixTree() *RadixTree { return &RadixTree{} } // Insert inserts given key into the radix tree. // You can add duplicate keys, this radix tree is like a set. func (t *RadixTree) Insert(key Key, value Value) { ok := t.recursiveInsert(&t.root, key, value, 0) if ok { t.size++ } } // Size returns the number of keys stored in the tree. func (t *RadixTree) Size() int { if t == nil || t.root == nil { return 0 } return t.size } // MinimalLength computes the minimal key length that avoid collision if keys are shorten/compressed. func (t *RadixTree) MinimalLength(minimum int) int { if t == nil || t.root == nil { return minimum } v, ok := t.recursiveMinimalLength(t.root, 0) if ok && int(v) > minimum { return int(v) } return minimum } // ForEach executes the given callback once per leaf. // It returns the first error encountered from a callback, or continue otherwise. func (t *RadixTree) ForEach(callback Callback) error { return t.recursiveForEachCallback(t.root, callback) } // String returns an human friendly format of the adaptive radix tree. func (t *RadixTree) String() string { return debugNode(t.root) } func (t *RadixTree) recursiveMinimalLength(current *artNode, depth uint32) (uint32, bool) { if current == nil { return 0, false } switch current.kind { case radixLeaf: return depth, true case radixNode4: node := current.node4() nlist := node.children[:] ndepth := depth + node.prefixLen + 1 return t.forEachChildrenMinimalLength(nlist, ndepth) case radixNode16: node := current.node16() nlist := node.children[:] ndepth := depth + node.prefixLen + 1 return t.forEachChildrenMinimalLength(nlist, ndepth) case radixNode48: node := current.node48() nlist := node.children[:] ndepth := depth + node.prefixLen + 1 return t.forEachChildrenMinimalLength(nlist, ndepth) case radixNode256: node := current.node256() nlist := node.children[:] ndepth := depth + node.prefixLen + 1 return t.forEachChildrenMinimalLength(nlist, ndepth) default: return 0, false } } func (t *RadixTree) forEachChildrenMinimalLength(childrens []*artNode, depth uint32) (uint32, bool) { lengthVal := uint32(0) lengthOk := false for _, child := range childrens { if child != nil { val, ok := t.recursiveMinimalLength(child, depth) if ok && val > lengthVal { lengthVal = val lengthOk = ok } } } return lengthVal, lengthOk } func (t *RadixTree) recursiveForEachCallback(current *artNode, callback Callback) error { if current == nil { return nil } switch current.kind { case radixLeaf: node := current.leaf() return callback(node.key, node.value) case radixNode4: list := current.node4().children[:] return t.forEachChildrenCallback(list, callback) case radixNode16: list := current.node16().children[:] return t.forEachChildrenCallback(list, callback) case radixNode48: list := current.node48().children[:] return t.forEachChildrenCallback(list, callback) case radixNode256: list := current.node256().children[:] return t.forEachChildrenCallback(list, callback) default: return nil } } func (t *RadixTree) forEachChildrenCallback(childrens []*artNode, callback Callback) error { for _, child := range childrens { if child != nil { err := t.recursiveForEachCallback(child, callback) if err != nil { return err } } } return nil } func (t *RadixTree) recursiveInsert(curNode **artNode, key Key, value Value, depth uint32) bool { current := *curNode if current == nil { replaceRef(curNode, newLeaf(key, value)) return true } if current.isLeaf() { return t.recursiveInsertOnLeaf(curNode, current, key, value, depth) } node := current.node() if node.prefixLen == 0 { return t.recursiveInsertOnNextNode(curNode, current, key, value, depth) } return t.recursiveInsertOnCurrentNode(curNode, current, key, value, depth) } func (t *RadixTree) recursiveInsertOnLeaf(curNode **artNode, current *artNode, key Key, value Value, depth uint32) bool { leaf := current.leaf() if leaf.match(key) { return false } // new value, split the leaf into new node4 newLeaf := newLeaf(key, value) leaf2 := newLeaf.leaf() leafsLCP := t.longestCommonPrefix(leaf, leaf2, depth) newNode := newNode4() newNode.setPrefix(key[depth:], leafsLCP) depth += leafsLCP newNode.addChild(leaf.key.charAt(int(depth)), leaf.key.valid(int(depth)), current) newNode.addChild(leaf2.key.charAt(int(depth)), leaf2.key.valid(int(depth)), newLeaf) replaceRef(curNode, newNode) return true } func (t *RadixTree) recursiveInsertOnCurrentNode(curNode **artNode, current *artNode, key Key, value Value, depth uint32) bool { node := current.node() prefixMismatchIdx := current.matchDeep(key, depth) if prefixMismatchIdx >= node.prefixLen { depth += node.prefixLen return t.recursiveInsertOnNextNode(curNode, current, key, value, depth) } newNode := newNode4() node4 := newNode.node() node4.prefixLen = prefixMismatchIdx for i := 0; i < int(min(prefixMismatchIdx, maxPrefixLen)); i++ { node4.prefix[i] = node.prefix[i] } if node.prefixLen <= maxPrefixLen { node.prefixLen -= (prefixMismatchIdx + 1) newNode.addChild(node.prefix[prefixMismatchIdx], true, current) for i, limit := uint32(0), min(node.prefixLen, maxPrefixLen); i < limit; i++ { node.prefix[i] = node.prefix[prefixMismatchIdx+i+1] } } else { node.prefixLen -= (prefixMismatchIdx + 1) leaf := current.minimum() newNode.addChild(leaf.key.charAt(int(depth+prefixMismatchIdx)), leaf.key.valid(int(depth+prefixMismatchIdx)), current) for i, limit := uint32(0), min(node.prefixLen, maxPrefixLen); i < limit; i++ { node.prefix[i] = leaf.key[depth+prefixMismatchIdx+i+1] } } // Insert the new leaf newNode.addChild(key.charAt(int(depth+prefixMismatchIdx)), key.valid(int(depth+prefixMismatchIdx)), newLeaf(key, value)) replaceRef(curNode, newNode) return true } func (t *RadixTree) recursiveInsertOnNextNode(curNode **artNode, current *artNode, key Key, value Value, depth uint32) bool { // Find a child to recursive to next := current.findChild(key.charAt(int(depth)), key.valid(int(depth))) if *next != nil { return t.recursiveInsert(next, key, value, depth+1) } // No Child, artNode goes with us current.addChild(key.charAt(int(depth)), key.valid(int(depth)), newLeaf(key, value)) return true } func (t *RadixTree) longestCommonPrefix(l1 *leaf, l2 *leaf, depth uint32) uint32 { l1key, l2key := l1.key, l2.key idx, limit := depth, min(uint32(len(l1key)), uint32(len(l2key))) for ; idx < limit; idx++ { if l1key[idx] != l2key[idx] { break } } return idx - depth } // X helpers func min(a, b uint32) uint32 { if a < b { return a } return b }
pkg/koyeb/idmapper/radix_tree.go
0.873012
0.424412
radix_tree.go
starcoder
package main import ( "math" "sync" "time" "github.com/go-gl/glfw/v3.2/glfw" "github.com/go-gl/mathgl/mgl32" ) type Player struct { pos, rot, velocity mgl32.Vec3 lastMousePosition mgl32.Vec2 mouseInit sync.Once } func NewPlayer(pos mgl32.Vec3) *Player { return &Player{ pos: pos, } } func (p *Player) handleInput(window *glfw.Window, keys keyStates) { p.keyboardInput(keys) p.mouseInput(window) } func (p *Player) update(dt time.Duration) { p.pos = p.pos.Add(p.velocity.Mul(float32(dt.Seconds()))) p.velocity = p.velocity.Mul(0.95) } func (p *Player) mouseInput(window *glfw.Window) { const bound = 80 p.mouseInit.Do(func() { x, y := window.GetCursorPos() p.lastMousePosition[0] = float32(x) p.lastMousePosition[1] = float32(y) }) x, y := window.GetCursorPos() change := mgl32.Vec2{ float32(x) - p.lastMousePosition[0], float32(y) - p.lastMousePosition[1], } p.rot[1] += change[0] * 0.05 p.rot[0] += change[1] * 0.05 if p.rot[0] > bound { p.rot[0] = bound } else if p.rot[0] < -bound { p.rot[0] = -bound } if p.rot[1] > 360 { p.rot[1] = 0 } else if p.rot[1] < 0 { p.rot[1] = 360 } cx, cy := window.GetSize() window.SetCursorPos(float64(cx)/4, float64(cy)/4) x, y = window.GetCursorPos() p.lastMousePosition[0] = float32(x) p.lastMousePosition[1] = float32(y) } func (p *Player) keyboardInput(keys keyStates) { var change mgl32.Vec3 const speed = 0.01 if keys.w { change[0] = float32(math.Cos(float64(mgl32.DegToRad(p.rot.Y()+90))) * speed) change[2] = float32(math.Sin(float64(mgl32.DegToRad(p.rot.Y()+90))) * speed) } if keys.s { change[0] = -float32(math.Cos(float64(mgl32.DegToRad(p.rot.Y()+90))) * speed) change[2] = -float32(math.Sin(float64(mgl32.DegToRad(p.rot.Y()+90))) * speed) } if keys.a { change[0] = float32(math.Cos(float64(mgl32.DegToRad(p.rot.Y()))) * speed) change[2] = float32(math.Sin(float64(mgl32.DegToRad(p.rot.Y()))) * speed) } if keys.d { change[0] = -float32(math.Cos(float64(mgl32.DegToRad(p.rot.Y()))) * speed) change[2] = -float32(math.Sin(float64(mgl32.DegToRad(p.rot.Y()))) * speed) } p.velocity = p.velocity.Add(change) } func (p *Player) position() mgl32.Vec3 { return p.pos } func (p *Player) rotation() mgl32.Vec3 { return p.rot }
player.go
0.601008
0.425725
player.go
starcoder
package datadog import ( "encoding/json" "fmt" ) // LogsIndex Object describing a Datadog Log index. type LogsIndex struct { // The number of log events you can send in this index per day before you are rate-limited. DailyLimit *int64 `json:"daily_limit,omitempty"` // An array of exclusion objects. The logs are tested against the query of each filter, following the order of the array. Only the first matching active exclusion matters, others (if any) are ignored. ExclusionFilters *[]LogsExclusion `json:"exclusion_filters,omitempty"` Filter LogsFilter `json:"filter"` // A boolean stating if the index is rate limited, meaning more logs than the daily limit have been sent. Rate limit is reset every-day at 2pm UTC. IsRateLimited *bool `json:"is_rate_limited,omitempty"` // The name of the index. Name string `json:"name"` // The number of days before logs are deleted from this index. Available values depend on retention plans specified in your organization's contract/subscriptions. NumRetentionDays *int64 `json:"num_retention_days,omitempty"` // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct UnparsedObject map[string]interface{} `json:-` } // NewLogsIndex instantiates a new LogsIndex 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 NewLogsIndex(filter LogsFilter, name string) *LogsIndex { this := LogsIndex{} this.Filter = filter this.Name = name return &this } // NewLogsIndexWithDefaults instantiates a new LogsIndex 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 NewLogsIndexWithDefaults() *LogsIndex { this := LogsIndex{} return &this } // GetDailyLimit returns the DailyLimit field value if set, zero value otherwise. func (o *LogsIndex) GetDailyLimit() int64 { if o == nil || o.DailyLimit == nil { var ret int64 return ret } return *o.DailyLimit } // GetDailyLimitOk returns a tuple with the DailyLimit field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsIndex) GetDailyLimitOk() (*int64, bool) { if o == nil || o.DailyLimit == nil { return nil, false } return o.DailyLimit, true } // HasDailyLimit returns a boolean if a field has been set. func (o *LogsIndex) HasDailyLimit() bool { if o != nil && o.DailyLimit != nil { return true } return false } // SetDailyLimit gets a reference to the given int64 and assigns it to the DailyLimit field. func (o *LogsIndex) SetDailyLimit(v int64) { o.DailyLimit = &v } // GetExclusionFilters returns the ExclusionFilters field value if set, zero value otherwise. func (o *LogsIndex) GetExclusionFilters() []LogsExclusion { if o == nil || o.ExclusionFilters == nil { var ret []LogsExclusion return ret } return *o.ExclusionFilters } // GetExclusionFiltersOk returns a tuple with the ExclusionFilters field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsIndex) GetExclusionFiltersOk() (*[]LogsExclusion, bool) { if o == nil || o.ExclusionFilters == nil { return nil, false } return o.ExclusionFilters, true } // HasExclusionFilters returns a boolean if a field has been set. func (o *LogsIndex) HasExclusionFilters() bool { if o != nil && o.ExclusionFilters != nil { return true } return false } // SetExclusionFilters gets a reference to the given []LogsExclusion and assigns it to the ExclusionFilters field. func (o *LogsIndex) SetExclusionFilters(v []LogsExclusion) { o.ExclusionFilters = &v } // GetFilter returns the Filter field value func (o *LogsIndex) GetFilter() LogsFilter { if o == nil { var ret LogsFilter return ret } return o.Filter } // GetFilterOk returns a tuple with the Filter field value // and a boolean to check if the value has been set. func (o *LogsIndex) GetFilterOk() (*LogsFilter, bool) { if o == nil { return nil, false } return &o.Filter, true } // SetFilter sets field value func (o *LogsIndex) SetFilter(v LogsFilter) { o.Filter = v } // GetIsRateLimited returns the IsRateLimited field value if set, zero value otherwise. func (o *LogsIndex) GetIsRateLimited() bool { if o == nil || o.IsRateLimited == nil { var ret bool return ret } return *o.IsRateLimited } // GetIsRateLimitedOk returns a tuple with the IsRateLimited field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsIndex) GetIsRateLimitedOk() (*bool, bool) { if o == nil || o.IsRateLimited == nil { return nil, false } return o.IsRateLimited, true } // HasIsRateLimited returns a boolean if a field has been set. func (o *LogsIndex) HasIsRateLimited() bool { if o != nil && o.IsRateLimited != nil { return true } return false } // SetIsRateLimited gets a reference to the given bool and assigns it to the IsRateLimited field. func (o *LogsIndex) SetIsRateLimited(v bool) { o.IsRateLimited = &v } // GetName returns the Name field value func (o *LogsIndex) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *LogsIndex) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *LogsIndex) SetName(v string) { o.Name = v } // GetNumRetentionDays returns the NumRetentionDays field value if set, zero value otherwise. func (o *LogsIndex) GetNumRetentionDays() int64 { if o == nil || o.NumRetentionDays == nil { var ret int64 return ret } return *o.NumRetentionDays } // GetNumRetentionDaysOk returns a tuple with the NumRetentionDays field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LogsIndex) GetNumRetentionDaysOk() (*int64, bool) { if o == nil || o.NumRetentionDays == nil { return nil, false } return o.NumRetentionDays, true } // HasNumRetentionDays returns a boolean if a field has been set. func (o *LogsIndex) HasNumRetentionDays() bool { if o != nil && o.NumRetentionDays != nil { return true } return false } // SetNumRetentionDays gets a reference to the given int64 and assigns it to the NumRetentionDays field. func (o *LogsIndex) SetNumRetentionDays(v int64) { o.NumRetentionDays = &v } func (o LogsIndex) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.UnparsedObject != nil { return json.Marshal(o.UnparsedObject) } if o.DailyLimit != nil { toSerialize["daily_limit"] = o.DailyLimit } if o.ExclusionFilters != nil { toSerialize["exclusion_filters"] = o.ExclusionFilters } if true { toSerialize["filter"] = o.Filter } if o.IsRateLimited != nil { toSerialize["is_rate_limited"] = o.IsRateLimited } if true { toSerialize["name"] = o.Name } if o.NumRetentionDays != nil { toSerialize["num_retention_days"] = o.NumRetentionDays } return json.Marshal(toSerialize) } func (o *LogsIndex) UnmarshalJSON(bytes []byte) (err error) { raw := map[string]interface{}{} required := struct { Filter *LogsFilter `json:"filter"` Name *string `json:"name"` }{} all := struct { DailyLimit *int64 `json:"daily_limit,omitempty"` ExclusionFilters *[]LogsExclusion `json:"exclusion_filters,omitempty"` Filter LogsFilter `json:"filter"` IsRateLimited *bool `json:"is_rate_limited,omitempty"` Name string `json:"name"` NumRetentionDays *int64 `json:"num_retention_days,omitempty"` }{} err = json.Unmarshal(bytes, &required) if err != nil { return err } if required.Filter == nil { return fmt.Errorf("Required field filter missing") } if required.Name == nil { return fmt.Errorf("Required field name missing") } err = json.Unmarshal(bytes, &all) if err != nil { err = json.Unmarshal(bytes, &raw) if err != nil { return err } o.UnparsedObject = raw return nil } o.DailyLimit = all.DailyLimit o.ExclusionFilters = all.ExclusionFilters o.Filter = all.Filter o.IsRateLimited = all.IsRateLimited o.Name = all.Name o.NumRetentionDays = all.NumRetentionDays return nil }
api/v1/datadog/model_logs_index.go
0.753285
0.413803
model_logs_index.go
starcoder
package main func GitServer() *Container { return &Container{ Name: "gitserver", Title: "Git Server", Description: "Stores, manages, and operates Git repositories.", Groups: []Group{ { Title: "General", Rows: []Row{ { { Name: "disk_space_remaining", Description: "disk space remaining by instance", Query: `(src_gitserver_disk_space_available / src_gitserver_disk_space_total) * 100`, DataMayNotExist: true, Warning: Alert{LessOrEqual: 25}, Critical: Alert{LessOrEqual: 15}, PanelOptions: PanelOptions().LegendFormat("{{instance}}").Unit(Percentage), PossibleSolutions: ` - **Provision more disk space:** Sourcegraph will begin deleting least-used repository clones at 10% disk space remaining which may result in decreased performance, users having to wait for repositories to clone, etc. `, }, { Name: "running_git_commands", Description: "running git commands (signals load)", Query: "max(src_gitserver_exec_running)", DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 50}, Critical: Alert{GreaterOrEqual: 100}, PanelOptions: PanelOptions().LegendFormat("running commands"), PossibleSolutions: ` - **Check if the problem may be an intermittent and temporary peak** using the "Container monitoring" section at the bottom of the Git Server dashboard. - **Single container deployments:** Consider upgrading to a [Docker Compose deployment](../install/docker-compose/migrate.md) which offers better scalability and resource isolation. - **Kubernetes and Docker Compose:** Check that you are running a similar number of git server replicas and that their CPU/memory limits are allocated according to what is shown in the [Sourcegraph resource estimator](../install/resource_estimator.md). `, }, }, { { Name: "repository_clone_queue_size", Description: "repository clone queue size", Query: "sum(src_gitserver_clone_queue)", DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 25}, PanelOptions: PanelOptions().LegendFormat("queue size"), PossibleSolutions: ` - **If you just added several repositories**, the warning may be expected. - **Check which repositories need cloning**, by visiting e.g. https://sourcegraph.example.com/site-admin/repositories?filter=not-cloned `, }, { Name: "repository_existence_check_queue_size", Description: "repository existence check queue size", Query: "sum(src_gitserver_lsremote_queue)", DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 25}, PanelOptions: PanelOptions().LegendFormat("queue size"), PossibleSolutions: ` - **Check the code host status indicator for errors:** on the Sourcegraph app homepage, when signed in as an admin click the cloud icon in the top right corner of the page. - **Check if the issue continues to happen after 30 minutes**, it may be temporary. - **Check the gitserver logs for more information.** `, }, }, { { Name: "echo_command_duration_test", Description: "echo command duration test", Query: "max(src_gitserver_echo_duration_seconds)", DataMayNotExist: true, Warning: Alert{GreaterOrEqual: 1.0}, Critical: Alert{GreaterOrEqual: 2.0}, PanelOptions: PanelOptions().LegendFormat("running commands").Unit(Seconds), PossibleSolutions: ` - **Check if the problem may be an intermittent and temporary peak** using the "Container monitoring" section at the bottom of the Git Server dashboard. - **Single container deployments:** Consider upgrading to a [Docker Compose deployment](../install/docker-compose/migrate.md) which offers better scalability and resource isolation. - **Kubernetes and Docker Compose:** Check that you are running a similar number of git server replicas and that their CPU/memory limits are allocated according to what is shown in the [Sourcegraph resource estimator](../install/resource_estimator.md). `, }, sharedFrontendInternalAPIErrorResponses("gitserver"), }, }, }, { Title: "Container monitoring (not available on server)", Hidden: true, Rows: []Row{ { sharedContainerRestarts("gitserver"), sharedContainerMemoryUsage("gitserver"), sharedContainerCPUUsage("gitserver"), }, }, }, { Title: "Provisioning indicators (not available on server)", Hidden: true, Rows: []Row{ { sharedProvisioningCPUUsage1d("gitserver"), sharedProvisioningMemoryUsage1d("gitserver"), }, { sharedProvisioningCPUUsage5m("gitserver"), sharedProvisioningMemoryUsage5m("gitserver"), }, }, }, }, } }
monitoring/git_server.go
0.58261
0.406479
git_server.go
starcoder
package rtc import ( "math" ) // Cone creates a cone at the origin with its axis on the Y axis. // It implements the Object interface. func Cone() *ConeT { return &ConeT{ Shape: Shape{Transform: M4Identity(), Material: GetMaterial()}, Minimum: math.Inf(-1), Maximum: math.Inf(1), Closed: false, } } // ConeT represents a Cone. type ConeT struct { Shape Minimum float64 Maximum float64 Closed bool } var _ Object = &ConeT{} // SetTransform sets the object's transform 4x4 matrix. func (c *ConeT) SetTransform(m M4) Object { c.Transform = m return c } // SetMaterial sets the object's material. func (c *ConeT) SetMaterial(material MaterialT) Object { c.Material = material return c } // SetParent sets the object's parent object. func (c *ConeT) SetParent(parent Object) Object { c.Parent = parent return c } // Bounds returns the minimum bounding box of the object in object // (untransformed) space. func (c *ConeT) Bounds() *BoundsT { return &BoundsT{ Min: Point(c.Minimum, c.Minimum, c.Minimum), Max: Point(c.Maximum, c.Maximum, c.Maximum), } } func (c *ConeT) intersectCaps(ray RayT, xs []IntersectionT) []IntersectionT { if !c.Closed || math.Abs(ray.Direction.Y()) < epsilon { return xs } t := (c.Minimum - ray.Origin.Y()) / ray.Direction.Y() if checkCap(ray, t, c.Minimum) { // Abs not necessary for radius here. xs = append(xs, Intersection(t, c)) } t = (c.Maximum - ray.Origin.Y()) / ray.Direction.Y() if checkCap(ray, t, c.Maximum) { // Abs not necessary for radius here. xs = append(xs, Intersection(t, c)) } return xs } // LocalIntersect returns a slice of IntersectionT values where the // transformed (object space) ray intersects the object. func (c *ConeT) LocalIntersect(ray RayT) []IntersectionT { a := ray.Direction.X()*ray.Direction.X() - ray.Direction.Y()*ray.Direction.Y() + ray.Direction.Z()*ray.Direction.Z() b := 2*ray.Origin.X()*ray.Direction.X() - 2*ray.Origin.Y()*ray.Direction.Y() + 2*ray.Origin.Z()*ray.Direction.Z() if math.Abs(a) < epsilon && math.Abs(b) < epsilon { return c.intersectCaps(ray, nil) } c2 := ray.Origin.X()*ray.Origin.X() - ray.Origin.Y()*ray.Origin.Y() + ray.Origin.Z()*ray.Origin.Z() if math.Abs(a) < epsilon { t := -c2 / (2 * b) return c.intersectCaps(ray, []IntersectionT{Intersection(t, c)}) } discriminant := b*b - 4*a*c2 if discriminant < 0 { return c.intersectCaps(ray, nil) } sr := math.Sqrt(discriminant) t1 := (-b - sr) / (2 * a) t2 := (-b + sr) / (2 * a) if t1 > t2 { t1, t2 = t2, t1 } y1 := ray.Origin.Y() + t1*ray.Direction.Y() y2 := ray.Origin.Y() + t2*ray.Direction.Y() var xs []IntersectionT if c.Minimum < y1 && y1 < c.Maximum { xs = append(xs, Intersection(t1, c)) } if c.Minimum < y2 && y2 < c.Maximum { xs = append(xs, Intersection(t2, c)) } xs = c.intersectCaps(ray, xs) return xs } // LocalNormalAt returns the normal vector at the given point of intersection // (transformed to object space) with the object. func (c *ConeT) LocalNormalAt(objectPoint Tuple, hit *IntersectionT) Tuple { dist := objectPoint.X()*objectPoint.X() + objectPoint.Z()*objectPoint.Z() if dist < 1 && objectPoint.Y() >= c.Maximum-epsilon { return Vector(0, 1, 0) } if dist < 1 && objectPoint.Y() <= c.Minimum+epsilon { return Vector(0, -1, 0) } y := math.Sqrt(objectPoint.X()*objectPoint.X() + objectPoint.Z()*objectPoint.Z()) if objectPoint.Y() > 0 { y = -y } return Vector(objectPoint.X(), y, objectPoint.Z()) } // Includes returns whether this object includes (or actually is) the // other object. func (c *ConeT) Includes(other Object) bool { return c == other }
rtc/cone.go
0.91967
0.519399
cone.go
starcoder
package helpers import ( "errors" "strconv" ) var visaelectron map[string][]interface{} type digits [6]int func (d *digits) At(i int) int { return d[i-1] } //ReturningTypeCreditCard func ReturningTypeCreditCard(num string) (Company, error) { ccLen := len(num) ccDigits := digits{} for i := 0; i < 6; i++ { if i < ccLen { ccDigits[i], _ = strconv.Atoi(num[:i+1]) } } switch { case ccDigits.At(2) == 34 || ccDigits.At(2) == 37: return Company{"amex", "American Express"}, nil case ccDigits.At(4) == 5610 || (ccDigits.At(6) == 560221 && ccDigits.At(6) == 560225): return Company{"bankcard", "Bankcard"}, nil case ccDigits.At(2) == 62: return Company{"china-unionpay", "China UnionPay"}, nil case ccDigits.At(3) >= 300 && ccDigits.At(3) <= 305 && ccLen == 15: return Company{"diners-club-carte-blanche", "Diners Club Carte Blanche"}, nil case ccDigits.At(4) == 2014 || ccDigits.At(4) == 2149: return Company{"diners-club-enroute", "Diners Club enRoute"}, nil case ((ccDigits.At(3) >= 300 && ccDigits.At(3) <= 305) || ccDigits.At(3) == 309 || ccDigits.At(2) == 36 || ccDigits.At(2) == 38 || ccDigits.At(2) == 39) && ccLen <= 14: return Company{"diners-club-international", "Diners Club International"}, nil case ccDigits.At(4) == 6011 || (ccDigits.At(6) >= 622126 && ccDigits.At(6) <= 622925) || (ccDigits.At(3) >= 644 && ccDigits.At(3) <= 649) || ccDigits.At(2) == 65: return Company{"discover", "Discover"}, nil case ccDigits.At(3) == 636 && ccLen >= 16 && ccLen <= 19: return Company{"interpayment", "InterPayment"}, nil case ccDigits.At(3) >= 637 && ccDigits.At(3) <= 639 && ccLen == 16: return Company{"instapayment", "InstaPayment"}, nil case ccDigits.At(4) >= 3528 && ccDigits.At(4) <= 3589: return Company{"jcb", "JCB"}, nil case ccDigits.At(4) == 5018 || ccDigits.At(4) == 5020 || ccDigits.At(4) == 5038 || ccDigits.At(4) == 5612 || ccDigits.At(4) == 5893 || ccDigits.At(4) == 6304 || ccDigits.At(4) == 6759 || ccDigits.At(4) == 6761 || ccDigits.At(4) == 6762 || ccDigits.At(4) == 6763 || num[:3] == "0604" || ccDigits.At(4) == 6390: return Company{"maestro", "Maestro"}, nil case ccDigits.At(4) == 5019: return Company{"dankort", "Dankort"}, nil case ccDigits.At(2) >= 51 && ccDigits.At(2) <= 55: return Company{"mastercard", "MasterCard"}, nil case ccDigits.At(4) == 4026 || ccDigits.At(6) == 417500 || ccDigits.At(4) == 4405 || ccDigits.At(4) == 4508 || ccDigits.At(4) == 4844 || ccDigits.At(4) == 4913 || ccDigits.At(4) == 4917: return Company{"visa-electron", "Visa Electron"}, nil case ccDigits.At(1) == 4: return Company{"visa", "Visa"}, nil default: return Company{"", ""}, errors.New("Unknown credit card method.") } }
helpers/maps.go
0.540196
0.614683
maps.go
starcoder
package attrs import ( "github.com/influx6/haiku/trees" ) // InputType defines the set type of input values for the input elements type InputType string // Types of input for attribute input types. const ( TypeButton InputType = "button" TypeCheckbox InputType = "checkbox" TypeColor InputType = "color" TypeDate InputType = "date" TypeDatetime InputType = "datetime" TypeDatetimelocal InputType = "datetime-local" TypeEmail InputType = "email" TypeFile InputType = "file" TypeHidden InputType = "hidden" TypeImage InputType = "image" TypeMonth InputType = "month" TypeNumber InputType = "number" TypePassword InputType = "password" TypeRadio InputType = "radio" TypeRange InputType = "range" TypeMin InputType = "min" TypeMax InputType = "max" TypeValue InputType = "value" TypeStep InputType = "step" TypeReset InputType = "reset" TypeSearch InputType = "search" TypeSubmit InputType = "submit" TypeTel InputType = "tel" TypeText InputType = "text" TypeTime InputType = "time" TypeURL InputType = "url" TypeWeek InputType = "week" ) // Name defines attributes of type "Name" for html element types func Name(val string) *trees.Attribute { return &trees.Attribute{Name: "name", Value: val} } // Checked defines attributes of type "Checked" for html element types func Checked(val string) *trees.Attribute { return &trees.Attribute{Name: "checked", Value: val} } // ClassName defines attributes of type "ClassName" for html element types func ClassName(val string) *trees.Attribute { return &trees.Attribute{Name: "className", Value: val} } // Autofocus defines attributes of type "Autofocus" for html element types func Autofocus(val string) *trees.Attribute { return &trees.Attribute{Name: "autofocus", Value: val} } // ID defines attributes of type "Id" for html element types func ID(val string) *trees.Attribute { return &trees.Attribute{Name: "id", Value: val} } // HTMLFor defines attributes of type "HtmlFor" for html element types func HTMLFor(val string) *trees.Attribute { return &trees.Attribute{Name: "htmlFor", Value: val} } // Class defines attributes of type "Class" for html element types func Class(val string) *trees.Attribute { return &trees.Attribute{Name: "class", Value: val} } // Src defines attributes of type "Src" for html element types func Src(val string) *trees.Attribute { return &trees.Attribute{Name: "src", Value: val} } // Href defines attributes of type "Href" for html element types func Href(val string) *trees.Attribute { return &trees.Attribute{Name: "href", Value: val} } // Rel defines attributes of type "Rel" for html element types func Rel(val string) *trees.Attribute { return &trees.Attribute{Name: "rel", Value: val} } // IType defines attributes of type "Type" for html element types func IType(val InputType) *trees.Attribute { return Type(string(val)) } // Type defines attributes of type "Type" for html element types func Type(val string) *trees.Attribute { return &trees.Attribute{Name: "type", Value: val} } // Placeholder defines attributes of type "Placeholder" for html element types func Placeholder(val string) *trees.Attribute { return &trees.Attribute{Name: "placeholder", Value: val} } // Value defines attributes of type "Value" for html element types func Value(val string) *trees.Attribute { return &trees.Attribute{Name: "value", Value: val} }
trees/attrs/attrs.go
0.773901
0.487124
attrs.go
starcoder
package reflection import ( "errors" "fmt" "reflect" "strconv" ) // Creates an instance of caller for methods. func ForMethod(m interface{}) Caller { return &caller{value: m} } // Creates an instance of reflector for structs. func ForInstance(value interface{}) Reflector { return &reflector{ value: value, entryName: make(map[string]reflect.Value), entryType: make(map[reflect.Type]reflect.Value), } } // Calls a method with given parameters in order corresponding to invoked method's // and returns the value of called method and nil if and only if invocation is // success; otherwise, returns nil and an error. func (c *caller) Call(params ...interface{}) ([]interface{}, error) { t := reflect.TypeOf(c.value) if t.Kind() != reflect.Func { return nil, errors.New("Called 'method' is not a method. ") } // Checks number of method's parameters with given parameters. if parameterNum := t.NumIn(); parameterNum == len(params) { var in = make([]reflect.Value, parameterNum) for i := 0; i < parameterNum; i++ { parameterType := t.In(i) // Checks type of parameters with given parameters. if pt := reflect.TypeOf(params[i]); parameterType.Kind() != pt.Kind() { return nil, errors.New("Type {" + parameterType.Kind().String() + "} of invoked method does not match given type {" + pt.Kind().String() + "} of parameter {" + fmt.Sprint(params[i]) + "}.") } else { in[i] = reflect.ValueOf(params[i]) } } // Invokes method and processes returned values. res := reflect.ValueOf(c.value).Call(in) out := convertResponse(res) return out, nil } else { return nil, errors.New("Number of invoked method's {" + strconv.Itoa(parameterNum) + "} does not match given parameters' {" + strconv.Itoa(len(params)) + "}.") } } // Calls a method with given parameters whose type differs from each other and // returns the value of called method and nil if and only if invocation is // success; otherwise, returns nil and an error. func (c *caller) CallType(params ...interface{}) ([]interface{}, error) { t := reflect.TypeOf(c.value) if t.Kind() != reflect.Func { return nil, errors.New("Called 'method' is not a method. ") } // Checks number of method's parameters with given parameters. if parameterNum := t.NumIn(); parameterNum == len(params) { // Maps given parameters with key-value entry. var m = make(map[reflect.Type]reflect.Value) for i := 0; i < len(params); i++ { m[reflect.TypeOf(params[i])] = reflect.ValueOf(params[i]) } var in = make([]reflect.Value, parameterNum) for i := 0; i < parameterNum; i++ { parameterType := t.In(i) if val, ok := m[parameterType]; ok { in[i] = val } else { return nil, errors.New("Type {" + parameterType.Kind().String() + "} of invoked method does not exists in given parameters.") } } res := reflect.ValueOf(c.value).Call(in) out := convertResponse(res) return out, nil } else { return nil, errors.New("Number of invoked method's {" + strconv.Itoa(parameterNum) + "} does not match given parameters' {" + strconv.Itoa(len(params)) + "}.") } } func (r *reflector) transform() (*reflect.Value, error) { v := reflect.ValueOf(r.value) for v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { return nil, errors.New("Parameter of invoked method ForInstance(interface{}) is not a pointer of struct. ") } return &v, nil } // Adds an entry representing a field of struct to modify that one // and returns an pointer of injector. func (r *reflector) Map(key string, value interface{}) *reflector { r.entryName[key] = reflect.ValueOf(value) return r } // Adds an entry representing a field of struct whose fields' type are // different from each other. func (r *reflector) MapType(value interface{}) *reflector { r.entryType[reflect.TypeOf(value)] = reflect.ValueOf(value) return r } // Injects all entries into the given struct and returns an pointer // of injector and nil if and only if this method succeed; otherwise, // returns nil and an error. func (r *reflector) Inject() (*reflector, error) { if len(r.entryType) > 0 && len(r.entryName) == 0 { fmt.Println("Maybe method invoked is 'InjectType()', and this method injects nothing.") } v, err := r.transform() if err != nil { return nil, err } t := (*v).Type() for i := 0; i < v.NumField(); i++ { tf := t.Field(i) vf := v.Field(i) // Checks whether current field can be modified. if vf.CanSet() { // Lookups of value with corresponding field name. if val, ok := r.entryName[tf.Name]; ok { // Checks type of field with given parameter's if tf.Type.Kind() == val.Type().Kind() { vf.Set(val) } else { return nil, errors.New("Type {" + tf.Type.Kind().String() + "} of field {" + tf.Name + "} does not match given type {" + val.Type().Kind().String() + "} of parameter {" + val.String() + "}.") } } else { //fmt.Printf("{ %s } does not have a given value, using default zero-value.\n", tf.Name) } } else { //fmt.Printf("Field { %s } can not be changed\n", vf) } } return r, nil } // Injects all entries into the given struct and returns an pointer of // injector and nil if and only if this method succeed; otherwise, returns // nil and an error. func (r *reflector) InjectType() (*reflector, error) { if len(r.entryName) > 0 && len(r.entryType) == 0 { fmt.Println("Maybe method invoked is 'Inject()', and this method injects nothing.") } v, err := r.transform() if err != nil { return nil, err } t := (*v).Type() for i := 0; i < v.NumField(); i++ { tf, vf := t.Field(i), v.Field(i) if vf.CanSet() { if val, ok := r.entryType[tf.Type]; ok { vf.Set(val) } else { //fmt.Printf("{ %s } does not have a given name, using default zero-value.\n", tf.Name) } } else { //fmt.Printf("Field { %s } can not be changed.\n", vf) } } return r, nil } // Invokes a method by function name with given parameters and returns responses of invoked // method and nil if and only if invocation is success; otherwise, returns nil and an error. func (r *reflector) Invoke(function string, params ...interface{}) ([]interface{}, error) { v, err := r.transform() if err != nil { return nil, err } // Checks existence of invoked method. if funcExist := v.MethodByName(function).Kind() == reflect.Invalid; !funcExist { invokedFunc, invokedFuncType := v.MethodByName(function), v.MethodByName(function).Type() // Checks number of invoked method's parameters with given one. if numParams := invokedFuncType.NumIn(); numParams == len(params) { var in = make([]reflect.Value, numParams) for i := 0; i < numParams; i++ { // Checks type of parameter of invoked method with given one. if ift, rft := invokedFuncType.In(i), reflect.TypeOf(params[i]); ift.Kind() != rft.Kind() { return nil, errors.New("Type {" + ift.Kind().String() + "} of invoked method's " + "parameter does not match given parameter {" + fmt.Sprint(params[i]) + "} type {" + rft.Kind().String() + "}.") } else { in[i] = reflect.ValueOf(params[i]) } } // Invokes method and processes value of invoked method. res := invokedFunc.Call(in) out := convertResponse(res) return out, nil } else { return nil, errors.New("Number of invoked method's parameter {" + strconv.Itoa(numParams) + "} does not match given parameters' {" + strconv.Itoa(len(params)) + "}.") } } else { return nil, errors.New("Method Invoked {" + function + "} does not exists. ") } } // Invokes a method by function name with given parameters whose type are different from each other // and returns responses of invoked method and nil if and only if invocation is success; otherwise, // returns nil and an error. func (r *reflector) InvokeType(function string, params ...interface{}) ([]interface{}, error) { v, err := r.transform() if err != nil { return nil, err } // Checks existence of invoked method. if funcExist := v.MethodByName(function).Kind() == reflect.Invalid; !funcExist { invokedFunc, invokedFuncType := v.MethodByName(function), v.MethodByName(function).Type() // Checks number of parameters of invoked method with given parameters. if numParams := invokedFuncType.NumIn(); numParams == len(params) { // Converts given parameters into a map whose key is reflect.Type and value is reflect.Value. var parameterMap = make(map[reflect.Type]reflect.Value) for i := 0; i < len(params); i++ { parameterMap[reflect.TypeOf(params[i])] = reflect.ValueOf(params[i]) } var in = make([]reflect.Value, numParams) for i := 0; i < numParams; i++ { // Checks existence of current parameter by type of invoked method. if val, ok := parameterMap[invokedFuncType.In(i)]; ok { in[i] = val } else { return nil, errors.New("Type {" + invokedFuncType.In(i).String() + "} does not exists.") } } res := invokedFunc.Call(in) out := convertResponse(res) return out, nil } else { return nil, errors.New("Number of invoked method's parameter {" + strconv.Itoa(numParams) + "} does not match given parameters' {" + strconv.Itoa(len(params)) + "}.") } } else { return nil, errors.New("Method Invoked {" + function + "} does not exists. ") } } // Converts the responses of invoked method represented by slice of // reflect.Value into slice of interface{}. func convertResponse(res []reflect.Value) []interface{} { var out = make([]interface{}, len(res)) for i := 0; i < len(out); i++ { out[i] = res[i].Interface() } return out }
Reflection.go
0.776114
0.494507
Reflection.go
starcoder
package game // findwinner returns a color if four contiguous fields of the given // board of that color in a horizontal, vertical or diagonal line exist. // It returns none otherwise. // If this condition applies for both colors one of both will be returned. func findwinner(b *Board) color { if color := winHorizontal(b); none != color { return color } if color := winVertical(b); none != color { return color } if color := winDiagonal(b); none != color { return color } return none } // winHorizontal returns a color if four contiguous fields of the given // board of that color in a horizontal line exist. It returns none otherwise. // If this condition applies for both colors one of both will be returned. func winHorizontal(b *Board) color { color := none for _, row := range b.Fields { color = hasFour(row[:]) if none != color { break } } return color } // winVertical returns a color if four contiguous fields of the // board of that color in a vertical line exist. It returns none otherwise. // If this condition applies for both colors one of both will be returned. func winVertical(b *Board) color { color := none for index := range b.Fields[0] { color = hasFour(column(&b.Fields, index)) if none != color { break } } return color } // winDiagonal returns a color if four contiguous fields of the // board of that color in a diagonal line exist. It returns none otherwise. // If this condition applies for both colors one of both will be returned. func winDiagonal(b *Board) color { color := none for y := 0; y <= len(b.Fields)-4; y++ { color = hasFour(diagonalTopLeftBottomRight(&b.Fields, y, 0)) if none != color { return color } } for x := 0; x <= len(b.Fields[0])-4; x++ { color = hasFour(diagonalTopLeftBottomRight(&b.Fields, 0, x)) if none != color { return color } } for y := 0; y <= len(b.Fields)-4; y++ { color = hasFour(diagonalTopRightBottomLeft(&b.Fields, y, len(b.Fields[0])-1)) if none != color { return color } } for x := 3; x < len(b.Fields[0]); x++ { color = hasFour(diagonalTopRightBottomLeft(&b.Fields, 0, x)) if none != color { return color } } return none } // hasFour is the working horse of the win detection algorithm. // It returns the (first) color (red or blue) that is value of // four contiguous items (like i_k, i_k+1, i_k+2, i_k+3) of the given slice. // If non-existent none will be returned. // If this condition applies for both colors one of both will be returned. func hasFour(c []color) color { current := none count := 0 for _, color := range c { if current != color || none == color { count = 0 } count++ if 4 == count { return color } current = color } return none } // column returns the column with given index of the given array func column(fields *[nRows][nCols]color, index int) []color { column := make([]color, nRows) for _, row := range fields { column = append(column, row[index]) } return column } // diagonalTopLeftBottomRight returns the diagonal of the given array starting at (row, column) // leading to the right lower corner func diagonalTopLeftBottomRight(fields *[nRows][nCols]color, row int, column int) []color { diagonal := make([]color, 0) x := column for y := row; y < len(fields); y++ { if x < len(fields[0]) { diagonal = append(diagonal, fields[y][x]) } x++ } return diagonal } // diagonalTopRightBottomLeft returns the diagonal of the given array starting at (row, column) // leading to the left lower corner func diagonalTopRightBottomLeft(fields *[nRows][nCols]color, row int, column int) []color { diagonal := make([]color, 0) x := column for y := row; y < len(fields); y++ { if x >= 0 { diagonal = append(diagonal, fields[y][x]) } x-- } return diagonal }
game/win.go
0.901627
0.434701
win.go
starcoder
package phass import ( "fmt" "time" ) /** * Constants */ // TimeLayout common date representation. const TimeLayout = "2006-Jan-02" // Gender constant values. const ( Male int = iota Female ) /** * Interfaces */ // Measurer is the interface to be implemented by any struct that should convey // a measurement in physical assessment. type Measurer interface { // Proxy to retrieve the measurement name. GetName() string // Result shows the meaningful information available from the measurement // itself. It can also show an error with the measurement process is // somehow invalid. Result() ([]string, error) } /** * Assessment */ // Assessment represents a collection of measurements made in a given date. // Also knows how to represent the collection of measurements through Measurer // interface. type Assessment struct { Date time.Time Measures []Measurer } // NewAssessment returns an Assessment instance. It receives the date whe it // was made, and a list of measurements. Returns an Assessment pointer and // error. func NewAssessment(date string, measurements ...Measurer) (*Assessment, error) { a := &Assessment{Measures: measurements} d, err := time.Parse(TimeLayout, date) if err != nil { return a, err } a.Date = d return a, nil } func (a *Assessment) String() string { measurements := "" for idx, m := range a.Measures { tmpl := "%s, %s" if idx == 0 { tmpl = "%s%s" } measurements = fmt.Sprintf(tmpl, measurements, m.GetName()) } return fmt.Sprintf("Assessment made in %s. With the measurements %s.", a.Date.Format(TimeLayout), measurements) } // GetName returns this assessment name representation. func (a *Assessment) GetName() string { return a.String() } // Result aggregates all measures results into one representation. If one // measure has error, then the given error is returned. func (a *Assessment) Result() ([]string, error) { accum := []string{} for _, measure := range a.Measures { rs, err := measure.Result() if err != nil { return []string{}, fmt.Errorf("Measure _%s_ failed: %s", measure.GetName(), err) } accum = append(accum, measure.GetName()) accum = append(accum, rs...) } return accum, nil } // AddMeasure allow to add a new measure to the ones available in a given // assessment. func (a *Assessment) AddMeasure(m Measurer) { a.Measures = append(a.Measures, m) } /** * Person */ // Person is the common information from the individual being measured type Person struct { FullName string Birthday time.Time Gender int } // NewPerson creates a Person representation, for assessment purposes a person // must have a full name, a birth date, and a gender. This returnas a pointer // to a Person instance, and an error, when some information is invalid. func NewPerson(fullName string, birth string, gender int) (*Person, error) { p := &Person{} b, err := time.Parse(TimeLayout, birth) if err != nil { return p, err } p.FullName = fullName p.Birthday = b.UTC() p.Gender = gender return p, nil } func (p *Person) String() string { return fmt.Sprintf("Name: %s\nGender: %s\nAge: %.0f", p.FullName, p.genderRepr(), p.Age()) } // GetName return this measurement name. func (p *Person) GetName() string { return "Person" } // Result get common representation for this measurement result. func (p *Person) Result() ([]string, error) { rs := []string{ fmt.Sprintf("Name: %s", p.FullName), fmt.Sprintf("Gender: %s", p.genderRepr()), fmt.Sprintf("Age: %.0f years", p.Age()), fmt.Sprintf("Age: %.1f months", p.AgeInMonths()), } return rs, nil } // Age calculate this Person age in years. func (p *Person) Age() float64 { return p.AgeFromDate(time.Now().UTC()) } // AgeInMonths calculate this Person age in months. func (p *Person) AgeInMonths() float64 { return p.AgeInMonthsFromDate(time.Now().UTC()) } // AgeFromDate calculate this Person age in years, based in a given time. func (p *Person) AgeFromDate(t time.Time) float64 { age := t.Year() - p.Birthday.Year() if t.Month() < p.Birthday.Month() || (t.Month() == p.Birthday.Month() && t.Day() < p.Birthday.Day()) { age-- } return float64(age) } // AgeInMonthsFromDate calculate this Person age in months, based in a given // time. func (p *Person) AgeInMonthsFromDate(t time.Time) float64 { return elapsedFromDateIn(p.Birthday, t, secondsInMonth) } // genderRepr convert the constant gender into string representation. func (p *Person) genderRepr() string { choices := map[int]string{ Male: "Male", Female: "Female", } return choices[p.Gender] } /** * Private methods */ // elapsedFromDateIn calculates the amont of time passsed between two time.Time // instances and convert it to a common time frame. func elapsedFromDateIn(from time.Time, to time.Time, in float64) float64 { return to.Sub(from).Seconds() / in } // these variables make it easier the conversion between different times frames var ( daysInYear = 365.25 // approximate days in a year, assuming no leap year daysInMonth = daysInYear / 12 // approximate days in month, assuming constant distribution secondsInMinute = 60.0 // seconds in a minute minutesInHour = 60.0 // minutes in a hour hoursInDay = 24.0 // hours in a day secondsInDay = hoursInDay * minutesInHour * secondsInMinute // seconds in a days secondsInMonth = daysInMonth * secondsInDay // approximate seconds in a month )
assessment.go
0.857664
0.467393
assessment.go
starcoder
package main import "math" var ( // NeuronConnectionWeight the weight of a single neuron connection NeuronConnectionWeight = 0.1 // NeuronConnectionCountStep the step size for how much to increment/decrement // the neuron connection count NeuronConnectionCountStep = 1 // NeuronConnectionCountMinimum the minimum number of connections that the // neuron connection can have NeuronConnectionCountMinimum = 0 // PotentialThreshold the minimum weight of a neuron connection before it will // fire against its outgoing connections PotentialThreshold = 0.0 ) // NeuronConnection the dendrites for the neurons type NeuronConnection struct { Connections int `json:"connections"` Source *Neuron `json:"source"` Target *Neuron `json:"target"` Weight float64 `json:"weight"` } // NewNeuronConnection creates a new default neuron connection func NewNeuronConnection(src, target *Neuron) *NeuronConnection { return &NeuronConnection{ Connections: NeuronConnectionCountStep, Source: src, Target: target, Weight: NeuronConnectionWeight, } } // CalculateIntensity calculates the final intensity of this neuron's fire // event func (n *NeuronConnection) CalculateIntensity() float64 { // Make sure excitatory neurons add to the potential and inhibitory neurons // subtract from it if n.Source.Type == TypeExcitatory { return float64(n.Connections) * n.Weight } return -1.0 * float64(n.Connections) * n.Weight } // Strengthen strengthens this connection by 1 step func (n *NeuronConnection) Strengthen() int { n.Connections += NeuronConnectionCountStep return n.Connections } // Weaken weakens this connection by 1 step func (n *NeuronConnection) Weaken() int { n.Connections -= NeuronConnectionCountStep if n.Connections < NeuronConnectionCountMinimum { n.Connections = NeuronConnectionCountMinimum } return n.Connections } // Fire fires the current dendrite connection from the source neuron to the // target neuron func (n *NeuronConnection) Fire() bool { if n.Source.Potential >= PotentialThreshold { n.Target.Potential += n.CalculateIntensity() if math.IsNaN(n.Target.Potential) || math.IsInf(n.Target.Potential, 1) || math.IsInf(n.Target.Potential, -1) { panic("fuck you") } return true } return false }
neuron_connection.go
0.782953
0.447219
neuron_connection.go
starcoder
package timeutil import ( "fmt" "strings" "time" ) // Period represents a unit of time type Period int const ( // PeriodNone represents no period PeriodNone Period = iota // PeriodYear represents years as a Period PeriodYear // PeriodMonth represents months as a Period PeriodMonth // PeriodDay represents days as a Period PeriodDay // PeriodHour represents hours as a Period PeriodHour // PeriodMinute represents minutes as a Period PeriodMinute ) // PeriodFromString does a best attempt at parsing string as a period func PeriodFromString(s string) (Period, error) { if len(s) == 1 { return PeriodFromByte(s[0]) } s = strings.ToLower(s) switch s { case "minute": return PeriodMinute, nil case "hour": return PeriodHour, nil case "day": return PeriodDay, nil case "month": return PeriodMonth, nil case "year": return PeriodYear, nil default: return 0, fmt.Errorf("no period matches '%v'", s) } } // PeriodFromByte is the reverse of Period.Byte() func PeriodFromByte(b byte) (Period, error) { switch b { case 'm': return PeriodMinute, nil case 'H': return PeriodHour, nil case 'd': return PeriodDay, nil case 'M': return PeriodMonth, nil case 'y': return PeriodYear, nil default: return 0, fmt.Errorf("no period matches '%v'", b) } } // Byte returns the Period as a letter func (p Period) Byte() byte { switch p { case PeriodMinute: return 'm' case PeriodHour: return 'H' case PeriodDay: return 'd' case PeriodMonth: return 'M' case PeriodYear: return 'y' default: panic(fmt.Errorf("unknown period '%d'", p)) } } // String returns the Period as a letter func (p Period) String() string { switch p { case PeriodMinute: return "Minute" case PeriodHour: return "Hour" case PeriodDay: return "Day" case PeriodMonth: return "Month" case PeriodYear: return "Year" default: panic(fmt.Errorf("unknown period '%d'", p)) } } // Count returns the number of periods between two times func (p Period) Count(from, until time.Time) int { switch p { case PeriodMinute: return int(until.Sub(from).Minutes()) case PeriodHour: return int(until.Sub(from).Hours()) case PeriodDay: return int(until.Sub(from).Hours() / 24) case PeriodMonth: uy, um, _ := until.Date() fy, fm, _ := from.Date() count := (uy-fy)*12 + int(um) - int(fm) return count case PeriodYear: uy, _, _ := until.Date() fy, _, _ := from.Date() count := uy - fy return count default: panic(fmt.Errorf("unknown period '%d'", p)) } }
pkg/timeutil/period.go
0.807423
0.625209
period.go
starcoder
package enigma import "fmt" // RotorSet Represents a set of Rotors that are part of an Enigma machine. // Set to represent a Type 1 Enigma (3 Rotors) type RotorSet struct { refRotor Rotor leftRotor Rotor middleRotor Rotor rightRotor Rotor // Here for posterity. In the real machine, this rotor converts the electrical signal // used by the keyboard/plugboard to the mechanical contact system used by the rotors. // In this application, it has no use. echoRotor Rotor } // NewRotorSet Initializes a new rotor set using the provided initial rotor/ring settings. func NewRotorSet(settings Settings) *RotorSet { r := RotorSet{ refRotor: *NewRotor(ReflectorC, 'a', 'a'), // Reflector rotor does not have ring settings or positionality leftRotor: *NewRotor(settings.RotorTypes[0], settings.RingOffsets[0], settings.RotorInits[0]), middleRotor: *NewRotor(settings.RotorTypes[1], settings.RingOffsets[1], settings.RotorInits[1]), rightRotor: *NewRotor(settings.RotorTypes[2], settings.RingOffsets[2], settings.RotorInits[2]), echoRotor: *NewRotor(Echo, 'a', 'a'), } return &r } // Map Passes a letter through the rotor set func (r *RotorSet) Map(inByte byte) byte { fmt.Println("==========================================") r.turnRotors() // Before doing anything, turn the rotors fmt.Printf("Rotor states: (%v%v%v)\n", string(r.leftRotor.GetPosition()), string(r.middleRotor.GetPosition()), string(r.rightRotor.GetPosition()), ) // First Pass fmt.Println("RIGHT") val := r.rightRotor.Enc(inByte) fmt.Println("MIDDLE") val = r.middleRotor.Enc(val) fmt.Println("LEFT") val = r.leftRotor.Enc(val) fmt.Println("-------------------------------") fmt.Println("REFLECTOR") fmt.Printf("Type: %v ... ", ReflectorC) fmt.Printf("In: %v -> ", string(val)) val = RotorCiphers[r.refRotor.Type][val-97] fmt.Printf("Out: %v\n", string(val)) fmt.Println("-------------------------------") // On the flip-side. fmt.Println("LEFT") val = r.leftRotor.Dec(val) fmt.Println("MIDDLE") val = r.middleRotor.Dec(val) fmt.Println("RIGHT") val = r.rightRotor.Dec(val) fmt.Println("==========================================") return val } // RotateRotors turns the rotors in the set, turning over as needed. func (r *RotorSet) turnRotors() { if r.rightRotor.GetPosition() == Turnovers[r.rightRotor.Type] { // Right rotor has turnedover, so we need to rotate the middle rotor if r.middleRotor.GetPosition() == Turnovers[r.middleRotor.Type] { // Middle rotor also turned, so rotate the left rotor. r.leftRotor.Rotate() } r.middleRotor.Rotate() } else { // Account for the double stepping of the middle rotor. if r.middleRotor.GetPosition() == Turnovers[r.middleRotor.Type] { r.middleRotor.Rotate() r.leftRotor.Rotate() } } r.rightRotor.Rotate() }
rotorset.go
0.779406
0.483648
rotorset.go
starcoder
package main import ( "fmt" "io/ioutil" "strconv" "strings" ) type ship struct { pos []int waypoint []int } // makeShip creates a ship located at position (x, y) with a waypoint at (wx, wy) func makeShip(x, y, wx, wy int) ship { // The waypoint starts 10 units east and 1 unit north relative to the ship. return ship{ pos: []int{x, y}, waypoint: []int{wx, wy}, } } // movePart1 is the movement logic for Part 1 of the puzzle func (s *ship) movePart1(instr string) { action := instr[0] value, err := strconv.Atoi(instr[1:]) if err != nil { panic("bad instruction: " + instr) } if action == 'N' { scaled := scale([]int{0, -1}, value) s.pos = add(s.pos, scaled) } else if action == 'S' { scaled := scale([]int{0, 1}, value) s.pos = add(s.pos, scaled) } else if action == 'W' { scaled := scale([]int{-1, 0}, value) s.pos = add(s.pos, scaled) } else if action == 'E' { scaled := scale([]int{1, 0}, value) s.pos = add(s.pos, scaled) } else if action == 'L' { s.waypoint = rotateL(s.waypoint, value) } else if action == 'R' { s.waypoint = rotateR(s.waypoint, value) } else if action == 'F' { scaled := scale(s.waypoint, value) s.pos = add(s.pos, scaled) } } // movePart2 is the movement logic for Part 2 of the puzzle func (s *ship) movePart2(instr string) { action := instr[0] value, err := strconv.Atoi(instr[1:]) if err != nil { panic("bad instruction: " + instr) } if action == 'N' { s.waypoint = moveN(s.waypoint, value) } else if action == 'S' { s.waypoint = moveS(s.waypoint, value) } else if action == 'W' { s.waypoint = moveW(s.waypoint, value) } else if action == 'E' { s.waypoint = moveE(s.waypoint, value) } else if action == 'L' { s.waypoint = rotateL(s.waypoint, value) } else if action == 'R' { s.waypoint = rotateR(s.waypoint, value) } else if action == 'F' { scaled := scale(s.waypoint, value) s.pos = add(s.pos, scaled) } } func readInput(fname string) string { data, err := ioutil.ReadFile(fname) if err != nil { panic("Cannot read input data.") } s := string(data) return strings.TrimRight(s, "\n") } // matmul multiplies vector v on the left side by matrix r func matmul(r [][]int, v []int) []int { if len(r[0]) != len(v) { panic(fmt.Sprintf("incompatible matrix and vector sizes %d and %d", len(r[0]), len(v))) } output := make([]int, len(r)) for i, row := range r { for j := range row { output[i] += row[j] * v[j] } } return output } // rotateR rotates the vector v by theta degrees clockwise, // where theta is one of 90, 180, or 270 func rotateR(v []int, theta int) []int { var r [][]int if theta == 90 { r = [][]int{ []int{0, -1}, []int{1, 0}, } } else if theta == 180 { r = [][]int{ []int{-1, 0}, []int{0, -1}, } } else if theta == 270 { r = [][]int{ []int{0, 1}, []int{-1, 0}, } } else { panic("not implemented") } return matmul(r, v) } // rotateL rotates the vector v by theta degrees counterclockwise, // where theta is one of 90, 180, or 270 func rotateL(v []int, theta int) []int { if theta == 90 { return rotateR(v, 270) } else if theta == 270 { return rotateR(v, 90) } else { return rotateR(v, theta) } } // add vectors a and b func add(a, b []int) []int { res := make([]int, len(a)) for i := range a { res[i] = a[i] + b[i] } return res } // scale the vector v by x func scale(v []int, x int) []int { y := make([]int, len(v)) for i := range v { y[i] = v[i] * x } return y } func moveN(v []int, dist int) []int { x := []int{0, -dist} return add(v, x) } func moveS(v []int, dist int) []int { x := []int{0, dist} return add(v, x) } func moveW(v []int, dist int) []int { x := []int{-dist, 0} return add(v, x) } func moveE(v []int, dist int) []int { x := []int{dist, 0} return add(v, x) } func abs(x int) int { if x < 0 { return -x } return x } func part1(instructions []string) int { // The ship starts by facing east. s := makeShip(0, 0, 1, 0) for _, instr := range instructions { s.movePart1(instr) } return abs(s.pos[0]) + abs(s.pos[1]) } func part2(instructions []string) int { // The waypoint starts 10 units east and 1 unit north relative to the ship. s := makeShip(0, 0, 10, -1) for _, instr := range instructions { s.movePart2(instr) } return abs(s.pos[0]) + abs(s.pos[1]) } func main() { txt := readInput("input.txt") lines := strings.Split(txt, "\n") p1 := part1(lines) fmt.Println("[PART 1] Result:", p1) p2 := part2(lines) fmt.Println("[PART 2] Result:", p2) }
day12/main.go
0.612541
0.426441
main.go
starcoder
package gcode import ( "fmt" "math" "strings" ) const ( forceX = 1 << iota forceY forceZ forceXY = forceX | forceY forceYZ = forceY | forceZ forceXZ = forceX | forceZ forceXYZ = forceX | forceY | forceZ ) func (g *GCode) genChangedXYZ(opCode string, p Tuple, force int) string { pos := g.Position() var parts []string if (!g.hasMoved && (force&forceX) != 0) || math.Abs(p.X()-pos.X()) >= epsilon { parts = append(parts, fmt.Sprintf("X%.8f", p.X())) } if (!g.hasMoved && (force&forceY) != 0) || math.Abs(p.Y()-pos.Y()) >= epsilon { parts = append(parts, fmt.Sprintf("Y%.8f", p.Y())) } if (!g.hasMoved && (force&forceZ) != 0) || math.Abs(p.Z()-pos.Z()) >= epsilon { parts = append(parts, fmt.Sprintf("Z%.8f", p.Z())) } if len(parts) == 0 { return "" } s := fmt.Sprintf("%v %v", opCode, strings.Join(parts, " ")) return s } // moveOrGo optimizes the movement to only include the // axes that have changed since the last moveOrGo. // As a special case, for the very first move/goto command, // force the output of all the mentioned axes, even if 0. func (g *GCode) moveOrGo(opCode string, p Tuple, force int) { s := g.genChangedXYZ(opCode, p, force) if s == "" { return } p[3] = 1 g.steps = append(g.steps, &Step{s: s, pos: p}) g.hasMoved = true } // GotoX performs one or more rapid move(s) on the X axis. func (g *GCode) GotoX(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(p.X(), pos.Y(), pos.Z()) g.moveOrGo("G0", newPos, forceX) } return g } // GotoY performs one or more rapid move(s) on the Y axis. func (g *GCode) GotoY(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(pos.X(), p.Y(), pos.Z()) g.moveOrGo("G0", newPos, forceY) } return g } // GotoZ performs one or more rapid move(s) on the Z axis. func (g *GCode) GotoZ(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(pos.X(), pos.Y(), p.Z()) g.moveOrGo("G0", newPos, forceZ) } return g } // GotoXY performs one or more rapid move(s) on the XY axes. func (g *GCode) GotoXY(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(p.X(), p.Y(), pos.Z()) g.moveOrGo("G0", newPos, forceXY) } return g } // GotoYZ performs one or more rapid move(s) on the YZ axes. func (g *GCode) GotoYZ(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(pos.X(), p.Y(), p.Z()) g.moveOrGo("G0", newPos, forceYZ) } return g } // GotoXZ performs one or more rapid move(s) on the XZ axes. func (g *GCode) GotoXZ(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(p.X(), pos.Y(), p.Z()) g.moveOrGo("G0", newPos, forceXZ) } return g } // GotoXYZ performs one or more rapid move(s) on the XYZ axes. func (g *GCode) GotoXYZ(ps ...Tuple) *GCode { for _, p := range ps { g.moveOrGo("G0", p, forceXYZ) } return g } // GotoXYZWithF performs one or more move(s) on the XYZ axes using the provided feed-rate. func (g *GCode) GotoXYZWithF(feedrate float64, ps ...Tuple) *GCode { for i, p := range ps { g.moveOrGo("G0", p, forceXYZ) if i == 0 { lastStep := len(g.steps) - 1 g.steps[lastStep].s += fmt.Sprintf(" F%v", feedrate) } } return g } // MoveX performs one or more move(s) on the X axis at the current feed-rate. func (g *GCode) MoveX(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(p.X(), pos.Y(), pos.Z()) g.moveOrGo("G1", newPos, forceX) } return g } // MoveY performs one or more move(s) on the Y axis at the current feed-rate. func (g *GCode) MoveY(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(pos.X(), p.Y(), pos.Z()) g.moveOrGo("G1", newPos, forceY) } return g } // MoveZ performs one or more move(s) on the Z axis at the current feed-rate. func (g *GCode) MoveZ(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(pos.X(), pos.Y(), p.Z()) g.moveOrGo("G1", newPos, forceZ) } return g } // MoveZWithF performs one or more move(s) on the Z axis using the provided feed-rate. func (g *GCode) MoveZWithF(feedrate float64, ps ...Tuple) *GCode { pos := g.Position() for i, p := range ps { newPos := XYZ(pos.X(), pos.Y(), p.Z()) g.moveOrGo("G1", newPos, forceZ) if i == 0 { lastStep := len(g.steps) - 1 g.steps[lastStep].s += fmt.Sprintf(" F%v", feedrate) } } return g } // MoveXY performs one or more move(s) on the XY axes at the current feed-rate. func (g *GCode) MoveXY(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(p.X(), p.Y(), pos.Z()) g.moveOrGo("G1", newPos, forceXY) } return g } // MoveYZ performs one or more move(s) on the YZ axes at the current feed-rate. func (g *GCode) MoveYZ(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(pos.X(), p.Y(), p.Z()) g.moveOrGo("G1", newPos, forceYZ) } return g } // MoveXZ performs one or more move(s) on the XZ axes at the current feed-rate. func (g *GCode) MoveXZ(ps ...Tuple) *GCode { pos := g.Position() for _, p := range ps { newPos := XYZ(p.X(), pos.Y(), p.Z()) g.moveOrGo("G1", newPos, forceXZ) } return g } // MoveXYZ performs one or more move(s) on the XYZ axes at the current feed-rate. func (g *GCode) MoveXYZ(ps ...Tuple) *GCode { for _, p := range ps { g.moveOrGo("G1", p, forceXYZ) } return g } // MoveXYZRel performs one or more move(s) on the XYZ axes at the current feed-rate // using relative offsets. func (g *GCode) MoveXYZRel(ps ...Tuple) *GCode { for _, p := range ps { pos := g.Position() g.moveOrGo("G1", pos.Add(p), forceXYZ) } return g }
gcode/move.go
0.625324
0.41739
move.go
starcoder
package docs import ( "bytes" "encoding/json" "strings" "text/template" "github.com/swaggo/swag" ) var doc = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "contact": {}, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/cookies": { "get": { "description": "Requests using GET should only retrieve data.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Cookies" ], "summary": "Get all cookies of the request.", "responses": { "200": { "description": "OK", "schema": { "type": "array", "items": { "$ref": "#/definitions/cookies.GetCookies" } } } } } }, "/cookies/{cookieName}": { "post": { "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Cookies" ], "summary": "Create a new cookie.", "parameters": [ { "type": "string", "description": "The name of the new cookie", "name": "cookieName", "in": "path" }, { "description": "The cookie", "name": "cookie", "in": "body", "required": true, "schema": { "$ref": "#/definitions/cookies.SetCookie" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/cookies.GetCookies" } } } }, "delete": { "description": "Delete a specific cookie.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Cookies" ], "summary": "Delete a cookie.", "parameters": [ { "type": "string", "description": "The name of the cookie to delete", "name": "cookieName", "in": "path" } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/cookies.GetCookies" } } } } }, "/delete": { "delete": { "description": "The DELETE method deletes the specified resource.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "HTTP Methods" ], "summary": "Do a DELETE request.", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/http.Response" } } } } }, "/get": { "get": { "description": "Requests using GET should only retrieve data.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "HTTP Methods" ], "summary": "Do a GET request.", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/http.Response" } } } } }, "/jwt": { "get": { "description": "Requests using GET should only retrieve data.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "JWT" ], "summary": "Get jwt passed as authorization bearer token of the request.", "parameters": [ { "type": "string", "description": "if set, the jwt is verified with the key received from jwks endpoint", "name": "jwksUri", "in": "query" } ], "responses": { "200": { "description": "OK", "schema": { "type": "array", "items": { "$ref": "#/definitions/jwt.Response" } } } } } }, "/patch": { "patch": { "description": "The PATCH method is used to apply partial modifications to a resource.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "HTTP Methods" ], "summary": "Do a PATCH request.", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/http.Response" } } } } }, "/post": { "post": { "description": "The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "HTTP Methods" ], "summary": "Do a POST request.", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/http.Response" } } } } }, "/proxy": { "get": { "description": "Query httpod as reverse proxy to uri.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Proxy Methods" ], "summary": "Do a GET request.", "parameters": [ { "type": "string", "description": "Full URI to use for the backend request. Mandatory. e.g. https://example.org/path ", "name": "uri", "in": "header" }, { "type": "string", "description": "Method to use for the backend request. Optional, defaults to 'GET'.", "name": "method", "in": "header" } ], "responses": { "200": { "description": "" }, "400": { "description": "" }, "500": { "description": "" } } } }, "/put": { "put": { "description": "The PUT method replaces all current representations of the target resource with the request payload.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "HTTP Methods" ], "summary": "Do PUT request.", "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/http.Response" } } } } }, "/status/{code}": { "get": { "description": "Requests using GET should only retrieve data.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Status codes" ], "summary": "Do a GET request.", "parameters": [ { "type": "string", "description": "return status code", "name": "code", "in": "path" } ], "responses": { "100": { "description": "Informational responses", "schema": { "type": "string" } }, "200": { "description": "Success", "schema": { "type": "string" } }, "300": { "description": "Redirection", "schema": { "type": "string" } }, "400": { "description": "Client Errors", "schema": { "type": "string" } }, "418": { "description": "I'm a teapot", "schema": { "type": "string" } }, "500": { "description": "Server Errors", "schema": { "type": "string" } } } }, "put": { "description": "The PUT method replaces all current representations of the target resource with the request payload.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Status codes" ], "summary": "Do PUT request.", "parameters": [ { "type": "string", "description": "return status code", "name": "code", "in": "path" } ], "responses": { "100": { "description": "Informational responses", "schema": { "type": "string" } }, "200": { "description": "Success", "schema": { "type": "string" } }, "300": { "description": "Redirection", "schema": { "type": "string" } }, "400": { "description": "Client Errors", "schema": { "type": "string" } }, "418": { "description": "I'm a teapot", "schema": { "type": "string" } }, "500": { "description": "Server Errors", "schema": { "type": "string" } } } }, "post": { "description": "The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Status codes" ], "summary": "Do a POST request.", "parameters": [ { "type": "string", "description": "return status code", "name": "code", "in": "path" } ], "responses": { "100": { "description": "Informational responses", "schema": { "type": "string" } }, "200": { "description": "Success", "schema": { "type": "string" } }, "300": { "description": "Redirection", "schema": { "type": "string" } }, "400": { "description": "Client Errors", "schema": { "type": "string" } }, "418": { "description": "I'm a teapot", "schema": { "type": "string" } }, "500": { "description": "Server Errors", "schema": { "type": "string" } } } }, "delete": { "description": "The DELETE method deletes the specified resource.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Status codes" ], "summary": "Do a DELETE request.", "parameters": [ { "type": "string", "description": "return status code", "name": "code", "in": "path" } ], "responses": { "100": { "description": "Informational responses", "schema": { "type": "string" } }, "200": { "description": "Success", "schema": { "type": "string" } }, "300": { "description": "Redirection", "schema": { "type": "string" } }, "400": { "description": "Client Errors", "schema": { "type": "string" } }, "418": { "description": "I'm a teapot", "schema": { "type": "string" } }, "500": { "description": "Server Errors", "schema": { "type": "string" } } } }, "patch": { "description": "The PATCH method is used to apply partial modifications to a resource.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "Status codes" ], "summary": "Do a PATCH request.", "parameters": [ { "type": "string", "description": "return status code", "name": "code", "in": "path" } ], "responses": { "100": { "description": "Informational responses", "schema": { "type": "string" } }, "200": { "description": "Success", "schema": { "type": "string" } }, "300": { "description": "Redirection", "schema": { "type": "string" } }, "400": { "description": "Client Errors", "schema": { "type": "string" } }, "418": { "description": "I'm a teapot", "schema": { "type": "string" } }, "500": { "description": "Server Errors", "schema": { "type": "string" } } } } } }, "definitions": { "cookies.GetCookies": { "type": "object", "properties": { "domain": { "type": "string" }, "expires": { "$ref": "#/definitions/cookies.JSONTime" }, "httpOnly": { "type": "boolean" }, "maxAge": { "type": "integer" }, "name": { "type": "string" }, "path": { "type": "string" }, "rawExpires": { "type": "string" }, "sameSite": { "type": "string" }, "secure": { "type": "boolean" }, "value": { "type": "string" } } }, "cookies.JSONTime": { "type": "object", "properties": { "time.Time": { "type": "string" } } }, "cookies.SetCookie": { "type": "object", "properties": { "expiresSeconds": { "type": "integer", "example": 3600 }, "httpOnly": { "type": "boolean", "example": true }, "maxAge": { "type": "integer", "example": 0 }, "path": { "type": "string", "example": "/" }, "sameSite": { "type": "string", "example": "Strict" }, "secure": { "type": "boolean", "example": true }, "value": { "type": "string", "example": "Test" } } }, "http.Response": { "type": "object", "properties": { "args": { "type": "object", "additionalProperties": { "type": "string" } }, "headers": { "type": "object", "additionalProperties": { "type": "string" } }, "host": { "type": "string" }, "remote-address": { "type": "string" }, "url": { "type": "string" } } }, "jwt.Response": { "type": "object", "properties": { "header": { "type": "object", "additionalProperties": true }, "payload": { "type": "object", "additionalProperties": true }, "raw": { "type": "string" }, "valid": { "type": "boolean" } } } }, "tags": [ { "description": "Testing different HTTP methods", "name": "HTTP Methods" }, { "description": "Generates responses with given status code", "name": "Status codes" }, { "description": "Creates, reads and deletes Cookies", "name": "Cookies" } ] }` type swaggerInfo struct { Version string Host string BasePath string Schemes []string Title string Description string } // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = swaggerInfo{ Version: "0.0.4", Host: "", BasePath: "", Schemes: []string{}, Title: "httPod", Description: "A simple HTTP Request & HTTPResponse Service, shamelessly stolen from httpbin.org.", } type s struct{} func (s *s) ReadDoc() string { sInfo := SwaggerInfo sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1) t, err := template.New("swagger_info").Funcs(template.FuncMap{ "marshal": func(v interface{}) string { a, _ := json.Marshal(v) return string(a) }, "escape": func(v interface{}) string { // escape tabs str := strings.Replace(v.(string), "\t", "\\t", -1) // replace " with \", and if that results in \\", replace that with \\\" str = strings.Replace(str, "\"", "\\\"", -1) return strings.Replace(str, "\\\\\"", "\\\\\\\"", -1) }, }).Parse(doc) if err != nil { return doc } var tpl bytes.Buffer if err := t.Execute(&tpl, sInfo); err != nil { return doc } return tpl.String() } func init() { swag.Register("swagger", &s{}) }
internal/docs/docs.go
0.586641
0.400925
docs.go
starcoder
package circheatmap import ( "fmt" "math" "github.com/knightjdr/prohits-viz-analysis/pkg/color" "github.com/knightjdr/prohits-viz-analysis/pkg/float" customMath "github.com/knightjdr/prohits-viz-analysis/pkg/math" ) // Circle has properties for drawing one circle in a circular heatmap. type Circle struct { Attribute string Color string Max float64 Min float64 Radius float64 Thickness float64 Values []float64 } // Segment has properties for a single circle segment type Segment struct { A SegmentPath B SegmentPath C SegmentPath D SegmentPath Fill string } // SegmentPath contains x and y coordinates for drawing the path type SegmentPath struct { Arc int X float64 Y float64 } func writeCircles(c *CircHeatmapSVG, writeString func(string)) { reformatted := reformatCircHeatmapData(c) writeString("\t\t<g>\n") for _, circle := range reformatted { writeCircle(circle, writeString) } writeString("\t\t</g>\n") } func reformatCircHeatmapData(c *CircHeatmapSVG) []Circle { reformatted := make([]Circle, len(c.Legend)) space := c.Dimensions.Thickness / 4 for i, legendItem := range c.Legend { attribute := legendItem.Attribute reformatted[i] = Circle{ Attribute: attribute, Color: legendItem.Color, Max: legendItem.Max, Min: legendItem.Min, Radius: c.Dimensions.Radius - (float64(i) * (c.Dimensions.Thickness + space)), Thickness: c.Dimensions.Thickness, Values: make([]float64, len(c.Plot.Readouts)), } for j, readout := range c.Plot.Readouts { reformatted[i].Values[j] = float64(readout.Segments[attribute]) } } return reformatted } func writeCircle(c Circle, writeString func(string)) { radii := calculateRadii(c.Radius, c.Thickness) colors := createColourRange(c) segments := defineSegments(colors, radii) writeString("\t\t\t<g>\n") for _, segment := range segments { drawSegment(segment, radii, writeString) } writeString("\t\t\t</g>\n") } func createGradient(gradientColor string) []color.Space { gradient := color.InitializeGradient() gradient.ColorSpace = gradientColor gradient.NumColors = 101 return gradient.CreateColorGradient() } func calculateRadii(radius, thickness float64) map[string]float64 { return map[string]float64{ "inner": math.Floor(radius - thickness), "outer": radius, } } func createColourRange(c Circle) []string { colorGradient := createGradient(c.Color) convertValueToColorIndex := float.GetRange(c.Min, c.Max, 0, 100) colors := make([]string, len(c.Values)) for i, value := range c.Values { index := int(convertValueToColorIndex(value)) colors[i] = colorGradient[index].Hex } return colors } func defineSegments(colors []string, radii map[string]float64) []Segment { numSegments := len(colors) segments := make([]Segment, numSegments) var cumulativePercent float64 last := map[string][]float64{ "inner": {radii["inner"], 0}, "outer": {radii["outer"], 0}, } arc := 0 if numSegments < 2 { arc = 1 } percent := customMath.Round(1/float64(numSegments), 0.000001) for i, color := range colors { cumulativePercent += percent innerPoint := percentToCoordinate(cumulativePercent, radii["inner"]) outerPoint := percentToCoordinate(cumulativePercent, radii["outer"]) start := map[string][]float64{ "inner": last["inner"], "outer": last["outer"], } last["inner"] = innerPoint last["outer"] = outerPoint segments[i] = Segment{ A: SegmentPath{ X: start["outer"][0], Y: start["outer"][1], }, B: SegmentPath{ Arc: arc, X: outerPoint[0], Y: outerPoint[1], }, C: SegmentPath{ X: innerPoint[0], Y: innerPoint[1], }, D: SegmentPath{ Arc: arc, X: start["inner"][0], Y: start["inner"][1], }, Fill: color, } } return segments } func drawSegment(segment Segment, radii map[string]float64, writeString func(string)) { path := fmt.Sprintf( "M %s %s A %s %s 0 %d 1 %s %s L %s %s A %s %s 0 %d 0 %s %s Z", float.RemoveTrailingZeros(customMath.Round(segment.A.X, 0.01)), float.RemoveTrailingZeros(customMath.Round(segment.A.Y, 0.01)), float.RemoveTrailingZeros(customMath.Round(radii["outer"], 0.01)), float.RemoveTrailingZeros(customMath.Round(radii["outer"], 0.01)), segment.B.Arc, float.RemoveTrailingZeros(customMath.Round(segment.B.X, 0.01)), float.RemoveTrailingZeros(customMath.Round(segment.B.Y, 0.01)), float.RemoveTrailingZeros(customMath.Round(segment.C.X, 0.01)), float.RemoveTrailingZeros(customMath.Round(segment.C.Y, 0.01)), float.RemoveTrailingZeros(customMath.Round(radii["inner"], 0.01)), float.RemoveTrailingZeros(customMath.Round(radii["inner"], 0.01)), segment.D.Arc, float.RemoveTrailingZeros(customMath.Round(segment.D.X, 0.01)), float.RemoveTrailingZeros(customMath.Round(segment.D.Y, 0.01)), ) writeString("\t\t\t\t<g transform=\"scale(0.85)\">\n") writeString(fmt.Sprintf( "\t\t\t\t\t<path d=\"%s\" fill=\"%s\" stroke=\"#f5f5f5\" strokeLinejoin=\"round\" strokeWidth=\"2\"/>\n", path, segment.Fill, )) writeString("\t\t\t\t</g>\n") }
pkg/svg/circheatmap/circles.go
0.692746
0.437343
circles.go
starcoder
package bbvm import ( "context" "github.com/wenerme/bbvm/bbasm" "math" "math/rand" "time" ) func StdBase(rt bbasm.Runtime, std *Std) *Std { random := rand.New(rand.NewSource(0)) dataPtr := 0 return &Std{ FloatToInt: func(ctx context.Context, v float32) int { return int(v) }, IntToFloat: func(ctx context.Context, v int) float32 { return float32(v) }, Sin: func(ctx context.Context, a float32) float32 { return float32(math.Sin(float64(a))) }, Cos: func(ctx context.Context, a float32) float32 { return float32(math.Cos(float64(a))) }, Tan: func(ctx context.Context, a float32) float32 { return float32(math.Tan(float64(a))) }, Sqrt: func(ctx context.Context, a float32) float32 { return float32(math.Sqrt(float64(a))) }, IntAbs: func(ctx context.Context, a int) int { if a >= 0 { return a } return -a }, FloatAbs: func(ctx context.Context, a float32) float32 { if a >= 0 { return a } return -a }, Delay: func(ctx context.Context, msec int) { time.Sleep(time.Duration(msec) * time.Millisecond) }, Tick: func(ctx context.Context) int { return int(time.Now().Unix()) }, Read: func(ctx context.Context, addr int) int { return rt.GetInt(addr) }, Write: func(ctx context.Context, addr int, v int) { rt.SetInt(addr, v) }, GetEnv: func(ctx context.Context) int { // Sim return 0 }, DataPtrSet: func(ctx context.Context, v int) { dataPtr = v }, DataReadInt: func(ctx context.Context) int { v := rt.GetInt(dataPtr) dataPtr += 4 return v }, DataReadFloat: func(ctx context.Context) float32 { v := rt.GetFloat(dataPtr) dataPtr += 4 return v }, DataReadString: func(ctx context.Context, hdr StringHandler) { v := rt.GetString(dataPtr) bytes, _ := std.StringToBytes(v) dataPtr += len(bytes) std.StringSet(ctx, hdr, v) }, RandSeed: func(ctx context.Context, seed int) { random.Seed(int64(seed)) }, Rand: func(ctx context.Context, n int) int { return random.Intn(n) }, VmTest: func(ctx context.Context) { }, } }
bbvm/std_base.go
0.544559
0.403684
std_base.go
starcoder
package timex import ( "time" ) const WeekStartDay = time.Monday type Time struct { time.Time } func New(t time.Time) *Time { return &Time{Time: t} } func (now *Time) BeginningOfMinute() time.Time { return now.Truncate(time.Minute) } func (now *Time) BeginningOfHour() time.Time { y, m, d := now.Date() return time.Date(y, m, d, now.Time.Hour(), 0, 0, 0, now.Time.Location()) } func (now *Time) BeginningOfDay() time.Time { y, m, d := now.Date() return time.Date(y, m, d, 0, 0, 0, 0, now.Time.Location()) } func (now *Time) BeginningOfWeek() time.Time { return now.BeginningOfWeekday(WeekStartDay) } func (now *Time) BeginningOfWeekday(weekStartDay time.Weekday) time.Time { b := now.BeginningOfDay() weekday := int(b.Weekday()) if weekStartDay != time.Sunday { weekStartDayInt := int(weekStartDay) if weekday < weekStartDayInt { weekday = weekday + 7 - weekStartDayInt } else { weekday = weekday - weekStartDayInt } } return b.AddDate(0, 0, -weekday) } func (now *Time) BeginningOfMonth() time.Time { y, m, _ := now.Date() return time.Date(y, m, 1, 0, 0, 0, 0, now.Location()) } func (now *Time) BeginningOfQuarter() time.Time { month := now.BeginningOfMonth() offset := (int(month.Month()) - 1) % 3 return month.AddDate(0, -offset, 0) } func (now *Time) BeginningOfHalf() time.Time { month := now.BeginningOfMonth() offset := (int(month.Month()) - 1) % 6 return month.AddDate(0, -offset, 0) } func (now *Time) BeginningOfYear() time.Time { y, _, _ := now.Date() return time.Date(y, time.January, 1, 0, 0, 0, 0, now.Location()) } func (now *Time) EndOfMinute() time.Time { return now.BeginningOfMinute().Add(time.Minute - time.Nanosecond) } func (now *Time) EndOfHour() time.Time { return now.BeginningOfHour().Add(time.Hour - time.Nanosecond) } func (now *Time) EndOfDay() time.Time { y, m, d := now.Date() return time.Date(y, m, d, 23, 59, 59, int(time.Second-time.Nanosecond), now.Location()) } func (now *Time) EndOfWeek() time.Time { return now.BeginningOfWeek().AddDate(0, 0, 7).Add(-time.Nanosecond) } func (now *Time) EndOfWeekday(weekStartDay time.Weekday) time.Time { return now.BeginningOfWeekday(weekStartDay).AddDate(0, 0, 7).Add(-time.Nanosecond) } func (now *Time) EndOfMonth() time.Time { return now.BeginningOfMonth().AddDate(0, 1, 0).Add(-time.Nanosecond) } func (now *Time) EndOfQuarter() time.Time { return now.BeginningOfQuarter().AddDate(0, 3, 0).Add(-time.Nanosecond) } func (now *Time) EndOfHalf() time.Time { return now.BeginningOfHalf().AddDate(0, 6, 0).Add(-time.Nanosecond) } func (now *Time) EndOfYear() time.Time { return now.BeginningOfYear().AddDate(1, 0, 0).Add(-time.Nanosecond) } func (now *Time) Yesterday() time.Time { return now.BeginningOfDay().AddDate(0, 0, -1) } func (now *Time) Today() time.Time { return now.BeginningOfDay() } func (now *Time) Tomorrow() time.Time { return now.BeginningOfDay().AddDate(0, 0, 1) } func (now *Time) Monday() time.Time { b := now.BeginningOfDay() weekday := int(b.Weekday()) if weekday == 0 { weekday = 7 } return b.AddDate(0, 0, -weekday+1) } func (now *Time) Sunday() time.Time { b := now.BeginningOfDay() weekday := int(b.Weekday()) if weekday == 0 { return b } return b.AddDate(0, 0, 7-weekday) } func (now *Time) Quarter() uint { return (uint(now.Month())-1)/3 + 1 }
timex/time.go
0.673943
0.450782
time.go
starcoder
package pricing import ( "fmt" "github.com/tealeg/xlsx" "go.uber.org/zap" "github.com/transcom/mymove/pkg/models" ) var parseDomesticMoveAccessorialPrices processXlsxSheet = func(params ParamConfig, sheetIndex int, logger Logger) (interface{}, error) { // XLSX Sheet consts const xlsxDataSheetNum int = 17 // 5a) Access. and Add. Prices const domAccessorialRowIndexStart int = 11 const firstColumnIndexStart = 2 const secondColumnIndexStart = 3 const thirdColumnIndexStart = 4 if xlsxDataSheetNum != sheetIndex { return nil, fmt.Errorf("parseDomesticMoveAccessorialPrices expected to process sheet %d, but received sheetIndex %d", xlsxDataSheetNum, sheetIndex) } logger.Info("Parsing domestic move accessorial prices") var prices []models.StageDomesticMoveAccessorialPrice dataRows := params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[domAccessorialRowIndexStart:] for _, row := range dataRows { price := models.StageDomesticMoveAccessorialPrice{ ServicesSchedule: getCell(row.Cells, firstColumnIndexStart), ServiceProvided: getCell(row.Cells, secondColumnIndexStart), PricePerUnit: getCell(row.Cells, thirdColumnIndexStart), } // All the rows are consecutive, if we get a blank we're done if price.ServicesSchedule == "" { break } if params.ShowOutput == true { logger.Info("", zap.Any("StageDomesticMoveAccessorialPrice", price)) } prices = append(prices, price) } return prices, nil } var parseInternationalMoveAccessorialPrices processXlsxSheet = func(params ParamConfig, sheetIndex int, logger Logger) (interface{}, error) { // XLSX Sheet consts const xlsxDataSheetNum int = 17 // 5a) Access. and Add. Prices const intlAccessorialRowIndexStart int = 25 const firstColumnIndexStart = 2 const secondColumnIndexStart = 3 const thirdColumnIndexStart = 4 if xlsxDataSheetNum != sheetIndex { return nil, fmt.Errorf("parseInternationalMoveAccessorialPrices expected to process sheet %d, but received sheetIndex %d", xlsxDataSheetNum, sheetIndex) } logger.Info("Parsing international move accessorial prices") var prices []models.StageInternationalMoveAccessorialPrice dataRows := params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[intlAccessorialRowIndexStart:] for _, row := range dataRows { price := models.StageInternationalMoveAccessorialPrice{ Market: getCell(row.Cells, firstColumnIndexStart), ServiceProvided: getCell(row.Cells, secondColumnIndexStart), PricePerUnit: getCell(row.Cells, thirdColumnIndexStart), } // All the rows are consecutive, if we get a blank we're done if price.Market == "" { break } if params.ShowOutput == true { logger.Info("", zap.Any("StageInternationalMoveAccessorialPrice", price)) } prices = append(prices, price) } return prices, nil } var parseDomesticInternationalAdditionalPrices processXlsxSheet = func(params ParamConfig, sheetIndex int, logger Logger) (interface{}, error) { // XLSX Sheet consts const xlsxDataSheetNum int = 17 // 5a) Access. and Add. Prices const additionalPricesRowIndexStart int = 39 const firstColumnIndexStart = 2 const secondColumnIndexStart = 3 const thirdColumnIndexStart = 4 if xlsxDataSheetNum != sheetIndex { return nil, fmt.Errorf("parseDomesticInternationalAdditionalPrices expected to process sheet %d, but received sheetIndex %d", xlsxDataSheetNum, sheetIndex) } logger.Info("Parsing domestic/international additional prices") var prices []models.StageDomesticInternationalAdditionalPrice dataRows := params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[additionalPricesRowIndexStart:] for _, row := range dataRows { price := models.StageDomesticInternationalAdditionalPrice{ Market: getCell(row.Cells, firstColumnIndexStart), ShipmentType: getCell(row.Cells, secondColumnIndexStart), Factor: getCell(row.Cells, thirdColumnIndexStart), } // All the rows are consecutive, if we get a blank we're done if price.Market == "" { break } if params.ShowOutput == true { logger.Info("", zap.Any("StageDomesticInternationalAdditionalPrice", price)) } prices = append(prices, price) } return prices, nil } var verifyAccessAndAddPrices verifyXlsxSheet = func(params ParamConfig, sheetIndex int) error { // XLSX Sheet consts const xlsxDataSheetNum = 17 // 5a) Access. and Add. Prices const domAccessorialRowIndexStart = 11 const intlAccessorialRowIndexStart = 25 const additionalPricesRowIndexStart = 39 const firstColumnIndexStart = 2 const secondColumnIndexStart = 3 const thirdColumnIndexStart = 4 if xlsxDataSheetNum != sheetIndex { return fmt.Errorf("verifyAccessAndAddPrices expected to process sheet %d, but received sheetIndex %d", xlsxDataSheetNum, sheetIndex) } dataRows := params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[domAccessorialRowIndexStart-2 : domAccessorialRowIndexStart-1] err := helperCheckHeadersFor5a("Services Schedule", "Service Provided", "PricePerUnitofMeasure", dataRows) if err != nil { return err } dataRows = params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[domAccessorialRowIndexStart-1 : domAccessorialRowIndexStart] err = helperCheckHeadersFor5a("X", "EXAMPLE (per unit of measure)", "$X.XX", dataRows) if err != nil { return err } dataRows = params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[intlAccessorialRowIndexStart-2 : intlAccessorialRowIndexStart-1] err = helperCheckHeadersFor5a("Market", "Service Provided", "PricePerUnitofMeasure", dataRows) if err != nil { return err } dataRows = params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[intlAccessorialRowIndexStart-1 : intlAccessorialRowIndexStart] err = helperCheckHeadersFor5a("X", "EXAMPLE (per unit of measure)", "$X.XX", dataRows) if err != nil { return err } dataRows = params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[additionalPricesRowIndexStart-2 : additionalPricesRowIndexStart-1] err = helperCheckHeadersFor5a("Market", "Shipment Type", "Factor", dataRows) if err != nil { return err } dataRows = params.XlsxFile.Sheets[xlsxDataSheetNum].Rows[additionalPricesRowIndexStart-1 : additionalPricesRowIndexStart] return helperCheckHeadersFor5a("CONUS / OCONUS", "EXAMPLE", "X.XX", dataRows) } func helperCheckHeadersFor5a(firstHeader string, secondHeader string, thirdHeader string, dataRows []*xlsx.Row) error { const firstColumnIndexStart = 2 const secondColumnIndexStart = 3 const thirdColumnIndexStart = 4 for _, dataRow := range dataRows { if header := getCell(dataRow.Cells, firstColumnIndexStart); header != firstHeader { return fmt.Errorf("verifyAccessAndAddPrices expected to find header '%s', but received header '%s'", firstHeader, header) } if header := getCell(dataRow.Cells, secondColumnIndexStart); header != secondHeader { return fmt.Errorf("verifyAccessAndAddPrices expected to find header '%s', but received header '%s'", secondHeader, header) } if header := removeWhiteSpace(getCell(dataRow.Cells, thirdColumnIndexStart)); header != thirdHeader { return fmt.Errorf("verifyAccessAndAddPrices expected to find header '%s', but received header '%s'", thirdHeader, header) } } return nil }
pkg/parser/pricing/parse_access_and_add_prices.go
0.523177
0.419232
parse_access_and_add_prices.go
starcoder
package types import ( "io" "reflect" "github.com/lyraproj/pcore/px" "github.com/lyraproj/pcore/utils" ) type PatternType struct { regexps []*RegexpType } var PatternMetaType px.ObjectType func init() { PatternMetaType = newObjectType(`Pcore::PatternType`, `Pcore::ScalarDataType { attributes => { patterns => Array[Regexp] } }`, func(ctx px.Context, args []px.Value) px.Value { return newPatternType2(args...) }) } func DefaultPatternType() *PatternType { return patternTypeDefault } func NewPatternType(regexps []*RegexpType) *PatternType { return &PatternType{regexps} } func newPatternType2(regexps ...px.Value) *PatternType { return newPatternType3(WrapValues(regexps)) } func newPatternType3(regexps px.List) *PatternType { cnt := regexps.Len() switch cnt { case 0: return DefaultPatternType() case 1: if av, ok := regexps.At(0).(*Array); ok { return newPatternType3(av) } } rs := make([]*RegexpType, cnt) regexps.EachWithIndex(func(arg px.Value, idx int) { switch arg := arg.(type) { case *RegexpType: rs[idx] = arg case *Regexp: rs[idx] = arg.PType().(*RegexpType) case stringValue: rs[idx] = newRegexpType2(arg) default: panic(illegalArgumentType(`Pattern[]`, idx, `Type[Regexp], Regexp, or String`, arg)) } }) return NewPatternType(rs) } func (t *PatternType) Accept(v px.Visitor, g px.Guard) { v(t) for _, rx := range t.regexps { rx.Accept(v, g) } } func (t *PatternType) Default() px.Type { return patternTypeDefault } func (t *PatternType) Equals(o interface{}, g px.Guard) bool { if ot, ok := o.(*PatternType); ok { return len(t.regexps) == len(ot.regexps) && px.IncludesAll(t.regexps, ot.regexps, g) } return false } func (t *PatternType) Get(key string) (value px.Value, ok bool) { switch key { case `patterns`: return WrapValues(t.Parameters()), true } return nil, false } func (t *PatternType) IsAssignable(o px.Type, g px.Guard) bool { if _, ok := o.(*PatternType); ok { return len(t.regexps) == 0 } if _, ok := o.(*stringType); ok { if len(t.regexps) == 0 { return true } } if vc, ok := o.(*vcStringType); ok { if len(t.regexps) == 0 { return true } str := vc.value return utils.MatchesString(MapToRegexps(t.regexps), str) } if et, ok := o.(*EnumType); ok { if len(t.regexps) == 0 { return true } enums := et.values return len(enums) > 0 && utils.MatchesAllStrings(MapToRegexps(t.regexps), enums) } return false } func (t *PatternType) IsInstance(o px.Value, g px.Guard) bool { str, ok := o.(stringValue) return ok && (len(t.regexps) == 0 || utils.MatchesString(MapToRegexps(t.regexps), string(str))) } func (t *PatternType) MetaType() px.ObjectType { return PatternMetaType } func (t *PatternType) Name() string { return `Pattern` } func (t *PatternType) Parameters() []px.Value { top := len(t.regexps) if top == 0 { return px.EmptyValues } rxs := make([]px.Value, top) for idx, rx := range t.regexps { rxs[idx] = WrapRegexp2(rx.pattern) } return rxs } func (t *PatternType) Patterns() *Array { rxs := make([]px.Value, len(t.regexps)) for idx, rx := range t.regexps { rxs[idx] = rx } return WrapValues(rxs) } func (t *PatternType) ReflectType(c px.Context) (reflect.Type, bool) { return reflect.TypeOf(`x`), true } func (t *PatternType) CanSerializeAsString() bool { return true } func (t *PatternType) SerializationString() string { return t.String() } func (t *PatternType) ToString(b io.Writer, s px.FormatContext, g px.RDetect) { TypeToString(t, b, s, g) } func (t *PatternType) String() string { return px.ToString2(t, None) } func (t *PatternType) PType() px.Type { return &TypeType{t} } var patternTypeDefault = &PatternType{[]*RegexpType{}}
types/patterntype.go
0.647798
0.503357
patterntype.go
starcoder
package kinematics import ( "errors" "math" "math/rand" "gonum.org/v1/gonum/mat" "gonum.org/v1/gonum/optimize" ) // DhParameters stand for "Denavit-Hartenberg Parameters". These parameters // define a robotic arm for input into forward or reverse kinematics. type DhParameters struct { ThetaOffsets []float64 AlphaValues []float64 AValues []float64 DValues []float64 } type Quaternion struct { W float64 X float64 Y float64 Z float64 } // Position represents a position in 3D cartesian space. type Position struct { X float64 Y float64 Z float64 } // Pose represents a position and rotation, where Position is the translational // component, and Rot is the quaternion representing the rotation. type Pose struct { Position Position Rotation Quaternion } // approxEqual checks if this Quaternion is approximately equal to another // Quaternion. This checks the positive and negative Quaternion (which are // equivalent). func (quatA Quaternion) approxEqual(quatB Quaternion, tol float64) bool { isEqual := false if (math.Abs(quatA.X-quatB.X) < tol) && (math.Abs(quatA.Y-quatB.Y) < tol) && (math.Abs(quatA.Z-quatB.Z) < tol) && (math.Abs(quatA.W-quatB.W) < tol) { isEqual = true } if (math.Abs(quatA.X+quatB.X) < tol) && (math.Abs(quatA.Y+quatB.Y) < tol) && (math.Abs(quatA.Z+quatB.Z) < tol) && (math.Abs(quatA.W+quatB.W) < tol) { isEqual = true } return isEqual } // approxEqual checks if two Positions are approximately equal. func (posA Position) approxEqual(posB Position, tol float64) bool { isEqual := false if math.Abs(posA.X-posB.X) < tol && math.Abs(posA.Y-posB.Y) < tol && math.Abs(posA.Z-posB.Z) < tol { isEqual = true } return isEqual } // approxEqual checks if two Poses are approximately equal. func (poseA Pose) approxEqual(poseB Pose, tol float64) bool { return poseA.Position.approxEqual(poseB.Position, tol) && poseA.Rotation.approxEqual(poseB.Rotation, tol) } // RandTheta creates a random value from -pi to pi func RandTheta() float64 { return 2 * math.Pi * (rand.Float64() - 0.5) } // ForwardKinematics calculates the end effector Pose coordinates given // joint angles and robotic arm parameters. func ForwardKinematics(thetas []float64, dhParameters DhParameters) Pose { // First, setup variables. We use 4 variables - theta, alpha, a and d to // calculate a matrix which is then multiplied to an accumulator matrix. var theta float64 var alpha float64 var a float64 var d float64 // Setup accumulator matrix - an identity matrix. accumulatortMat := mat.NewDense(4, 4, []float64{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, }) // Iterate through each joint and built a new // matrix, multiplying it against the accumulator. for jointIdx := 0; jointIdx < len(thetas); jointIdx++ { theta = thetas[jointIdx] theta = theta + dhParameters.ThetaOffsets[jointIdx] alpha = dhParameters.AlphaValues[jointIdx] a = dhParameters.AValues[jointIdx] d = dhParameters.DValues[jointIdx] tMat := mat.NewDense(4, 4, []float64{ // First row math.Cos(theta), -math.Sin(theta) * math.Cos(alpha), math.Sin(theta) * math.Sin(alpha), a * math.Cos(theta), // Second row math.Sin(theta), math.Cos(theta) * math.Cos(alpha), -math.Cos(theta) * math.Sin(alpha), a * math.Sin(theta), // Third row 0, math.Sin(alpha), math.Cos(alpha), d, // Forth row 0, 0, 0, 1, }) // Multiply tMat against accumulatortMat x := mat.NewDense(4, 4, nil) x.Mul(accumulatortMat, tMat) accumulatortMat = x } // Now that we have the final accumulatorMatrix, lets figure out the // output Pose. var output Pose output.Position.X = accumulatortMat.At(0, 3) output.Position.Y = accumulatortMat.At(1, 3) output.Position.Z = accumulatortMat.At(2, 3) output.Rotation = matrixToQuaterion(accumulatortMat) return output } // MaxInverseKinematicIteration is the max number of times InverseKinematics // should try new seeds before failing. 50 is used here because it is // approximately the number of iterations that will take 1 second to compute. var MaxInverseKinematicIteration int = 50 // InverseKinematics calculates joint angles to achieve a desired end effector // Pose, robotic arm DH parameters and the intial joint angles. func InverseKinematics(desiredEndEffector Pose, dhParameters DhParameters, thetasInit []float64) ([]float64, error) { // Initialize an objective function for the optimization problem objectiveFunction := func(s []float64) float64 { currentEndEffector := ForwardKinematics(s, dhParameters) // Get XYZ offsets xOffset := desiredEndEffector.Position.X - currentEndEffector.Position.X yOffset := desiredEndEffector.Position.Y - currentEndEffector.Position.Y zOffset := desiredEndEffector.Position.Z - currentEndEffector.Position.Z // Get rotational offsets. Essentially, do this in Golang (from python): // np.arccos(np.clip(2*(np.dot(target_quat, source_quat)**2) - 1, -1, 1)) dotOffset := (desiredEndEffector.Rotation.W * currentEndEffector.Rotation.W) + (desiredEndEffector.Rotation.X * currentEndEffector.Rotation.X) + (desiredEndEffector.Rotation.Y * currentEndEffector.Rotation.Y) + (desiredEndEffector.Rotation.Z * currentEndEffector.Rotation.Z) dotOffset = (2*(dotOffset*dotOffset) - 1) if dotOffset > 1 { dotOffset = 1 } rotationalOffset := math.Acos(dotOffset) // Get the error vector errorVector := ((xOffset * xOffset) + (yOffset * yOffset) + (zOffset * zOffset) + (rotationalOffset * rotationalOffset)) * 0.25 return errorVector } // Setup problem and method for solving problem := optimize.Problem{Func: objectiveFunction} // Solve result, err := optimize.Minimize(problem, thetasInit, nil, nil) if err != nil { return []float64{}, err } f := result.Location.F // If the results aren't up to spec, queue up another theta seed and test // again. We arbitrarily choose 1e-6 because that is small enough that the // errors do not matter. for i := 0; f > 1e-6; i++ { // Get a random seed between -pi and pi in radians. randomSeed := make([]float64, len(thetasInit)) for j := range randomSeed { randomSeed[j] = RandTheta() } // Solve result, err := optimize.Minimize(problem, randomSeed, nil, nil) if err != nil { return []float64{}, err } f = result.Location.F if i == MaxInverseKinematicIteration { return []float64{}, errors.New("desired position out of range of" + " the robotic arm") } } return result.Location.X, nil } // matrixToQuaterion converts a rotation matrix to a quaterion. This code has // been tested in all cases vs the python implementation with scipy rotation // and works properly. func matrixToQuaterion(accumulatortMat *mat.Dense) Quaternion { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ var qw float64 var qx float64 var qy float64 var qz float64 var tr float64 var s float64 tr = accumulatortMat.At(0, 0) + accumulatortMat.At(1, 1) + accumulatortMat.At(2, 2) switch { case tr > 0: s = math.Sqrt(tr+1.0) * 2 qw = 0.25 * s qx = (accumulatortMat.At(2, 1) - accumulatortMat.At(1, 2)) / s qy = (accumulatortMat.At(0, 2) - accumulatortMat.At(2, 0)) / s qz = (accumulatortMat.At(1, 0) - accumulatortMat.At(0, 1)) / s case accumulatortMat.At(0, 0) > accumulatortMat.At(1, 1) && accumulatortMat.At(0, 0) > accumulatortMat.At(2, 2): s = math.Sqrt(1.0+accumulatortMat.At(0, 0)-accumulatortMat.At(1, 1)- accumulatortMat.At(2, 2)) * 2 qw = (accumulatortMat.At(2, 1) - accumulatortMat.At(1, 2)) / s qx = 0.25 * s qy = (accumulatortMat.At(0, 1) + accumulatortMat.At(1, 0)) / s qz = (accumulatortMat.At(0, 2) + accumulatortMat.At(2, 0)) / s case accumulatortMat.At(1, 1) > accumulatortMat.At(2, 2): s = math.Sqrt(1.0+accumulatortMat.At(1, 1)-accumulatortMat.At(0, 0)- accumulatortMat.At(2, 2)) * 2 qw = (accumulatortMat.At(0, 2) - accumulatortMat.At(2, 0)) / s qx = (accumulatortMat.At(0, 1) + accumulatortMat.At(1, 0)) / s qy = 0.25 * s qz = (accumulatortMat.At(2, 1) + accumulatortMat.At(1, 2)) / s default: s = math.Sqrt(1.0+accumulatortMat.At(2, 2)-accumulatortMat.At(0, 0)- accumulatortMat.At(1, 1)) * 2 qw = (accumulatortMat.At(0, 1) - accumulatortMat.At(1, 0)) qx = (accumulatortMat.At(0, 2) + accumulatortMat.At(2, 0)) / s qy = (accumulatortMat.At(2, 1) + accumulatortMat.At(1, 2)) / s qz = 0.25 * s } return Quaternion{W: qw, X: qx, Y: qy, Z: qz} }
kinematics.go
0.840292
0.621799
kinematics.go
starcoder
package formula import ( "github.com/Chadius/creating-symmetry/entities/formula/coefficient" "math/cmplx" ) // Rosette formulas transform points around a central origin, similar to a rosette surrounding a center. type Rosette struct { formulaLevelTerms []Term } // NewRosetteFormula returns a new formula func NewRosetteFormula(formulaLevelTerms []Term) (*Rosette, error) { return &Rosette{ formulaLevelTerms: formulaLevelTerms, }, nil } // WavePackets returns an empty array, this type of formula does not use WavePackets. func (r *Rosette) WavePackets() []WavePacket { return nil } // Calculate applies the Rosette formula to the complex number z. func (r *Rosette) Calculate(coordinate complex128) complex128 { sumOfTermCalculations := complex(0, 0) for _, term := range r.formulaLevelTerms { termCalculation := r.calculateTerm(term, coordinate) sumOfTermCalculations += termCalculation } return sumOfTermCalculations } func (r *Rosette) calculateTerm(term Term, coordinate complex128) complex128 { sum := complex(0.0, 0.0) coefficientRelationships := []coefficient.Relationship{coefficient.PlusNPlusM} coefficientRelationships = append(coefficientRelationships, term.CoefficientRelationships...) coefficientSets := coefficient.Pairing{ PowerN: term.PowerN, PowerM: term.PowerM, }.GenerateCoefficientSets(coefficientRelationships) for _, relationshipSet := range coefficientSets { multiplier := term.Multiplier if relationshipSet.NegateMultiplier == true { multiplier *= -1 } sum += CalculateExponentTerm(coordinate, relationshipSet.PowerN, relationshipSet.PowerM, multiplier, term.IgnoreComplexConjugate) } return sum } // CalculateExponentTerm calculates (z^power * zConj^conjugatePower) // where z is a complex number, zConj is the complex conjugate // and power and conjugatePower are integers. func CalculateExponentTerm(coordinate complex128, power1, power2 int, scale complex128, ignoreComplexConjugate bool) complex128 { zRaisedToN := cmplx.Pow(coordinate, complex(float64(power1), 0)) if ignoreComplexConjugate { return zRaisedToN * scale } complexConjugate := complex(real(coordinate), -1*imag(coordinate)) complexConjugateRaisedToM := cmplx.Pow(complexConjugate, complex(float64(power2), 0)) return zRaisedToN * complexConjugateRaisedToM * scale } // FormulaLevelTerms returns the terms this formula will use. func (r *Rosette) FormulaLevelTerms() []Term { return r.formulaLevelTerms } // LatticeVectors returns an empty list, this formula does not use them func (r *Rosette) LatticeVectors() []complex128 { return nil } // SymmetriesFound returns all symmetries found in this pattern. func (r *Rosette) SymmetriesFound() []Symmetry { return nil }
entities/formula/rosette.go
0.877451
0.408395
rosette.go
starcoder
package main import ( "math/rand" "sync" "github.com/dhconnelly/rtreego" "github.com/gravestench/mathlib" ) const tol = 0.01 type Boid struct { Id int position rtreego.Point Velocity *mathlib.Vector2 trail []mathlib.Vector2 } func (boid Boid) Bounds() *rtreego.Rect { return boid.position.ToRect(tol) } func (boid *Boid) Position() *mathlib.Vector2 { return mathlib.NewVector2(boid.position[0], boid.position[1]) } func (boid *Boid) calculateVelocity() { var velocityChan = make(chan *mathlib.Vector2, global.velocityComponentCount) var wg sync.WaitGroup wg.Add(global.velocityComponentCount) for _, velocityComponent := range global.velocityComponents { component := velocityComponent go func() { defer wg.Done() velocityChan <- component.Delta(boid) }() } wg.Wait() close(velocityChan) for velocity := range velocityChan { boid.Velocity.Add(velocity) } boid.Velocity.Limit(global.params.maximumVelocity.value()) } func wrap(position *mathlib.Vector2) { switch { case position.X < 0: position.X += fWidth case position.X > fWidth: position.X -= fWidth } switch { case position.Y < 0: position.Y += fHeight case position.Y > fHeight: position.Y -= fHeight } } func (boid *Boid) update(tick int) { position := boid.Position() boid.trail[tick%global.params.trailLength.value()] = *position boid.calculateVelocity() position.Add(boid.Velocity) wrap(position) boid.position = rtreego.Point{position.X, position.Y} } type TrailPixel struct { pixelIndex int colourValue byte } func newTrailPixel(pixelIndex int, colourValue byte) *TrailPixel { return &TrailPixel{pixelIndex, colourValue} } func (boid *Boid) getTrailPixels(tick int, trailChan chan *TrailPixel) { var wg sync.WaitGroup trailLength := global.params.trailLength.value() wg.Add(trailLength) for i := 0; i < trailLength; i++ { trailPartIndex := i go func() { defer wg.Done() trailPosition := boid.trail[(tick+trailPartIndex)%trailLength] x := int(trailPosition.X) y := int(trailPosition.Y) pixelIndex := (y*Width + x) * 4 colourValue := byte(255 * float64(trailLength-trailPartIndex) / float64(trailLength)) trailChan <- newTrailPixel(pixelIndex, colourValue) }() } wg.Wait() close(trailChan) } func newBoid(id int, position *mathlib.Vector2) *Boid { if position == nil { px := rand.Float64() * Width py := rand.Float64() * Height position = mathlib.NewVector2(px, py) } vx := rand.Float64() - .5 vy := rand.Float64() - .5 trailLength := global.params.trailLength.value() trail := make([]mathlib.Vector2, trailLength) for i := 0; i < trailLength; i++ { trail = append(trail, *position) } return &Boid{ Id: id, position: rtreego.Point{position.X, position.Y}, Velocity: mathlib.NewVector2(vx, vy), trail: trail, } }
boid.go
0.673729
0.548008
boid.go
starcoder
package queue const smallSize = 16 // Queue represents a single instance of the queue data structure. The zero // value for a Queue is an empty queue ready to use. type Queue struct { head, tail []interface{} } // Init initializes or clears the Queue. func (q *Queue) Init() { q.head, q.tail = nil, nil } // Cap returns the capacity of the internal buffer. If Cap() equals to Len(), // new Push(x) causes the internal buffer to grow. func (q *Queue) Cap() int { return cap(q.tail) } // Len returns the number of elements currently stored in the Queue. func (q *Queue) Len() int { return len(q.head) + len(q.tail) } // Push inserts an element at the end of the Queue. func (q *Queue) Push(x interface{}) { if ql, qc := q.Len(), q.Cap(); ql == qc { // Grow if full. buf := append(q.tail[:qc], nil) q.setbuf(buf[:cap(buf)]) } if len(q.head) < cap(q.head) { q.head = append(q.head, x) } else { q.tail = append(q.tail, x) } } // Pop removes and returns the first element. It panics if the Queue is empty. func (q *Queue) Pop() interface{} { if len(q.head) > 0 { x := q.head[0] q.head[0] = nil q.head = q.head[1:] if cap(q.head) == 0 { q.head = q.tail q.tail = q.tail[:0] } if ql, qc := q.Len(), q.Cap(); ql == qc>>2 && qc > smallSize { // Shrink if sparse. q.setbuf(make([]interface{}, ql<<1)) } return x } panic("queue: Pop called on empty Queue") } // At returns the i-th element in the Queue. It panics if i is out of range. func (q *Queue) At(i int) interface{} { if i >= 0 { headsize := len(q.head) if i < headsize { return q.head[i] } i -= headsize if i < len(q.tail) { return q.tail[i] } } panic("queue: At called with index out of range") } // Front returns the first element. It panics if the Queue is empty. func (q *Queue) Front() interface{} { if len(q.head) > 0 { return q.head[0] } panic("queue: Front called on empty Queue") } // Back returns the last element. It panics if the Queue is empty. func (q *Queue) Back() interface{} { if n := len(q.tail); n > 0 { return q.tail[n-1] } if n := len(q.head); n > 0 { return q.head[n-1] } panic("queue: Back called on empty Queue") } // CopyTo copies elements of the Queue into a destination slice. CopyTo // returns the number of elements copied, which will be the minimum of // q.Len() and len(dst). func (q *Queue) CopyTo(dst []interface{}) int { n := copy(dst, q.head) return n + copy(dst[n:], q.tail) } // Clone clones the Queue. func (q *Queue) Clone() Queue { var buf []interface{} if q.head != nil { buf = make([]interface{}, q.Len(), q.Cap()) q.CopyTo(buf) } return Queue{buf, buf[:0]} } func (q *Queue) setbuf(buf []interface{}) { q.head, q.tail = buf[:q.CopyTo(buf)], buf[:0] }
internal/queue/queue.go
0.850515
0.49408
queue.go
starcoder
package details import "github.com/gsiems/go-marc21/pkg/marc21" /* http://www.loc.gov/marc/bibliographic/bdintro.html Leader - Data elements that primarily provide information for the processing of the record. The data elements contain numbers or coded values and are identified by relative character position. The Leader is fixed in length at 24 character positions and is the first field of a MARC record. Also: http://www.loc.gov/marc/holdings/hdleader.html http://www.loc.gov/marc/authority/adleader.html http://www.loc.gov/marc/classification/cdleader.html http://www.loc.gov/marc/community/cileader.html While the general leader layout is the same for the different MARC formats there are differences. MARC 21 Bibliography 00-04 - Record length 05 - Record status 06 - Type of record 07 - Bibliographic level 08 - Type of control 09 - Character coding scheme 10 - Indicator count 11 - Subfield code count 12-16 - Base address of data 17 - Encoding level 18 - Descriptive cataloging form 19 - Multipart resource record level 20 - Length of the length-of-field portion 21 - Length of the starting-character-position portion 22 - Length of the implementation-defined portion 23 - Undefined MARC 21 Holdings 00-04 - Record length 05 - Record status 06 - Type of record 07-08 - Undefined character positions 09 - Character coding scheme 10 - Indicator count 11 - Subfield code length 12-16 - Base address of data 17 - Encoding level 18 - Item information in record 19 - Undefined character position 20 - Length of the length-of-field portion 21 - Length of the starting-character-position portion 22 - Length of the implementation-defined portion 23 - Undefined MARC 21 Authority 00-04 - Record length 05 - Record status 06 - Type of record 07-08 - Undefined character positions 09 - Character coding scheme 10 - Indicator count 11 - Subfield code length 12-16 - Base address of data 17 - Encoding level 18 - Punctuation policy 19 - Undefined 20 - Length of the length-of-field portion 21 - Length of the starting-character-position portion 22 - Length of the implementation-defined portion 23 - Undefined MARC 21 Classification 00-04 - Record length 05 - Record status 06 - Type of record 07-08 - Undefined character positions 09 - Character coding scheme 10 - Indicator count 11 - Subfield code length 12-16 - Base address of data 17 - Encoding level 18-19 - Undefined character positions 20 - Length of the length-of-field portion 21 - Length of the starting-character-position portion 22 - Length of the implementation-defined portion 23 - Undefined MARC 21 Community Information 00-04 - Record length 05 - Record status 06 - Type of record 07 - Kind of data 08 - Undefined character position 09 - Character coding scheme 10 - Indicator count 11 - Subfield code length 12-16 - Base address of data 17-19 - Undefined character positions 20 - Length of the length-of-field portion 21 - Length of the starting-character-position portion 22 - Length of the implementation-defined portion 23 - Undefined */ // LdrDesc is the structure for holding the description from the // parsing of the MARC record leader type LdrDesc map[string]CodeValue // ParseLeader parses the leader for a record and returns a, // hopefully, human readable translation of the contents. func ParseLeader(rec marc21.Record) (ldr LdrDesc) { rf := rec.RecordFormat() switch rf { case marc21.Bibliography: return parseBibliographyLdr(rec.Leader.Text) case marc21.Holdings: return parseHoldingsLdr(rec.Leader.Text) case marc21.Community: return parseCommunityLdr(rec.Leader.Text) case marc21.Authority: return parseAuthorityLdr(rec.Leader.Text) case marc21.Classification: return parseClassificationLdr(rec.Leader.Text) } ldr = make(LdrDesc) return ldr }
pkg/details/leader.go
0.720467
0.436082
leader.go
starcoder
package fsm import ( "fmt" ) // State represents a possible transition state for the FSM type State string // FSM is an interface that defines the operation of different types of // state machines. Note that the interface does not include a Transition() function // that should be implemented separately by each concrete type of FSM. type FSM interface { State() State Allowable(from, to State) bool transition(to State, guards ...transitionGuard) error reset() error } // Machine is a basic finite state machine type Machine struct { current State initial State allowable map[State][]State stoppable stoppable } // NewMachine returns a new basic Machine with configured options. If you do not utilize any // options, the machine will not have any configured transitions. func NewMachine(initial State, opts ...MachineOption) (*Machine, error) { machine := &Machine{ current: initial, initial: initial, allowable: map[State][]State{}, } for _, opt := range opts { if err := opt(machine); err != nil { return nil, err } } return machine, nil } // State returns the current state of the Machine func (m *Machine) State() State { return m.current } // Allowable checks whether a transition between two states is allowable func (m *Machine) Allowable(from, to State) bool { return contains(to, m.allowable[from]) } // Transition will change the current state of the machine if it is allowable func (m *Machine) Transition(to State) error { return m.transition(to, m.stoppable) } // Reset will reset the machine to its initial state and remove any stop condition if it // exists func (m *Machine) Reset() { m.reset() } func (m *Machine) reset() error { m.current = m.initial m.stoppable.stopped = false return nil } func (m *Machine) transition(to State, guards ...transitionGuard) error { for _, guard := range guards { if err := guard.ok(); err != nil { m.stoppable.stopped = true return err } } switch m.Allowable(m.current, to) { case true: m.current = to return nil default: m.stoppable.stopped = true return TransitionNotAllowed{Msg: fmt.Sprintf("cannot transition from state %s to %s", m.current, to)} } } func contains(s State, all []State) bool { for _, a := range all { if s == a { return true } } return false }
pkg/fsm/fsm.go
0.824321
0.473414
fsm.go
starcoder
package quadtree import ( "code.google.com/p/draw2d/draw2d" "image" "image/color" "image/draw" "image/png" "bufio" "log" "os" ) type QuadTree struct { MaxPointsPerNode int points []image.Point BoundingBox image.Rectangle BLeft, TLeft *QuadTree BRight, TRight *QuadTree hasChildren bool } func (q *QuadTree) InsertPoint(p image.Point) { if q.hasChildren { if p.In(q.BLeft.BoundingBox) { q.BLeft.InsertPoint(p) return } if p.In(q.BRight.BoundingBox) { q.BRight.InsertPoint(p) return } if p.In(q.TLeft.BoundingBox) { q.TLeft.InsertPoint(p) return } if p.In(q.TRight.BoundingBox) { q.TRight.InsertPoint(p) return } return } q.points = append(q.points, p) if !q.acceptingPoints() && !q.hasChildren { q.rebalance() } } func (q *QuadTree) acceptingPoints() bool { return len(q.points) < q.MaxPointsPerNode } func (q *QuadTree) LowerLeft() image.Rectangle { min := image.Point{q.BoundingBox.Min.X, q.BoundingBox.Max.Y} return image.Rect( (q.BoundingBox.Min.X+min.X)/2, (q.BoundingBox.Min.Y+min.Y)/2, (q.BoundingBox.Max.X+min.X)/2, (q.BoundingBox.Max.Y+min.Y)/2, ) } func (q *QuadTree) UpperLeft() image.Rectangle { return image.Rect( q.BoundingBox.Min.X, q.BoundingBox.Min.Y, (q.BoundingBox.Min.X+q.BoundingBox.Max.X)/2, (q.BoundingBox.Min.Y+q.BoundingBox.Max.Y)/2, ) } func (q *QuadTree) UpperRight() image.Rectangle { max := image.Point{q.BoundingBox.Max.X, q.BoundingBox.Min.Y} return image.Rect( (q.BoundingBox.Min.X+max.X)/2, q.BoundingBox.Min.Y, max.X, (q.BoundingBox.Max.Y+max.Y)/2, ) } func (q *QuadTree) LowerRight() image.Rectangle { Min := q.UpperLeft().Max return image.Rect( Min.X, Min.Y, q.BoundingBox.Max.X, q.BoundingBox.Max.Y, ) } func (q *QuadTree) rebalance() { if q.acceptingPoints() { return } q.TLeft = &QuadTree{ MaxPointsPerNode: q.MaxPointsPerNode, BoundingBox: q.UpperLeft(), } q.BLeft = &QuadTree{ MaxPointsPerNode: q.MaxPointsPerNode, BoundingBox: q.LowerLeft(), } q.TRight = &QuadTree{ MaxPointsPerNode: q.MaxPointsPerNode, BoundingBox: q.UpperRight(), } q.BRight = &QuadTree{ MaxPointsPerNode: q.MaxPointsPerNode, BoundingBox: q.LowerRight(), } for _, p := range q.points { if p.In(q.BLeft.BoundingBox) { q.BLeft.InsertPoint(p) continue } if p.In(q.BRight.BoundingBox) { q.BRight.InsertPoint(p) continue } if p.In(q.TLeft.BoundingBox) { q.TLeft.InsertPoint(p) continue } if p.In(q.TRight.BoundingBox) { q.TRight.InsertPoint(p) continue } } q.hasChildren = true } func (q QuadTree) Walk() []QuadTree { if q.acceptingPoints() { return []QuadTree{q} } if q.hasChildren { var nodes []QuadTree nodes = append(nodes, q.BLeft.Walk()...) nodes = append(nodes, q.TLeft.Walk()...) nodes = append(nodes, q.TRight.Walk()...) return append(nodes, q.BRight.Walk()...) } return []QuadTree{} } func saveToPngFile(filePath string, m image.Image) error { f, err := os.Create(filePath) if err != nil { log.Println(err) os.Exit(1) } defer f.Close() b := bufio.NewWriter(f) err = png.Encode(b, m) if err != nil { log.Println(err) os.Exit(1) } return b.Flush() } func (q *QuadTree) drawOnContext(gc *draw2d.ImageGraphicContext) { max := image.Point{q.BoundingBox.Max.X, q.BoundingBox.Min.Y} min := image.Point{q.BoundingBox.Min.X, q.BoundingBox.Max.Y} gc.MoveTo(float64(q.BoundingBox.Min.X), float64(q.BoundingBox.Min.Y)) gc.LineTo(float64(max.X), float64(max.Y)) gc.LineTo(float64(q.BoundingBox.Max.X), float64(q.BoundingBox.Max.Y)) gc.LineTo(float64(min.X), float64(min.Y)) gc.Stroke() } func drawDot(gc *draw2d.ImageGraphicContext, p image.Point) { gc.MoveTo(float64(p.X), float64(p.Y)) gc.LineTo(float64(p.X+3), float64(p.Y+3)) gc.Stroke() } func (q *QuadTree) Draw(fpath string) error { Nodes := q.Walk() img := image.NewRGBA(image.Rect(0, 0, q.BoundingBox.Max.X, q.BoundingBox.Max.Y)) draw.Draw(img, q.BoundingBox, &image.Uniform{color.White}, image.Point{0, 0}, draw.Over) gc := draw2d.NewGraphicContext(img) for _, node := range Nodes { node.drawOnContext(gc) for _, point := range node.points { drawDot(gc, point) } } return saveToPngFile(fpath, img) }
ds-algorithms/quadtree/qtree.go
0.590543
0.457985
qtree.go
starcoder
package v1 import ( "context" "reflect" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Gets the details of a rate plan. func LookupRatePlan(ctx *pulumi.Context, args *LookupRatePlanArgs, opts ...pulumi.InvokeOption) (*LookupRatePlanResult, error) { var rv LookupRatePlanResult err := ctx.Invoke("google-native:apigee/v1:getRatePlan", args, &rv, opts...) if err != nil { return nil, err } return &rv, nil } type LookupRatePlanArgs struct { ApiproductId string `pulumi:"apiproductId"` OrganizationId string `pulumi:"organizationId"` RateplanId string `pulumi:"rateplanId"` } type LookupRatePlanResult struct { // Name of the API product that the rate plan is associated with. Apiproduct string `pulumi:"apiproduct"` // Frequency at which the customer will be billed. BillingPeriod string `pulumi:"billingPeriod"` // API call volume ranges and the fees charged when the total number of API calls is within a given range. The method used to calculate the final fee depends on the selected pricing model. For example, if the pricing model is `STAIRSTEP` and the ranges are defined as follows: ```{ "start": 1, "end": 100, "fee": 75 }, { "start": 101, "end": 200, "fee": 100 }, }``` Then the following fees would be charged based on the total number of API calls (assuming the currency selected is `USD`): * 1 call costs $75 * 50 calls cost $75 * 150 calls cost $100 The number of API calls cannot exceed 200. ConsumptionPricingRates []GoogleCloudApigeeV1RateRangeResponse `pulumi:"consumptionPricingRates"` // Pricing model used for consumption-based charges. ConsumptionPricingType string `pulumi:"consumptionPricingType"` // Time that the rate plan was created in milliseconds since epoch. CreatedAt string `pulumi:"createdAt"` // Currency to be used for billing. Consists of a three-letter code as defined by the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) standard. CurrencyCode string `pulumi:"currencyCode"` // Description of the rate plan. Description string `pulumi:"description"` // Display name of the rate plan. DisplayName string `pulumi:"displayName"` // Time when the rate plan will expire in milliseconds since epoch. Set to 0 or `null` to indicate that the rate plan should never expire. EndTime string `pulumi:"endTime"` // Frequency at which the fixed fee is charged. FixedFeeFrequency int `pulumi:"fixedFeeFrequency"` // Fixed amount that is charged at a defined interval and billed in advance of use of the API product. The fee will be prorated for the first billing period. FixedRecurringFee GoogleTypeMoneyResponse `pulumi:"fixedRecurringFee"` // Time the rate plan was last modified in milliseconds since epoch. LastModifiedAt string `pulumi:"lastModifiedAt"` // Name of the rate plan. Name string `pulumi:"name"` // Details of the revenue sharing model. RevenueShareRates []GoogleCloudApigeeV1RevenueShareRangeResponse `pulumi:"revenueShareRates"` // Method used to calculate the revenue that is shared with developers. RevenueShareType string `pulumi:"revenueShareType"` // Initial, one-time fee paid when purchasing the API product. SetupFee GoogleTypeMoneyResponse `pulumi:"setupFee"` // Time when the rate plan becomes active in milliseconds since epoch. StartTime string `pulumi:"startTime"` // Current state of the rate plan (draft or published). State string `pulumi:"state"` } func LookupRatePlanOutput(ctx *pulumi.Context, args LookupRatePlanOutputArgs, opts ...pulumi.InvokeOption) LookupRatePlanResultOutput { return pulumi.ToOutputWithContext(context.Background(), args). ApplyT(func(v interface{}) (LookupRatePlanResult, error) { args := v.(LookupRatePlanArgs) r, err := LookupRatePlan(ctx, &args, opts...) return *r, err }).(LookupRatePlanResultOutput) } type LookupRatePlanOutputArgs struct { ApiproductId pulumi.StringInput `pulumi:"apiproductId"` OrganizationId pulumi.StringInput `pulumi:"organizationId"` RateplanId pulumi.StringInput `pulumi:"rateplanId"` } func (LookupRatePlanOutputArgs) ElementType() reflect.Type { return reflect.TypeOf((*LookupRatePlanArgs)(nil)).Elem() } type LookupRatePlanResultOutput struct{ *pulumi.OutputState } func (LookupRatePlanResultOutput) ElementType() reflect.Type { return reflect.TypeOf((*LookupRatePlanResult)(nil)).Elem() } func (o LookupRatePlanResultOutput) ToLookupRatePlanResultOutput() LookupRatePlanResultOutput { return o } func (o LookupRatePlanResultOutput) ToLookupRatePlanResultOutputWithContext(ctx context.Context) LookupRatePlanResultOutput { return o } // Name of the API product that the rate plan is associated with. func (o LookupRatePlanResultOutput) Apiproduct() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.Apiproduct }).(pulumi.StringOutput) } // Frequency at which the customer will be billed. func (o LookupRatePlanResultOutput) BillingPeriod() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.BillingPeriod }).(pulumi.StringOutput) } // API call volume ranges and the fees charged when the total number of API calls is within a given range. The method used to calculate the final fee depends on the selected pricing model. For example, if the pricing model is `STAIRSTEP` and the ranges are defined as follows: ```{ "start": 1, "end": 100, "fee": 75 }, { "start": 101, "end": 200, "fee": 100 }, }``` Then the following fees would be charged based on the total number of API calls (assuming the currency selected is `USD`): * 1 call costs $75 * 50 calls cost $75 * 150 calls cost $100 The number of API calls cannot exceed 200. func (o LookupRatePlanResultOutput) ConsumptionPricingRates() GoogleCloudApigeeV1RateRangeResponseArrayOutput { return o.ApplyT(func(v LookupRatePlanResult) []GoogleCloudApigeeV1RateRangeResponse { return v.ConsumptionPricingRates }).(GoogleCloudApigeeV1RateRangeResponseArrayOutput) } // Pricing model used for consumption-based charges. func (o LookupRatePlanResultOutput) ConsumptionPricingType() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.ConsumptionPricingType }).(pulumi.StringOutput) } // Time that the rate plan was created in milliseconds since epoch. func (o LookupRatePlanResultOutput) CreatedAt() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.CreatedAt }).(pulumi.StringOutput) } // Currency to be used for billing. Consists of a three-letter code as defined by the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) standard. func (o LookupRatePlanResultOutput) CurrencyCode() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.CurrencyCode }).(pulumi.StringOutput) } // Description of the rate plan. func (o LookupRatePlanResultOutput) Description() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.Description }).(pulumi.StringOutput) } // Display name of the rate plan. func (o LookupRatePlanResultOutput) DisplayName() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.DisplayName }).(pulumi.StringOutput) } // Time when the rate plan will expire in milliseconds since epoch. Set to 0 or `null` to indicate that the rate plan should never expire. func (o LookupRatePlanResultOutput) EndTime() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.EndTime }).(pulumi.StringOutput) } // Frequency at which the fixed fee is charged. func (o LookupRatePlanResultOutput) FixedFeeFrequency() pulumi.IntOutput { return o.ApplyT(func(v LookupRatePlanResult) int { return v.FixedFeeFrequency }).(pulumi.IntOutput) } // Fixed amount that is charged at a defined interval and billed in advance of use of the API product. The fee will be prorated for the first billing period. func (o LookupRatePlanResultOutput) FixedRecurringFee() GoogleTypeMoneyResponseOutput { return o.ApplyT(func(v LookupRatePlanResult) GoogleTypeMoneyResponse { return v.FixedRecurringFee }).(GoogleTypeMoneyResponseOutput) } // Time the rate plan was last modified in milliseconds since epoch. func (o LookupRatePlanResultOutput) LastModifiedAt() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.LastModifiedAt }).(pulumi.StringOutput) } // Name of the rate plan. func (o LookupRatePlanResultOutput) Name() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.Name }).(pulumi.StringOutput) } // Details of the revenue sharing model. func (o LookupRatePlanResultOutput) RevenueShareRates() GoogleCloudApigeeV1RevenueShareRangeResponseArrayOutput { return o.ApplyT(func(v LookupRatePlanResult) []GoogleCloudApigeeV1RevenueShareRangeResponse { return v.RevenueShareRates }).(GoogleCloudApigeeV1RevenueShareRangeResponseArrayOutput) } // Method used to calculate the revenue that is shared with developers. func (o LookupRatePlanResultOutput) RevenueShareType() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.RevenueShareType }).(pulumi.StringOutput) } // Initial, one-time fee paid when purchasing the API product. func (o LookupRatePlanResultOutput) SetupFee() GoogleTypeMoneyResponseOutput { return o.ApplyT(func(v LookupRatePlanResult) GoogleTypeMoneyResponse { return v.SetupFee }).(GoogleTypeMoneyResponseOutput) } // Time when the rate plan becomes active in milliseconds since epoch. func (o LookupRatePlanResultOutput) StartTime() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.StartTime }).(pulumi.StringOutput) } // Current state of the rate plan (draft or published). func (o LookupRatePlanResultOutput) State() pulumi.StringOutput { return o.ApplyT(func(v LookupRatePlanResult) string { return v.State }).(pulumi.StringOutput) } func init() { pulumi.RegisterOutputType(LookupRatePlanResultOutput{}) }
sdk/go/google/apigee/v1/getRatePlan.go
0.819099
0.649273
getRatePlan.go
starcoder