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 bufferChanLearning //buffer is a buffer type buffer struct { ChOut chan int //ChOut, the channel out to be read by client Slice []int //Slice which is the actual buffer confirmNewRead chan bool //used to wait for confirmation of grabbing the next value from input channel. size int //size of buffer } //NewBuffer creates a new buffer, takes the buffer size as an input argument, and returns a *buffer. func NewBuffer(m int) *buffer { return &buffer{ ChOut: make(chan int), confirmNewRead: make(chan bool), size: m, } } //Start will start filling the buffer, to continue filling buffer use the readNext method. func (b *buffer) Start(chIn chan int) { go func() { for len(b.Slice) < b.size-1 { v, ok := <-chIn if !ok { //log.Println("SERVER: done reading chIn in the slice filling loop at the top") break } b.Slice = append(b.Slice, v) } //Loop and read another value as long as the slice is > 0. // Since we fill the buffer when we start as the first thing // the only reason for the length of the slice is 0 is that // the input channel is closed, and the decrement of the channel // value by value have started. for len(b.Slice) > 0 { v, ok := <-chIn //input channel closed ? if !ok { b.Slice = b.Slice[1:] } //length of slice already full ? if len(b.Slice) == b.size { b.Slice = b.Slice[1:] b.Slice = append(b.Slice, v) } //input channel not closed, and slice buffer not filled to size. if ok && len(b.Slice) < b.size { b.Slice = append(b.Slice, v) } //slice have been emptied, break out of for loop. if len(b.Slice) == 0 { break } b.ChOut <- b.Slice[0] //Wait for confirmation for another read from main. <-b.confirmNewRead } close(b.ChOut) }() } //ReadNext will, relese the lock on the go routine inside the start method, //and let it read another value from the incomming channel and put it //into the buffer. func (b *buffer) ReadNext() { b.confirmNewRead <- true }
concurrency/17-slice-buffer-reading-from-channel/main.go
0.526099
0.452778
main.go
starcoder
// Package scene encodes and decodes graphics commands in the format used by the // compute renderer. package scene import ( "image/color" "math" "unsafe" "gioui.org/f32" ) type Op uint32 type Command [sceneElemSize / 4]uint32 // GPU commands from scene.h const ( OpNop Op = iota OpLine OpQuad OpCubic OpFillColor OpLineWidth OpTransform OpBeginClip OpEndClip OpFillImage OpSetFillMode ) // FillModes, from setup.h. type FillMode uint32 const ( FillModeNonzero = 0 FillModeStroke = 1 ) const CommandSize = int(unsafe.Sizeof(Command{})) const sceneElemSize = 36 func (c Command) Op() Op { return Op(c[0]) } func Line(start, end f32.Point) Command { return Command{ 0: uint32(OpLine), 1: math.Float32bits(start.X), 2: math.Float32bits(start.Y), 3: math.Float32bits(end.X), 4: math.Float32bits(end.Y), } } func Cubic(start, ctrl0, ctrl1, end f32.Point) Command { return Command{ 0: uint32(OpCubic), 1: math.Float32bits(start.X), 2: math.Float32bits(start.Y), 3: math.Float32bits(ctrl0.X), 4: math.Float32bits(ctrl0.Y), 5: math.Float32bits(ctrl1.X), 6: math.Float32bits(ctrl1.Y), 7: math.Float32bits(end.X), 8: math.Float32bits(end.Y), } } func Quad(start, ctrl, end f32.Point) Command { return Command{ 0: uint32(OpQuad), 1: math.Float32bits(start.X), 2: math.Float32bits(start.Y), 3: math.Float32bits(ctrl.X), 4: math.Float32bits(ctrl.Y), 5: math.Float32bits(end.X), 6: math.Float32bits(end.Y), } } func Transform(m f32.Affine2D) Command { sx, hx, ox, hy, sy, oy := m.Elems() return Command{ 0: uint32(OpTransform), 1: math.Float32bits(sx), 2: math.Float32bits(hy), 3: math.Float32bits(hx), 4: math.Float32bits(sy), 5: math.Float32bits(ox), 6: math.Float32bits(oy), } } func SetLineWidth(width float32) Command { return Command{ 0: uint32(OpLineWidth), 1: math.Float32bits(width), } } func BeginClip(bbox f32.Rectangle) Command { return Command{ 0: uint32(OpBeginClip), 1: math.Float32bits(bbox.Min.X), 2: math.Float32bits(bbox.Min.Y), 3: math.Float32bits(bbox.Max.X), 4: math.Float32bits(bbox.Max.Y), } } func EndClip(bbox f32.Rectangle) Command { return Command{ 0: uint32(OpEndClip), 1: math.Float32bits(bbox.Min.X), 2: math.Float32bits(bbox.Min.Y), 3: math.Float32bits(bbox.Max.X), 4: math.Float32bits(bbox.Max.Y), } } func FillColor(col color.RGBA) Command { return Command{ 0: uint32(OpFillColor), 1: uint32(col.R)<<24 | uint32(col.G)<<16 | uint32(col.B)<<8 | uint32(col.A), } } func FillImage(index int) Command { return Command{ 0: uint32(OpFillImage), 1: uint32(index), } } func SetFillMode(mode FillMode) Command { return Command{ 0: uint32(OpSetFillMode), 1: uint32(mode), } } func DecodeLine(cmd Command) (from, to f32.Point) { if cmd[0] != uint32(OpLine) { panic("invalid command") } from = f32.Pt(math.Float32frombits(cmd[1]), math.Float32frombits(cmd[2])) to = f32.Pt(math.Float32frombits(cmd[3]), math.Float32frombits(cmd[4])) return } func DecodeQuad(cmd Command) (from, ctrl, to f32.Point) { if cmd[0] != uint32(OpQuad) { panic("invalid command") } from = f32.Pt(math.Float32frombits(cmd[1]), math.Float32frombits(cmd[2])) ctrl = f32.Pt(math.Float32frombits(cmd[3]), math.Float32frombits(cmd[4])) to = f32.Pt(math.Float32frombits(cmd[5]), math.Float32frombits(cmd[6])) return } func DecodeCubic(cmd Command) (from, ctrl0, ctrl1, to f32.Point) { if cmd[0] != uint32(OpCubic) { panic("invalid command") } from = f32.Pt(math.Float32frombits(cmd[1]), math.Float32frombits(cmd[2])) ctrl0 = f32.Pt(math.Float32frombits(cmd[3]), math.Float32frombits(cmd[4])) ctrl1 = f32.Pt(math.Float32frombits(cmd[5]), math.Float32frombits(cmd[6])) to = f32.Pt(math.Float32frombits(cmd[7]), math.Float32frombits(cmd[8])) return }
internal/scene/scene.go
0.637821
0.546799
scene.go
starcoder
package etensor import ( "errors" "fmt" "log" "strings" "github.com/apache/arrow/go/arrow" "github.com/emer/etable/bitslice" "github.com/goki/ki/ints" "github.com/goki/ki/kit" "gonum.org/v1/gonum/mat" ) // BoolType not in arrow.. type BoolType struct{} func (t *BoolType) ID() arrow.Type { return arrow.BOOL } func (t *BoolType) Name() string { return "bool" } func (t *BoolType) BitWidth() int { return 1 } // etensor.Bits is a tensor of bits backed by a bitslice.Slice for efficient storage // of binary data type Bits struct { Shape Values bitslice.Slice Meta map[string]string } // NewBits returns a new n-dimensional array of bits // If strides is nil, row-major strides will be inferred. // If names is nil, a slice of empty strings will be created. func NewBits(shape, strides []int, names []string) *Bits { bt := &Bits{} bt.SetShape(shape, strides, names) ln := bt.Len() bt.Values = bitslice.Make(ln, 0) return bt } // NewBitsShape returns a new n-dimensional array of bits // If strides is nil, row-major strides will be inferred. // If names is nil, a slice of empty strings will be created. func NewBitsShape(shape *Shape) *Bits { bt := &Bits{} bt.CopyShape(shape) ln := bt.Len() bt.Values = bitslice.Make(ln, 0) return bt } func (tsr *Bits) ShapeObj() *Shape { return &tsr.Shape } func (tsr *Bits) DataType() Type { return BOOL } // Value returns value at given tensor index func (tsr *Bits) Value(i []int) bool { j := int(tsr.Offset(i)); return tsr.Values.Index(j) } // Value1D returns value at given tensor 1D (flat) index func (tsr *Bits) Value1D(i int) bool { return tsr.Values.Index(i) } func (tsr *Bits) Set(i []int, val bool) { j := int(tsr.Offset(i)); tsr.Values.Set(j, val) } func (tsr *Bits) Set1D(i int, val bool) { tsr.Values.Set(i, val) } // Null not supported for bits func (tsr *Bits) IsNull(i []int) bool { return false } func (tsr *Bits) IsNull1D(i int) bool { return false } func (tsr *Bits) SetNull(i []int, nul bool) {} func (tsr *Bits) SetNull1D(i int, nul bool) {} func Float64ToBool(val float64) bool { bv := true if val == 0 { bv = false } return bv } func BoolToFloat64(bv bool) float64 { if bv { return 1 } else { return 0 } } func (tsr *Bits) FloatVal(i []int) float64 { j := tsr.Offset(i) return BoolToFloat64(tsr.Values.Index(j)) } func (tsr *Bits) SetFloat(i []int, val float64) { j := tsr.Offset(i) tsr.Values.Set(j, Float64ToBool(val)) } func (tsr *Bits) StringVal(i []int) string { j := tsr.Offset(i) return kit.ToString(tsr.Values.Index(j)) } func (tsr *Bits) SetString(i []int, val string) { if bv, ok := kit.ToBool(val); ok { j := tsr.Offset(i) tsr.Values.Set(j, bv) } } func (tsr *Bits) FloatVal1D(off int) float64 { return BoolToFloat64(tsr.Values.Index(off)) } func (tsr *Bits) SetFloat1D(off int, val float64) { tsr.Values.Set(off, Float64ToBool(val)) } func (tsr *Bits) FloatValRowCell(row, cell int) float64 { _, sz := tsr.RowCellSize() return BoolToFloat64(tsr.Values.Index(row*sz + cell)) } func (tsr *Bits) SetFloatRowCell(row, cell int, val float64) { _, sz := tsr.RowCellSize() tsr.Values.Set(row*sz+cell, Float64ToBool(val)) } func (tsr *Bits) Floats(flt *[]float64) { sz := tsr.Len() SetFloat64SliceLen(flt, sz) for j := 0; j < sz; j++ { (*flt)[j] = BoolToFloat64(tsr.Values.Index(j)) } } // SetFloats sets tensor values from a []float64 slice (copies values). func (tsr *Bits) SetFloats(vals []float64) { sz := ints.MinInt(tsr.Len(), len(vals)) for j := 0; j < sz; j++ { tsr.Values.Set(j, Float64ToBool(vals[j])) } } func (tsr *Bits) StringVal1D(off int) string { return kit.ToString(tsr.Values.Index(off)) } func (tsr *Bits) SetString1D(off int, val string) { if bv, ok := kit.ToBool(val); ok { tsr.Values.Set(off, bv) } } func (tsr *Bits) StringValRowCell(row, cell int) string { _, sz := tsr.RowCellSize() return kit.ToString(tsr.Values.Index(row*sz + cell)) } func (tsr *Bits) SetStringRowCell(row, cell int, val string) { if bv, ok := kit.ToBool(val); ok { _, sz := tsr.RowCellSize() tsr.Values.Set(row*sz+cell, bv) } } // SubSpace is not applicable to Bits tensor func (tsr *Bits) SubSpace(offs []int) Tensor { return nil } // SubSpaceTry is not applicable to Bits tensor func (tsr *Bits) SubSpaceTry(offs []int) (Tensor, error) { return nil, errors.New("etensor.Bits does not support SubSpace") } // Range is not applicable to Bits tensor func (tsr *Bits) Range() (min, max float64, minIdx, maxIdx int) { minIdx = -1 maxIdx = -1 return } // Agg applies given aggregation function to each element in the tensor // (automatically skips IsNull and NaN elements), using float64 conversions of the values. // init is the initial value for the agg variable. returns final aggregate value func (tsr *Bits) Agg(ini float64, fun AggFunc) float64 { ln := tsr.Len() ag := ini for j := 0; j < ln; j++ { ag = fun(j, BoolToFloat64(tsr.Values.Index(j)), ag) } return ag } // Eval applies given function to each element in the tensor, using float64 // conversions of the values, and puts the results into given float64 slice, which is // ensured to be of the proper length func (tsr *Bits) Eval(res *[]float64, fun EvalFunc) { ln := tsr.Len() if len(*res) != ln { *res = make([]float64, ln) } for j := 0; j < ln; j++ { (*res)[j] = fun(j, BoolToFloat64(tsr.Values.Index(j))) } } // SetFunc applies given function to each element in the tensor, using float64 // conversions of the values, and writes the results back into the same tensor values func (tsr *Bits) SetFunc(fun EvalFunc) { ln := tsr.Len() for j := 0; j < ln; j++ { tsr.Values.Set(j, Float64ToBool(fun(j, BoolToFloat64(tsr.Values.Index(j))))) } } // SetZeros is simple convenience function initialize all values to 0 func (tsr *Bits) SetZeros() { ln := tsr.Len() for j := 0; j < ln; j++ { tsr.Values.Set(j, false) } } // Clone clones this tensor, creating a duplicate copy of itself with its // own separate memory representation of all the values, and returns // that as a Tensor (which can be converted into the known type as needed). func (tsr *Bits) Clone() Tensor { csr := NewBitsShape(&tsr.Shape) csr.Values = tsr.Values.Clone() return csr } // CopyFrom copies all avail values from other tensor into this tensor, with an // optimized implementation if the other tensor is of the same type, and // otherwise it goes through appropriate standard type. // Copies Null state as well if present. func (tsr *Bits) CopyFrom(frm Tensor) { if fsm, ok := frm.(*Bits); ok { copy(tsr.Values, fsm.Values) return } sz := ints.MinInt(len(tsr.Values), frm.Len()) for i := 0; i < sz; i++ { tsr.Values.Set(i, Float64ToBool(frm.FloatVal1D(i))) } } // CopyShapeFrom copies just the shape from given source tensor // calling SetShape with the shape params from source (see for more docs). func (tsr *Bits) CopyShapeFrom(frm Tensor) { tsr.SetShape(frm.Shapes(), frm.Strides(), frm.DimNames()) } // CopyCellsFrom copies given range of values from other tensor into this tensor, // using flat 1D indexes: to = starting index in this Tensor to start copying into, // start = starting index on from Tensor to start copying from, and n = number of // values to copy. Uses an optimized implementation if the other tensor is // of the same type, and otherwise it goes through appropriate standard type. func (tsr *Bits) CopyCellsFrom(frm Tensor, to, start, n int) { if fsm, ok := frm.(*Bits); ok { for i := 0; i < n; i++ { tsr.Values.Set(to+i, fsm.Values.Index(start+i)) } return } for i := 0; i < n; i++ { tsr.Values.Set(to+i, Float64ToBool(frm.FloatVal1D(start+i))) } } // SetShape sets the shape params, resizing backing storage appropriately func (tsr *Bits) SetShape(shape, strides []int, names []string) { tsr.Shape.SetShape(shape, strides, names) nln := tsr.Len() tsr.Values.SetLen(nln) } // SetNumRows sets the number of rows (outer-most dimension) in a RowMajor organized tensor. func (tsr *Bits) SetNumRows(rows int) { if !tsr.IsRowMajor() { return } rows = ints.MaxInt(1, rows) // must be > 0 cln := tsr.Len() crows := tsr.Dim(0) inln := cln / crows // length of inner dims nln := rows * inln tsr.Shape.Shp[0] = rows tsr.Values.SetLen(nln) } // Dims is the gonum/mat.Matrix interface method for returning the dimensionality of the // 2D Matrix. Not supported for Bits -- do not call! func (tsr *Bits) Dims() (r, c int) { log.Println("etensor Dims gonum Matrix call made on Bits Tensor -- not supported") return 0, 0 } // At is the gonum/mat.Matrix interface method for returning 2D matrix element at given // row, column index. Not supported for Bits -- do not call! func (tsr *Bits) At(i, j int) float64 { log.Println("etensor At gonum Matrix call made on Bits Tensor -- not supported") return 0 } // T is the gonum/mat.Matrix transpose method. // Not supported for Bits -- do not call! func (tsr *Bits) T() mat.Matrix { log.Println("etensor T gonum Matrix call made on Bits Tensor -- not supported") return mat.Transpose{tsr} } // Label satisfies the gi.Labeler interface for a summary description of the tensor func (tsr *Bits) Label() string { return fmt.Sprintf("Bits: %s", tsr.Shape.String()) } // String satisfies the fmt.Stringer interface for string of tensor data func (tsr *Bits) String() string { str := tsr.Label() sz := tsr.Len() if sz > 1000 { return str } var b strings.Builder b.WriteString(str) b.WriteString("\n") oddRow := true rows, cols, _, _ := Prjn2DShape(&tsr.Shape, oddRow) for r := 0; r < rows; r++ { rc, _ := Prjn2DCoords(&tsr.Shape, oddRow, r, 0) b.WriteString(fmt.Sprintf("%v: ", rc)) for c := 0; c < cols; c++ { vl := Prjn2DVal(tsr, oddRow, r, c) b.WriteString(fmt.Sprintf("%g ", vl)) } b.WriteString("\n") } return b.String() } // SetMetaData sets a key=value meta data (stored as a map[string]string). // For TensorGrid display: top-zero=+/-, odd-row=+/-, image=+/-, // min, max set fixed min / max values, background=color func (tsr *Bits) SetMetaData(key, val string) { if tsr.Meta == nil { tsr.Meta = make(map[string]string) } tsr.Meta[key] = val } // MetaData retrieves value of given key, bool = false if not set func (tsr *Bits) MetaData(key string) (string, bool) { if tsr.Meta == nil { return "", false } val, ok := tsr.Meta[key] return val, ok } // MetaDataMap returns the underlying map used for meta data func (tsr *Bits) MetaDataMap() map[string]string { return tsr.Meta } // CopyMetaData copies meta data from given source tensor func (tsr *Bits) CopyMetaData(frm Tensor) { fmap := frm.MetaDataMap() if len(fmap) == 0 { return } if tsr.Meta == nil { tsr.Meta = make(map[string]string) } for k, v := range fmap { tsr.Meta[k] = v } }
etensor/bits.go
0.734976
0.412234
bits.go
starcoder
package iterator import "github.com/gopherd/gonum/graph" // OrderedEdges implements the graph.Edges and graph.EdgeSlicer interfaces. // The iteration order of OrderedEdges is the order of edges passed to // NewEdgeIterator. type OrderedEdges struct { idx int edges []graph.Edge } // NewOrderedEdges returns an OrderedEdges initialized with the provided edges. func NewOrderedEdges(edges []graph.Edge) *OrderedEdges { return &OrderedEdges{idx: -1, edges: edges} } // Len returns the remaining number of edges to be iterated over. func (e *OrderedEdges) Len() int { if e.idx >= len(e.edges) { return 0 } if e.idx <= 0 { return len(e.edges) } return len(e.edges[e.idx:]) } // Next returns whether the next call of Edge will return a valid edge. func (e *OrderedEdges) Next() bool { if uint(e.idx)+1 < uint(len(e.edges)) { e.idx++ return true } e.idx = len(e.edges) return false } // Edge returns the current edge of the iterator. Next must have been // called prior to a call to Edge. func (e *OrderedEdges) Edge() graph.Edge { if e.idx >= len(e.edges) || e.idx < 0 { return nil } return e.edges[e.idx] } // EdgeSlice returns all the remaining edges in the iterator and advances // the iterator. func (e *OrderedEdges) EdgeSlice() []graph.Edge { if e.idx >= len(e.edges) { return nil } idx := e.idx if idx == -1 { idx = 0 } e.idx = len(e.edges) return e.edges[idx:] } // Reset returns the iterator to its initial state. func (e *OrderedEdges) Reset() { e.idx = -1 } // OrderedWeightedEdges implements the graph.Edges and graph.EdgeSlicer interfaces. // The iteration order of OrderedWeightedEdges is the order of edges passed to // NewEdgeIterator. type OrderedWeightedEdges struct { idx int edges []graph.WeightedEdge } // NewOrderedWeightedEdges returns an OrderedWeightedEdges initialized with the provided edges. func NewOrderedWeightedEdges(edges []graph.WeightedEdge) *OrderedWeightedEdges { return &OrderedWeightedEdges{idx: -1, edges: edges} } // Len returns the remaining number of edges to be iterated over. func (e *OrderedWeightedEdges) Len() int { if e.idx >= len(e.edges) { return 0 } if e.idx <= 0 { return len(e.edges) } return len(e.edges[e.idx:]) } // Next returns whether the next call of WeightedEdge will return a valid edge. func (e *OrderedWeightedEdges) Next() bool { if uint(e.idx)+1 < uint(len(e.edges)) { e.idx++ return true } e.idx = len(e.edges) return false } // WeightedEdge returns the current edge of the iterator. Next must have been // called prior to a call to WeightedEdge. func (e *OrderedWeightedEdges) WeightedEdge() graph.WeightedEdge { if e.idx >= len(e.edges) || e.idx < 0 { return nil } return e.edges[e.idx] } // WeightedEdgeSlice returns all the remaining edges in the iterator and advances // the iterator. func (e *OrderedWeightedEdges) WeightedEdgeSlice() []graph.WeightedEdge { if e.idx >= len(e.edges) { return nil } idx := e.idx if idx == -1 { idx = 0 } e.idx = len(e.edges) return e.edges[idx:] } // Reset returns the iterator to its initial state. func (e *OrderedWeightedEdges) Reset() { e.idx = -1 }
graph/iterator/edges.go
0.812793
0.592018
edges.go
starcoder
package slices // Slice provides a generic slice methods. type Slice[T comparable] struct { s []T } // NewSlice returns Slice[T]. func NewSlice[T comparable]() *Slice[T] { return &Slice[T]{ s: make([]T, 0), } } // Cap returns Slice[T] capacity. func (s *Slice[T]) Cap() int { return cap(s.s) } // Len returns Slice[T] length. func (s *Slice[T]) Len() int { return len(s.s) } // Shrink reduces the capacity to 'cap'. func (s *Slice[T]) Shrink(cap int) { size := s.Len() if cap-size > 0 { ns := make([]T, size, cap) copy(ns, s.s) s.s = ns } } // Reserve extends the capacity to 'cap'. func (s *Slice[T]) Reserve(cap int) { size := s.Len() n := cap - size if n > 0 { s.s = append(s.s, make([]T, n)...)[:size] } } // Resize changes the number of elements to 'len'. func (s *Slice[T]) Resize(len int) { size := s.Len() n := len - size if n > 0 { s.s = append(s.s, make([]T, n)...) } else { s.s = s.s[:len] } } // At returns the i-th element. func (s *Slice[T]) At(i int) T { return s.s[i] } // Set sets 'v' to the i-th element. func (s *Slice[T]) Set(i int, v T) { s.s[i] = v } // Insert inserts 'v' into the i-th element. func (s *Slice[T]) Insert(i int, v T) { s.s = append(s.s[:i+1], s.s[i:]...) s.s[i] = v } // Append appends 'v' to the end of the slice. func (s *Slice[T]) Append(v T) { s.s = append(s.s, v) } // Appends adds one or more elements to the end. func (s *Slice[T]) Appends(vs ...T) { s.s = append(s.s, vs...) } // Delete deletes the i-th element. func (s *Slice[T]) Delete(i int) { copy(s.s[i:], s.s[i+1:]) s.s = s.s[:len(s.s)-1] } // Erase deletes elements from 'begin' to 'end - 1'. func (s *Slice[T]) Erase(begin int, end int) { n := s.Len() - (end - begin) copy(s.s[begin:], s.s[end:]) s.s = s.s[:n] } // Clear erases all elements. func (s *Slice[T]) Clear() { s.s = make([]T, 0) } // Clone returns a Slice with all elements copied. func (s *Slice[T]) Clone() *Slice[T] { ns := make([]T, len(s.s)) copy(ns, s.s) return &Slice[T]{ s: ns, } } // Sub returns a reference to an Slice from 'begin' to 'end - 1'. func (s *Slice[T]) Sub(begin int, end int) *Slice[T] { return &Slice[T]{ s: s.s[begin:end], } } // Data returns the raw internal array. func (s *Slice[T]) Data() []T { return s.s[:] }
slices/generic.go
0.827236
0.480479
generic.go
starcoder
package ion import ( "math/big" ) // uintLen pre-calculates the length, in bytes, of the given uint value. func uintLen(v uint64) uint64 { length := uint64(1) v >>= 8 for v > 0 { length++ v >>= 8 } return length } // appendUint appends a uint value to the given slice. The reader is // expected to know how many bytes the value takes up. func appendUint(b []byte, v uint64) []byte { var buf [8]byte i := 7 buf[i] = byte(v & 0xFF) v >>= 8 for v > 0 { i-- buf[i] = byte(v & 0xFF) v >>= 8 } return append(b, buf[i:]...) } // intLen pre-calculates the length, in bytes, of the given int value. func intLen(n int64) uint64 { if n == 0 { return 0 } mag := uint64(n) if n < 0 { mag = uint64(-n) } length := uintLen(mag) // If the high bit is a one, we need an extra byte to store the sign bit. hb := mag >> ((length - 1) * 8) if hb&0x80 != 0 { length++ } return length } // appendInt appends a (signed) int to the given slice. The reader is // expected to know how many bytes the value takes up. func appendInt(b []byte, n int64) []byte { if n == 0 { return b } neg := false mag := uint64(n) if n < 0 { neg = true mag = uint64(-n) } var buf [8]byte bits := buf[:0] bits = appendUint(bits, mag) if bits[0]&0x80 == 0 { // We've got space we can use for the sign bit. if neg { bits[0] ^= 0x80 } } else { // We need to add more space. bit := byte(0) if neg { bit = 0x80 } b = append(b, bit) } return append(b, bits...) } // bigIntLen pre-calculates the length, in bytes, of the given big.Int value. func bigIntLen(v *big.Int) uint64 { if v.Sign() == 0 { return 0 } bitl := v.BitLen() bytel := bitl / 8 // Either bitl is evenly divisible by 8, in which case we need another // byte for the sign bit, or its not in which case we need to round up // (but will then have room for the sign bit). return uint64(bytel) + 1 } // appendBigInt appends a (signed) big.Int to the given slice. The reader is // expected to know how many bytes the value takes up. func appendBigInt(b []byte, v *big.Int) []byte { sign := v.Sign() if sign == 0 { return b } bits := v.Bytes() if bits[0]&0x80 == 0 { // We've got space we can use for the sign bit. if sign < 0 { bits[0] ^= 0x80 } } else { // We need to add more space. bit := byte(0) if sign < 0 { bit = 0x80 } b = append(b, bit) } return append(b, bits...) } // varUintLen pre-calculates the length, in bytes, of the given varUint value. func varUintLen(v uint64) uint64 { length := uint64(1) v >>= 7 for v > 0 { length++ v >>= 7 } return length } // appendVarUint appends a variable-length-encoded uint to the given slice. // Each byte stores seven bits of value; the high bit is a flag marking the // last byte of the value. func appendVarUint(b []byte, v uint64) []byte { var buf [10]byte i := 9 buf[i] = 0x80 | byte(v&0x7F) v >>= 7 for v > 0 { i-- buf[i] = byte(v & 0x7F) v >>= 7 } return append(b, buf[i:]...) } // varIntLen pre-calculates the length, in bytes, of the given varInt value. func varIntLen(v int64) uint64 { mag := uint64(v) if v < 0 { mag = uint64(-v) } // Reserve one extra bit of the first byte for sign. length := uint64(1) mag >>= 6 for mag > 0 { length++ mag >>= 7 } return length } // appendVarInt appends a variable-length-encoded int to the given slice. // Most bytes store seven bits of value; the high bit is a flag marking the // last byte of the value. The first byte additionally stores a sign bit. func appendVarInt(b []byte, v int64) []byte { var buf [10]byte signbit := byte(0) mag := uint64(v) if v < 0 { signbit = 0x40 mag = uint64(-v) } next := mag >> 6 if next == 0 { // The whole thing fits in one byte. return append(b, 0x80|signbit|byte(mag&0x3F)) } i := 9 buf[i] = 0x80 | byte(mag&0x7F) mag >>= 7 next = mag >> 6 for next > 0 { i-- buf[i] = byte(mag & 0x7F) mag >>= 7 next = mag >> 6 } i-- buf[i] = signbit | byte(mag&0x3F) return append(b, buf[i:]...) } // tagLen pre-calculates the length, in bytes, of a tag. func tagLen(length uint64) uint64 { if length < 0x0E { return 1 } return 1 + varUintLen(length) } // appendTag appends a code+len tag to the given slice. func appendTag(b []byte, code byte, length uint64) []byte { if length < 0x0E { // Short form, with length embedded in the code byte. return append(b, code|byte(length)) } // Long form, with separate length. b = append(b, code|0x0E) return appendVarUint(b, length) } // timestampLen pre-calculates the length, in bytes, of the given timestamp value. func timestampLen(offset int, utc Timestamp) uint64 { var ret uint64 if utc.kind == TimezoneUnspecified { ret = 1 } else { ret = varIntLen(int64(offset)) } // We expect at least Year precision. ret += varUintLen(uint64(utc.dateTime.Year())) // Month, day, hour, minute, and second are all guaranteed to be one byte. switch utc.precision { case TimestampPrecisionMonth: ret++ case TimestampPrecisionDay: ret += 2 case TimestampPrecisionMinute: // Hour and Minute combined ret += 4 case TimestampPrecisionSecond, TimestampPrecisionNanosecond: ret += 5 } if utc.precision == TimestampPrecisionNanosecond && utc.numFractionalSeconds > 0 { ret++ // For fractional seconds precision indicator ns := utc.TruncatedNanoseconds() if ns > 0 { ret += intLen(int64(ns)) } } return ret } // appendTimestamp appends a timestamp value func appendTimestamp(b []byte, offset int, utc Timestamp) []byte { if utc.kind == TimezoneUnspecified { // Unknown offset b = append(b, 0xC0) } else { b = appendVarInt(b, int64(offset)) } // We expect at least Year precision. b = appendVarUint(b, uint64(utc.dateTime.Year())) switch utc.precision { case TimestampPrecisionMonth: b = appendVarUint(b, uint64(utc.dateTime.Month())) case TimestampPrecisionDay: b = appendVarUint(b, uint64(utc.dateTime.Month())) b = appendVarUint(b, uint64(utc.dateTime.Day())) case TimestampPrecisionMinute: b = appendVarUint(b, uint64(utc.dateTime.Month())) b = appendVarUint(b, uint64(utc.dateTime.Day())) // The hour and minute is considered as a single component. b = appendVarUint(b, uint64(utc.dateTime.Hour())) b = appendVarUint(b, uint64(utc.dateTime.Minute())) case TimestampPrecisionSecond, TimestampPrecisionNanosecond: b = appendVarUint(b, uint64(utc.dateTime.Month())) b = appendVarUint(b, uint64(utc.dateTime.Day())) // The hour and minute is considered as a single component. b = appendVarUint(b, uint64(utc.dateTime.Hour())) b = appendVarUint(b, uint64(utc.dateTime.Minute())) b = appendVarUint(b, uint64(utc.dateTime.Second())) } if utc.precision == TimestampPrecisionNanosecond && utc.numFractionalSeconds > 0 { b = append(b, utc.numFractionalSeconds|0xC0) ns := utc.TruncatedNanoseconds() if ns > 0 { b = appendInt(b, int64(ns)) } } return b }
ion/bits.go
0.830834
0.652048
bits.go
starcoder
package views import ( "encoding/json" "github.com/hyperledger-labs/fabric-smart-client/integration/fabric/atsa/fsc/states" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric" "github.com/hyperledger-labs/fabric-smart-client/platform/fabric/services/state" "github.com/hyperledger-labs/fabric-smart-client/platform/view/services/assert" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" ) type AgreeToSell struct { Agreement *states.AgreementToSell Approver view.Identity } type AgreeToSellView struct { *AgreeToSell } func (a *AgreeToSellView) Call(context view.Context) (interface{}, error) { // The asset owner creates a new transaction, and tx, err := state.NewTransaction(context) assert.NoError(err, "failed creating transaction") // Sets the namespace where the state should appear, and tx.SetNamespace("asset_transfer") // Specifies the command this transaction wants to execute. // In particular, the asset owner wants to express the willingness to sell a given asset. // The approver will use this information to decide how to validate the transaction // Let's now retrieve the asset whose agreement to sell must be posted on the ledger. // This is needed to retrieve the identity owning that asset. asset := &states.Asset{ID: a.Agreement.ID} assetID, err := asset.GetLinearID() assert.NoError(err, "cannot compute linear state's id") assert.NoError( state.GetVault(context).GetState("asset_transfer", assetID, asset), "failed loading asset [%s]", assetID, ) // Specifies the command this transaction wants to execute. // In particular, the asset owner wants to agree to sell the asset. // The approver will use this information to decide how to validate the transaction. assert.NoError(tx.AddCommand("agreeToSell", asset.Owner), "failed adding issue command") // Add the agreement to sell to the transaction a.Agreement.Owner = asset.Owner assert.NoError(tx.AddOutput(a.Agreement, state.WithHashHiding()), "failed adding output") // The asset owner is ready to collect all the required signatures. // Namely from the asset owner itself and the approver. In this order. // All signatures are required. _, err = context.RunView(state.NewCollectEndorsementsView(tx, asset.Owner, a.Approver)) assert.NoError(err, "failed collecting endorsement") // Send to the ordering service and wait for confirmation _, err = context.RunView(state.NewOrderingAndFinalityView(tx)) assert.NoError(err, "failed asking ordering") return tx.ID(), nil } type AgreeToSellViewFactory struct{} func (a *AgreeToSellViewFactory) NewView(in []byte) (view.View, error) { f := &AgreeToSellView{AgreeToSell: &AgreeToSell{}} err := json.Unmarshal(in, f.AgreeToSell) assert.NoError(err, "failed unmarshalling input") return f, nil } type AgreeToBuy struct { Agreement *states.AgreementToBuy Approver view.Identity } type AgreeToBuyView struct { *AgreeToBuy } func (a *AgreeToBuyView) Call(context view.Context) (interface{}, error) { // Prepare transaction tx, err := state.NewTransaction(context) assert.NoError(err, "failed creating transaction") tx.SetNamespace("asset_transfer") me := fabric.GetDefaultIdentityProvider(context).DefaultIdentity() assert.NoError(tx.AddCommand("agreeToBuy", me), "failed adding issue command") a.Agreement.Owner = me assert.NoError(tx.AddOutput(a.Agreement, state.WithHashHiding()), "failed adding output") _, err = context.RunView(state.NewCollectEndorsementsView(tx, me)) assert.NoError(err, "failed collecting endorsement") _, err = context.RunView(state.NewCollectApprovesView(tx, a.Approver)) assert.NoError(err, "failed collecting approves") // Send to the ordering service and wait for confirmation _, err = context.RunView(state.NewOrderingAndFinalityView(tx)) assert.NoError(err, "failed asking ordering") return tx.ID(), nil } type AgreeToBuyViewFactory struct{} func (a *AgreeToBuyViewFactory) NewView(in []byte) (view.View, error) { f := &AgreeToBuyView{AgreeToBuy: &AgreeToBuy{}} err := json.Unmarshal(in, f.AgreeToBuy) assert.NoError(err, "failed unmarshalling input") return f, nil }
integration/fabric/atsa/fsc/views/agree.go
0.622804
0.400984
agree.go
starcoder
package ogletest import ( "path" "runtime" "github.com/smartystreets/goconvey/convey/assertions/oglematchers" ) func getCallerForAlias() (fileName string, lineNumber int) { _, fileName, lineNumber, _ = runtime.Caller(2) fileName = path.Base(fileName) return } // ExpectEq(e, a) is equivalent to ExpectThat(a, oglematchers.Equals(e)). func ExpectEq(expected, actual interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(actual, oglematchers.Equals(expected), errorParts...) res.SetCaller(getCallerForAlias()) return res } // ExpectNe(e, a) is equivalent to ExpectThat(a, oglematchers.Not(oglematchers.Equals(e))). func ExpectNe(expected, actual interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(actual, oglematchers.Not(oglematchers.Equals(expected)), errorParts...) res.SetCaller(getCallerForAlias()) return res } // ExpectLt(x, y) is equivalent to ExpectThat(x, oglematchers.LessThan(y)). func ExpectLt(x, y interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(x, oglematchers.LessThan(y), errorParts...) res.SetCaller(getCallerForAlias()) return res } // ExpectLe(x, y) is equivalent to ExpectThat(x, oglematchers.LessOrEqual(y)). func ExpectLe(x, y interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(x, oglematchers.LessOrEqual(y), errorParts...) res.SetCaller(getCallerForAlias()) return res } // ExpectGt(x, y) is equivalent to ExpectThat(x, oglematchers.GreaterThan(y)). func ExpectGt(x, y interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(x, oglematchers.GreaterThan(y), errorParts...) res.SetCaller(getCallerForAlias()) return res } // ExpectGe(x, y) is equivalent to ExpectThat(x, oglematchers.GreaterOrEqual(y)). func ExpectGe(x, y interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(x, oglematchers.GreaterOrEqual(y), errorParts...) res.SetCaller(getCallerForAlias()) return res } // ExpectTrue(b) is equivalent to ExpectThat(b, oglematchers.Equals(true)). func ExpectTrue(b interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(b, oglematchers.Equals(true), errorParts...) res.SetCaller(getCallerForAlias()) return res } // ExpectFalse(b) is equivalent to ExpectThat(b, oglematchers.Equals(false)). func ExpectFalse(b interface{}, errorParts ...interface{}) ExpectationResult { res := ExpectThat(b, oglematchers.Equals(false), errorParts...) res.SetCaller(getCallerForAlias()) return res }
Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions/ogletest/expect_aliases.go
0.641984
0.476397
expect_aliases.go
starcoder
package specs import ( "testing" "github.com/Fs02/grimoire" "github.com/Fs02/grimoire/c" "github.com/Fs02/grimoire/changeset" "github.com/Fs02/grimoire/params" "github.com/stretchr/testify/assert" ) // Update tests update specifications. func Update(t *testing.T, repo grimoire.Repo) { user := User{Name: "update"} repo.From(users).MustSave(&user) address := Address{Address: "update"} repo.From(addresses).MustSave(&address) tests := []struct { query grimoire.Query record interface{} params params.Params }{ {repo.From(users).Find(user.ID), &User{}, params.Map{"name": "insert", "age": 100}}, {repo.From(users).Find(user.ID), &User{}, params.Map{"name": "insert", "age": 100, "note": "note"}}, {repo.From(users).Find(user.ID), &User{}, params.Map{"note": "note"}}, {repo.From(addresses).Find(address.ID), &Address{}, params.Map{"address": "address"}}, {repo.From(addresses).Find(address.ID), &Address{}, params.Map{"user_id": user.ID}}, {repo.From(addresses).Find(address.ID), &Address{}, params.Map{"address": "address", "user_id": user.ID}}, } for _, test := range tests { ch := changeset.Cast(test.record, test.params, []string{"name", "age", "note", "address", "user_id"}) statement, _ := builder.Update(test.query.Collection, ch.Changes(), test.query.Condition) t.Run("Update|"+statement, func(t *testing.T) { assert.Nil(t, ch.Error()) assert.Nil(t, test.query.Update(nil, ch)) assert.Nil(t, test.query.Update(test.record, ch)) }) } } // UpdateWhere tests update specifications. func UpdateWhere(t *testing.T, repo grimoire.Repo) { user := User{Name: "update all"} repo.From(users).MustSave(&user) address := Address{Address: "update all"} repo.From(addresses).MustSave(&address) tests := []struct { query grimoire.Query schema interface{} record interface{} params params.Params }{ {repo.From(users).Where(c.Eq(name, "update all")), User{}, &[]User{}, params.Map{"name": "insert", "age": 100}}, {repo.From(addresses).Where(c.Eq(c.I("address"), "update_all")), Address{}, &[]Address{}, params.Map{"address": "address", "user_id": user.ID}}, } for _, test := range tests { ch := changeset.Cast(test.schema, test.params, []string{"name", "age", "note", "address", "user_id"}) statement, _ := builder.Update(test.query.Collection, ch.Changes(), test.query.Condition) t.Run("UpdateWhere|"+statement, func(t *testing.T) { assert.Nil(t, ch.Error()) assert.Nil(t, test.query.Update(nil, ch)) assert.Nil(t, test.query.Update(test.record, ch)) }) } } // UpdateSet tests update specifications using Set query. func UpdateSet(t *testing.T, repo grimoire.Repo) { user := User{Name: "update"} repo.From(users).MustSave(&user) address := Address{Address: "update"} repo.From(addresses).MustSave(&address) tests := []struct { query grimoire.Query record interface{} }{ {repo.From(users).Find(user.ID).Set("name", "update set"), &User{}}, {repo.From(users).Find(user.ID).Set("name", "update set").Set("age", 18), &User{}}, {repo.From(users).Find(user.ID).Set("note", "note set"), &User{}}, {repo.From(addresses).Find(address.ID).Set("address", "address set"), &Address{}}, {repo.From(addresses).Find(address.ID).Set("user_id", user.ID), &Address{}}, } for _, test := range tests { statement, _ := builder.Update(test.query.Collection, test.query.Changes, test.query.Condition) t.Run("UpdateSet|"+statement, func(t *testing.T) { assert.Nil(t, test.query.Update(nil)) assert.Nil(t, test.query.Update(test.record)) }) } }
adapter/specs/update.go
0.578924
0.493592
update.go
starcoder
package grok import "github.com/vjeantet/bitfan/processors/doc" func (p *processor) Doc() *doc.Processor { return &doc.Processor{ Name: "grok", ImportPath: "github.com/vjeantet/bitfan/processors/filter-grok", Doc: "", DocShort: "", Options: &doc.ProcessorOptions{ Doc: "", Options: []*doc.ProcessorOption{ &doc.ProcessorOption{ Name: "processors.CommonOptions", Alias: ",squash", Doc: "", Required: false, Type: "processors.CommonOptions", DefaultValue: nil, PossibleValues: []string{}, ExampleLS: "", }, &doc.ProcessorOption{ Name: "BreakOnMatch", Alias: "break_on_match", Doc: "Break on first match. The first successful match by grok will result in the filter being\nfinished. If you want grok to try all patterns (maybe you are parsing different things),\nthen set this to false", Required: false, Type: "bool", DefaultValue: nil, PossibleValues: []string{}, ExampleLS: "", }, &doc.ProcessorOption{ Name: "KeepEmptyCaptures", Alias: "keep_empty_captures", Doc: "If true, keep empty captures as event fields", Required: false, Type: "bool", DefaultValue: nil, PossibleValues: []string{}, ExampleLS: "", }, &doc.ProcessorOption{ Name: "Match", Alias: "match", Doc: "A hash of matches of field ⇒ value\n@nodefault\n\nFor example:\n```\n filter {\n grok { match => { \"message\" => \"Duration: %{NUMBER:duration}\" } }\n }\n```\nIf you need to match multiple patterns against a single field, the value can be an array of patterns\n```\n filter {\n grok { match => { \"message\" => [ \"Duration: %{NUMBER:duration}\", \"Speed: %{NUMBER:speed}\" ] } }\n }\n```", Required: true, Type: "hash", DefaultValue: nil, PossibleValues: []string{}, ExampleLS: "", }, &doc.ProcessorOption{ Name: "NamedCapturesOnly", Alias: "named_capture_only", Doc: "If true, only store named captures from grok.", Required: false, Type: "bool", DefaultValue: nil, PossibleValues: []string{}, ExampleLS: "", }, &doc.ProcessorOption{ Name: "PatternsDir", Alias: "patterns_dir", Doc: "BitFan ships by default with a bunch of patterns, so you don’t necessarily need to\ndefine this yourself unless you are adding additional patterns. You can point to\nmultiple pattern directories using this setting Note that Grok will read all files\nin the directory and assume its a pattern file (including any tilde backup files)", Required: false, Type: "array", DefaultValue: nil, PossibleValues: []string{}, ExampleLS: "", }, &doc.ProcessorOption{ Name: "TagOnFailure", Alias: "tag_on_failure", Doc: "Append values to the tags field when there has been no successful match", Required: false, Type: "array", DefaultValue: nil, PossibleValues: []string{}, ExampleLS: "", }, }, }, Ports: []*doc.ProcessorPort{ &doc.ProcessorPort{ Default: true, Name: "PORT_SUCCESS", Number: 0, Doc: "", }, }, } }
processors/filter-grok/docdoc.go
0.763484
0.461684
docdoc.go
starcoder
package runtime import ( "encoding/base64" "strconv" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/timestamp" ) // String just returns the given string. // It is just for compatibility to other types. func String(val string) (string, error) { return val, nil } // Bool converts the given string representation of a boolean value into bool. func Bool(val string) (bool, error) { return strconv.ParseBool(val) } // Float64 converts the given string representation into representation of a floating point number into float64. func Float64(val string) (float64, error) { return strconv.ParseFloat(val, 64) } // Float32 converts the given string representation of a floating point number into float32. func Float32(val string) (float32, error) { f, err := strconv.ParseFloat(val, 32) if err != nil { return 0, err } return float32(f), nil } // Int64 converts the given string representation of an integer into int64. func Int64(val string) (int64, error) { return strconv.ParseInt(val, 0, 64) } // Int32 converts the given string representation of an integer into int32. func Int32(val string) (int32, error) { i, err := strconv.ParseInt(val, 0, 32) if err != nil { return 0, err } return int32(i), nil } // Uint64 converts the given string representation of an integer into uint64. func Uint64(val string) (uint64, error) { return strconv.ParseUint(val, 0, 64) } // Uint32 converts the given string representation of an integer into uint32. func Uint32(val string) (uint32, error) { i, err := strconv.ParseUint(val, 0, 32) if err != nil { return 0, err } return uint32(i), nil } // Bytes converts the given string representation of a byte sequence into a slice of bytes // A bytes sequence is encoded in URL-safe base64 without padding func Bytes(val string) ([]byte, error) { b, err := base64.RawURLEncoding.DecodeString(val) if err != nil { return nil, err } return b, nil } // Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp. func Timestamp(val string) (*timestamp.Timestamp, error) { var r *timestamp.Timestamp err := jsonpb.UnmarshalString(val, r) return r, err } // Duration converts the given string into a timestamp.Duration. func Duration(val string) (*duration.Duration, error) { var r *duration.Duration err := jsonpb.UnmarshalString(val, r) return r, err }
runtime/convert.go
0.773002
0.405596
convert.go
starcoder
package geo // Point presents interface of point type Point interface { // X returns value of X dimension X() float64 // Y returns value of X dimension Y() float64 // Z returns value of X dimension Z() float64 // M returns value of X dimension M() float64 } type point struct{ x, y float64 } func (p point) X() float64 { return p.x } func (p point) Y() float64 { return p.y } func (p point) Z() float64 { return 0 } func (p point) M() float64 { return 0 } // NewPoint returns new 2 dimensions point func NewPoint(x, y float64) Point { return point{x, y} } type pointZ struct{ x, y, z float64 } func (p pointZ) X() float64 { return p.x } func (p pointZ) Y() float64 { return p.y } func (p pointZ) Z() float64 { return p.z } func (p pointZ) M() float64 { return 0 } // NewPointZ returns new 3 dimensions point with Z dimension func NewPointZ(x, y, z float64) Point { return pointZ{x, y, z} } type pointM struct{ x, y, m float64 } func (p pointM) X() float64 { return p.x } func (p pointM) Y() float64 { return p.y } func (p pointM) Z() float64 { return 0 } func (p pointM) M() float64 { return p.m } // NewPointM returns new 3 dimensions point with M dimension func NewPointM(x, y, m float64) Point { return pointM{x, y, m} } type pointZM struct{ x, y, z, m float64 } func (p pointZM) X() float64 { return p.x } func (p pointZM) Y() float64 { return p.y } func (p pointZM) Z() float64 { return p.z } func (p pointZM) M() float64 { return p.m } // NewPointZM returns new 4 dimensions point func NewPointZM(x, y, z, m float64) Point { return pointZM{x, y, z, m} } // MultiPoint presents interface of multi point type MultiPoint interface { // Point returns point with specified index Point(int) Point // Len returns count of points Len() int } type multiPoint struct { points []Point } func (p multiPoint) Point(idx int) Point { return p.points[idx] } func (p multiPoint) Len() int { return len(p.points) } // NewMultiPoint returns new multi point func NewMultiPoint(points []Point) MultiPoint { return multiPoint{points} } // Polygon presents interface of polygon type Polygon interface { // Ring returns ring with specified index Ring(int) MultiPoint // Len returns count of rings Len() int } type polygon struct { rings []MultiPoint } func (p polygon) Ring(idx int) MultiPoint { return p.rings[idx] } func (p polygon) Len() int { return len(p.rings) } // NewPolygon returns new polygon func NewPolygon(rings []MultiPoint) Polygon { return polygon{rings} } // MultiLine presents interface of multi line type MultiLine interface { // Line returns line with specified index Line(int) MultiPoint // Len returns count of lines Len() int } type multiLine struct { lines []MultiPoint } func (l multiLine) Line(idx int) MultiPoint { return l.lines[idx] } func (l multiLine) Len() int { return len(l.lines) } // NewMultiLine returns new multi line func NewMultiLine(lines []MultiPoint) MultiLine { return multiLine{lines} } // MultiPolygon presents interface of multi polygon type MultiPolygon interface { // Polygon returns polygon with specified index Polygon(int) Polygon // Len returns count of polygons Len() int } type multiPolygon struct { pols []Polygon } func (p multiPolygon) Polygon(idx int) Polygon { return p.pols[idx] } func (p multiPolygon) Len() int { return len(p.pols) } // NewMultiPolygon returns new multi polygon func NewMultiPolygon(pols []Polygon) MultiPolygon { return multiPolygon{pols} }
geo/geo.go
0.908866
0.713057
geo.go
starcoder
package timeutil import ( "errors" "fmt" "sort" "strings" "time" ) /* // TimeSlice is used for sorting. e.g. // sort.Sort(sort.Reverse(timeSlice)) // sort.Sort(timeSlice) // var times TimeSlice := []time.Time{time.Now()} type TimeSlice []time.Time func (s TimeSlice) Less(i, j int) bool { return s[i].Before(s[j]) } func (s TimeSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s TimeSlice) Len() int { return len(s) } */ func Sort(times []time.Time) []time.Time { sort.Slice( times, func(i, j int) bool { return times[i].Before(times[j]) }) return times } func Earliest(times []time.Time, skipZeroes bool) (time.Time, error) { if len(times) == 0 { return time.Now(), errors.New("no times") } sort.Slice( times, func(i, j int) bool { return times[i].Before(times[j]) }) first := times[0] if skipZeroes && TimeIsZeroAny(first) { return first, fmt.Errorf("latest time is zero [%s]", first.Format(time.RFC3339)) } return first, nil } func Latest(times []time.Time, skipZeroes bool) (time.Time, error) { if len(times) == 0 { return time.Now(), errors.New("no times") } sort.Slice( times, func(i, j int) bool { return times[i].Before(times[j]) }) last := times[len(times)-1] if skipZeroes && TimeIsZeroAny(last) { return last, fmt.Errorf("latest time is zero [%s]", last.Format(time.RFC3339)) } return last, nil } func QuarterSlice(min, max time.Time) []time.Time { min, max = MinMax(min, max) minQ := QuarterStart(min) maxQ := QuarterStart(max) times := []time.Time{} cur := minQ for cur.Before(maxQ) || cur.Equal(maxQ) { times = append(times, cur) cur = NextQuarter(cur) } return times } func FirstNonZeroTimeParsed(format string, times []string) (time.Time, error) { if len(times) == 0 { return time.Now(), errors.New("no times provided") } for _, timeString := range times { timeString = strings.TrimSpace(timeString) if len(timeString) == 0 { continue } t, err := time.Parse(format, timeString) if err != nil { return t, err } if !IsZeroAny(t) { return t, nil } } return time.Now(), errors.New("no times provided") } func FirstNonZeroTime(times ...time.Time) (time.Time, error) { if len(times) == 0 { return time.Now(), errors.New("no times provided") } for _, t := range times { if !IsZeroAny(t) { return t, nil } } return time.Now(), errors.New("no times provided") } func MustFirstNonZeroTime(times ...time.Time) time.Time { t, err := FirstNonZeroTime(times...) if err != nil { return TimeZeroRFC3339() } return t } func TimeSliceMinMax(times []time.Time) (time.Time, time.Time, error) { min := TimeZeroRFC3339() max := TimeZeroRFC3339() if len(times) == 0 { return min, max, errors.New("timeutil.TimeSliceMinMax provided with empty slice") } for i, t := range times { if i == 0 { min = t max = t } else { if t.Before(min) { min = t } if t.After(max) { max = t } } } return min, max, nil } // Distinct returns a time slice with distinct, or unique, times. func Distinct(times []time.Time) []time.Time { filtered := []time.Time{} seen := map[time.Time]int{} for _, t := range times { if _, ok := seen[t]; !ok { seen[t] = 1 filtered = append(filtered, t) } } return filtered }
time/timeutil/slice.go
0.578448
0.427815
slice.go
starcoder
// Package mgm provides a custom implementation of Multilinear Galois Mode (MGM) suitable for RU-WireGuard. // The supported tag and block sizes are 128 bit only. package mgm import ( "crypto/cipher" "crypto/hmac" "encoding/binary" "errors" "math/big" ) var ( r128 = new(big.Int).SetBytes([]byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87}, ) ) const ( mgmTagSize = 16 mgmBlockSize = 16 mgmMaxSize = uint64(1<<uint(mgmBlockSize*8/2) - 1) mgmMaxBit = 128 - 1 ) type MGM struct { cipher cipher.Block } func NewMGM(cipher cipher.Block) (cipher.AEAD, error) { if !(cipher.BlockSize() == 16) { return nil, errors.New("ru-wireguard/gogost/mgm: only 128 blocksize allowed") } mgm := MGM{ cipher: cipher, } return &mgm, nil } func (mgm *MGM) NonceSize() int { return mgmBlockSize } func (mgm *MGM) Overhead() int { return mgmTagSize } func incr(data []byte) { for i := len(data) - 1; i >= 0; i-- { data[i]++ if data[i] != 0 { return } } } func (mgm *MGM) auth(out, text, ad, icn []byte) { var sum [16]byte var bufC [mgmBlockSize]byte var padded [mgmBlockSize]byte var bufP [mgmBlockSize]byte adLen := len(ad) * 8 textLen := len(text) * 8 icn[0] |= 0x80 mgm.cipher.Encrypt(bufP[:], icn) // Z_1 = E_K(1 || ICN) for len(ad) >= mgmBlockSize { mgm.cipher.Encrypt(bufC[:], bufP[:]) // H_i = E_K(Z_i) xor( // sum (xor)= H_i (x) A_i sum[:], sum[:], mgm.mul(bufC[:], ad[:mgmBlockSize]), ) incr(bufP[:mgmBlockSize/2]) // Z_{i+1} = incr_l(Z_i) ad = ad[mgmBlockSize:] } if len(ad) > 0 { copy(padded[:], ad) for i := len(ad); i < mgmBlockSize; i++ { padded[i] = 0 } mgm.cipher.Encrypt(bufC[:], bufP[:]) xor(sum[:], sum[:], mgm.mul(bufC[:], padded[:])) incr(bufP[:mgmBlockSize/2]) } for len(text) >= mgmBlockSize { mgm.cipher.Encrypt(bufC[:], bufP[:]) // H_{h+j} = E_K(Z_{h+j}) xor( // sum (xor)= H_{h+j} (x) C_j sum[:], sum[:], mgm.mul(bufC[:], text[:mgmBlockSize]), ) incr(bufP[:mgmBlockSize/2]) // Z_{h+j+1} = incr_l(Z_{h+j}) text = text[mgmBlockSize:] } if len(text) > 0 { copy(padded[:], text) for i := len(text); i < mgmBlockSize; i++ { padded[i] = 0 } mgm.cipher.Encrypt(bufC[:], bufP[:]) xor(sum[:], sum[:], mgm.mul(bufC[:], padded[:])) incr(bufP[:mgmBlockSize/2]) } mgm.cipher.Encrypt(bufP[:], bufP[:]) // H_{h+q+1} = E_K(Z_{h+q+1}) // len(A) || len(C) binary.BigEndian.PutUint64(bufC[:], uint64(adLen)) binary.BigEndian.PutUint64(bufC[mgmBlockSize/2:], uint64(textLen)) // sum (xor)= H_{h+q+1} (x) (len(A) || len(C)) xor(sum[:], sum[:], mgm.mul(bufP[:], bufC[:])) mgm.cipher.Encrypt(bufP[:], sum[:]) // E_K(sum) copy(out, bufP[:mgmTagSize]) // MSB_S(E_K(sum)) } func (mgm *MGM) crypt(out, in []byte, icn []byte) { var bufP [mgmBlockSize]byte var bufC [mgmBlockSize]byte icn[0] &= 0x7F mgm.cipher.Encrypt(bufP[:], icn) // Y_1 = E_K(0 || ICN) for len(in) >= mgmBlockSize { mgm.cipher.Encrypt(bufC[:], bufP[:]) // E_K(Y_i) xor(out, bufC[:], in) // C_i = P_i (xor) E_K(Y_i) incr(bufP[mgmBlockSize/2:]) // Y_i = incr_r(Y_{i-1}) out = out[mgmBlockSize:] in = in[mgmBlockSize:] } if len(in) > 0 { mgm.cipher.Encrypt(bufC[:], bufP[:]) xor(out, in, bufC[:]) } } func (mgm *MGM) Seal(dst, nonce, plaintext, additionalData []byte) []byte { if len(nonce) != mgmBlockSize || nonce[0]&0x80 > 0 { panic("mgm: incorrect nonce") } if len(plaintext) == 0 && len(additionalData) == 0 { panic("mgm seal: at least either *text or additionalData must be provided") } if uint64(len(additionalData)) > mgmMaxSize { panic("additionalData is too big") } if uint64(len(plaintext)+len(additionalData)) > mgmMaxSize { panic("*text with additionalData are too big") } if uint64(len(plaintext)) > mgmMaxSize { panic("plaintext is too big") } ret, out := sliceForAppend(dst, len(plaintext)+mgmTagSize) var icn [mgmBlockSize]byte copy(icn[:], nonce) mgm.crypt(out, plaintext, icn[:]) mgm.auth( out[len(plaintext):len(plaintext)+mgmTagSize], out[:len(plaintext)], additionalData, icn[:], ) return ret } func (mgm *MGM) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) { if len(nonce) != mgmBlockSize || nonce[0]&0x80 > 0 { panic("mgm: incorrect nonce") } if len(ciphertext) == 0 && len(additionalData) == 0 { panic("mgm open: at least either *text or additionalData must be provided") } if uint64(len(additionalData)) > mgmMaxSize { panic("additionalData is too big") } if uint64(len(ciphertext)+len(additionalData)) > mgmMaxSize { panic("*text with additionalData are too big") } if uint64(len(ciphertext)-mgmTagSize) > mgmMaxSize { panic("ciphertext is too big") } if len(ciphertext) < mgmTagSize { panic("ciphertext is to small") } ret, out := sliceForAppend(dst, len(ciphertext)-mgmTagSize) ct := ciphertext[:len(ciphertext)-mgmTagSize] var icn [mgmBlockSize]byte copy(icn[:], nonce) var expectedTag [mgmTagSize]byte mgm.auth(expectedTag[:], ct, additionalData, icn[:]) if !hmac.Equal(expectedTag[:], ciphertext[len(ciphertext)-mgmTagSize:]) { return nil, errors.New("gogost/mgm: invalid authentication tag") } mgm.crypt(out, ct, icn[:]) return ret, nil }
crypto/mgm/mgm.go
0.504394
0.40645
mgm.go
starcoder
package metrics import ( "context" "github.com/status-im/go-waku/waku/v2/utils" "go.opencensus.io/stats" "go.opencensus.io/stats/view" "go.opencensus.io/tag" "go.uber.org/zap" ) var ( Messages = stats.Int64("node_messages", "Number of messages received", stats.UnitDimensionless) Peers = stats.Int64("peers", "Number of connected peers", stats.UnitDimensionless) Dials = stats.Int64("dials", "Number of peer dials", stats.UnitDimensionless) StoreMessages = stats.Int64("store_messages", "Number of historical messages", stats.UnitDimensionless) FilterSubscriptions = stats.Int64("filter_subscriptions", "Number of filter subscriptions", stats.UnitDimensionless) StoreErrors = stats.Int64("errors", "Number of errors in store protocol", stats.UnitDimensionless) LightpushErrors = stats.Int64("errors", "Number of errors in lightpush protocol", stats.UnitDimensionless) ) var ( KeyType, _ = tag.NewKey("type") ErrorType, _ = tag.NewKey("error_type") ) var ( PeersView = &view.View{ Name: "gowaku_connected_peers", Measure: Peers, Description: "Number of connected peers", Aggregation: view.Sum(), } DialsView = &view.View{ Name: "gowaku_peers_dials", Measure: Dials, Description: "Number of peer dials", Aggregation: view.Count(), } MessageView = &view.View{ Name: "gowaku_node_messages", Measure: Messages, Description: "The number of the messages received", Aggregation: view.Count(), } StoreMessagesView = &view.View{ Name: "gowaku_store_messages", Measure: StoreMessages, Description: "The distribution of the store protocol messages", Aggregation: view.LastValue(), TagKeys: []tag.Key{KeyType}, } FilterSubscriptionsView = &view.View{ Name: "gowaku_filter_subscriptions", Measure: FilterSubscriptions, Description: "The number of content filter subscriptions", Aggregation: view.LastValue(), } StoreErrorTypesView = &view.View{ Name: "gowaku_store_errors", Measure: StoreErrors, Description: "The distribution of the store protocol errors", Aggregation: view.Count(), TagKeys: []tag.Key{KeyType}, } LightpushErrorTypesView = &view.View{ Name: "gowaku_lightpush_errors", Measure: LightpushErrors, Description: "The distribution of the lightpush protocol errors", Aggregation: view.Count(), TagKeys: []tag.Key{KeyType}, } ) func RecordLightpushError(ctx context.Context, tagType string) { if err := stats.RecordWithTags(ctx, []tag.Mutator{tag.Insert(tag.Key(ErrorType), tagType)}, LightpushErrors.M(1)); err != nil { utils.Logger().Error("failed to record with tags", zap.Error(err)) } } func RecordMessage(ctx context.Context, tagType string, len int) { if err := stats.RecordWithTags(ctx, []tag.Mutator{tag.Insert(KeyType, tagType)}, StoreMessages.M(int64(len))); err != nil { utils.Logger().Error("failed to record with tags", zap.Error(err)) } } func RecordStoreError(ctx context.Context, tagType string) { if err := stats.RecordWithTags(ctx, []tag.Mutator{tag.Insert(ErrorType, tagType)}, StoreErrors.M(1)); err != nil { utils.Logger().Error("failed to record with tags", zap.Error(err)) } }
waku/v2/metrics/metrics.go
0.508544
0.451568
metrics.go
starcoder
package models type Talents struct { fight *FightAnalysis `json:"-"` Points [3]int64 `json:"points"` Spec Specialization `json:"spec"` } func NewTalents(fight *FightAnalysis, points [3]int64) *Talents { t := &Talents{ fight: fight, Points: points, } t.guessSpec() return t } var guessers = []specGuesser{restokingGuesser, defaultGuesser} func (t *Talents) guessSpec() { for _, guesser := range guessers { if spec := guesser(t); spec != Specialization_Unknown { t.Spec = spec return } } } func defaultGuesser(t *Talents) Specialization { for spec, data := range specs { if t.fight.player.SubType == string(data.Class) { match := false switch data.HasMorePointsIn { case 0: match = t.Points[0] >= t.Points[1] && t.Points[0] >= t.Points[2] case 1: match = t.Points[1] >= t.Points[0] && t.Points[1] >= t.Points[2] case 2: match = t.Points[2] >= t.Points[0] && t.Points[2] >= t.Points[1] } if match { return spec } } } return Specialization_Unknown } func (t *Talents) BenefitsFromWindfuryTotem() bool { return specs[t.Spec].BenefitsFromWindfuryTotem } var ( specs = map[Specialization]struct { HasMorePointsIn int Class Class Role map[Role]bool BenefitsFromWindfuryTotem bool }{ Specialization_HolyPaladin: { HasMorePointsIn: 0, Class: Class_Paladin, Role: map[Role]bool{Role_Heal: true}, }, Specialization_ProtectionPaladin: { HasMorePointsIn: 1, Class: Class_Paladin, Role: map[Role]bool{Role_Tank: true, Role_Magic: true}, }, Specialization_RetributionPaladin: { HasMorePointsIn: 2, Class: Class_Paladin, Role: map[Role]bool{Role_Melee: true, Role_Physical: true}, BenefitsFromWindfuryTotem: true, }, Specialization_AssassinationRogue: { HasMorePointsIn: 0, Class: Class_Rogue, Role: map[Role]bool{Role_Melee: true, Role_Physical: true}, BenefitsFromWindfuryTotem: true, }, Specialization_CombatRogue: { HasMorePointsIn: 1, Class: Class_Rogue, Role: map[Role]bool{Role_Melee: true, Role_Physical: true}, BenefitsFromWindfuryTotem: true, }, Specialization_SubtletyRogue: { HasMorePointsIn: 2, Class: Class_Rogue, Role: map[Role]bool{Role_Melee: true, Role_Physical: true}, BenefitsFromWindfuryTotem: true, }, Specialization_ArmsWarrior: { HasMorePointsIn: 0, Class: Class_Warrior, Role: map[Role]bool{Role_Melee: true, Role_Physical: true}, BenefitsFromWindfuryTotem: true, }, Specialization_FuryWarrior: { HasMorePointsIn: 1, Class: Class_Warrior, Role: map[Role]bool{Role_Melee: true, Role_Physical: true}, BenefitsFromWindfuryTotem: true, }, Specialization_ProtectionWarrior: { HasMorePointsIn: 2, Class: Class_Warrior, Role: map[Role]bool{Role_Tank: true, Role_Physical: true}, BenefitsFromWindfuryTotem: true, }, Specialization_ElementalShaman: { HasMorePointsIn: 0, Class: Class_Shaman, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_EnhancementShaman: { HasMorePointsIn: 1, Class: Class_Shaman, Role: map[Role]bool{Role_Melee: true, Role_Physical: true}, }, Specialization_RestorationShaman: { HasMorePointsIn: 2, Class: Class_Shaman, Role: map[Role]bool{Role_Heal: true}, }, Specialization_BalanceDruid: { HasMorePointsIn: 0, Class: Class_Druid, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_FeralDruid: { HasMorePointsIn: 1, Class: Class_Druid, Role: map[Role]bool{Role_Melee: true, Role_Tank: true, Role_Physical: true}, }, Specialization_RestorationDruid: { HasMorePointsIn: 2, Class: Class_Druid, Role: map[Role]bool{Role_Heal: true}, }, Specialization_DisciplinePriest: { HasMorePointsIn: 0, Class: Class_Priest, Role: map[Role]bool{Role_Heal: true}, }, Specialization_HolyPriest: { HasMorePointsIn: 1, Class: Class_Priest, Role: map[Role]bool{Role_Heal: true}, }, Specialization_ShadowPriest: { HasMorePointsIn: 2, Class: Class_Priest, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_AfflictionWarlock: { HasMorePointsIn: 0, Class: Class_Warlock, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_DemonologyWarlock: { HasMorePointsIn: 1, Class: Class_Warlock, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_DestructionWarlock: { HasMorePointsIn: 2, Class: Class_Warlock, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_ArcaneMage: { HasMorePointsIn: 0, Class: Class_Mage, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_FireMage: { HasMorePointsIn: 1, Class: Class_Mage, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_FrostMage: { HasMorePointsIn: 2, Class: Class_Mage, Role: map[Role]bool{Role_Ranged: true, Role_Magic: true}, }, Specialization_SurvivalHunter: { HasMorePointsIn: 0, Class: Class_Hunter, Role: map[Role]bool{Role_Ranged: true, Role_Physical: true}, }, Specialization_MarksmanshipHunter: { HasMorePointsIn: 1, Class: Class_Hunter, Role: map[Role]bool{Role_Ranged: true, Role_Physical: true}, }, Specialization_BeastMasteryHunter: { HasMorePointsIn: 2, Class: Class_Hunter, Role: map[Role]bool{Role_Ranged: true, Role_Physical: true}, }, Specialization_Unknown: { HasMorePointsIn: 0, Class: Class_Unknown, Role: map[Role]bool{}, }, } ) type specGuesser func(*Talents) Specialization func restokingGuesser(t *Talents) Specialization { if len(t.Points) != 3 || t.fight.player.SubType != string(Class_Druid) { return Specialization_Unknown } if t.Points[0] >= 33 && t.Points[0] <= 37 && t.Points[2] >= 25 { return Specialization_RestorationDruid } return Specialization_Unknown }
internal/models/talents.go
0.535098
0.41182
talents.go
starcoder
// Dotted Version Vector Sets implementation // based on http://haslab.uminho.pt/tome/files/dvvset-dais.pdf package dt import ( "sort" "time" "golang.org/x/xerrors" ) // Timestamp of individual event type Dot struct { node string counter uint32 timestamp uint32 } // Individual event with timestamp type DVV struct { vector []Dot } // For sort. Returns length of vector of the dvv func (d DVV) Len() int { return len(d.vector) } // For sort. Returns the result of compare two node func (d DVV) Less(i, j int) bool { return d.vector[i].node < d.vector[j].node } // For sort. Swap element func (d DVV) Swap(i, j int) { d.vector[i], d.vector[j] = d.vector[j], d.vector[i] } // Instantiate a new DVV struct func NewDVV() DVV { DVV := new(DVV) return *DVV } // Return true if the vclock va is a direct descendant of vclock vb, else false. func (va DVV) Descends(vb DVV) bool { acc := true for _, dot_b := range vb.vector { if dot_a, err := va.GetDot(dot_b.node); err == nil { acc = (dot_a.counter >= dot_b.counter) && acc } else { acc = acc && false } } return acc } // true if vclock va strictly dominates vclock vb. Note: ignores timestamps // In riak it is possible to have vclocks that are identical except for timestamps. // when two vclocks descend each other, but are not equal, they are concurrent. // See source comment for more details. func (va DVV) Dominates(vb DVV) bool { // In a same world if two vclocks descend each ether they must be equal. // In riak they can descend each other and have different timestamps // How? Deleted keys, re-written, then restored is one example. return va.Descends(vb) && !vb.Descends(va) } // Combine all vclocks in the input list in to their least possible common descendant. func (v *DVV) Merge(vclocks []DVV) { nclock := *v for len(vclocks) > 0 { vclock := vclocks[0] acc := NewDVV() for nclock.Len() > 0 || vclock.Len() > 0 { if vclock.Len() < 1 { acc.vector = append(acc.vector, nclock.vector...) break } if nclock.Len() < 1 { acc.vector = append(acc.vector, vclock.vector...) break } else { if vclock.vector[0].node < nclock.vector[0].node { acc.vector = append(acc.vector, vclock.vector[0]) vclock.vector = vclock.vector[1:] } else if vclock.vector[0].node > nclock.vector[0].node { acc.vector = append(acc.vector, nclock.vector[0]) nclock.vector = nclock.vector[1:] } else { var cnt uint32 var ts uint32 node := nclock.vector[0].node if vclock.vector[0].counter > nclock.vector[0].counter { cnt = vclock.vector[0].counter ts = vclock.vector[0].timestamp } else if vclock.vector[0].counter < nclock.vector[0].counter { cnt = nclock.vector[0].counter ts = nclock.vector[0].timestamp } else { if vclock.vector[0].timestamp < nclock.vector[0].timestamp { cnt = vclock.vector[0].counter ts = nclock.vector[0].timestamp } else { cnt = vclock.vector[0].counter ts = vclock.vector[0].timestamp } } vclock.vector = vclock.vector[1:] nclock.vector = nclock.vector[1:] ct := Dot{node: node, counter: cnt, timestamp: ts} acc.vector = append(acc.vector, ct) } } } vclocks = vclocks[1:] nclock = acc } v.vector = nclock.vector } // Get the counter value in a DVV set from node func (v *DVV) GetCounter(id string) uint32 { if dot, err := v.GetDot(id); err == nil { return dot.counter } else { return 0 } } // Get the timestamp value in a DVV set from node func (v *DVV) GetTimestamp(id string) (uint32, error) { if dot, err := v.GetDot(id); err == nil { return dot.timestamp, nil } else { return 0, xerrors.New("Not found timestamp of id in vector") } } // Get the timestamp value in a DVV set from node func (v *DVV) GetDot(id string) (*Dot, error) { for _, dot := range v.vector { if dot.node == id { return &dot, nil } } return nil, xerrors.New("Not found dot of id in vector") } // Increment vclock at Node func (v *DVV) Increment(node string) { ts := uint32(time.Now().Unix()) for idx, dot := range v.vector { if dot.node == node { v.vector[idx].counter = v.vector[idx].counter + 1 v.vector[idx].timestamp = ts return } } dot := Dot{node: node, counter: 1, timestamp: ts} v.vector = append(v.vector, dot) } // Possibly shrink the size of a vclock, depending on current age and size. func (v *DVV) Prune(now uint32, props map[string]int) { // This sort need to be deterministic, to avoid spurious merge conflicts later. // We achieve this by using the node ID as secondary key. v.sort_by_dot() for v.Len() > GetSmallVclock(props) { head_time := v.vector[0].timestamp is_young := (now - head_time) < uint32(GetYoungVclock(props)) if is_young { return } else { is_big := v.Len() > GetBigVclock(props) is_old := ((now - head_time) > uint32(GetOldVclock(props))) if is_big || is_old { v.vector = v.vector[1:] } else { return } } } } // ------------------- private functions ------------------- func (v *DVV) sort_by_dot() { sort.Slice(v.vector, func(i, j int) bool { left := uint64(v.vector[i].counter)<<63 | uint64(v.vector[i].timestamp) right := uint64(v.vector[j].counter)<<63 | uint64(v.vector[j].timestamp) return left < right }) }
vclock.go
0.710226
0.455562
vclock.go
starcoder
package types import "sync" type TSafeInt64s interface { // Reset the slice. Reset() // Contains say if "s" contains "values". Contains(...int64) bool // ContainsOneOf says if "s" contains one of the "values". ContainsOneOf(...int64) bool // Copy create a new copy of the slice. Copy() TSafeInt64s // Diff returns the difference between "s" and "s2". Diff(Int64s) Int64s // Empty says if the slice is empty. Empty() bool // Equal says if "s" and "s2" are equal. Equal(Int64s) bool // Find the first element matching the pattern. Find(func(v int64) bool) (int64, bool) // FindAll elements matching the pattern. FindAll(func(v int64) bool) Int64s // First return the value of the first element. First() (int64, bool) // Get the element "i" and say if it has been found. Get(int) (int64, bool) // Intersect return the intersection between "s" and "s2". Intersect(Int64s) Int64s // Last return the value of the last element. Last() (int64, bool) // Len returns the size of the slice. Len() int // Take n element and return a new slice. Take(int) Int64s // S convert s into []interface{} S() []interface{} // S convert s into Int64s Int64s() Int64s } func SyncInt64s() TSafeInt64s { return &tsafeInt64s{&sync.RWMutex{}, Int64s{}} } type tsafeInt64s struct { mu *sync.RWMutex values Int64s } func (s *tsafeInt64s) Reset() { s.mu.Lock() s.values.Reset() s.mu.Unlock() } func (s *tsafeInt64s) Contains(values ...int64) (ok bool) { s.mu.RLock() ok = s.values.Contains(values...) s.mu.RUnlock() return } func (s *tsafeInt64s) ContainsOneOf(values ...int64) (ok bool) { s.mu.RLock() ok = s.values.ContainsOneOf(values...) s.mu.RUnlock() return } func (s *tsafeInt64s) Copy() TSafeInt64s { s2 := &tsafeInt64s{mu: &sync.RWMutex{}} s.mu.RLock() s2.values = s.values.Copy() s.mu.RUnlock() return s2 } func (s *tsafeInt64s) Diff(s2 Int64s) (out Int64s) { s.mu.RLock() out = s.values.Diff(s2) s.mu.RUnlock() return } func (s *tsafeInt64s) Empty() (ok bool) { s.mu.RLock() ok = s.values.Empty() s.mu.RUnlock() return } func (s *tsafeInt64s) Equal(s2 Int64s) (ok bool) { s.mu.RLock() ok = s.values.Equal(s2) s.mu.RUnlock() return } func (s *tsafeInt64s) Find(matcher func(v int64) bool) (v int64, ok bool) { s.mu.RLock() v, ok = s.values.Find(matcher) s.mu.RUnlock() return } func (s *tsafeInt64s) FindAll(matcher func(v int64) bool) (v Int64s) { s.mu.RLock() v = s.values.FindAll(matcher) s.mu.RUnlock() return } func (s *tsafeInt64s) First() (v int64, ok bool) { s.mu.RLock() v, ok = s.values.First() s.mu.RUnlock() return } func (s *tsafeInt64s) Get(i int) (v int64, ok bool) { s.mu.RLock() v, ok = s.values.Get(i) s.mu.RUnlock() return } func (s *tsafeInt64s) Intersect(s2 Int64s) (v Int64s) { s.mu.RLock() v = s.values.Intersect(s2) s.mu.RUnlock() return } func (s *tsafeInt64s) Last() (v int64, ok bool) { s.mu.RLock() v, ok = s.values.Last() s.mu.RUnlock() return } func (s *tsafeInt64s) Len() (v int) { s.mu.RLock() v = s.values.Len() s.mu.RUnlock() return } func (s *tsafeInt64s) Take(n int) (v Int64s) { s.mu.RLock() v = s.values.Take(n) s.mu.RUnlock() return } func (s *tsafeInt64s) S() (out []interface{}) { s.mu.RLock() out = s.values.S() s.mu.RUnlock() return } func (s *tsafeInt64s) Int64s() (v Int64s) { s.mu.RLock() v = s.values.Copy() s.mu.RUnlock() return }
syncint64s.go
0.700178
0.458591
syncint64s.go
starcoder
package vesper import ( "strings" ) // QuoteSymbol represents a quoted expression var QuoteSymbol = defaultVM.Intern("quote") // QuasiquoteSymbol represents a quasiquoted expression var QuasiquoteSymbol = defaultVM.Intern("quasiquote") // UnquoteSymbol represents an unquoted expression var UnquoteSymbol = defaultVM.Intern("unquote") // UnquoteSplicingSymbol represents an unquote-splicing expression var UnquoteSplicingSymbol = defaultVM.Intern("unquote-splicing") // EmptyList - the value of (), terminates linked lists var EmptyList = initEmpty() // Cons - create a new list consisting of the first object and the rest of the list func Cons(car *Object, cdr *Object) *Object { return &Object{ Type: ListType, car: car, cdr: cdr, } } // Car - return the first object in a list func Car(lst *Object) *Object { if lst == EmptyList { return Null } return lst.car } // Cdr - return the rest of the list func Cdr(lst *Object) *Object { if lst == EmptyList { return lst } return lst.cdr } // Caar - return the Car of the Car of the list func Caar(lst *Object) *Object { return Car(Car(lst)) } // Cadr - return the Car of the Cdr of the list func Cadr(lst *Object) *Object { return Car(Cdr(lst)) } // Cdar - return the Cdr of the Car of the list func Cdar(lst *Object) *Object { return Car(Cdr(lst)) } // Cddr - return the Cdr of the Cdr of the list func Cddr(lst *Object) *Object { return Cdr(Cdr(lst)) } // Cadar - return the Car of the Cdr of the Car of the list func Cadar(lst *Object) *Object { return Car(Cdr(Car(lst))) } // Caddr - return the Car of the Cdr of the Cdr of the list func Caddr(lst *Object) *Object { return Car(Cdr(Cdr(lst))) } // Cdddr - return the Cdr of the Cdr of the Cdr of the list func Cdddr(lst *Object) *Object { return Cdr(Cdr(Cdr(lst))) } // Cadddr - return the Car of the Cdr of the Cdr of the Cdr of the list func Cadddr(lst *Object) *Object { return Car(Cdr(Cdr(Cdr(lst)))) } // Cddddr - return the Cdr of the Cdr of the Cdr of the Cdr of the list func Cddddr(lst *Object) *Object { return Cdr(Cdr(Cdr(Cdr(lst)))) } func initEmpty() *Object { return &Object{Type: ListType} //car and cdr are both nil } // ListEqual returns true if the object is equal to the argument func ListEqual(lst *Object, a *Object) bool { for lst != EmptyList { if a == EmptyList { return false } if !Equal(lst.car, a.car) { return false } lst = lst.cdr a = a.cdr } return lst == a } func listToString(lst *Object) string { var buf strings.Builder if lst != EmptyList && lst.cdr != EmptyList && Cddr(lst) == EmptyList { switch lst.car { case QuoteSymbol: buf.WriteString("'") buf.WriteString(Cadr(lst).String()) return buf.String() case QuasiquoteSymbol: buf.WriteString("`") buf.WriteString(Cadr(lst).String()) return buf.String() case UnquoteSymbol: buf.WriteString("~") buf.WriteString(Cadr(lst).String()) return buf.String() case UnquoteSplicingSymbol: buf.WriteString("~@") buf.WriteString(Cadr(lst).String()) return buf.String() } } buf.WriteString("(") delim := "" for lst != EmptyList { buf.WriteString(delim) delim = " " buf.WriteString(lst.car.String()) lst = lst.cdr } buf.WriteString(")") return buf.String() } // ListLength returns the length of the list func ListLength(lst *Object) int { if lst == EmptyList { return 0 } count := 1 o := lst.cdr for o != EmptyList { count++ o = o.cdr } return count } // MakeList creates a list of length count, with all values set to val func MakeList(count int, val *Object) *Object { result := EmptyList for i := 0; i < count; i++ { result = Cons(val, result) } return result } // ListFromValues creates a list from the given array func ListFromValues(values []*Object) *Object { p := EmptyList for i := len(values) - 1; i >= 0; i-- { v := values[i] p = Cons(v, p) } return p } // List creates a new list from the arguments func List(values ...*Object) *Object { return ListFromValues(values) } func listToArray(lst *Object) *Object { var elems []*Object for lst != EmptyList { elems = append(elems, lst.car) lst = lst.cdr } return ArrayFromElementsNoCopy(elems) } // ToList - convert the argument to a List, if possible func ToList(obj *Object) (*Object, error) { switch obj.Type { case ListType: return obj, nil case ArrayType: return ListFromValues(obj.elements), nil case StructType: return structToList(obj) case StringType: return stringToList(obj), nil } return nil, Error(ArgumentErrorKey, "to-list cannot accept ", obj.Type) } // Reverse reverses a linked list func Reverse(lst *Object) *Object { rev := EmptyList for lst != EmptyList { rev = Cons(lst.car, rev) lst = lst.cdr } return rev } // Flatten flattens a list into a single list func Flatten(lst *Object) *Object { result := EmptyList tail := EmptyList for lst != EmptyList { item := lst.car switch item.Type { case ListType: item = Flatten(item) case ArrayType: litem, _ := ToList(item) item = Flatten(litem) default: item = List(item) } if tail == EmptyList { result = item tail = result } else { tail.cdr = item } for tail.cdr != EmptyList { tail = tail.cdr } lst = lst.cdr } return result } // Concat joins two lists func Concat(seq1 *Object, seq2 *Object) (*Object, error) { rev := Reverse(seq1) if rev == EmptyList { return seq2, nil } lst := seq2 for rev != EmptyList { lst = Cons(rev.car, lst) rev = rev.cdr } return lst, nil }
list.go
0.69946
0.440048
list.go
starcoder
package gotalib // A simple moving average is formed by computing the average price of a security // over a specific number of periods. Most moving averages are based on closing // prices; for example, a 5-day simple moving average is the five-day sum of closing // prices divided by five. As its name implies, a moving average is an average that // moves. Old data is dropped as new data becomes available, causing the average // to move along the time scale. The example below shows a 5-day moving average // evolving over three days. // https://school.stockcharts.com/doku.php?id=technical_indicators:moving_averages // https://www.investopedia.com/terms/s/sma.asp // https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/sma type Sma struct { n int64 hist *CBuf sz int64 sum float64 } func NewSma(n int64) *Sma { return &Sma{ n: n, hist: NewCBuf(n), sz: 0, sum: 0, } } func (s *Sma) Update(v float64) float64 { s.sz++ old := s.hist.Append(v) s.sum += v - old if s.sz < s.n { return 0 } return s.sum / float64(s.n) } func (s *Sma) InitPeriod() int64 { return s.n - 1 } func (s *Sma) Valid() bool { return s.sz > s.InitPeriod() } // A simple moving average is formed by computing the average price of a security // over a specific number of periods. Most moving averages are based on closing // prices; for example, a 5-day simple moving average is the five-day sum of closing // prices divided by five. As its name implies, a moving average is an average that // moves. Old data is dropped as new data becomes available, causing the average // to move along the time scale. The example below shows a 5-day moving average // evolving over three days. // https://school.stockcharts.com/doku.php?id=technical_indicators:moving_averages // https://www.investopedia.com/terms/s/sma.asp // https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/sma func SmaArr(in []float64, n int64) []float64 { out := make([]float64, len(in)) s := NewSma(n) for i, v := range in { out[i] = s.Update(v) } return out }
sma.go
0.840684
0.68541
sma.go
starcoder
package onshape import ( "encoding/json" ) // BTPStatementVarDeclaration282 struct for BTPStatementVarDeclaration282 type BTPStatementVarDeclaration282 struct { BTPStatement269 BtType *string `json:"btType,omitempty"` Name *BTPIdentifier8 `json:"name,omitempty"` StandardType *string `json:"standardType,omitempty"` Type *BTPTypeName290 `json:"type,omitempty"` TypeName *string `json:"typeName,omitempty"` Value *BTPExpression9 `json:"value,omitempty"` } // NewBTPStatementVarDeclaration282 instantiates a new BTPStatementVarDeclaration282 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 NewBTPStatementVarDeclaration282() *BTPStatementVarDeclaration282 { this := BTPStatementVarDeclaration282{} return &this } // NewBTPStatementVarDeclaration282WithDefaults instantiates a new BTPStatementVarDeclaration282 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 NewBTPStatementVarDeclaration282WithDefaults() *BTPStatementVarDeclaration282 { this := BTPStatementVarDeclaration282{} return &this } // GetBtType returns the BtType field value if set, zero value otherwise. func (o *BTPStatementVarDeclaration282) GetBtType() string { if o == nil || o.BtType == nil { var ret string return ret } return *o.BtType } // GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPStatementVarDeclaration282) GetBtTypeOk() (*string, bool) { if o == nil || o.BtType == nil { return nil, false } return o.BtType, true } // HasBtType returns a boolean if a field has been set. func (o *BTPStatementVarDeclaration282) HasBtType() bool { if o != nil && o.BtType != nil { return true } return false } // SetBtType gets a reference to the given string and assigns it to the BtType field. func (o *BTPStatementVarDeclaration282) SetBtType(v string) { o.BtType = &v } // GetName returns the Name field value if set, zero value otherwise. func (o *BTPStatementVarDeclaration282) GetName() BTPIdentifier8 { if o == nil || o.Name == nil { var ret BTPIdentifier8 return ret } return *o.Name } // GetNameOk returns a tuple with the Name field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPStatementVarDeclaration282) GetNameOk() (*BTPIdentifier8, bool) { if o == nil || o.Name == nil { return nil, false } return o.Name, true } // HasName returns a boolean if a field has been set. func (o *BTPStatementVarDeclaration282) HasName() bool { if o != nil && o.Name != nil { return true } return false } // SetName gets a reference to the given BTPIdentifier8 and assigns it to the Name field. func (o *BTPStatementVarDeclaration282) SetName(v BTPIdentifier8) { o.Name = &v } // GetStandardType returns the StandardType field value if set, zero value otherwise. func (o *BTPStatementVarDeclaration282) GetStandardType() string { if o == nil || o.StandardType == nil { var ret string return ret } return *o.StandardType } // GetStandardTypeOk returns a tuple with the StandardType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPStatementVarDeclaration282) GetStandardTypeOk() (*string, bool) { if o == nil || o.StandardType == nil { return nil, false } return o.StandardType, true } // HasStandardType returns a boolean if a field has been set. func (o *BTPStatementVarDeclaration282) HasStandardType() bool { if o != nil && o.StandardType != nil { return true } return false } // SetStandardType gets a reference to the given string and assigns it to the StandardType field. func (o *BTPStatementVarDeclaration282) SetStandardType(v string) { o.StandardType = &v } // GetType returns the Type field value if set, zero value otherwise. func (o *BTPStatementVarDeclaration282) GetType() BTPTypeName290 { if o == nil || o.Type == nil { var ret BTPTypeName290 return ret } return *o.Type } // GetTypeOk returns a tuple with the Type field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPStatementVarDeclaration282) GetTypeOk() (*BTPTypeName290, bool) { if o == nil || o.Type == nil { return nil, false } return o.Type, true } // HasType returns a boolean if a field has been set. func (o *BTPStatementVarDeclaration282) HasType() bool { if o != nil && o.Type != nil { return true } return false } // SetType gets a reference to the given BTPTypeName290 and assigns it to the Type field. func (o *BTPStatementVarDeclaration282) SetType(v BTPTypeName290) { o.Type = &v } // GetTypeName returns the TypeName field value if set, zero value otherwise. func (o *BTPStatementVarDeclaration282) GetTypeName() string { if o == nil || o.TypeName == nil { var ret string return ret } return *o.TypeName } // GetTypeNameOk returns a tuple with the TypeName field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPStatementVarDeclaration282) GetTypeNameOk() (*string, bool) { if o == nil || o.TypeName == nil { return nil, false } return o.TypeName, true } // HasTypeName returns a boolean if a field has been set. func (o *BTPStatementVarDeclaration282) HasTypeName() bool { if o != nil && o.TypeName != nil { return true } return false } // SetTypeName gets a reference to the given string and assigns it to the TypeName field. func (o *BTPStatementVarDeclaration282) SetTypeName(v string) { o.TypeName = &v } // GetValue returns the Value field value if set, zero value otherwise. func (o *BTPStatementVarDeclaration282) GetValue() BTPExpression9 { if o == nil || o.Value == nil { var ret BTPExpression9 return ret } return *o.Value } // GetValueOk returns a tuple with the Value field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPStatementVarDeclaration282) GetValueOk() (*BTPExpression9, bool) { if o == nil || o.Value == nil { return nil, false } return o.Value, true } // HasValue returns a boolean if a field has been set. func (o *BTPStatementVarDeclaration282) HasValue() bool { if o != nil && o.Value != nil { return true } return false } // SetValue gets a reference to the given BTPExpression9 and assigns it to the Value field. func (o *BTPStatementVarDeclaration282) SetValue(v BTPExpression9) { o.Value = &v } func (o BTPStatementVarDeclaration282) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} serializedBTPStatement269, errBTPStatement269 := json.Marshal(o.BTPStatement269) if errBTPStatement269 != nil { return []byte{}, errBTPStatement269 } errBTPStatement269 = json.Unmarshal([]byte(serializedBTPStatement269), &toSerialize) if errBTPStatement269 != nil { return []byte{}, errBTPStatement269 } if o.BtType != nil { toSerialize["btType"] = o.BtType } if o.Name != nil { toSerialize["name"] = o.Name } if o.StandardType != nil { toSerialize["standardType"] = o.StandardType } if o.Type != nil { toSerialize["type"] = o.Type } if o.TypeName != nil { toSerialize["typeName"] = o.TypeName } if o.Value != nil { toSerialize["value"] = o.Value } return json.Marshal(toSerialize) } type NullableBTPStatementVarDeclaration282 struct { value *BTPStatementVarDeclaration282 isSet bool } func (v NullableBTPStatementVarDeclaration282) Get() *BTPStatementVarDeclaration282 { return v.value } func (v *NullableBTPStatementVarDeclaration282) Set(val *BTPStatementVarDeclaration282) { v.value = val v.isSet = true } func (v NullableBTPStatementVarDeclaration282) IsSet() bool { return v.isSet } func (v *NullableBTPStatementVarDeclaration282) Unset() { v.value = nil v.isSet = false } func NewNullableBTPStatementVarDeclaration282(val *BTPStatementVarDeclaration282) *NullableBTPStatementVarDeclaration282 { return &NullableBTPStatementVarDeclaration282{value: val, isSet: true} } func (v NullableBTPStatementVarDeclaration282) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBTPStatementVarDeclaration282) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
onshape/model_btp_statement_var_declaration_282.go
0.690037
0.417568
model_btp_statement_var_declaration_282.go
starcoder
package bookingclient import ( "encoding/json" ) // ReplaceBlockModel struct for ReplaceBlockModel type ReplaceBlockModel struct { // Start date and time from which the inventory will be blocked<br />Specify either a pure date or a date and time (without fractional second part) in UTC or with UTC offset as defined in <a href=\"https://en.wikipedia.org/wiki/ISO_8601\">ISO8601:2004</a> From string `json:"from"` // End date and time until which the inventory will be blocked. Cannot be more than 5 years after the start date.<br />Specify either a pure date or a date and time (without fractional second part) in UTC or with UTC offset as defined in <a href=\"https://en.wikipedia.org/wiki/ISO_8601\">ISO8601:2004</a> To string `json:"to"` GrossDailyRate MonetaryValueModel `json:"grossDailyRate"` // The list of time slices TimeSlices []CreateBlockTimeSliceModel `json:"timeSlices"` } // NewReplaceBlockModel instantiates a new ReplaceBlockModel 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 NewReplaceBlockModel(from string, to string, grossDailyRate MonetaryValueModel, timeSlices []CreateBlockTimeSliceModel) *ReplaceBlockModel { this := ReplaceBlockModel{} this.From = from this.To = to this.GrossDailyRate = grossDailyRate this.TimeSlices = timeSlices return &this } // NewReplaceBlockModelWithDefaults instantiates a new ReplaceBlockModel 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 NewReplaceBlockModelWithDefaults() *ReplaceBlockModel { this := ReplaceBlockModel{} return &this } // GetFrom returns the From field value func (o *ReplaceBlockModel) GetFrom() string { if o == nil { var ret string return ret } return o.From } // GetFromOk returns a tuple with the From field value // and a boolean to check if the value has been set. func (o *ReplaceBlockModel) GetFromOk() (*string, bool) { if o == nil { return nil, false } return &o.From, true } // SetFrom sets field value func (o *ReplaceBlockModel) SetFrom(v string) { o.From = v } // GetTo returns the To field value func (o *ReplaceBlockModel) GetTo() string { if o == nil { var ret string return ret } return o.To } // GetToOk returns a tuple with the To field value // and a boolean to check if the value has been set. func (o *ReplaceBlockModel) GetToOk() (*string, bool) { if o == nil { return nil, false } return &o.To, true } // SetTo sets field value func (o *ReplaceBlockModel) SetTo(v string) { o.To = v } // GetGrossDailyRate returns the GrossDailyRate field value func (o *ReplaceBlockModel) GetGrossDailyRate() MonetaryValueModel { if o == nil { var ret MonetaryValueModel return ret } return o.GrossDailyRate } // GetGrossDailyRateOk returns a tuple with the GrossDailyRate field value // and a boolean to check if the value has been set. func (o *ReplaceBlockModel) GetGrossDailyRateOk() (*MonetaryValueModel, bool) { if o == nil { return nil, false } return &o.GrossDailyRate, true } // SetGrossDailyRate sets field value func (o *ReplaceBlockModel) SetGrossDailyRate(v MonetaryValueModel) { o.GrossDailyRate = v } // GetTimeSlices returns the TimeSlices field value func (o *ReplaceBlockModel) GetTimeSlices() []CreateBlockTimeSliceModel { if o == nil { var ret []CreateBlockTimeSliceModel return ret } return o.TimeSlices } // GetTimeSlicesOk returns a tuple with the TimeSlices field value // and a boolean to check if the value has been set. func (o *ReplaceBlockModel) GetTimeSlicesOk() (*[]CreateBlockTimeSliceModel, bool) { if o == nil { return nil, false } return &o.TimeSlices, true } // SetTimeSlices sets field value func (o *ReplaceBlockModel) SetTimeSlices(v []CreateBlockTimeSliceModel) { o.TimeSlices = v } func (o ReplaceBlockModel) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["from"] = o.From } if true { toSerialize["to"] = o.To } if true { toSerialize["grossDailyRate"] = o.GrossDailyRate } if true { toSerialize["timeSlices"] = o.TimeSlices } return json.Marshal(toSerialize) } type NullableReplaceBlockModel struct { value *ReplaceBlockModel isSet bool } func (v NullableReplaceBlockModel) Get() *ReplaceBlockModel { return v.value } func (v *NullableReplaceBlockModel) Set(val *ReplaceBlockModel) { v.value = val v.isSet = true } func (v NullableReplaceBlockModel) IsSet() bool { return v.isSet } func (v *NullableReplaceBlockModel) Unset() { v.value = nil v.isSet = false } func NewNullableReplaceBlockModel(val *ReplaceBlockModel) *NullableReplaceBlockModel { return &NullableReplaceBlockModel{value: val, isSet: true} } func (v NullableReplaceBlockModel) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableReplaceBlockModel) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/clients/bookingclient/model_replace_block_model.go
0.80329
0.495361
model_replace_block_model.go
starcoder
package svgFill // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill type Fill int // en: For <animate>, fill defines the final state of the animation. // Value freeze (Keep the state of the last animation frame) | remove (Keep the // state of the first animation frame) // Default value remove // Animatable No func (el *Fill) Animate() {} // en: For <animateMotion>, fill defines the final state of the animation. // Value freeze (Keep the state of the last animation frame) | remove (Keep the // state of the first animation frame) //Default value remove //Animatable No func (el *Fill) AnimateMotion() {} // en: For <animateTransform>, fill defines the final state of the animation. // Value freeze (Keep the state of the last animation frame) | remove (Keep the // state of the first animation frame) // Default value remove // Animatable No func (el *Fill) AnimateTransform() {} // en: For <circle>, fill is a presentation attribute that defines the color of the // circle. // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) Circle() {} // en: For <ellipse>, fill is a presentation attribute that defines the color of the // ellipse. // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) Ellipse() {} // en: For <path>, fill is a presentation attribute that defines the color of the // interior of the shape. (Interior is define by the fill-rule attribute) // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) Path() {} // en: For <polygon>, fill is a presentation attribute that defines the color of the // interior of the shape. (Interior is define by the fill-rule attribute) // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) Polygon() {} // en: For <polyline>, fill is a presentation attribute that defines the color of the // interior of the shape. (Interior is define by the fill-rule attribute) // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) Polyline() {} // en: For <rect>, fill is a presentation attribute that defines the color of the // rectangle. // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) Rect() {} // en: For <set>, fill defines the final state of the animation. // Value freeze (Keep the state of the last animation frame) | remove (Keep the // state of the first animation frame) // Default value remove // Animatable No func (el *Fill) Set() {} // en: For <text>, fill is a presentation attribute that defines what the color of // the text. // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) Text() {} // en: For <textPath>, fill is a presentation attribute that defines the color of the // text. // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) TextPath() {} // en: For <tspan>, fill is a presentation attribute that defines the color of the // text. // Value <paint> // Default value black // Animatable Yes // Note: As a presentation attribute fill can be used as a CSS property. func (el *Fill) TSpan() {}
abstractType/svgFill/typeFill.go
0.843847
0.484685
typeFill.go
starcoder
package crypto import ( "crypto" "crypto/hmac" crand "crypto/rand" "math/big" ) // BlindPoint generates a random blinding factor, scalar multiplies it to the // supplied point, and returns both the new point and the blinding factor. func BlindPoint(p *Point) (*Point, []byte) { r, _, err := randScalar(p.Curve, crand.Reader) if err != nil { return nil, nil } Ax, Ay := p.Curve.ScalarMult(p.X, p.Y, r) A := &Point{Curve: p.Curve, X: Ax, Y: Ay} return A, r } // UnblindPoint removes the given blinding factor from the point. func UnblindPoint(p *Point, blind []byte) *Point { r := new(big.Int).SetBytes(blind) r.ModInverse(r, p.Curve.Params().N) x, y := p.Curve.ScalarMult(p.X, p.Y, r.Bytes()) return &Point{Curve: p.Curve, X: x, Y: y} } // This just executes a scalar mult and returns both the new point and its byte encoding. // It essentially "signs" a point with the given key. func SignPoint(P *Point, secret []byte) *Point { curve := P.Curve Qx, Qy := curve.ScalarMult(P.X, P.Y, secret) Q := &Point{Curve: curve, X: Qx, Y: Qy} return Q } // Derives the shared key used for redemption MACs func DeriveKey(hash crypto.Hash, N *Point, token []byte) []byte { h := hmac.New(hash.New, []byte("hash_derive_key")) h.Write(token) h.Write(N.Marshal()) return h.Sum(nil) } func CreateRequestBinding(hash crypto.Hash, key []byte, data [][]byte) []byte { h := hmac.New(hash.New, key) h.Write([]byte("hash_request_binding")) for i := 0; i < len(data); i++ { h.Write(data[i]) } return h.Sum(nil) } func CheckRequestBinding(hash crypto.Hash, key []byte, supplied []byte, observed [][]byte) bool { h := hmac.New(hash.New, key) h.Write([]byte("hash_request_binding")) for i := 0; i < len(observed); i++ { h.Write(observed[i]) } return hmac.Equal(supplied, h.Sum(nil)) } // Creates t, T=H(t), and blinding factor r // Turns out key generation is helpfully congruent to token generation and projection. func CreateBlindToken(h2cObj H2CObject) (token []byte, blindPoint *Point, blindFactor []byte, err error) { token, T, err := NewRandomPoint(h2cObj) if err != nil { return nil, nil, nil, err } // T = H(token) => Point // P := rT P, r := BlindPoint(T) return token, P, r, nil }
crypto/voprf.go
0.784608
0.438785
voprf.go
starcoder
package encoding import ( "bytes" "encoding/binary" "io" "github.com/lindb/lindb/pkg/stream" ) const ( adjustValue = 1 lengthOfHeader = 1 EmptyOffset = -1 ) // FixedOffsetEncoder represents the offset encoder with fixed length type FixedOffsetEncoder struct { values []int buf *bytes.Buffer max int bw *stream.BufferWriter } // NewFixedOffsetEncoder creates the fixed length offset encoder func NewFixedOffsetEncoder() *FixedOffsetEncoder { var buf bytes.Buffer bw := stream.NewBufferWriter(&buf) return &FixedOffsetEncoder{ buf: &buf, bw: bw, max: EmptyOffset, } } // IsEmpty returns if is empty func (e *FixedOffsetEncoder) IsEmpty() bool { return len(e.values) == 0 } // Size returns the size func (e *FixedOffsetEncoder) Size() int { return len(e.values) } // Reset resets the encoder context for reuse func (e *FixedOffsetEncoder) Reset() { e.bw.Reset() e.max = 0 e.values = e.values[:0] } // Add adds the offset value, func (e *FixedOffsetEncoder) Add(v int) { e.values = append(e.values, v) if e.max < v { e.max = v } } // FromValues resets the encoder, then init it with multi values. func (e *FixedOffsetEncoder) FromValues(values []int) { e.Reset() e.values = values for _, value := range values { if e.max < value { e.max = value } } } // MarshalBinary marshals the values to binary func (e *FixedOffsetEncoder) MarshalBinary() []byte { _ = e.WriteTo(e.buf) return e.buf.Bytes() } // WriteTo writes the data to the writer. func (e *FixedOffsetEncoder) WriteTo(writer io.Writer) error { if len(e.values) == 0 { return nil } if e.max < 0 { e.max = EmptyOffset } width := Uint32MinWidth(uint32(e.max + adjustValue)) // fixed value width e.bw.PutByte(byte(width)) // put all values with fixed length buf := make([]byte, 4) for _, value := range e.values { if value < 0 { value = EmptyOffset } binary.LittleEndian.PutUint32(buf, uint32(value+adjustValue)) if _, err := writer.Write(buf[:width]); err != nil { return err } } return nil } // FixedOffsetDecoder represents the fixed offset decoder, supports random reads offset by index type FixedOffsetDecoder struct { buf []byte width int scratch []byte } // NewFixedOffsetDecoder creates the fixed offset decoder func NewFixedOffsetDecoder(buf []byte) *FixedOffsetDecoder { if len(buf) == 0 { return &FixedOffsetDecoder{ buf: nil, } } return &FixedOffsetDecoder{ buf: buf[lengthOfHeader:], width: int(buf[0]), scratch: make([]byte, 4), } } // Header returns the length of header func (d *FixedOffsetDecoder) Header() int { return lengthOfHeader } // ValueWidth returns the width of all stored values func (d *FixedOffsetDecoder) ValueWidth() int { return d.width } // Size returns the size of offset values func (d *FixedOffsetDecoder) Size() int { if d.width == 0 { return 0 } return len(d.buf) / d.width } // Get gets the offset value by index func (d *FixedOffsetDecoder) Get(index int) (int, bool) { start := index * d.width if start < 0 || len(d.buf) == 0 || start >= len(d.buf) || d.width > 4 { return 0, false } end := start + d.width if end > len(d.buf) { return 0, false } copy(d.scratch, d.buf[start:end]) offset := int(binary.LittleEndian.Uint32(d.scratch)) - adjustValue if offset < 0 { return 0, false } return offset, true } func ByteSlice2Uint32(slice []byte) uint32 { var buf = make([]byte, 4) copy(buf, slice) return binary.LittleEndian.Uint32(buf) }
pkg/encoding/fixed_offset.go
0.748076
0.403244
fixed_offset.go
starcoder
package bitbox // BitBox is a dynamically sized bit container which allows // bits to be set and read quickly and somewhat efficiently. type BitBox struct { max int Bytes []byte } // NewBitBox returns a new BitBox configured for the given // number of bits. func NewBitBox(bits int) *BitBox { b := &BitBox{} b.Resize(bits) return b } // Resize will reallocate the BitBox, used both to optimize // future insertions, and to shrink the BitBox as needed. // The actual allocation will reflect a suitable byte size. func (b *BitBox) Resize(bits int) int { if bits > b.max { add := (bits >> 3) - len(b.Bytes) if bits&7 > 0 { add++ } b.Bytes = append(b.Bytes, make([]byte, add)...) } else { bytes := (bits >> 3) if bits&7 > 0 { bytes++ } b.Bytes = append([]byte(nil), b.Bytes[:bytes]...) } b.max = len(b.Bytes) << 3 return b.max } // position returns the byte index and a bitmask for a given bit. func (b *BitBox) Position(n int) (int, uint8) { byteNum := n >> 3 n -= (byteNum << 3) var bitPos uint8 = 1 bitPos <<= uint(7 - n) return byteNum, bitPos } // Get the given bit position, returning true if it is set. func (b *BitBox) Get(n int) bool { if n >= b.max { return false } byteNum, bitPos := b.Position(n) return !((b.Bytes[byteNum] & bitPos) == 0) } // Set the given bit position to true. func (b *BitBox) Set(n int) { byteNum, bitPos := b.Position(n) if n >= b.max { if n == 0 { b.Resize(1) } else { b.Resize(n) } } b.Bytes[byteNum] |= bitPos } // Unset sets the given bit position to false. func (b *BitBox) Unset(n int) { if n < b.max { byteNum, bitPos := b.Position(n) b.Bytes[byteNum] &^= bitPos } } // Toggle flips the given bit position. func (b *BitBox) Toggle(n int) { if n >= b.max { b.Resize(n) } byteNum, bitPos := b.Position(n) b.Bytes[byteNum] ^= bitPos } // GetByte returns a byte from the BitBox func (b *BitBox) GetByte(n int) byte { if len(b.Bytes) < n { return 0x0 } return b.Bytes[n] } // Size() returns the bit size of the BitBox func (b *BitBox) Size() int { return b.max //len(b.Bytes) * 8 } // Clear zeros all bits, effectively setting all bits to false. func (b *BitBox) Clear() { for i := range b.Bytes { b.Bytes[i] = 0x00 } } // And executes a bitwise AND operation on the given bit positions. func (b *BitBox) And(bs []int) bool { for _, n := range bs { if !b.Get(n) { return false } } return true } // Or executes a bitwise OR operation on the given bit positions. func (b *BitBox) Or(bs []int) bool { for _, n := range bs { if b.Get(n) { return true } } return false } // Xor executes a bitwise XOR operation on the given bit positions. func (b *BitBox) Xor(bs []int) bool { var c int for _, n := range bs { if b.Get(n) { c++ } if c > 1 { return false } } if c == 1 { return true } return false }
bitbox.go
0.761095
0.51013
bitbox.go
starcoder
package main import ( "bufio" "fmt" "os" ) type vector struct { x, y, z int } type planet struct { pos vector vel vector startpos vector startvel vector } func (p planet) String() string { return fmt.Sprintf("pos: %v, vel: %v", p.pos, p.vel) } type universe struct { planets []planet minX, minY, maxX, maxY int } func (u *universe) Print() { for _, p := range u.planets { if p.pos.x > u.maxX { u.maxX = p.pos.x } if p.pos.x < u.minX { u.minX = p.pos.x } if p.pos.y > u.maxY { u.maxY = p.pos.y } if p.pos.y < u.minY { u.minY = p.pos.y } } for y := u.minY; y <= u.maxY; y++ { for x := u.minX; x <= u.maxX; x++ { for i, p := range u.planets { if p.pos.x == x && p.pos.y == y { fmt.Printf("%d", i) } else { fmt.Printf(" ") } } } fmt.Printf("\n") } } func (u universe) applyGravityToPlanet(index int) { for j := range u.planets { if j != index { u.planets[index].applyGravity(u.planets[j]) } } } func (p *planet) applyGravity(other planet) { if p.pos.x < other.pos.x { p.vel.x++ } else if p.pos.x > other.pos.x { p.vel.x-- } if p.pos.y < other.pos.y { p.vel.y++ } else if p.pos.y > other.pos.y { p.vel.y-- } if p.pos.z < other.pos.z { p.vel.z++ } else if p.pos.z > other.pos.z { p.vel.z-- } } func (p *planet) applyVelocity() { p.pos.x += p.vel.x p.pos.y += p.vel.y p.pos.z += p.vel.z } func check(e error) { if e != nil { panic(e) } } func InitStateFromFile(filename string) universe { file, err := os.Open(filename) check(err) defer file.Close() var universe universe scanner := bufio.NewScanner(file) for scanner.Scan() { planet := planet{} fmt.Sscanf(scanner.Text(), "<x=%d, y=%d, z=%d>\n", &planet.pos.x, &planet.pos.y, &planet.pos.z) planet.startpos = planet.pos planet.startvel = planet.vel universe.planets = append(universe.planets, planet) } return universe } // greatest common divisor (GCD) via Euclidean algorithm func gcd(a, b int) int { for b != 0 { t := b b = a % b a = t } return a } // find Least Common Multiple (LCM) via GCD func lcm(a, b int, integers ...int) int { result := a * b / gcd(a, b) for i := 0; i < len(integers); i++ { result = lcm(result, integers[i]) } return result } func main() { fmt.Println("*** PART 2 ***") universe := InitStateFromFile(os.Args[1]) num_steps := 0 x_period := 0 y_period := 0 z_period := 0 last_x := 0 last_y := 0 last_z := 0 //fmt.Printf("\033[2J;\033[H") for x_period == 0 || y_period == 0 || z_period == 0 { //fmt.Printf("\033[H") //universe.Print() //time.Sleep(100 * time.Millisecond) for j := range universe.planets { universe.applyGravityToPlanet(j) } for j := range universe.planets { universe.planets[j].applyVelocity() } xs_aligned := true for j := range universe.planets { if universe.planets[j].vel.x != universe.planets[j].startvel.x || universe.planets[j].pos.x != universe.planets[j].startpos.x { xs_aligned = false break } } if xs_aligned { if last_x != 0 { x_period = num_steps - last_x } last_x = num_steps } ys_aligned := true for j := range universe.planets { if universe.planets[j].vel.y != universe.planets[j].startvel.y || universe.planets[j].pos.y != universe.planets[j].startpos.y { ys_aligned = false break } } if ys_aligned { if last_y != 0 { y_period = num_steps - last_y } last_y = num_steps } zs_aligned := true for j := range universe.planets { if universe.planets[j].vel.z != universe.planets[j].startvel.z || universe.planets[j].pos.z != universe.planets[j].startpos.z { zs_aligned = false break } } if zs_aligned { if last_z != 0 { z_period = num_steps - last_z } last_z = num_steps } num_steps++ } fmt.Println(lcm(x_period, y_period, z_period)) }
12/12-pt2.go
0.521959
0.464962
12-pt2.go
starcoder
// Package resources contains common objects and conversion functions. package resources const ( // fleetspeakPrefix is the default label prefix prepended to all client labels. fleetspeakPrefix = "alphabet-" // LocationNamePrefix is the Fleetspeak label prefix for sensor location name. LocationNamePrefix = fleetspeakPrefix + "location-name-" // LocationZonePrefix is the Fleetspeak label prefix for sensor location zone. LocationZonePrefix = fleetspeakPrefix + "location-zone-" ) // Location defines an arbirary organization of sensors, segmented into a least one zone. type Location struct { // The unique name of the location, e.g. "company1". Name string `mutable:"false"` // The list of zones or "segments" to organize sensors, e.g. {"dmz", "prod"}. Zones []string `mutable:"true"` // Last modified time of the message. Applied by the Store. LastModified string `mutable:"true"` } // ZoneFilterMode defines how the location zones will be selected. type ZoneFilterMode string const ( // All is to select all zones. All ZoneFilterMode = "all" // Include is to select only a specific subset of zones. Include ZoneFilterMode = "include" // Exclude is to select all zones except a specific subset of zones. Exclude ZoneFilterMode = "exclude" ) // LocationSelector represents a way to select zones from a given location. type LocationSelector struct { // The unique name of the location. Name string // Define how the location zones will be selected. Mode ZoneFilterMode // List of zones which to be filtered in or out of the location zones, depending on the Mode. Zones []string } // Rule is an IDS rule, e.g. Snort or Suricata. type Rule struct { // The unique rule ID. ID int64 `mutable:"false"` // The rule itself. Body string `mutable:"true"` // Select in which organization and zone the rule is enabled, e.g. "google:dmz". LocZones []string `mutable:"true"` // Last modified time of the message. Applied by the Store. LastModified string `mutable:"true"` } // SensorRequestType represents the type of sensor request message. type SensorRequestType string // Sensor request types as described in the sensor proto. const ( DeployRules SensorRequestType = "DeployRules" ReloadRules SensorRequestType = "ReloadRules" ) // SensorRequest contains the details and state of a sensor request message. type SensorRequest struct { // The request message ID. ID string `mutable:"false"` // The creation time of the message. Time string `mutable:"false"` // Fleetspeak client ID (Hex-encoded bytes). ClientID string `mutable:"false"` // Type of message. Type SensorRequestType `mutable:"false"` // Status of the request. Status string `mutable:"true"` // Last modified time of the message. Applied by the Store. LastModified string `mutable:"true"` } // SensorMessageType represents the type of message issued from a sensor. type SensorMessageType string const ( // Response represents a sensor response to a sensor request. Response SensorMessageType = "Response" // Alert represents a sensor alert. Alert SensorMessageType = "Alert" // Heartbeat represents a sensor heartbeat. Heartbeat SensorMessageType = "Heartbeat" ) // SensorMessage contains the details and state of a sensor message. type SensorMessage struct { // The message ID. ID string `mutable:"false"` // The creation time of the message. Time string `mutable:"false"` // Fleetspeak client ID (Hex-encoded bytes). ClientID string `mutable:"false"` // Type of message. Type SensorMessageType `mutable:"false"` // Host information of sender. Host string `mutable:"false"` // Status of the request. Status string `mutable:"false"` }
source/resources/resources.go
0.694095
0.474022
resources.go
starcoder
package correlation import ( "sort" "github.com/knightjdr/prohits-viz-analysis/pkg/matrix" "github.com/knightjdr/prohits-viz-analysis/pkg/slice" ) // Data correlation settings. type Data struct { Columns []string Dimension string // Either "column" or "row" (default). IgnoreSourceTargetMatches bool Matrix [][]float64 Method string Rows []string } // Correlate calculates the correlation between the columns or rows. func (data *Data) Correlate() [][]float64 { matrix, columns, rows := transposeMatrix(data) n := len(matrix) correlation := make([][]float64, n) for i := 0; i < n; i++ { correlation[i] = make([]float64, n) } calculateStatistic := getStatistic(data.Method) filterData := getDataFilter(matrix, data.IgnoreSourceTargetMatches, columns, rows) for i := 0; i < n; i++ { correlation[i][i] = 1 for j := i + 1; j < n; j++ { x, y := filterData(i, j) value := calculateStatistic(x, y) correlation[i][j] = value correlation[j][i] = value } } return correlation } func transposeMatrix(data *Data) ([][]float64, []string, []string) { if data.Dimension == "column" { return matrix.Transpose(data.Matrix), data.Rows, data.Columns } return data.Matrix, data.Columns, data.Rows } func getStatistic(method string) func([]float64, []float64) float64 { switch method { case "kendall": return Kendall case "spearman": return Spearman default: return Pearson } } func getDataFilter(matrix [][]float64, IgnoreSourceTargetMatches bool, columns, rows []string) func(int, int) ([]float64, []float64) { if IgnoreSourceTargetMatches { columnNameToIndicies := make(map[string][]int) for index, value := range columns { if _, ok := columnNameToIndicies[value]; !ok { columnNameToIndicies[value] = make([]int, 0) } columnNameToIndicies[value] = append(columnNameToIndicies[value], index) } addIndex := func(indices *[]int, name string) { if _, ok := columnNameToIndicies[name]; ok { (*indices) = append((*indices), columnNameToIndicies[name]...) } } return func(i, j int) ([]float64, []float64) { ignoreIndices := make([]int, 0) addIndex(&ignoreIndices, rows[i]) addIndex(&ignoreIndices, rows[j]) sort.Ints(ignoreIndices) ignoreIndices = slice.ReverseInt(ignoreIndices) x := make([]float64, len(matrix[i])) copy(x, matrix[i]) y := make([]float64, len(matrix[j])) copy(y, matrix[j]) for _, indexToIgnore := range ignoreIndices { x = append(x[:indexToIgnore], x[indexToIgnore+1:]...) y = append(y[:indexToIgnore], y[indexToIgnore+1:]...) } return x, y } } return func(i, j int) ([]float64, []float64) { return matrix[i], matrix[j] } }
pkg/correlation/matrix.go
0.727395
0.482368
matrix.go
starcoder
package bezier import ( "math" "github.com/adamcolton/geom/calc/comb" "github.com/adamcolton/geom/d2" "github.com/adamcolton/geom/d2/affine" ) // Bezier curve defined by a slice of control points type Bezier []d2.Pt // Pt1 fulfills d2.Pt1 and returns the parametric curve point on the bezier // curve. func (b Bezier) Pt1(t float64) d2.Pt { l := len(b) - 1 l64 := float64(l) if t == 1 { return b[l] } if t == 0 { return b[0] } // B(t) = ∑ binomialCo(l,i) * (1-t)^(l-i) * t^(i) * points[i] // let s = (1-t)^(l-i) * t^(i) // then s[i] = s[i-1] * t/(1-t) // and s[0] = (1-t) ^ l ti := 1 - t s := math.Pow(ti, l64) sd := t / ti w := &affine.Weighted{} for i, p := range b { b := float64(comb.Binomial(l, i)) w.Weight(p, s*b) s *= sd } return w.Centroid() } // Tangent returns a curve that is the derivative of the Bezier curve func (b Bezier) Tangent() Tangent { return Tangent{ Bezier: Bezier(diffPoints(b...)), } } // V1c0 aliases Tangent and fulfills d2.V1c0. This is more efficient if many // tangents points are needed from one curve. func (b Bezier) V1c0() d2.V1 { return b.Tangent() } // V1 fulfills d2.V1 and returns the derivate at t. func (b Bezier) V1(t float64) d2.V { return b.Tangent().V1(t) } // L fulfills d2.Limiter. func (Bezier) L(t, c int) d2.Limit { if t == 1 && c == 1 { return d2.LimitUnbounded } return d2.LimitUndefined } // VL fulfills d2.VLimiter. func (Bezier) VL(t, c int) d2.Limit { if t == 1 && (c == 1 || c == 0) { return d2.LimitUnbounded } return d2.LimitUndefined } // Tangent holds a first derivative of a Bezier curve which mathematically is // also a bezier curve, but the returned type is V instead of Pt. type Tangent struct { Bezier Bezier } // V1 fulfills d2.V1 func (bt Tangent) V1(t float64) d2.V { return bt.Bezier.Pt1(t).V() } func diffPoints(points ...d2.Pt) []d2.Pt { l := len(points) - 1 scale := float64(l) dps := make([]d2.Pt, l) prev := points[0] for i, p := range points[1:] { dps[i] = p.Subtract(prev).Multiply(scale).Pt() prev = p } return dps } // Cache pre-computes the Tangent and returns a BezierCache func (b Bezier) Cache() BezierCache { return BezierCache{ Bezier: b, Tangent: b.Tangent(), } } // BezierCache holds both a Bezier curve and it's Tangent and is more efficient if // both Pts and Vs will be needed from a curve. type BezierCache struct { Bezier Tangent } // V1 fulfills d2.V1 func (bc BezierCache) V1(t float64) d2.V { return bc.Tangent.V1(t) } // V1c0 fulfills d2.V1c0 func (bc BezierCache) V1c0() d2.V1 { return bc }
d2/curve/bezier/bezier.go
0.867612
0.500305
bezier.go
starcoder
package cryptypes import "database/sql/driver" // EncryptedUint32 supports encrypting Uint32 data type EncryptedUint32 struct { Field Raw uint32 } // Scan converts the value from the DB into a usable EncryptedUint32 value func (s *EncryptedUint32) Scan(value interface{}) error { return decrypt(value.([]byte), &s.Raw) } // Value converts an initialized EncryptedUint32 value into a value that can safely be stored in the DB func (s EncryptedUint32) Value() (driver.Value, error) { return encrypt(s.Raw) } // NullEncryptedUint32 supports encrypting nullable Uint32 data type NullEncryptedUint32 struct { Field Raw uint32 Empty bool } // Scan converts the value from the DB into a usable NullEncryptedUint32 value func (s *NullEncryptedUint32) Scan(value interface{}) error { if value == nil { s.Raw = 0 s.Empty = true return nil } return decrypt(value.([]byte), &s.Raw) } // Value converts an initialized NullEncryptedUint32 value into a value that can safely be stored in the DB func (s NullEncryptedUint32) Value() (driver.Value, error) { if s.Empty { return nil, nil } return encrypt(s.Raw) } // SignedUint32 supports signing Uint32 data type SignedUint32 struct { Field Raw uint32 Valid bool } // Scan converts the value from the DB into a usable SignedUint32 value func (s *SignedUint32) Scan(value interface{}) (err error) { s.Valid, err = verify(value.([]byte), &s.Raw) return } // Value converts an initialized SignedUint32 value into a value that can safely be stored in the DB func (s SignedUint32) Value() (driver.Value, error) { return sign(s.Raw) } // NullSignedUint32 supports signing nullable Uint32 data type NullSignedUint32 struct { Field Raw uint32 Empty bool Valid bool } // Scan converts the value from the DB into a usable NullSignedUint32 value func (s *NullSignedUint32) Scan(value interface{}) (err error) { if value == nil { s.Raw = 0 s.Empty = true s.Valid = true return nil } s.Valid, err = verify(value.([]byte), &s.Raw) return } // Value converts an initialized NullSignedUint32 value into a value that can safely be stored in the DB func (s NullSignedUint32) Value() (driver.Value, error) { if s.Empty { return nil, nil } return sign(s.Raw) } // SignedEncryptedUint32 supports signing and encrypting Uint32 data type SignedEncryptedUint32 struct { Field Raw uint32 Valid bool } // Scan converts the value from the DB into a usable SignedEncryptedUint32 value func (s *SignedEncryptedUint32) Scan(value interface{}) (err error) { s.Valid, err = decryptVerify(value.([]byte), &s.Raw) return } // Value converts an initialized SignedEncryptedUint32 value into a value that can safely be stored in the DB func (s SignedEncryptedUint32) Value() (driver.Value, error) { return encryptSign(s.Raw) } // NullSignedEncryptedUint32 supports signing and encrypting nullable Uint32 data type NullSignedEncryptedUint32 struct { Field Raw uint32 Empty bool Valid bool } // Scan converts the value from the DB into a usable NullSignedEncryptedUint32 value func (s *NullSignedEncryptedUint32) Scan(value interface{}) (err error) { if value == nil { s.Raw = 0 s.Empty = true s.Valid = true return nil } s.Valid, err = decryptVerify(value.([]byte), &s.Raw) return } // Value converts an initialized NullSignedEncryptedUint32 value into a value that can safely be stored in the DB func (s NullSignedEncryptedUint32) Value() (driver.Value, error) { if s.Empty { return nil, nil } return encryptSign(s.Raw) }
cryptypes/type_uint32.go
0.806434
0.523664
type_uint32.go
starcoder
package jio // Bool Generates a schema object that matches bool data type func Bool() *BoolSchema { return &BoolSchema{ rules: make([]func(*Context), 0, 3), } } var _ Schema = new(BoolSchema) // BoolSchema match bool data type type BoolSchema struct { baseSchema required *bool rules []func(*Context) } // SetPriority same as AnySchema.SetPriority func (b *BoolSchema) SetPriority(priority int) *BoolSchema { b.priority = priority return b } // PrependTransform same as AnySchema.PrependTransform func (b *BoolSchema) PrependTransform(f func(*Context)) *BoolSchema { b.rules = append([]func(*Context){f}, b.rules...) return b } // Transform same as AnySchema.Transform func (b *BoolSchema) Transform(f func(*Context)) *BoolSchema { b.rules = append(b.rules, f) return b } // Custom adds a custom validation func (b *BoolSchema) Custom(name string, args ...interface{}) *BoolSchema { return b.Transform(func(ctx *Context) { b.baseSchema.custom(ctx, name, args...) }) } // Required same as AnySchema.Required func (b *BoolSchema) Required() *BoolSchema { b.required = boolPtr(true) return b.PrependTransform(func(ctx *Context) { if ctx.Value == nil { ctx.Abort(ErrorRequired(ctx)) } }) } // Optional same as AnySchema.Optional func (b *BoolSchema) Optional() *BoolSchema { b.required = boolPtr(false) return b.PrependTransform(func(ctx *Context) { if ctx.Value == nil { ctx.Skip() } }) } // Default same as AnySchema.Default func (b *BoolSchema) Default(value bool) *BoolSchema { b.required = boolPtr(false) return b.PrependTransform(func(ctx *Context) { if ctx.Value == nil { ctx.Value = value } }) } // Set same as AnySchema.Set func (b *BoolSchema) Set(value bool) *BoolSchema { return b.Transform(func(ctx *Context) { ctx.Value = value }) } // Equal same as AnySchema.Equal func (b *BoolSchema) Equal(value bool) *BoolSchema { return b.Transform(func(ctx *Context) { if value != ctx.Value { ctx.ErrorBag.Add(ErrorEqual(ctx, value)) } }) } // When same as AnySchema.When func (b *BoolSchema) When(refPath string, condition interface{}, then Schema) *BoolSchema { return b.Transform(func(ctx *Context) { b.whenEqual(ctx, refPath, condition, then) }) } // Truthy allow for additional values to be considered valid booleans by converting them to true during validation. func (b *BoolSchema) Truthy(values ...interface{}) *BoolSchema { return b.Transform(func(ctx *Context) { for _, v := range values { if v == ctx.Value { ctx.Value = true } } }) } // Falsy allow for additional values to be considered valid booleans by converting them to false during validation. func (b *BoolSchema) Falsy(values ...interface{}) *BoolSchema { return b.Transform(func(ctx *Context) { for _, v := range values { if v == ctx.Value { ctx.Value = false } } }) } // Validate same as AnySchema.Validate func (b *BoolSchema) Validate(ctx *Context) { if ctx.Value != nil { if _, ok := (ctx.Value).(bool); !ok { ctx.Abort(ErrorTypeBool(ctx)) return } } if b.required == nil { b.Optional() } for _, rule := range b.rules { rule(ctx) if ctx.skip { return } } if ctx.ErrorBag.Empty() { if _, ok := (ctx.Value).(bool); !ok { ctx.Abort(ErrorTypeBool(ctx)) } } }
bool.go
0.713531
0.448004
bool.go
starcoder
package firestorm import ( "bytes" "encoding/binary" "fmt" "github.com/golang/protobuf/proto" ) var TermFreqKeyPrefix = []byte{'t'} type TermFreqRow struct { field uint16 term []byte docID []byte docNum uint64 value TermFreqValue } func NewTermVector(field uint16, pos uint64, start uint64, end uint64, arrayPos []uint64) *TermVector { rv := TermVector{} rv.Field = proto.Uint32(uint32(field)) rv.Pos = proto.Uint64(pos) rv.Start = proto.Uint64(start) rv.End = proto.Uint64(end) if len(arrayPos) > 0 { rv.ArrayPositions = make([]uint64, len(arrayPos)) for i, apv := range arrayPos { rv.ArrayPositions[i] = apv } } return &rv } func NewTermFreqRow(field uint16, term []byte, docID []byte, docNum uint64, freq uint64, norm float32, termVectors []*TermVector) *TermFreqRow { return InitTermFreqRow(&TermFreqRow{}, field, term, docID, docNum, freq, norm, termVectors) } func InitTermFreqRow(tfr *TermFreqRow, field uint16, term []byte, docID []byte, docNum uint64, freq uint64, norm float32, termVectors []*TermVector) *TermFreqRow { tfr.field = field tfr.term = term tfr.docID = docID tfr.docNum = docNum tfr.value.Freq = proto.Uint64(freq) tfr.value.Norm = proto.Float32(norm) tfr.value.Vectors = termVectors return tfr } func NewTermFreqRowKV(key, value []byte) (*TermFreqRow, error) { rv := TermFreqRow{} err := rv.ParseKey(key) if err != nil { return nil, err } err = rv.value.Unmarshal(value) if err != nil { return nil, err } return &rv, nil } func (tfr *TermFreqRow) ParseKey(key []byte) error { keyLen := len(key) if keyLen < 3 { return fmt.Errorf("invalid term frequency key, no valid field") } tfr.field = binary.LittleEndian.Uint16(key[1:3]) termStartPos := 3 termEndPos := bytes.IndexByte(key[termStartPos:], ByteSeparator) if termEndPos < 0 { return fmt.Errorf("invalid term frequency key, no byte separator terminating term") } tfr.term = key[termStartPos : termStartPos+termEndPos] docStartPos := termStartPos + termEndPos + 1 docEndPos := bytes.IndexByte(key[docStartPos:], ByteSeparator) tfr.docID = key[docStartPos : docStartPos+docEndPos] docNumPos := docStartPos + docEndPos + 1 tfr.docNum, _ = binary.Uvarint(key[docNumPos:]) return nil } func (tfr *TermFreqRow) KeySize() int { return 3 + len(tfr.term) + 1 + len(tfr.docID) + 1 + binary.MaxVarintLen64 } func (tfr *TermFreqRow) KeyTo(buf []byte) (int, error) { buf[0] = 't' binary.LittleEndian.PutUint16(buf[1:3], tfr.field) termLen := copy(buf[3:], tfr.term) buf[3+termLen] = ByteSeparator docLen := copy(buf[3+termLen+1:], tfr.docID) buf[3+termLen+1+docLen] = ByteSeparator used := binary.PutUvarint(buf[3+termLen+1+docLen+1:], tfr.docNum) return 3 + termLen + 1 + docLen + 1 + used, nil } func (tfr *TermFreqRow) Key() []byte { buf := make([]byte, tfr.KeySize()) n, _ := tfr.KeyTo(buf) return buf[:n] } func (tfr *TermFreqRow) ValueSize() int { return tfr.value.Size() } func (tfr *TermFreqRow) ValueTo(buf []byte) (int, error) { return tfr.value.MarshalTo(buf) } func (tfr *TermFreqRow) Value() []byte { buf := make([]byte, tfr.ValueSize()) n, _ := tfr.ValueTo(buf) return buf[:n] } func (tfr *TermFreqRow) String() string { vectors := "" for i, v := range tfr.value.GetVectors() { vectors += fmt.Sprintf("%d - Field: %d Pos: %d Start: %d End: %d ArrayPos: %v - %#v\n", i, v.GetField(), v.GetPos(), v.GetStart(), v.GetEnd(), v.GetArrayPositions(), v.ArrayPositions) } return fmt.Sprintf("TermFreqRow - Field: %d\n", tfr.field) + fmt.Sprintf("Term '%s' - % x\n", tfr.term, tfr.term) + fmt.Sprintf("DocID '%s' - % x\n", tfr.docID, tfr.docID) + fmt.Sprintf("DocNum %d\n", tfr.docNum) + fmt.Sprintf("Freq: %d\n", tfr.value.GetFreq()) + fmt.Sprintf("Norm: %f\n", tfr.value.GetNorm()) + fmt.Sprintf("Vectors:\n%s", vectors) } func (tfr *TermFreqRow) Field() uint16 { return tfr.field } func (tfr *TermFreqRow) Term() []byte { return tfr.term } func (tfr *TermFreqRow) DocID() []byte { return tfr.docID } func (tfr *TermFreqRow) DocNum() uint64 { return tfr.docNum } func (tfr *TermFreqRow) Norm() float32 { return tfr.value.GetNorm() } func (tfr *TermFreqRow) Freq() uint64 { return tfr.value.GetFreq() } func (tfr *TermFreqRow) Vectors() []*TermVector { return tfr.value.GetVectors() } func (tfr *TermFreqRow) DictionaryRowKeySize() int { return 3 + len(tfr.term) } func (tfr *TermFreqRow) DictionaryRowKeyTo(buf []byte) (int, error) { dr := NewDictionaryRow(tfr.field, tfr.term, 0) return dr.KeyTo(buf) } func (tfr *TermFreqRow) DictionaryRowKey() []byte { dr := NewDictionaryRow(tfr.field, tfr.term, 0) return dr.Key() } func TermFreqIteratorStart(field uint16, term []byte) []byte { buf := make([]byte, 3+len(term)+1) buf[0] = 't' binary.LittleEndian.PutUint16(buf[1:3], field) termLen := copy(buf[3:], term) buf[3+termLen] = ByteSeparator return buf } func TermFreqPrefixFieldTermDocId(field uint16, term []byte, docID []byte) []byte { buf := make([]byte, 3+len(term)+1+len(docID)+1) buf[0] = 't' binary.LittleEndian.PutUint16(buf[1:3], field) termLen := copy(buf[3:], term) buf[3+termLen] = ByteSeparator docLen := copy(buf[3+termLen+1:], docID) buf[3+termLen+1+docLen] = ByteSeparator return buf }
index/firestorm/termfreq.go
0.525856
0.405625
termfreq.go
starcoder
package consistentHash /* Package consistentHash provides a consistent hashing implementation using murmur3 with a 64bit ring space. Virtual nodes are used to provide a good distribution. This package has an almost identical API to StatHat's consistent package at https://github.com/stathat/consistent, although that packages uses a crc32 hash and a smaller number of vnodes by default. See: http://en.wikipedia.org/wiki/Consistent_hashing http://en.wikipedia.org/wiki/MurmurHash The only time an error will be returned from a Get(), Get2(), or GetN() call is if there are not enough members added Basic Example: ch := consistentHash.New() ch.Add("server1") ch.Add("server2") ch.Add("server3") for _,key := range []string{"A","B","C","D","E","F","G"} { server,err := ch.Get([]byte(key) if err != nil { panic(err) } fmt.Println("key=%s server=%s\n",key,server) } Outputs: key=A server=server3 key=B server=server3 key=C server=server1 key=D server=server3 key=E server=server2 key=F server=server2 key=G server=server1 Example with 3 servers and then removing a member: ch := consistentHash.New() ch.Add("server1") ch.Add("server2") ch.Add("server3") keys := []string{"<KEY>"} fmt.Println("3 servers") for _, key := range keys { server, _ := ch.Get([]byte(key)) fmt.Printf("key=%s server=%s\n", key, server) } fmt.Println("Removing server3") ch.Remove("server3") for _, key := range keys { server, _ := ch.Get([]byte(key)) fmt.Printf("key=%s server=%s\n", key, server) } Output: Output: 3 servers key=A server=server3 key=B server=server3 key=C server=server1 key=D server=server3 key=E server=server2 key=F server=server2 key=G server=server1 Removing server3 key=A server=server1 // remapped from 3->1 key=B server=server2 // remapped from 3->2 key=C server=server1 // stayed in same location key=D server=server1 // remapped from 3->1 key=E server=server2 // stayed in same location key=F server=server2 // stayed in same location key=G server=server1 // stayed in same location */
doc.go
0.724286
0.411584
doc.go
starcoder
package ranking import ( "bytes" "encoding/json" "fmt" "io" "log" "math" "sort" "github.com/kiteco/kiteco/kite-golib/decisiontree" ) // DataPoint abstracts a data point that is to be ranked by the model. type DataPoint struct { ID int // index of this DataPoint Name string // name of this data point if any Score float64 // score that this data point gets Features []float64 // features of this data point } // ByScore implements the sort interface, so that we can rank // the data points by score. type ByScore []*DataPoint func (d ByScore) Len() int { return len(d) } func (d ByScore) Swap(i, j int) { d[j], d[i] = d[i], d[j] } func (d ByScore) Less(i, j int) bool { return d[i].Score < d[j].Score } // Normalizer normalizes input data as follows: x = (x + Offset) * Scale. type Normalizer struct { Offset []float64 Scale []float64 } // Normalize normalizes the input feature vector by the normalizer's // offset vector and scale vector. func (n *Normalizer) Normalize(features []float64) []float64 { if len(features) != len(n.Offset) { log.Fatalln("feature length is not equal to length of offset", len(features), len(n.Offset)) } if len(features) != len(n.Scale) { log.Fatalln("feature length is not equal to length of scale") } for i := 0; i < len(features); i++ { features[i] = (features[i] + n.Offset[i]) * n.Scale[i] } return features } // Print prints co-efficients of the normalizer. func (n *Normalizer) Print() { log.Println("Offset:", n.Offset) log.Println("Scale:", n.Scale) } // Ranker contains the scorer that is used to compute scores for the documents // to be ranked. type Ranker struct { Scorer Scorer ScorerType string Normalizer *Normalizer FeatureLabels []string } // Rank ranks the input data points using the scores that the ranker generates for each data point. func (r *Ranker) Rank(data []*DataPoint) { for _, dp := range data { dp.Score = r.evaluate(dp.Features) } sort.Sort(sort.Reverse(ByScore(data))) } // Evaluate normalizes the feature vector and evaluate the score // of the feature vector computed by using the linear model. func (r *Ranker) evaluate(features []float64) float64 { features = r.Normalizer.Normalize(features) return r.Scorer.Evaluate(features) } // Scorer defines the functions that a scorer (for example, a linear scorer or a tree scorer) should implement. // Evaluate computes the score of a feature vector using the scorer. type Scorer interface { Evaluate([]float64) float64 Print() } // LinearScorer represents a linear regressor type LinearScorer struct { Weights []float64 } // Print prints the weights of the linear model. func (l *LinearScorer) Print() { log.Println("Weights:", l.Weights) } // Evaluate returns the inner product of the weights and the input feature vector. func (l *LinearScorer) Evaluate(features []float64) float64 { if len(features) != len(l.Weights) { log.Fatal("feature length is not equal to lengh of offsets", len(features), len(l.Weights)) } var score float64 for i, f := range features { score += f * l.Weights[i] } return score } // A Kernel represents a Mercer kernel function. type Kernel interface { Evaluate(a, b []float64) float64 } // KernelScorer computes scores using Kernel. type KernelScorer struct { Support [][]float64 // the regression vectors Coefs []float64 // the coefficients for each regression vector Kernel Kernel } // Print prints out coefficients of a kernel scorer. func (s *KernelScorer) Print() { log.Println("Coefs:", s.Coefs) } // Evaluate maps a feature vector to a score. func (s *KernelScorer) Evaluate(features []float64) float64 { if len(s.Support) > 0 && len(features) != len(s.Support[0]) { log.Fatalf("expected feature size %d but receieved %d\n", len(s.Support[0]), len(features)) } var score float64 for i, c := range s.Coefs { score += c * s.Kernel.Evaluate(s.Support[i], features) } return score } // NewKernelScorer returns a pointer to a new KernelScorer. func NewKernelScorer(support [][]float64, coefs []float64, kernel Kernel) *KernelScorer { if len(support) != len(coefs) { log.Fatalf("Length mismatch: support=%d, coefs=%d\n", len(support), len(coefs)) } return &KernelScorer{ Support: support, Coefs: coefs, Kernel: kernel, } } // RbfKernel implements the radial basis function. type RbfKernel struct { Gamma float64 // Coefficient in exponent (always negative) } // NewRbfKernelScorer returns a RbfKernelScorer func NewRbfKernelScorer(support [][]float64, coefs []float64, gamma float64) *KernelScorer { return NewKernelScorer(support, coefs, &RbfKernel{gamma}) } // Evaluate returns the result of RBF(a, b) func (k *RbfKernel) Evaluate(a, b []float64) float64 { if len(a) != len(b) { log.Fatalf("Length mismatch: %d vs %d\n", len(a), len(b)) } // Compute the squared euclidean distance between A and B var ssd float64 for i := range a { ssd += (a[i] - b[i]) * (a[i] - b[i]) } return math.Exp(k.Gamma * ssd) } // NewRankerFromJSON loads a ranker from json. func NewRankerFromJSON(r io.Reader) (*Ranker, error) { var intermediate struct { Normalizer *Normalizer Scorer json.RawMessage ScorerType string FeatureLabels []string } d := json.NewDecoder(r) err := d.Decode(&intermediate) if err != nil { return nil, fmt.Errorf("error decoding top-level json: %v", err) } ranker := &Ranker{ Normalizer: intermediate.Normalizer, ScorerType: intermediate.ScorerType, FeatureLabels: intermediate.FeatureLabels, } switch intermediate.ScorerType { case "Linear": var scorer LinearScorer err := json.Unmarshal(intermediate.Scorer, &scorer) if err != nil { return nil, fmt.Errorf("error deserializing linear scorer: %v", err) } ranker.Scorer = &scorer case "RbfKernel": var params struct { Support [][]float64 Coefs []float64 Gamma float64 } err := json.Unmarshal(intermediate.Scorer, &params) if err != nil { return nil, fmt.Errorf("error deserializing RBF kernel scorer: %v", err) } ranker.Scorer = NewRbfKernelScorer(params.Support, params.Coefs, params.Gamma) case "TreeEnsemble": ranker.Scorer, err = decisiontree.Load(bytes.NewBuffer(intermediate.Scorer)) if err != nil { return nil, fmt.Errorf("error deserializing tree ensemble scorer: %v", err) } default: return nil, fmt.Errorf("found unknown scorer type '%s'", intermediate.ScorerType) } return ranker, nil } // NewScorerNormalizerFromJSON returns a Scorer and *Normalizer read from json. func NewScorerNormalizerFromJSON(r io.Reader) (Scorer, *Normalizer, error) { var intermediate struct { Normalizer *Normalizer Scorer json.RawMessage ScorerType string FeatureLabels []string } d := json.NewDecoder(r) err := d.Decode(&intermediate) if err != nil { return nil, nil, fmt.Errorf("error decoding top-level json: %v", err) } normalizer := intermediate.Normalizer var scorer Scorer switch intermediate.ScorerType { case "Linear": var scorerLin LinearScorer err := json.Unmarshal(intermediate.Scorer, &scorerLin) if err != nil { return nil, nil, fmt.Errorf("error deserializing linear scorer: %v", err) } scorer = &scorerLin case "RbfKernel": var params struct { Support [][]float64 Coefs []float64 Gamma float64 } err := json.Unmarshal(intermediate.Scorer, &params) if err != nil { return nil, nil, fmt.Errorf("error deserializing RBF kernel scorer: %v", err) } scorer = NewRbfKernelScorer(params.Support, params.Coefs, params.Gamma) case "TreeEnsemble": scorer, err = decisiontree.Load(bytes.NewBuffer(intermediate.Scorer)) if err != nil { return nil, nil, fmt.Errorf("error deserializing tree ensemble scorer: %v", err) } default: return nil, nil, fmt.Errorf("found unknown scorer type '%s'", intermediate.ScorerType) } return scorer, normalizer, nil }
kite-go/ranking/models.go
0.743913
0.469642
models.go
starcoder
// Package data implements Data API package data import ( "time" "github.com/farshidtz/senml/v2" ) //Specifying which field needs to be denormalized type DenormMask int32 const ( DenormMaskName DenormMask = 1 << iota DenormMaskTime DenormMaskUnit DenormMaskValue DenormMaskSum ) // RecordSet describes the recordset returned on querying the Data API type RecordSet struct { // SelfLink is the SelfLink of the returned recordset in the Data API SelfLink string `json:"selfLink"` // Data is a SenML object with data records, where // Name (bn and n) constitute the resource BrokerURL of the corresponding time series Data senml.Pack `json:"data"` // Time is the time of query in seconds TimeTook float64 `json:"took"` //Next link for the same query, in case there more entries to follow for the same query NextLink string `json:"nextLink,omitempty"` //Total number of entries Count *int `json:"count,omitempty"` } type Query struct { // From is the Time from which the data needs to be fetched From time.Time // Time to which the data needs to be fetched To time.Time // SortAsc if set to true, oldest measurements are listed first in the resulting pack. If set to false, latest entries are listed first. SortAsc bool // PerPage: in case of paginated query, number of measurements returned as part of the query. In case of streamed query, number of measurements per pack in the time series PerPage int // Denormalize is a set of flags to be set based on the fields to be denormalized (Base field) Denormalize DenormMask // AggrFunc is the function performing the aggregation AggrFunc string // AggrWindow is the duration for aggregation AggrWindow time.Duration // Limit is applicable only for streamed queries Limit int // Offset is applicable only for streamed queries Offset int // Page is applicable only for paginated queries Page int // Count: if enabled, it will return the total number of entries to the query. // applicable only for paginated queries Count bool }
vendor/github.com/linksmart/historical-datastore/data/data.go
0.657428
0.443721
data.go
starcoder
package bst // New Initializes BST func New(less, isEqual CompareKeys) *BST { return &BST{ Head: nil, LessThan: less, isKeyEqual: isEqual, } } func (tree *BST) Insert(key, data interface{}) error { newNode := &BSTNode{key, data, nil, nil} if tree.Head == nil { tree.Head = newNode return nil } temp := tree.Head for { if tree.isKeyEqual(newNode.Key, temp.Key) { return ErrDuplicateNode } lessThanTemp := tree.LessThan(newNode.Key, temp.Key) if temp.Left == nil && lessThanTemp { temp.Left = newNode return nil } else if temp.Left != nil && lessThanTemp { temp = temp.Left } else if temp.Right == nil && !lessThanTemp { temp.Right = newNode return nil } else { temp = temp.Right } } } func (tree *BST) SearchNode(key interface{}) (*BSTNode, error) { temp := tree.Head for temp != nil { if tree.isKeyEqual(key, temp.Key) { return temp, nil } else if lessThanTemp := tree.LessThan(key, temp.Key); lessThanTemp { temp = temp.Left } else { temp = temp.Right } } return nil, ErrNotFoundNode } func (tree *BST) Search(key interface{}) (interface{}, error) { node, err := tree.SearchNode(key) if err != nil { return nil, err } return node.Data, nil } func (root *BSTNode) SubTreeMin() (*BSTNode, *BSTNode) { var temp, parent *BSTNode = root, nil for temp != nil { if temp.Left == nil { break } parent, temp = temp, temp.Left } return temp, parent } func (tree *BST) FindMin() (key interface{}, data interface{}) { min, _ := tree.Head.SubTreeMin() if min == nil { return nil, nil } return min.Key, min.Data } func (root *BSTNode) SubTreeMax() (*BSTNode, *BSTNode) { var temp, parent *BSTNode = root, nil for temp != nil { if temp.Right == nil { break } parent, temp = temp, temp.Right } return temp, parent } func (tree *BST) FindMax() (key interface{}, data interface{}) { max, _ := tree.Head.SubTreeMax() if max == nil { return nil, nil } return max.Key, max.Data } func (tree *BST) Delete(key interface{}) error { if tree.Head == nil { return ErrNotFoundNode } return tree.Head.DeleteNode(tree, key) } func (n *BSTNode) replaceNode(parent, replacement *BSTNode) { if parent.Left == n { parent.Left = replacement } else { parent.Right = replacement } } func (n *BSTNode) DeleteNode(tree *BST, key interface{}) error { var temp, parent *BSTNode = n, nil for temp != nil { if tree.isKeyEqual(temp.Key, key) { // has both children if temp.Left != nil && temp.Right != nil { replacement, replacementParent := temp.Right, temp // replacement will be min most of right subtree if repl, parentRepl := temp.Right.SubTreeMin(); parentRepl != nil { replacement, replacementParent = repl, parentRepl } temp.Key, temp.Data = replacement.Key, replacement.Data // transfer data from replacement node temp, parent = replacement, replacementParent key = replacement.Key // delete replacement } else if temp.Left == nil && temp.Right == nil { // has no children temp.replaceNode(parent, nil) return nil } else if temp.Left != nil { // only has left child temp.replaceNode(parent, temp.Left) return nil } else { // only has right child temp.replaceNode(parent, temp.Right) return nil } } else if lessThanTemp := tree.LessThan(key, temp.Key); lessThanTemp { // search for target node parent = temp temp = temp.Left } else { parent = temp temp = temp.Right } } return ErrNotFoundNode }
bst/bst.go
0.538983
0.632928
bst.go
starcoder
package main /** 有一个正整数数组arr,现给你一个对应的查询数组queries,其中queries[i] = [Li,Ri]。 对于每个查询i,请你计算从Li到Ri的XOR值(即arr[Li] xor arr[Li+1] xor ... xor arr[Ri])作为本次查询的结果。 并返回一个包含给定查询queries所有结果的数组。 示例 1: 输入:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] 输出:[2,7,14,8] 解释: 数组中元素的二进制表示形式是: 1 = 0001 3 = 0011 4 = 0100 8 = 1000 查询的 XOR 值为: [0,1] = 1 xor 3 = 2 [1,2] = 3 xor 4 = 7 [0,3] = 1 xor 3 xor 4 xor 8 = 14 [3,3] = 8 示例 2: 输入:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]] 输出:[8,0,4,4] 提示: 1 <= arr.length <= 3 *10^4 1 <= arr[i] <= 10^9 1 <= queries.length <= 3 * 10^4 queries[i].length == 2 0 <= queries[i][0] <= queries[i][1] < arr.length */ /** 前缀和 */ func xorQueries(arr []int, queries [][]int) []int { n := len(arr) dp := make([]int, n+1) for i := 1; i <= n; i++ { dp[i] = dp[i-1] ^ arr[i-1] } m := len(queries) res := make([]int, m) for i := 0; i < m; i++ { x := queries[i][0] y := queries[i][1] res[i] = dp[x] ^ dp[y+1] } return res } /** 树状数组 */ func xorQueries2(arr []int, queries [][]int) []int { n := len(arr) m := len(queries) c := make([]int, 100009) var lowbit func(x int) int lowbit = func(x int) int { return x & -x } var add func(x int, u int) add = func(x int, u int) { for i := x; i <= n; i += lowbit(i) { c[i] ^= u } } var query func(x int) int query = func(x int) int { ans := 0 for i := x; i > 0; i -= lowbit(i) { ans ^= c[i] } return ans } for i := 1; i <= n; i++ { add(i, arr[i-1]) } res := make([]int, m) for i := 0; i < m; i++ { l := queries[i][0] + 1 r := queries[i][1] + 1 res[i] = query(r) ^ query(l-1) } return res } /** class Solution { int n; int[] c = new int[100009]; int lowbit(int x) { return x & -x; } void add(int x, int u) { for (int i = x; i <= n; i += lowbit(i)) c[i] ^= u; } int query(int x) { int ans = 0; for (int i = x; i > 0; i -= lowbit(i)) ans ^= c[i]; return ans; } public int[] xorQueries(int[] arr, int[][] qs) { n = arr.length; int m = qs.length; for (int i = 1; i <= n; i++) add(i, arr[i - 1]); int[] ans = new int[m]; for (int i = 0; i < m; i++) { int l = qs[i][0] + 1, r = qs[i][1] + 1; ans[i] = query(r) ^ query(l - 1); } return ans; } } class Solution { public int[] xorQueries(int[] arr, int[][] queries) { int n = arr.length; int[] dp = new int[n + 1]; for (int i = 1; i <= n; i++) { dp[i] = dp[i - 1] ^ arr[i - 1]; } int m = queries.length; int[] res = new int[m]; for (int i = 0; i < m; i++) { int x = queries[i][0]; int y = queries[i][1]; res[i] = dp[x] ^ dp[y + 1]; } return res; } } */ func main() { }
leetcode/xorQueries/xorQueries.go
0.507324
0.471649
xorQueries.go
starcoder
package persistent_treap import ( "log" "math/rand" ) type PersistentTreap struct { root *treapNode } func NewPersistentTreap() PersistentTreap { return PersistentTreap{root: nil} } func (tree PersistentTreap) Find(key Sortable) bool { return tree.root.find(key) } func (tree PersistentTreap) GetValue(key Sortable) (Equitable, bool) { return tree.root.getValue(key) } // Return a new tree whose data is equal to previous tree + key, value func (tree PersistentTreap) Insert(key Sortable, value Equitable) PersistentTreap { newRoot := tree.root.insert(key, value) if newRoot == tree.root { return tree } return PersistentTreap{newRoot} } // Return a new tree whose data is equal to previous tree - key. // If the key is not exist, the new tree's root is the same as previous one func (tree PersistentTreap) Remove(key Sortable) PersistentTreap { newRoot := tree.root.remove(key) if newRoot == tree.root { return tree } return PersistentTreap{newRoot} } func (tree PersistentTreap) Size() uint32 { return tree.root.size() } func (tree PersistentTreap) Clear() PersistentTreap { return NewPersistentTreap() } type TreapKeyValueRef struct { Key *Sortable Value *Equitable } func (u *PersistentTreap) GetAllKeyValue() []TreapKeyValueRef { var uKV []TreapKeyValueRef u.root.getAllKeyValue(&uKV) return uKV } func IsSameTreap(u, v PersistentTreap) bool { if u.Size() != v.Size() { return false } uKV := make([]TreapKeyValueRef, 0, u.Size()) vKV := make([]TreapKeyValueRef, 0, u.Size()) u.root.getAllKeyValue(&uKV) v.root.getAllKeyValue(&vKV) if len(uKV) != len(vKV) || len(uKV) != int(u.Size()) { log.Panicf("keyValue size not equal, len(u):%v, len(v):%v, size:%v", len(uKV), len(vKV), u.Size()) } for i := 0; i < len(uKV); i++ { if !(*uKV[i].Key).Equals(*vKV[i].Key) || !(*uKV[i].Value).Equals(*vKV[i].Value) { return false } } return true } type Equitable interface { Equals(b Equitable) bool } type Sortable interface { Equitable Less(b Sortable) bool } type treapNode struct { left *treapNode right *treapNode key Sortable val Equitable priority uint32 sz uint32 } func newTreapNode(key Sortable, value Equitable) *treapNode { return &treapNode{ left: nil, right: nil, key: key, val: value, priority: rand.Uint32(), sz: 1, } } func (u *treapNode) updateSize() { if u != nil { u.sz = u.left.size() + u.right.size() + 1 } } // If leftEqual is true, means the range is (-∞, key], (key, +∞) // Otherwise the range is (-∞, key), [key, +∞) func split(u *treapNode, key Sortable, leftEqual bool) (*treapNode, *treapNode) { if u == nil { return nil, nil } newRoot := *u if key.Less(newRoot.key) || (!leftEqual && key.Equals(newRoot.key)) { leftNode, rightNode := split(newRoot.left, key, leftEqual) newRoot.left = rightNode newRoot.updateSize() return leftNode, &newRoot } else { leftNode, rightNode := split(newRoot.right, key, leftEqual) newRoot.right = leftNode newRoot.updateSize() return &newRoot, rightNode } } func merge(u *treapNode, v *treapNode) *treapNode { if u == nil { return v } else if v == nil { return u } leftBigger := true if u.priority < v.priority { leftBigger = false } else if u.priority == v.priority { if rand.Uint32()%2 == 1 { leftBigger = false } } if leftBigger { u.right = merge(u.right, v) u.updateSize() return u } else { v.left = merge(u, v.left) v.updateSize() return v } } func (u *treapNode) find(key Sortable) bool { _, ret := u.getValue(key) return ret } func (u *treapNode) getValue(key Sortable) (Equitable, bool) { node := u for { if node == nil { return nil, false } if key.Equals(node.key) { return node.val, true } else if key.Less(node.key) { node = node.left } else { node = node.right } } } func (u *treapNode) insert(key Sortable, value Equitable) *treapNode { if u == nil { return newTreapNode(key, value) } oldValue, isFind := u.getValue(key) if isFind { if oldValue.Equals(value) { return u } root := *u node := &root for { if key.Equals(node.key) { node.val = value break } else if key.Less(node.key) { newLeft := *node.left node.left = &newLeft node = node.left } else { newRight := *node.right node.right = &newRight node = node.right } } return &root } newLeft, newRight := split(u, key, true) return merge(merge(newLeft, newTreapNode(key, value)), newRight) } func (u *treapNode) remove(key Sortable) *treapNode { if u == nil || !u.find(key) { return u } left1, right1 := split(u, key, false) _, right2 := split(right1, key, true) return merge(left1, right2) } func (u *treapNode) size() uint32 { if u == nil { return 0 } return u.sz } func (u *treapNode) getAllKeyValue(s *[]TreapKeyValueRef) { if u == nil { return } u.left.getAllKeyValue(s) *s = append(*s, TreapKeyValueRef{&u.key, &u.val}) u.right.getAllKeyValue(s) }
persistent_treap/persistent_treap.go
0.747524
0.486819
persistent_treap.go
starcoder
// Package other wraps an hash-to-curve implementation and exposes functions for operations on points and scalars. package other import ( nist "crypto/elliptic" "fmt" "math/big" "github.com/bytemare/crypto/group/internal" Curve "github.com/armfazh/h2c-go-ref/curve" C "github.com/armfazh/tozan-ecc/curve" "github.com/armfazh/tozan-ecc/field" ) // Point implements the Point interface for Hash-to-Curve points. type Point struct { *Hash2Curve *curve point C.Point } // Add adds the argument to the receiver, sets the receiver to the result and returns it. func (p *Point) Add(element internal.Point) internal.Point { if element == nil { panic("element is nil") } po, ok := element.(*Point) if !ok { panic("could not cast to same group element : wrong group ?") } return &Point{ Hash2Curve: p.Hash2Curve, curve: p.curve, point: p.curve.Add(p.point, po.point), } } // Sub subtracts the argument from the receiver, sets the receiver to the result and returns it. func (p *Point) Sub(element internal.Point) internal.Point { if element == nil { panic("element is nil") } pt, ok := element.(*Point) if !ok { panic("could not cast to same group element : wrong group ?") } return &Point{ Hash2Curve: p.Hash2Curve, curve: p.curve, point: p.curve.Add(p.point, p.Neg(pt.point)), } } // Mult returns the scalar multiplication of the receiver element with the given scalar. func (p *Point) Mult(scalar internal.Scalar) internal.Point { sc, ok := scalar.(*Scalar) if !ok { panic("could not cast to hash2curve scalar") } h2 := getH2C(p.suite, nil) if !h2.GetHashToScalar().GetScalarField().IsEqual(sc.f) { panic("cannot multiply with scalar from a different field") } return &Point{ Hash2Curve: p.Hash2Curve, curve: p.curve, point: p.ScalarMult(p.point, sc.s.Polynomial()[0]), } } // InvertMult returns the scalar multiplication of the receiver element with the inverse of the given scalar. func (p *Point) InvertMult(s internal.Scalar) internal.Point { if s == nil { panic(errParamNilScalar) } return p.Mult(s.Invert()) } // IsIdentity returns whether the element is the Group's identity element. func (p *Point) IsIdentity() bool { return p.point.IsIdentity() } // Copy returns a copy of the element. func (p *Point) Copy() internal.Point { return &Point{ Hash2Curve: p.Hash2Curve, curve: p.curve, point: p.point.Copy(), } } // Bytes returns the compressed byte encoding of the element. func (p *Point) Bytes() []byte { x := p.point.X().Polynomial()[0] y := p.point.Y().Polynomial()[0] return encodeSignPrefix(x, y, pointLen(p.Field().BitLen())) } // Decode decodes the input an sets the current element to its value, and returns it. func (p *Point) Decode(input []byte) (internal.Point, error) { if p.id == Curve.P256 || p.id == Curve.P384 || p.id == Curve.P521 { x, y := nist.UnmarshalCompressed(h2cToNist(p.id), input) if x == nil { return nil, errParamDecPoint } if err := p.set(x, y); err != nil { return nil, err } return p, nil } return p.recoverPoint(input) } func (p *Point) set(x, y *big.Int) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("%v", r) } }() X := p.Field().Elt(x) Y := p.Field().Elt(y) p.point = p.NewPoint(X, Y) return err } func getX(f field.Field, input []byte) (*big.Int, error) { byteLen := (f.BitLen() + 7) / 8 if len(input) != 1+byteLen { return nil, errParamInvalidSize } if input[0] != 2 && input[0] != 3 { return nil, errParamInvalidFormat } x := new(big.Int).SetBytes(input[1:]) if x.Cmp(f.Order()) >= 0 { return nil, errParamDecXExceeds } return x, nil }
group/other/point.go
0.906991
0.518302
point.go
starcoder
package types import ( "github.com/jcmturner/asn1" ) // Reference: https://www.ietf.org/rfc/rfc4120.txt // Section: 5.2.6 /* AuthorizationData -- NOTE: AuthorizationData is always used as an OPTIONAL field and -- should not be empty. AuthorizationData ::= SEQUENCE OF SEQUENCE { ad-type [0] Int32, ad-data [1] OCTET STRING } ad-data This field contains authorization data to be interpreted according to the value of the corresponding ad-type field. ad-type This field specifies the format for the ad-data subfield. All negative values are reserved for local use. Non-negative values are reserved for registered use. Each sequence of type and data is referred to as an authorization element. Elements MAY be application specific; however, there is a common set of recursive elements that should be understood by all implementations. These elements contain other elements embedded within them, and the interpretation of the encapsulating element determines which of the embedded elements must be interpreted, and which may be ignored. These common authorization data elements are recursively defined, meaning that the ad-data for these types will itself contain a sequence of authorization data whose interpretation is affected by the encapsulating element. Depending on the meaning of the encapsulating element, the encapsulated elements may be ignored, might be interpreted as issued directly by the KDC, or might be stored in a separate plaintext part of the ticket. The types of the encapsulating elements are specified as part of the Kerberos specification because the behavior based on these values should be understood across implementations, whereas other elements need only be understood by the applications that they affect. Authorization data elements are considered critical if present in a ticket or authenticator. If an unknown authorization data element type is received by a server either in an AP-REQ or in a ticket contained in an AP-REQ, then, unless it is encapsulated in a known authorization data element amending the criticality of the elements it contains, authentication MUST fail. Authorization data is intended to restrict the use of a ticket. If the service cannot determine whether the restriction applies to that service, then a security weakness may result if the ticket can be used for that service. Authorization elements that are optional can be enclosed in an AD-IF-RELEVANT element. In the definitions that follow, the value of the ad-type for the element will be specified as the least significant part of the subsection number, and the value of the ad-data will be as shown in the ASN.1 structure that follows the subsection heading. Contents of ad-data ad-type DER encoding of AD-IF-RELEVANT 1 DER encoding of AD-KDCIssued 4 DER encoding of AD-AND-OR 5 DER encoding of AD-MANDATORY-FOR-KDC 8 */ // AuthorizationData implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.6 type AuthorizationData []AuthorizationDataEntry // AuthorizationDataEntry implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.6 type AuthorizationDataEntry struct { ADType int `asn1:"explicit,tag:0"` ADData []byte `asn1:"explicit,tag:1"` } // ADIfRelevant implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.6.1 type ADIfRelevant AuthorizationData // ADKDCIssued implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.6.2 type ADKDCIssued struct { ADChecksum Checksum `asn1:"explicit,tag:0"` IRealm string `asn1:"optional,generalstring,explicit,tag:1"` Isname PrincipalName `asn1:"optional,explicit,tag:2"` Elements AuthorizationData `asn1:"explicit,tag:3"` } // ADAndOr implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.6.3 type ADAndOr struct { ConditionCount int `asn1:"explicit,tag:0"` Elements AuthorizationData `asn1:"explicit,tag:1"` } // ADMandatoryForKDC implements RFC 4120 type: https://tools.ietf.org/html/rfc4120#section-5.2.6.4 type ADMandatoryForKDC AuthorizationData // Unmarshal bytes into the ADKDCIssued. func (a *ADKDCIssued) Unmarshal(b []byte) error { _, err := asn1.Unmarshal(b, a) return err } // Unmarshal bytes into the AuthorizationData. func (a *AuthorizationData) Unmarshal(b []byte) error { _, err := asn1.Unmarshal(b, a) return err } // Unmarshal bytes into the AuthorizationDataEntry. func (a *AuthorizationDataEntry) Unmarshal(b []byte) error { _, err := asn1.Unmarshal(b, a) return err }
types/AuthorizationData.go
0.699152
0.552781
AuthorizationData.go
starcoder
package convey import "github.com/smartystreets/assertions" var ( ShouldEqual = assertions.ShouldEqual ShouldNotEqual = assertions.ShouldNotEqual ShouldAlmostEqual = assertions.ShouldAlmostEqual ShouldNotAlmostEqual = assertions.ShouldNotAlmostEqual ShouldResemble = assertions.ShouldResemble ShouldNotResemble = assertions.ShouldNotResemble ShouldPointTo = assertions.ShouldPointTo ShouldNotPointTo = assertions.ShouldNotPointTo ShouldBeNil = assertions.ShouldBeNil ShouldNotBeNil = assertions.ShouldNotBeNil ShouldBeTrue = assertions.ShouldBeTrue ShouldBeFalse = assertions.ShouldBeFalse ShouldBeZeroValue = assertions.ShouldBeZeroValue ShouldBeGreaterThan = assertions.ShouldBeGreaterThan ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo ShouldBeLessThan = assertions.ShouldBeLessThan ShouldBeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo ShouldBeBetween = assertions.ShouldBeBetween ShouldNotBeBetween = assertions.ShouldNotBeBetween ShouldBeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual ShouldNotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual ShouldContain = assertions.ShouldContain ShouldNotContain = assertions.ShouldNotContain ShouldContainKey = assertions.ShouldContainKey ShouldNotContainKey = assertions.ShouldNotContainKey ShouldBeIn = assertions.ShouldBeIn ShouldNotBeIn = assertions.ShouldNotBeIn ShouldBeEmpty = assertions.ShouldBeEmpty ShouldNotBeEmpty = assertions.ShouldNotBeEmpty ShouldHaveLength = assertions.ShouldHaveLength ShouldStartWith = assertions.ShouldStartWith ShouldNotStartWith = assertions.ShouldNotStartWith ShouldEndWith = assertions.ShouldEndWith ShouldNotEndWith = assertions.ShouldNotEndWith ShouldBeBlank = assertions.ShouldBeBlank ShouldNotBeBlank = assertions.ShouldNotBeBlank ShouldContainSubstring = assertions.ShouldContainSubstring ShouldNotContainSubstring = assertions.ShouldNotContainSubstring ShouldPanic = assertions.ShouldPanic ShouldNotPanic = assertions.ShouldNotPanic ShouldPanicWith = assertions.ShouldPanicWith ShouldNotPanicWith = assertions.ShouldNotPanicWith ShouldHaveSameTypeAs = assertions.ShouldHaveSameTypeAs ShouldNotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs ShouldImplement = assertions.ShouldImplement ShouldNotImplement = assertions.ShouldNotImplement ShouldHappenBefore = assertions.ShouldHappenBefore ShouldHappenOnOrBefore = assertions.ShouldHappenOnOrBefore ShouldHappenAfter = assertions.ShouldHappenAfter ShouldHappenOnOrAfter = assertions.ShouldHappenOnOrAfter ShouldHappenBetween = assertions.ShouldHappenBetween ShouldHappenOnOrBetween = assertions.ShouldHappenOnOrBetween ShouldNotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween ShouldHappenWithin = assertions.ShouldHappenWithin ShouldNotHappenWithin = assertions.ShouldNotHappenWithin ShouldBeChronological = assertions.ShouldBeChronological )
vendor/github.com/smartystreets/goconvey/convey/assertions.go
0.68437
0.763638
assertions.go
starcoder
// +build !reach /* Package cover is used to assert that code locations and variable values are covered by tests. The functions incur no runtime overhead unless the reach build tag was specified. Functions which observe a single subject value pass it through. Example: import "github.com/tsavola/reach/cover" func example1() { cover.Location() } func example2(i int) { cover.Cond(i < 0, i == 0, i > 0) } func example3(msg string) { if cover.Bool(msg != "") { log.Print(msg) } } func example4(path string) (err error) { f, err := os.Open(path) if cover.Error(err) != nil { log.Print(err) return } defer f.Close() return } The coverage may be checked using the parent package. */ package cover // Location of call must be reached. func Location() {} // Cond enumerates custom conditions each of which must be true during at least // one invocation. func Cond(conditions ...bool) {} // Bool's both values must be covered. func Bool(x bool) bool { return x } // Min value and some larger value must be covered. func Min(x, min int) int { return x } // MinInt8 value and some larger value must be covered. func MinInt8(x, min int8) int8 { return x } // MinInt16 value and some larger value must be covered. func MinInt16(x, min int16) int16 { return x } // MinInt32 value and some larger value must be covered. func MinInt32(x, min int32) int32 { return x } // MinInt64 value and some larger value must be covered. func MinInt64(x, min int64) int64 { return x } // MinUint value and some larger value must be covered. func MinUint(x, min uint) uint { return x } // MinUint8 value and some larger value must be covered. func MinUint8(x, min uint8) uint8 { return x } // MinUint16 value and some larger value must be covered. func MinUint16(x, min uint16) uint16 { return x } // MinUint32 value and some larger value must be covered. func MinUint32(x, min uint32) uint32 { return x } // MinUint64 value and some larger value must be covered. func MinUint64(x, min uint64) uint64 { return x } // MinUintptr value and some larger value must be covered. func MinUintptr(x, min uintptr) uintptr { return x } // MinMax requires that minimum value, maximum value and some value between // them are covered. func MinMax(x, min, max int) int { return x } // MinMaxInt8 requires that minimum value, maximum value and some value between // them are covered. func MinMaxInt8(x, min, max int8) int8 { return x } // MinMaxInt16 requires that minimum value, maximum value and some value // between them are covered. func MinMaxInt16(x, min, max int16) int16 { return x } // MinMaxInt32 requires that minimum value, maximum value and some value // between them are covered. func MinMaxInt32(x, min, max int32) int32 { return x } // MinMaxInt64 requires that minimum value, maximum value and some value // between them are covered. func MinMaxInt64(x, min, max int64) int64 { return x } // MinMaxUint requires that minimum value, maximum value and some value between // them are covered. func MinMaxUint(x, min, max uint) uint { return x } // MinMaxUint8 requires that minimum value, maximum value and some value // between them are covered. func MinMaxUint8(x, min, max uint8) uint8 { return x } // MinMaxUint16 requires that minimum value, maximum value and some value // between them are covered. func MinMaxUint16(x, min, max uint16) uint16 { return x } // MinMaxUint32 requires that minimum value, maximum value and some value // between them are covered. func MinMaxUint32(x, min, max uint32) uint32 { return x } // MinMaxUint64 requires that minimum value, maximum value and some value // between them are covered. func MinMaxUint64(x, min, max uint64) uint64 { return x } // MinMaxUintptr requires that minimum value, maximum value and some value // between them are covered. func MinMaxUintptr(x, min, max uintptr) uintptr { return x } // Error must be nil and non-nil. func Error(x error) error { return x } // EOF error must be nil, non-nil, and have value io.EOF. func EOF(x error) error { return x }
cover/nocover.go
0.680454
0.735274
nocover.go
starcoder
package govalidator // Iterator is the function that accepts element of slice/array and its index type Iterator func(interface{}, int) // ResultIterator is the function that accepts element of slice/array and its index and returns any result type ResultIterator func(interface{}, int) interface{} // ConditionIterator is the function that accepts element of slice/array and its index and returns boolean type ConditionIterator func(interface{}, int) bool // ReduceIterator is the function that accepts two element of slice/array and returns result of merging those values type ReduceIterator func(interface{}, interface{}) interface{} // Some validates that any item of array corresponds to ConditionIterator. Returns boolean. func Some(array []interface{}, iterator ConditionIterator) bool { res := false for index, data := range array { res = res || iterator(data, index) } return res } // Every validates that every item of array corresponds to ConditionIterator. Returns boolean. func Every(array []interface{}, iterator ConditionIterator) bool { res := true for index, data := range array { res = res && iterator(data, index) } return res } // Reduce boils down a list of values into a single value by ReduceIterator func Reduce(array []interface{}, iterator ReduceIterator, initialValue interface{}) interface{} { for _, data := range array { initialValue = iterator(initialValue, data) } return initialValue } // Each iterates over the slice and apply Iterator to every item func Each(array []interface{}, iterator Iterator) { for index, data := range array { iterator(data, index) } } // Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result. func Map(array []interface{}, iterator ResultIterator) []interface{} { var result = make([]interface{}, len(array)) for index, data := range array { result[index] = iterator(data, index) } return result } // Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise. func Find(array []interface{}, iterator ConditionIterator) interface{} { for index, data := range array { if iterator(data, index) { return data } } return nil } // Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice. func Filter(array []interface{}, iterator ConditionIterator) []interface{} { var result = make([]interface{}, 0) for index, data := range array { if iterator(data, index) { result = append(result, data) } } return result } // Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator. func Count(array []interface{}, iterator ConditionIterator) int { count := 0 for index, data := range array { if iterator(data, index) { count = count + 1 } } return count }
vendor/github.com/asaskevich/govalidator/arrays.go
0.843992
0.563438
arrays.go
starcoder
package hash const ( // MaxLoadFactor is the ratio of entries to buckets which will force a resize MaxLoadFactor float64 = .75 // DefaultTableSize is set higher to avoid many resizes DefaultTableSize uint64 = 128 // SizeIncrease is the resize multiple when determining the new size of an // updated hash table SizeIncrease uint64 = 2 // FNVOffset is the constant used in the FNV hash function as seen on // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function FNVOffset uint64 = 14695981039346656037 // FNVPrime is the constant prime factor used in the FNV hash function FNVPrime uint64 = 1099511628211 ) // HashTable is the primary data structure for storing our hash table. We keep // implicit counts of buckets and entries with buckets being singly linked // lists for separate chaining. type HashTable struct { Buckets []*List NumEntries, NumBuckets uint64 } // NewHashTable creates a hash table based on the default sizing constraints. func NewHashTable() *HashTable { return &HashTable{ Buckets: make([]*List, DefaultTableSize), NumBuckets: DefaultTableSize, NumEntries: 0, } } // resize rehashes a hash table which has grown beyond its load factor // bringing it back to a more efficient state. func (t *HashTable) resize() { newBucketSize := t.NumBuckets * SizeIncrease ht := &HashTable{ Buckets: make([]*List, newBucketSize), NumBuckets: newBucketSize, NumEntries: 0, } for _, list := range t.Buckets { if list != nil { for e := range list.Iter() { ht.Put(e.key, e.val) } } } *t = *ht } // LoadFactor returns the current load of the table. func (t *HashTable) LoadFactor() float64 { return float64(t.NumEntries) / float64(t.NumBuckets) } // Hash handles hashing the key based on the FNV hash function. More can be // read about it here: // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function func (t *HashTable) Hash(s string) uint64 { var hash uint64 bts := []byte(s) hash = FNVOffset for _, b := range bts { hash *= FNVPrime hash ^= uint64(b) } return hash } // Put attempts to insert a new key/value pair or update an existing key with // the new value. func (t *HashTable) Put(key string, val interface{}) { if t.LoadFactor() > MaxLoadFactor { t.resize() } index := t.Hash(key) % uint64(t.NumBuckets) if t.Buckets[index] == nil { l := NewList() l.Append(key, val) t.Buckets[index] = l t.NumEntries++ return } for n := range t.Buckets[index].Iter() { if n.key == key { n.val = val return } } t.Buckets[index].Append(key, val) t.NumEntries++ } // Get attempts to find the value based on a key. func (t *HashTable) Get(key string) interface{} { index := t.Hash(key) % uint64(t.NumBuckets) if t.Buckets[index] == nil { return nil } for n := range t.Buckets[index].Iter() { if n.key == key { return n.val } } return nil } // Del attempts to delete a key/value pair from the hash table. func (t *HashTable) Del(key string) { index := t.Hash(key) % uint64(t.NumBuckets) if t.Buckets[index] == nil { return } t.Buckets[index].Remove(key) t.NumEntries-- }
data-structures/hash-table/hash_table.go
0.815122
0.485844
hash_table.go
starcoder
package main import ( "fmt" "reflect" "github.com/hashicorp/hcl2/hcl" ) func findTraversalSpec(got hcl.Traversal, candidates []*TestFileExpectTraversal) *TestFileExpectTraversal { for _, candidate := range candidates { if traversalsAreEquivalent(candidate.Traversal, got) { return candidate } } return nil } func findTraversalForSpec(want *TestFileExpectTraversal, have []hcl.Traversal) hcl.Traversal { for _, candidate := range have { if traversalsAreEquivalent(candidate, want.Traversal) { return candidate } } return nil } func traversalsAreEquivalent(a, b hcl.Traversal) bool { if len(a) != len(b) { return false } for i := range a { aStep := a[i] bStep := b[i] if reflect.TypeOf(aStep) != reflect.TypeOf(bStep) { return false } // We can now assume that both are of the same type. switch ts := aStep.(type) { case hcl.TraverseRoot: if bStep.(hcl.TraverseRoot).Name != ts.Name { return false } case hcl.TraverseAttr: if bStep.(hcl.TraverseAttr).Name != ts.Name { return false } case hcl.TraverseIndex: if !bStep.(hcl.TraverseIndex).Key.RawEquals(ts.Key) { return false } default: return false } } return true } // checkTraversalsMatch determines if a given traversal matches the given // expectation, which must've been produced by an earlier call to // findTraversalSpec for the same traversal. func checkTraversalsMatch(got hcl.Traversal, filename string, match *TestFileExpectTraversal) hcl.Diagnostics { var diags hcl.Diagnostics gotRng := got.SourceRange() wantRng := match.Range if got, want := gotRng.Filename, filename; got != want { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Incorrect filename in detected traversal", Detail: fmt.Sprintf( "Filename was reported as %q, but was expecting %q.", got, want, ), Subject: match.Traversal.SourceRange().Ptr(), }) return diags } // If we have the expected filename then we'll use that to construct the // full "want range" here so that we can use it to point to the appropriate // location in the remaining diagnostics. wantRng.Filename = filename if got, want := gotRng.Start, wantRng.Start; got != want { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Incorrect start position in detected traversal", Detail: fmt.Sprintf( "Start position was reported as line %d column %d byte %d, but was expecting line %d column %d byte %d.", got.Line, got.Column, got.Byte, want.Line, want.Column, want.Byte, ), Subject: &wantRng, }) } if got, want := gotRng.End, wantRng.End; got != want { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, Summary: "Incorrect end position in detected traversal", Detail: fmt.Sprintf( "End position was reported as line %d column %d byte %d, but was expecting line %d column %d byte %d.", got.Line, got.Column, got.Byte, want.Line, want.Column, want.Byte, ), Subject: &wantRng, }) } return diags }
vendor/github.com/hashicorp/hcl2/cmd/hclspecsuite/traversals.go
0.645008
0.407893
traversals.go
starcoder
package poly import ( "bytes" "strings" "math/rand" "errors" ) // complementBaseRuneMap provides 1:1 mapping between bases and their complements var complementBaseRuneMap = map[rune]rune{ 65: 84, // A -> T 66: 86, // B -> V 67: 71, // C -> G 68: 72, // D -> H 71: 67, // G -> C 72: 68, // H -> D 75: 77, // K -> M 77: 75, // M -> K 78: 78, // N -> N 82: 89, // R -> Y 83: 83, // S -> S 84: 65, // T -> A 85: 65, // U -> A 86: 66, // V -> B 87: 87, // W -> W 89: 82, // Y -> R 97: 116, // a -> t 98: 118, // b -> v 99: 103, // c -> g 100: 104, // d -> h 103: 99, // g -> a 104: 100, // h -> d 107: 109, // k -> m 109: 107, // m -> k 110: 110, // n -> n 114: 121, // r -> y 115: 115, // s -> s 116: 97, // t -> a 117: 97, // u -> a 118: 98, // v -> b 119: 119, // w -> w 121: 114, // y -> r } // GetSequence is a method to get the full sequence of an annotated sequence func (sequence Sequence) GetSequence() string { return sequence.Sequence } // GetSequence is a method wrapper to get a Feature's sequence. Mutates with Sequence. func (feature Feature) GetSequence() string { return getFeatureSequence(feature, feature.SequenceLocation) } // ReverseComplement takes the reverse complement of a sequence func ReverseComplement(sequence string) string { complementString := strings.Map(ComplementBase, sequence) n := len(complementString) newString := make([]rune, n) for _, base := range complementString { n-- newString[n] = base } return string(newString) } // ComplementBase accepts a base pair and returns its complement base pair func ComplementBase(basePair rune) rune { return complementBaseRuneMap[basePair] } // getFeatureSequence takes a feature and location object and returns a sequence string. func getFeatureSequence(feature Feature, location Location) string { var sequenceBuffer bytes.Buffer var sequenceString string parentSequence := feature.ParentSequence.Sequence if len(location.SubLocations) == 0 { sequenceBuffer.WriteString(parentSequence[location.Start:location.End]) } else { for _, subLocation := range location.SubLocations { sequenceBuffer.WriteString(getFeatureSequence(feature, subLocation)) } } // reverse complements resulting string if needed. if location.Complement { sequenceString = ReverseComplement(sequenceBuffer.String()) } else { sequenceString = sequenceBuffer.String() } return sequenceString } //RandomProteinSequence returns a random protein sequence as a string that have size length, starts with aminoacid M (Methionine) and finishes with * (stop codon). The random generator uses the seed provided as parameter. func RandomProteinSequence(length int, seed int64) (string, error) { //The length needs to be greater than two because the random protein sequenced returned always contain a start and stop codon. You could see more about this stuff here: https://en.wikipedia.org/wiki/Genetic_code#Start_and_stop_codons if length <= 2 { err := errors.New("The length needs to be greater than two because the random protein sequenced returned always contain a start and stop codon. Please select a higher length in RandomProteinSequence function") return "", err } // https://en.wikipedia.org/wiki/Amino_acid#Table_of_standard_amino_acid_abbreviations_and_properties var aminoAcidsAlphabet = []rune("ACDEFGHIJLMNPQRSTVWY") rand.Seed(seed) randomSequence := make([]rune, length) for peptide := range randomSequence { if (peptide == 0) { //M is the standard abbreviation for the Methionine aminoacid. A protein sequence start with M because the start codon is translated to Methionine randomSequence[peptide] = 'M' } else if (peptide == length-1) { //* is the standard abbreviation for the stop codon. That's a signal for the ribosome to stop the translation and because of that a protein sequence is finished with * randomSequence[peptide] = '*' } else { randomIndex := rand.Intn(len(aminoAcidsAlphabet)) randomSequence[peptide] = aminoAcidsAlphabet[randomIndex] } } return string(randomSequence), nil } //RandomDNASequence returns random DNA sequences with specified length. package main import "fmt" import gonum as np func random_dna_sequence(length, gc_share=None, probas=None, seed=None) { if seed is not None { np.random.seed(seed)) } if gc_share is not None { g_or_c = gc_share / 2.0 not_g_or_c = (1 - gc_share) / 2.0 type probas struct { "G" var "C" var "A" var "T" var } probas := probas{ "G": g_or_c, "C": g_or_c, "A": not_g_or_c, "T": not_g_or_c, } if probas is None { sequence = np.random.choice(list("ATCG"), length) } else { bases, probas = zip(*probas.items()) sequence = np.random.choice(bases, length, p=probas) } return "".join(sequence) }
sequence.go
0.657758
0.459501
sequence.go
starcoder
package schema import ( // "bufio" // "fmt" "io/ioutil" "os" "github.com/muxmuse/schema/mfa" "path/filepath" "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing/object" ) func CreateNew(name string, path string, version string) { readme := []byte(`# ` + name + ` This is a [schema pm](https://github.com/muxmuse/schema) package Start by editing schema.yaml then select a database and install your schema ` + "``` bash" + ` schema context <your-database> schema install . ` + "```" + ` Files in top-level sub-direcory containing a file called schema.yaml are also considered in installation. This shall help to structure the code. `) schemaYaml := []byte(`kind: Schema # This is the name of the database schema name: ` + name + ` description: Describe here what functionality the package provides # All releases must be tagged with v + semver gitTag: ` + version + ` # Please set the url to a location reachable for all users of this schema gitRepoUrl: . `) migrate_0_1 := []byte(`-- Migrate mutable parts of ` + name + ` -- -- Schema will ask the user for confirmation before running migrations. -- -- For each vA.B.C_vX.Y.Z.migrate.sql there must be the opposite script vX.Y.Z_vA.B.C.migrate.sql -- Immutable parts of the schema should be defined in files ending on install.sql `) migrate_1_0 := []byte(`-- Migrate mutable parts of ` + name + ` -- -- Schema will ask the user for confirmation before running migrations. -- -- For each vA.B.C_vX.Y.Z.migrate.sql there must be the opposite script vX.Y.Z_vA.B.C.migrate.sql -- Immutable parts of the schema should be defined in files ending on install.sql `) install := []byte(`-- Install immutable parts of ` + name +` -- -- The file can include multiple batches separated with GO -- -- For each file ending on install.sql there must be file ending on uninstall.sql -- To delete data or alter tables, use files ending migrate.sql -- CREATE FUNCTION [` + name + `].HELLO_WORLD() RETURNS varchar(max) AS BEGIN RETURN 'Enter all the immutable code in install.sql files' END `) uninstall := []byte(`-- Uninstall immutable parts of ` + name +` -- -- The file can include multiple batches separated with GO -- -- For each file ending on install.sql there must be file ending on uninstall.sql -- To delete data or alter tables, use files ending migrate.sql -- DROP FUNCTION [` + name + `].HELLO_WORLD `) os.MkdirAll(path, os.ModePerm) mfa.CatchFatal(ioutil.WriteFile(filepath.Join(path, "schema.yaml"), schemaYaml, 0644)) mfa.CatchFatal(ioutil.WriteFile(filepath.Join(path, "v0.0.0_" + version + ".migrate.sql"), migrate_0_1, 0644)) mfa.CatchFatal(ioutil.WriteFile(filepath.Join(path, version + "_v0.0.0.migrate.sql"), migrate_1_0, 0644)) mfa.CatchFatal(ioutil.WriteFile(filepath.Join(path, "install.sql"), install, 0644)) mfa.CatchFatal(ioutil.WriteFile(filepath.Join(path, "uninstall.sql"), uninstall, 0644)) mfa.CatchFatal(ioutil.WriteFile(filepath.Join(path, "README.md"), readme, 0644)) repo, err := git.PlainInit(path, false) mfa.CatchFatal(err) sig := &object.Signature{ Email: "", Name: "schemapm", } w, err := repo.Worktree() mfa.CatchFatal(err) w.Add(filepath.Join("schema.yaml")) w.Add(filepath.Join("v0.0.0_" + version + ".migrate.sql")) w.Add(filepath.Join(version + "_v0.0.0.migrate.sql")) w.Add(filepath.Join("install.sql")) w.Add(filepath.Join("uninstall.sql")) w.Add(filepath.Join("README.md")) hash, err := w.Commit("initial", &git.CommitOptions{ Author: sig, }) mfa.CatchFatal(err) _, err = repo.CreateTag(version, hash, &git.CreateTagOptions{ Tagger: sig, Message: version, }) mfa.CatchFatal(err) }
schema/create.go
0.566858
0.449997
create.go
starcoder
package geom import ( "github.com/golang/geo/s2" "github.com/mmcloughlin/geohash" "math" ) const ( // EarthRadius According to Wikipedia, the Earth's radius is about 6,371,004 m EarthRadius = 6371000 ) func NewLngLat(coordinates ...float64) *LngLat { length := len(coordinates) switch length { case 0, 1: return nil case 2: return &LngLat{Longitude: coordinates[0], Latitude: coordinates[1]} case 3: return &LngLat{ Longitude: coordinates[0], Latitude: coordinates[1], Altitude: coordinates[2], } default: return nil } } func (x *LngLat) Equal(ll *LngLat) bool { if x != nil && ll != nil { return lngLatEqual(x.Longitude, ll.Longitude) && lngLatEqual(x.Latitude, ll.Latitude) } return x == nil && ll == nil } func (x *LngLat) IsEmpty() bool { return x == nil || (x.Longitude == 0 && x.Latitude == 0 && x.Altitude == 0) } func (x *LngLat) CellID() s2.CellID { return s2.CellFromLatLng(s2.LatLngFromDegrees(x.Latitude, x.Longitude)).ID() } func (x *LngLat) CellIDWithLevel(level int) s2.CellID { return x.CellID().Parent(level) } func (x *LngLat) GeoHash() string { return geohash.Encode(x.Latitude, x.Longitude) } func (x *LngLat) GeoHashWithLevel(level int) string { return geohash.EncodeWithPrecision(x.Latitude, x.Longitude, uint(level)) } // Distance Calculates the Haversine distance between two points in meters. func (x *LngLat) Distance(point *LngLat) float64 { if point == nil { return -1 } return Distance(x.Longitude, x.Latitude, point.Longitude, point.Latitude) } // PointAtDistanceAndBearing returns a LngLat populated with the Latitude and Longitude coordinates // by transposing the origin point the passed in distance (in meters) // by the passed in compass bearing (in degrees). // Original Implementation from: http://www.movable-type.co.uk/scripts/latlong.html func (x *LngLat) PointAtDistanceAndBearing(dist float64, bearing float64) *LngLat { dr := dist / EarthRadius bearing = bearing * (math.Pi / 180.0) lat1 := x.Latitude * (math.Pi / 180.0) lng1 := x.Longitude * (math.Pi / 180.0) lat2Part1 := math.Sin(lat1) * math.Cos(dr) lat2Part2 := math.Cos(lat1) * math.Sin(dr) * math.Cos(bearing) lat2 := math.Asin(lat2Part1 + lat2Part2) lng2Part1 := math.Sin(bearing) * math.Sin(dr) * math.Cos(lat1) lng2Part2 := math.Cos(dr) - (math.Sin(lat1) * math.Sin(lat2)) lng2 := lng1 + math.Atan2(lng2Part1, lng2Part2) lng2 = math.Mod(lng2+3*math.Pi, 2*math.Pi) - math.Pi lat2 = lat2 * (180.0 / math.Pi) lng2 = lng2 * (180.0 / math.Pi) return &LngLat{Latitude: lat2, Longitude: lng2} } // GreatCircleDistance Calculates the Haversine distance between two points in meters. // Original Implementation from: http://www.movable-type.co.uk/scripts/latlong.html func (x *LngLat) GreatCircleDistance(p2 *LngLat) float64 { dLat := (p2.Latitude - x.Latitude) * (math.Pi / 180.0) dLon := (p2.Longitude - x.Longitude) * (math.Pi / 180.0) lat1 := x.Latitude * (math.Pi / 180.0) lat2 := p2.Latitude * (math.Pi / 180.0) a1 := math.Sin(dLat/2) * math.Sin(dLat/2) a2 := math.Sin(dLon/2) * math.Sin(dLon/2) * math.Cos(lat1) * math.Cos(lat2) a := a1 + a2 c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) return EarthRadius * c } // BearingTo Calculates the initial bearing (sometimes referred to as forward azimuth) // Original Implementation from: http://www.movable-type.co.uk/scripts/latlong.html func (x *LngLat) BearingTo(p2 *LngLat) float64 { dLon := (p2.Longitude - x.Longitude) * math.Pi / 180.0 lat1 := x.Latitude * math.Pi / 180.0 lat2 := p2.Latitude * math.Pi / 180.0 vy := math.Sin(dLon) * math.Cos(lat2) vx := math.Cos(lat1)*math.Sin(lat2) - math.Sin(lat1)*math.Cos(lat2)*math.Cos(dLon) bearing := math.Atan2(vy, vx) * 180.0 / math.Pi return bearing } // MidpointTo Calculates the midpoint between 'this' point and the supplied point. // Original implementation from http://www.movable-type.co.uk/scripts/latlong.html func (x *LngLat) MidpointTo(p2 *LngLat) *LngLat { lat1 := x.Latitude * math.Pi / 180.0 lat2 := p2.Latitude * math.Pi / 180.0 lon1 := x.Longitude * math.Pi / 180.0 dLon := (p2.Longitude - x.Longitude) * math.Pi / 180.0 bx := math.Cos(lat2) * math.Cos(dLon) by := math.Cos(lat2) * math.Sin(dLon) lat3Rad := math.Atan2( math.Sin(lat1)+math.Sin(lat2), math.Sqrt(math.Pow(math.Cos(lat1)+bx, 2)+math.Pow(by, 2)), ) lon3Rad := lon1 + math.Atan2(by, math.Cos(lat1)+bx) lat3 := lat3Rad * 180.0 / math.Pi lon3 := lon3Rad * 180.0 / math.Pi return NewLngLat(lon3, lat3) } func DistanceBetween(pt1 *LngLat, pt2 *LngLat) float64 { if pt1 == nil { return -1 } return pt1.Distance(pt2) } const float64EqualityThreshold = 1e-9 func lngLatEqual(a, b float64) bool { return math.Abs(a-b) <= float64EqualityThreshold }
go/pkg/mojo/geom/lng_lat.go
0.901542
0.731874
lng_lat.go
starcoder
package math import ( "math" "go.starlark.net/starlark" ) // Return the arc cosine of x, in radians. func acos(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("acos", args, kwargs, math.Acos) } // asin(x) - Return the arc sine of x, in radians. func asin(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("asin", args, kwargs, math.Asin) } // atan(x) - Return the arc tangent of x, in radians. func atan(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("atan", args, kwargs, math.Atan) } // atan2(y, x) - Return atan(y / x), in radians. The result is between -pi and pi. // The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. // The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. // For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1, -1) is -3*pi/4. func atan2(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc2("atan2", args, kwargs, math.Atan2) } // cos(x) - Return the cosine of x radians. func cos(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("cos", args, kwargs, math.Cos) } // hypot(x, y) - Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the origin to point (x, y). func hypot(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc2("hypot", args, kwargs, math.Hypot) } // sin(x) - Return the sine of x radians. func sin(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("sin", args, kwargs, math.Sin) } // tan(x) - Return the tangent of x radians. func tan(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("tan", args, kwargs, math.Tan) } // degrees(x) - Convert angle x from radians to degrees. func degrees(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { toDeg := func(x float64) float64 { return x / oneRad } return floatFunc("degrees", args, kwargs, toDeg) } // radians(x) - Convert angle x from degrees to radians. func radians(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { toRad := func(x float64) float64 { return x * oneRad } return floatFunc("radians", args, kwargs, toRad) } // acosh(x) - Return the inverse hyperbolic cosine of x. func acosh(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("acosh", args, kwargs, math.Acosh) } // asinh(x) - Return the inverse hyperbolic sine of x. func asinh(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("asinh", args, kwargs, math.Asinh) } // atanh(x) - Return the inverse hyperbolic tangent of x. func atanh(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("atanh", args, kwargs, math.Atanh) } // cosh(x) - Return the hyperbolic cosine of x. func cosh(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("cosh", args, kwargs, math.Cosh) } // sinh(x) - Return the hyperbolic sine of x. func sinh(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("sinh", args, kwargs, math.Sinh) } // tanh(x) - Return the hyperbolic tangent of x. func tanh(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { return floatFunc("tanh", args, kwargs, math.Tanh) }
math/trig.go
0.868729
0.430566
trig.go
starcoder
package microgui import ( "image" "image/color" "github.com/hajimehoshi/ebiten" "github.com/hajimehoshi/ebiten/ebitenutil" ) // TextField displays a string and lets the user modify it type TextField struct { bounds image.Rectangle content string hasFocus bool cursorPosition int contentOffset int } // NewTextField creates a text field func NewTextField(content string, x, y, w, h int) *TextField { return &TextField{image.Rect(x, y, x+w, y+h), content, false, 0, 0} } // SetContent asynchronously sets the content of the text field func (t *TextField) SetContent(s string) { updates <- func() { t.content = s } } func (t *TextField) handleInput(input *userInput) { if input.lmb.clicked { t.hasFocus = input.mousePosition.In(t.bounds) } if t.hasFocus { if repeatingKeyPressed(ebiten.KeyBackspace) && t.content != "" { if t.cursorPosition > 0 { t.content = t.content[:t.cursorPosition-1] + t.content[t.cursorPosition:] t.cursorPosition-- } } else if repeatingKeyPressed(ebiten.KeyDelete) && t.content != "" { if t.cursorPosition < len(t.content) { t.content = t.content[:t.cursorPosition] + t.content[t.cursorPosition+1:] } } else if repeatingKeyPressed(ebiten.KeyLeft) { if t.cursorPosition > 0 { t.cursorPosition-- } } else if repeatingKeyPressed(ebiten.KeyRight) { if t.cursorPosition < len(t.content) { t.cursorPosition++ } } else if repeatingKeyPressed(ebiten.KeyHome) { t.cursorPosition = 0 } else if repeatingKeyPressed(ebiten.KeyEnd) { t.cursorPosition = len(t.content) } else { added := ebiten.InputChars() t.content = t.content[:t.cursorPosition] + string(added) + t.content[t.cursorPosition:] t.cursorPosition += len(added) } // scroll to cursor if t.cursorPosition < t.contentOffset { // cursor is left of visible text t.contentOffset = t.cursorPosition } else if t.cursorPosition > t.contentOffset+t.widthInChars() { // cursor is on right of visible text t.contentOffset = t.cursorPosition - t.widthInChars() } else if t.contentOffset > len(t.content)-t.widthInChars() { // cursor is inside visible text t.contentOffset = max(0, len(t.content)-t.widthInChars()) } } } func (t *TextField) draw(img *ebiten.Image) { b := t.bounds if !b.In(img.Bounds()) { return } col := color.RGBA{20, 20, 20, 0xff} ebitenutil.DrawRect(img, float64(b.Min.X), float64(b.Min.Y), float64(b.Dx()), float64(b.Dy()), col) ebitenutil.DebugPrintAt(img, t.visibleText(), b.Min.X+3, b.Min.Y+b.Dy()/2-8) if t.hasFocus { cursorX := float64(b.Min.X + 5 + (t.cursorPosition-t.contentOffset)*6) cursorY := float64(b.Min.Y + b.Dy()/2 - 6) ebitenutil.DrawLine(img, cursorX, cursorY, cursorX, cursorY+12.0, color.White) } x1 := float64(b.Min.X) y1 := float64(b.Min.Y) x2 := float64(b.Max.X) y2 := float64(b.Max.Y) ebitenutil.DrawLine(img, x1, y1, x2, y1, boderDarkColor) // top ebitenutil.DrawLine(img, x1, y2-1, x2, y2-1, borderLightColor) // bottom ebitenutil.DrawLine(img, x1+1, y1, x1+1, y2, boderDarkColor) // left ebitenutil.DrawLine(img, x2, y1, x2, y2, borderLightColor) // right // ellipses for text out of bounds if t.contentOffset > 0 { ebitenutil.DrawLine(img, x1+2, y2-3, x1+3, y2-3, fgColor) ebitenutil.DrawLine(img, x1+4, y2-3, x1+5, y2-3, fgColor) ebitenutil.DrawLine(img, x1+6, y2-3, x1+7, y2-3, fgColor) } if t.contentOffset < len(t.content)-t.widthInChars() { ebitenutil.DrawLine(img, x2-2, y2-3, x2-3, y2-3, fgColor) ebitenutil.DrawLine(img, x2-4, y2-3, x2-5, y2-3, fgColor) ebitenutil.DrawLine(img, x2-6, y2-3, x2-7, y2-3, fgColor) } } func (t *TextField) widthInChars() int { return t.bounds.Dx()/6 - 1 } func (t *TextField) visibleText() string { if len(t.content)-t.contentOffset < t.widthInChars() { return t.content[t.contentOffset:] } return t.content[t.contentOffset : t.contentOffset+t.widthInChars()] } func max(a, b int) int { if a > b { return a } return b } func (t *TextField) clicked(x, y int) {} func (t *TextField) mouseReleased() {} func (t *TextField) keyPressed() {} func (t *TextField) mouseMoved(x, y int) {}
textfield.go
0.554712
0.482856
textfield.go
starcoder
package memtable import ( "github.com/patrickgombert/lsmt/common" c "github.com/patrickgombert/lsmt/comparator" ) // Stack based iterator which keeps the trees lineage in memory while iterating. type memtableIterator struct { init bool stack []persistentNode end []byte } // Creates a new bounded iterator for the current state of the memtable. // Since the memtable is backed by a persistent data structure, this reflects a point in // time snapshot of the memtable. func (memtable *Memtable) Iterator(start, end []byte) common.Iterator { stack := []persistentNode{} node := memtable.sortedMap.getRoot() if node == nil { return &memtableIterator{init: false, stack: stack, end: end} } for c.Compare(start, node.getPair().Key) == c.GREATER_THAN { if node.getRight() == nil { return &memtableIterator{init: false, stack: stack, end: end} } } stack = appendStack(start, node, stack) return &memtableIterator{init: false, stack: stack, end: end} } // Creates a new unbounded iterator for the current state of the memtable. // Since the memtable is backed by a persistent data structure, this reflects a point in // time snapshot of the memtable. func (memtable *Memtable) UnboundedIterator() common.Iterator { stack := []persistentNode{} node := memtable.sortedMap.getRoot() if node == nil { return &memtableIterator{init: false, stack: stack, end: nil} } stack = appendStack(nil, node, stack) return &memtableIterator{init: false, stack: stack, end: nil} } // Moves the iterator forward. Returns false when either the end of the tree has been // reached or if the end key has been passed (if the iterator is bounded). // The Next() call should never error, but returns a nil error in order to // satisfy the Iterator interface. func (iter *memtableIterator) Next() (bool, error) { if len(iter.stack) == 0 { return false, nil } if !iter.init { iter.init = true return true, nil } idx := len(iter.stack) - 1 node := iter.stack[idx] iter.stack = appendStack(nil, node.getRight(), iter.stack[:idx]) if len(iter.stack) == 0 { return false, nil } else { idx = len(iter.stack) - 1 node = iter.stack[idx] if iter.end != nil && c.Compare(node.getPair().Key, iter.end) == c.GREATER_THAN { iter.stack = []persistentNode{} return false, nil } else { return true, nil } } } // Returns the current element's Pair. // The Get() call should never error, but returns a nil error in order to // satisfy the Iterator interface. func (iter *memtableIterator) Get() (*common.Pair, error) { if len(iter.stack) == 0 { return nil, nil } pair := iter.stack[len(iter.stack)-1].getPair() return &pair, nil } // Closes the instance of the iterator which has the effect of making subsequent calls // to Next() return false and Get() return nil. func (iter *memtableIterator) Close() error { iter.stack = []persistentNode{} return nil } func appendStack(start []byte, root persistentNode, stack []persistentNode) []persistentNode { node := root for node != nil { if start != nil { switch c.Compare(start, node.getPair().Key) { case c.EQUAL: stack = append(stack, node) return stack case c.LESS_THAN: stack = append(stack, node) node = node.getLeft() case c.GREATER_THAN: node = node.getRight() } } else { stack = append(stack, node) node = node.getLeft() } } return stack }
memtable/iterator.go
0.728169
0.441854
iterator.go
starcoder
package track import ( "fmt" "math" "github.com/anki/goverdrive/phys" ) // RoadPiece is the helper type used to define a track // - Straight or curved only; no fancy shapes like intersection or 'Y' // - Any anglular change through the piece is along a circular arc // - Maximum of angular change of +/- pi/2 radians (ie 90 degrees) // - Width is a parameter of the track, not individual road pieces type RoadPiece struct { cenLen phys.Meters // path length, at road center dAngle phys.Radians // delta angle when driving through the piece (0=>straight; +pi/2=>left turn; etc) } func NewRoadPiece(cenLen phys.Meters, dAngle phys.Radians) *RoadPiece { if cenLen <= 0 { panic(fmt.Sprintf("RoadPiece requires cenLen > 0; actual value is %v", cenLen)) } if dAngle > phys.Radians90DegreeTurnL || dAngle < phys.Radians90DegreeTurnR { panic(fmt.Sprintf("RoadPiece requires (%v <= DAngle <= %v); actual value is %v", phys.Radians90DegreeTurnR, phys.Radians90DegreeTurnL, dAngle)) } return &RoadPiece{cenLen: cenLen, dAngle: dAngle} } func (rp *RoadPiece) String() string { return fmt.Sprintf("RoadPice{cenLen: %v, dAngle: %v}", rp.cenLen, rp.dAngle) } func (rp *RoadPiece) CenLen() phys.Meters { return rp.cenLen } func (rp *RoadPiece) DAngle() phys.Radians { return rp.dAngle } func (rp *RoadPiece) IsStraight() bool { return rp.dAngle == 0 } // Len computes the path length of the road piece, at the specified center // offset. func (rp *RoadPiece) Len(cofs phys.Meters) phys.Meters { d := rp.cenLen d -= cofs * phys.Meters(rp.dAngle) return d } // CurveRadius computes the radius of the road piece, at the specified center // offset. Straight pieces, which have no curvature, will return 0. func (rp *RoadPiece) CurveRadius(cofs phys.Meters) phys.Meters { if rp.IsStraight() { return 0 } r := rp.cenLen / phys.Meters(math.Abs(float64(rp.dAngle))) if rp.dAngle < 0 { // curve right r += cofs } else { // curve left r -= cofs } return r } // DeltaPose returns the change in pose when travelling through the piece, // assuming the canonical starting pose: origin, facing right. func (rp *RoadPiece) DeltaPose() phys.Pose { if rp.IsStraight() { return phys.Pose{Point: phys.Point{X: rp.cenLen, Y: 0}, Theta: 0} } rc := rp.CurveRadius(0) angle := phys.Radians(rp.cenLen / rc) if rp.dAngle > 0 { // left turn pp := phys.PolarPoint{R: rc, A: phys.Radians(-(math.Pi / 2) + angle)} p := pp.ToPoint() p.Y += rc return phys.Pose{Point: p, Theta: rp.dAngle} } // else: right turn pp := phys.PolarPoint{R: rc, A: phys.Radians(+(math.Pi / 2) - angle)} p := pp.ToPoint() p.Y -= rc return phys.Pose{Point: p, Theta: rp.dAngle} }
goverdrive/robo/track/roadpiece.go
0.805135
0.409604
roadpiece.go
starcoder
package siaencoding import ( "encoding/binary" "math/big" ) // simple byte slice reversal func toggleEndianness(b []byte) []byte { r := make([]byte, len(b)) copy(r, b) i, j := 0, len(b)-1 for i < j { r[i], r[j] = r[j], r[i] i, j = i+1, j-1 } return r } // EncUint16 encodes a uint16 as a slice of 2 bytes. func EncUint16(i uint16) (b []byte) { b = make([]byte, 2) binary.LittleEndian.PutUint16(b, i) return } // DecUint16 decodes a slice of 2 bytes into a uint16. // It panics if len(b) < 2. func DecUint16(b []byte) uint16 { return binary.LittleEndian.Uint16(b) } // EncUint32 encodes a uint32 as a slice of 4 bytes. func EncUint32(i uint32) (b []byte) { b = make([]byte, 4) binary.LittleEndian.PutUint32(b, i) return } // DecUint32 decodes a slice of 4 bytes into a uint32. // It panics if len(b) < 4. func DecUint32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } // EncUint64 encodes a uint64 as a slice of 8 bytes. func EncUint64(i uint64) (b []byte) { b = make([]byte, 8) binary.LittleEndian.PutUint64(b, i) return } // DecUint64 decodes a slice of 8 bytes into a uint64. // It panics if len(b) < 8. func DecUint64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } // EncInt32 encodes an int32 as a slice of 4 bytes. func EncInt32(i int32) (b []byte) { b = make([]byte, 4) binary.LittleEndian.PutUint32(b, uint32(i)) return } // DecInt32 decodes a slice of 4 bytes into an int32. // It panics if len(b) < 4. func DecInt32(b []byte) int32 { return int32(binary.LittleEndian.Uint32(b)) } // EncInt64 encodes an int64 as a slice of 8 bytes. func EncInt64(i int64) (b []byte) { b = make([]byte, 8) binary.LittleEndian.PutUint64(b, uint64(i)) return } // DecInt64 decodes a slice of 8 bytes into an int64. // It panics if len(b) < 8. func DecInt64(b []byte) int64 { return int64(binary.LittleEndian.Uint64(b)) } // EncUint128 encodes a big.Int as a slice of 16 bytes. // big.Ints are stored in big-endian format, so they must be converted // to little-endian before being returned. func EncUint128(i *big.Int) (b []byte) { b = make([]byte, 16) copy(b, toggleEndianness(i.Bytes())) return } // DecUint128 decodes a slice of 16 bytes into a big.Int // It panics if len(b) < 16. func DecUint128(b []byte) (i *big.Int) { i = new(big.Int) i.SetBytes(toggleEndianness(b)) return }
siaencoding/integers.go
0.765243
0.53783
integers.go
starcoder
package botutil import ( "math" "github.com/chippydip/go-sc2ai/api" "github.com/chippydip/go-sc2ai/enums/ability" ) // Units ... type Units struct { raw []Unit filter func(Unit) bool } // NewUnits wraps a regular []Unit into a Units struct. func NewUnits(units []Unit) Units { return Units{raw: units} } func (units Units) ctx() *UnitContext { if len(units.raw) > 0 { return units.raw[0].ctx } return nil } func (units *Units) applyFilter(extra int) { if len(units.raw) == 0 { units.raw = nil // make sure it's actually nil } else if units.filter != nil { raw := make([]Unit, 0, len(units.raw)+extra) for _, u := range units.raw { if units.filter(u) { raw = append(raw, u) } } if len(raw) == 0 { raw = nil } units.raw = raw } units.filter = nil } func (units *Units) ensureOwns(extra int) { units.applyFilter(extra) if len(units.raw) == 0 { return // we may not even have a ctx to compare to } // Don't mess with the ctx's slice if sliceID(units.raw) == sliceID(units.ctx().wrapped) { tmp := make([]Unit, len(units.raw), len(units.raw)+extra) copy(tmp, units.raw) units.raw = tmp } } func sliceID(s []Unit) *Unit { if cap(s) > 0 { return &s[:cap(s)][cap(s)-1] } return nil } // Cache applies any filtering and returns a struct that owns the underlying Unit slice. func (units Units) Cache() Units { units.ensureOwns(0) return units } // Len returns the length of the underlying slice of units. func (units Units) Len() int { if units.filter == nil { return len(units.raw) } n := 0 for _, u := range units.raw { if units.filter(u) { n++ } } return n } // Slice copies the units into a regular slice and returns it. func (units Units) Slice() []Unit { return units.Cache().raw } func (units *Units) append(u Unit) { units.ensureOwns(1) units.raw = append(units.raw, u) } func (units *Units) concat(other *Units) { if len(units.raw) == 0 { *units = *other } else if len(other.raw) > 0 { units.ensureOwns(len(other.raw)) other.applyFilter(len(other.raw)) if len(other.raw) > 0 { units.raw = append(units.raw, other.raw...) } } } // Tags returns the UnitTags for each unit. func (units Units) Tags() []api.UnitTag { tags := make([]api.UnitTag, 0, len(units.raw)) for _, u := range units.raw { if units.filter == nil || units.filter(u) { tags = append(tags, u.Tag) } } return tags } // Each calls f on every unit. func (units Units) Each(f func(Unit)) { for _, u := range units.raw { if units.filter == nil || units.filter(u) { f(u) } } } // EachWhile calls f until it returns false or runs out of elements. // Returns the last result of f (false on early return). func (units Units) EachWhile(f func(Unit) bool) bool { for _, u := range units.raw { if units.filter == nil || units.filter(u) { if !f(u) { return false } } } return true } // EachUntil calls f until it returns true or runs out of elements. // Returns the last result of f (true on early return). func (units Units) EachUntil(f func(Unit) bool) bool { for _, u := range units.raw { if units.filter == nil || units.filter(u) { if f(u) { return true } } } return false } // Choose returns a new list with only the units for which filter returns true. func (units Units) Choose(filter func(Unit) bool) Units { // Don't filter empty lists if len(units.raw) == 0 { return units } // If this is the first filter, just set and return it if units.filter == nil { return Units{units.raw, filter} } // Otherwise, union the two filters prev := units.filter return Units{units.raw, func(u Unit) bool { return prev(u) && filter(u) }} } // Partition splits the units into ones that filter is true for and ones that filter is false for. func (units Units) Partition(filter func(Unit) bool) (choose Units, drop Units) { choose = Units{make([]Unit, 0, len(units.raw)), nil} drop = Units{make([]Unit, 0, len(units.raw)), nil} units.Each(func(u Unit) { if filter(u) { choose.raw = append(choose.raw, u) } else { drop.raw = append(drop.raw, u) } }) return } // Drop returns a new list without the units for which filter returns true. func (units Units) Drop(filter func(Unit) bool) Units { return units.Choose(func(u Unit) bool { return !filter(u) }) } // First returns the first unit in the list or a Unit.IsNil() if the list is empty. func (units Units) First() Unit { for _, u := range units.raw { if units.filter == nil || units.filter(u) { return u } } return Unit{} } // ClosestTo returns the closest unit from the latest observation. func (units Units) ClosestTo(pos api.Point2D) Unit { minDist := float32(math.Inf(1)) var closest Unit for _, u := range units.raw { if units.filter == nil || units.filter(u) { dist := pos.Distance2(u.Pos.ToPoint2D()) if dist < minDist { closest = u minDist = dist } } } return closest } // CloserThan returns all units less than or equal to dist from pos. func (units Units) CloserThan(dist float32, pos api.Point2D) Units { dist2 := dist * dist return units.Choose(func(u Unit) bool { return u.Pos2D().Distance2(pos) <= dist2 }) } // Center returns the average location of the units. func (units Units) Center() api.Point2D { sum, n := api.Vec2D{}, 0 units.Each(func(u Unit) { sum = sum.Add(api.Vec2D(u.Pos2D())) n++ }) if n == 0 { return api.Point2D{} } return api.Point2D(sum.Div(float32(n))) } // Tagged ... func (units Units) Tagged(m map[api.UnitTag]bool) Units { return units.Choose(func(u Unit) bool { return m[u.Tag] }) } // NotTagged ... func (units Units) NotTagged(m map[api.UnitTag]bool) Units { return units.Choose(func(u Unit) bool { return !m[u.Tag] }) } // HasEnergy ... func (units Units) HasEnergy(energy float32) Units { return units.Choose(func(u Unit) bool { return u.Energy >= energy }) } // HasBuff ... func (units Units) HasBuff(buffID api.BuffID) Units { return units.Choose(func(u Unit) bool { for _, b := range u.BuffIds { if b == buffID { return true } } return false }) } // NoBuff ... func (units Units) NoBuff(buffID api.BuffID) Units { return units.Choose(func(u Unit) bool { for _, b := range u.BuffIds { if b == buffID { return false } } return true }) } // CanOrder ... func (units Units) CanOrder(ability api.AbilityID) Units { return units.Choose(func(u Unit) bool { return u.CanOrder(ability) }) } // IsStarted ... func (units Units) IsStarted() Units { return units.Choose(Unit.IsStarted) } // IsBuilt ... func (units Units) IsBuilt() Units { return units.Choose(Unit.IsBuilt) } // IsIdle ... func (units Units) IsIdle() Units { return units.Choose(Unit.IsIdle) } // IsTownHall ... func (units Units) IsTownHall() Units { return units.Choose(Unit.IsTownHall) } // IsGasBuilding ... func (units Units) IsGasBuilding() Units { return units.Choose(Unit.IsGasBuilding) } // IsWorker ... func (units Units) IsWorker() Units { return units.Choose(Unit.IsWorker) } // AttackTarget issues an attack order to any unit that isn't already attacking the target. func (units Units) AttackTarget(target Unit) { units = units.Choose(func(u Unit) bool { return u.needsAttackTargetOrder(target) }) if ctx := units.ctx(); ctx != nil && ctx.WasObserved(target.Tag) && target.CanBeTargeted() { units.OrderTarget(ability.Attack, target) } else { units.OrderPos(ability.Attack, target.Pos2D()) } } // AttackMove issues an attack order to any unit that isn't already attacking within tollerance of pos. func (units Units) AttackMove(pos api.Point2D, tollerance float32) { units.Choose(func(u Unit) bool { return u.needsAttackMoveOrder(pos, tollerance) }).OrderPos(ability.Attack, pos) } // MoveTo issues a move order to any unit that isn't already moving to or within tollerance of pos. func (units Units) MoveTo(pos api.Point2D, tollerance float32) { units.Choose(func(u Unit) bool { return u.needsMoveToOrder(pos, tollerance) }).OrderPos(ability.Move, pos) }
botutil/units.go
0.759761
0.511168
units.go
starcoder
package search // Query struct includes the search query. type Query struct { // Expression is the (Lucene-like) string expression specifying the search query. // If not provided then all resources are listed (up to MaxResults). Expression string `json:"expression,omitempty"` // SortBy is the the field to sort by. You can specify more than one SortBy parameter; results will be sorted // according to the order of the fields provided. SortBy []SortByField `json:"sort_by,omitempty"` // Aggregate is the the name of a field (attribute) for which an aggregation count should be calculated and returned in the response. // (Tier 2 only) // You can specify more than one aggregate parameter. // For aggregation fields without discrete values, the results are divided into categories. Aggregate []Aggregation `json:"aggregate,omitempty"` // WithField contains names of additional asset attributes to include for each asset in the response. WithField []WithField `json:"with_field,omitempty"` // MaxResults is the maximum number of results to return. Default 50. Maximum 500. MaxResults int `json:"max_results,omitempty"` // NextCursor value is returned as part of the response when a search request has more results to return than MaxResults. // You can then specify this value as the NextCursor parameter of the following request. NextCursor string `json:"next_cursor,omitempty"` } // Aggregation is the aggregation field. type Aggregation = string const ( // AssetType aggregation field. AssetType Aggregation = "resource_type" // DeliveryType aggregation field. DeliveryType = "type" // Pixels aggregation field. Only the image assets in the response are aggregated. Pixels = "pixels" // Duration aggregation field. Only the video assets in the response are aggregated. Duration = "duration" // Format aggregation field. Format = "format" // Bytes aggregation field. Bytes = "bytes" ) // WithField is the name of the addition filed to include in result. type WithField = string const ( // ContextField is the context field. ContextField WithField = "context" // TagsField is the tags field. TagsField = "tags" // ImageMetadataField is the image metadata field. ImageMetadataField = "image_metadata" // ImageAnalysisField is the image analysis field. ImageAnalysisField = "image_analysis" ) // Direction is the sorting direction. type Direction string const ( // Ascending direction. Ascending Direction = "asc" // Descending direction. Descending = "desc" ) // SortByField is the the field to sort by and direction. type SortByField map[string]Direction
api/admin/search/search.go
0.78842
0.469581
search.go
starcoder
package shapes import ( "image" "image/color" "github.com/remogatto/mathgl" "github.com/remogatto/shaders" ) // Base represent a basic structure for shapes. type Base struct { // Vertices of the generic shape vertices []float32 // Matrices projMatrix mathgl.Mat4f modelMatrix mathgl.Mat4f viewMatrix mathgl.Mat4f // Center of the shape x, y float32 // Angle angle float32 // Bounds bounds image.Rectangle // Color color color.Color // Normalized RGBA color nColor [4]float32 // Color matrix (four color component for each vertex) vColor []float32 // Texture texBuffer uint32 texCoords []float32 // GLSL program program shaders.Program // GLSL variables IDs colorId uint32 posId uint32 projMatrixId uint32 modelMatrixId uint32 viewMatrixId uint32 texInId uint32 texRatioId uint32 textureId uint32 } // Rotate rotates the shape around its center, by the given angle in // degrees. func (b *Base) Rotate(angle float32) { b.modelMatrix = mathgl.Translate3D(b.x, b.y, 0).Mul4(mathgl.HomogRotate3DZ(angle)) b.angle = angle } // RotateAround rotates the shape around the given point, by the given // angle in degrees. func (b *Base) RotateAround(x, y, angle float32) { dx, dy := x-b.x, y-b.y b.modelMatrix = mathgl.Translate3D(x, y, 0).Mul4(mathgl.HomogRotate3DZ(angle)) b.modelMatrix = b.modelMatrix.Mul4(mathgl.Translate3D(-dx, -dy, 0)) b.angle = angle } // Scale scales the shape relative to its center, by the given // factors. func (b *Base) Scale(sx, sy float32) { b.modelMatrix = mathgl.Translate3D(b.x, b.y, 0).Mul4(mathgl.Scale3D(sx, sy, 1.0)) } // Move moves the shape by dx, dy. func (b *Base) Move(dx, dy float32) { b.modelMatrix = b.modelMatrix.Mul4(mathgl.Translate3D(dx, dy, 0)) b.bounds = b.bounds.Add(image.Point{int(dx), int(dy)}) b.x, b.y = b.x+dx, b.y+dy } // MoveTo moves the shape in x, y position. func (b *Base) MoveTo(x, y float32) { b.modelMatrix = mathgl.Translate3D(x, y, 0) dx := x - b.x dy := y - b.y b.x, b.y = x, y b.bounds = b.bounds.Add(image.Point{int(dx), int(dy)}) } // Vertices returns the vertices slice. func (b *Base) Vertices() []float32 { return b.vertices } // Center returns the coordinates of the transformed center of the // shape. func (b *Base) Center() (float32, float32) { return b.x, b.y } // SetCenter sets the coordinates of the center of the shape. func (b *Base) SetCenter(x, y float32) { b.x, b.y = x, y } // Angle returns the current angle of the shape in degrees. func (b *Base) Angle() float32 { return b.angle } // Bounds returns the bounds of the shape as a Rectangle. func (b *Base) Bounds() image.Rectangle { return b.bounds } // Color returns the color of the shape. func (b *Base) Color() color.Color { return b.color } // NColor returns the color of the shape as a normalized float32 // array. func (b *Base) NColor() [4]float32 { return b.nColor } // SetColor sets the color of the shape. func (s *Base) SetColor(c color.Color) { s.color = c // Convert to RGBA rgba := color.NRGBAModel.Convert(c).(color.NRGBA) r, g, b, a := rgba.R, rgba.G, rgba.B, rgba.A // Normalize the color components s.nColor = [4]float32{ float32(r) / 255, float32(g) / 255, float32(b) / 255, float32(a) / 255, } // TODO improve code vCount := len(s.vertices) / 2 s.vColor = s.vColor[:0] for i := 0; i < vCount; i++ { s.vColor = append(s.vColor, s.nColor[0], s.nColor[1], s.nColor[2], s.nColor[3]) } } // AttachToWorld fills projection and view matrices with world's // matrices. func (b *Base) AttachToWorld(world World) { b.projMatrix = world.Projection() b.viewMatrix = world.View() } // SetTexture sets a texture for the shape. Texture argument is an // uint32 value returned by the OpenGL context. It's a client-code // responsibility to provide that value. func (b *Base) SetTexture(texture uint32, texCoords []float32) error { b.texCoords = texCoords b.texBuffer = texture return nil } // String returns a string representation of the shape. func (b *Base) String() string { return b.bounds.String() }
base.go
0.858704
0.599045
base.go
starcoder
package ameda import ( "fmt" "math" ) // Float64ToInterface converts float64 to interface. func Float64ToInterface(v float64) interface{} { return v } // Float64ToInterfacePtr converts float64 to *interface. func Float64ToInterfacePtr(v float64) *interface{} { r := Float64ToInterface(v) return &r } // Float64ToString converts float64 to string. func Float64ToString(v float64) string { return fmt.Sprintf("%f", v) } // Float64ToStringPtr converts float64 to *string. func Float64ToStringPtr(v float64) *string { r := Float64ToString(v) return &r } // Float64ToBool converts float64 to bool. func Float64ToBool(v float64) bool { return v != 0 } // Float64ToBoolPtr converts float64 to *bool. func Float64ToBoolPtr(v float64) *bool { r := Float64ToBool(v) return &r } // Float64ToFloat32 converts float64 to float32. func Float64ToFloat32(v float64) (float32, error) { if v > math.MaxFloat32 || v < -math.MaxFloat32 { return 0, errOverflowValue } return float32(v), nil } // Float64ToFloat32Ptr converts float64 to *float32. func Float64ToFloat32Ptr(v float64) (*float32, error) { r, err := Float64ToFloat32(v) return &r, err } // Float64ToFloat64Ptr converts float64 to *float64. func Float64ToFloat64Ptr(v float64) *float64 { return &v } // Float64ToInt converts float64 to int. func Float64ToInt(v float64) (int, error) { if Host64bit { if v > math.MaxInt64 || v < math.MinInt64 { return 0, errOverflowValue } } else { if v > math.MaxInt32 || v < math.MinInt32 { return 0, errOverflowValue } } return int(v), nil } // Float64ToInt8 converts float64 to int8. func Float64ToInt8(v float64) (int8, error) { if v > math.MaxInt8 || v < math.MinInt8 { return 0, errOverflowValue } return int8(v), nil } // Float64ToInt8Ptr converts float64 to *int8. func Float64ToInt8Ptr(v float64) (*int8, error) { r, err := Float64ToInt8(v) return &r, err } // Float64ToInt16 converts float64 to int16. func Float64ToInt16(v float64) (int16, error) { if v > math.MaxInt16 || v < math.MinInt16 { return 0, errOverflowValue } return int16(v), nil } // Float64ToInt16Ptr converts float64 to *int16. func Float64ToInt16Ptr(v float64) (*int16, error) { r, err := Float64ToInt16(v) return &r, err } // Float64ToInt32 converts float64 to int32. func Float64ToInt32(v float64) (int32, error) { if v > math.MaxInt32 || v < math.MinInt32 { return 0, errOverflowValue } return int32(v), nil } // Float64ToInt32Ptr converts float64 to *int32. func Float64ToInt32Ptr(v float64) (*int32, error) { r, err := Float64ToInt32(v) return &r, err } // Float64ToInt64 converts float64 to int64. func Float64ToInt64(v float64) (int64, error) { if v > math.MaxInt64 || v < math.MinInt64 { return 0, errOverflowValue } return int64(v), nil } // Float64ToInt64Ptr converts float64 to *int64. func Float64ToInt64Ptr(v float64) (*int64, error) { r, err := Float64ToInt64(v) return &r, err } // Float64ToUint converts float64 to uint. func Float64ToUint(v float64) (uint, error) { if v < 0 { return 0, errNegativeValue } if Host64bit { if v > math.MaxUint64 { return 0, errOverflowValue } } else { if v > math.MaxUint32 { return 0, errOverflowValue } } return uint(v), nil } // Float64ToUintPtr converts float64 to *uint. func Float64ToUintPtr(v float64) (*uint, error) { r, err := Float64ToUint(v) return &r, err } // Float64ToUint8 converts float64 to uint8. func Float64ToUint8(v float64) (uint8, error) { if v < 0 { return 0, errNegativeValue } if v > math.MaxUint8 { return 0, errOverflowValue } return uint8(v), nil } // Float64ToUint8Ptr converts float64 to *uint8. func Float64ToUint8Ptr(v float64) (*uint8, error) { r, err := Float64ToUint8(v) return &r, err } // Float64ToUint16 converts float64 to uint16. func Float64ToUint16(v float64) (uint16, error) { if v < 0 { return 0, errNegativeValue } if v > math.MaxUint16 { return 0, errOverflowValue } return uint16(v), nil } // Float64ToUint16Ptr converts float64 to *uint16. func Float64ToUint16Ptr(v float64) (*uint16, error) { r, err := Float64ToUint16(v) return &r, err } // Float64ToUint32 converts float64 to uint32. func Float64ToUint32(v float64) (uint32, error) { if v < 0 { return 0, errNegativeValue } if v > math.MaxUint32 { return 0, errOverflowValue } return uint32(v), nil } // Float64ToUint32Ptr converts float64 to *uint32. func Float64ToUint32Ptr(v float64) (*uint32, error) { r, err := Float64ToUint32(v) return &r, err } // Float64ToUint64 converts float64 to uint64. func Float64ToUint64(v float64) (uint64, error) { if v < 0 { return 0, errNegativeValue } if v > math.MaxUint64 { return 0, errOverflowValue } return uint64(v), nil } // Float64ToUint64Ptr converts float64 to *uint64. func Float64ToUint64Ptr(v float64) (*uint64, error) { r, err := Float64ToUint64(v) return &r, err }
vendor/github.com/henrylee2cn/ameda/float64.go
0.768646
0.424293
float64.go
starcoder
package gmeasure import ( "fmt" "sort" "github.com/bsm/gomega/gmeasure/table" ) /* RankingCriteria is an enum representing the criteria by which Stats should be ranked. The enum names should be self explanatory. e.g. LowerMeanIsBetter means that Stats with lower mean values are considered more beneficial, with the lowest mean being declared the "winner" . */ type RankingCriteria uint const ( LowerMeanIsBetter RankingCriteria = iota HigherMeanIsBetter LowerMedianIsBetter HigherMedianIsBetter LowerMinIsBetter HigherMinIsBetter LowerMaxIsBetter HigherMaxIsBetter ) var rcEnumSupport = newEnumSupport(map[uint]string{uint(LowerMeanIsBetter): "Lower Mean is Better", uint(HigherMeanIsBetter): "Higher Mean is Better", uint(LowerMedianIsBetter): "Lower Median is Better", uint(HigherMedianIsBetter): "Higher Median is Better", uint(LowerMinIsBetter): "Lower Mins is Better", uint(HigherMinIsBetter): "Higher Min is Better", uint(LowerMaxIsBetter): "Lower Max is Better", uint(HigherMaxIsBetter): "Higher Max is Better"}) func (s RankingCriteria) String() string { return rcEnumSupport.String(uint(s)) } func (s *RankingCriteria) UnmarshalJSON(b []byte) error { out, err := rcEnumSupport.UnmarshJSON(b) *s = RankingCriteria(out) return err } func (s RankingCriteria) MarshalJSON() ([]byte, error) { return rcEnumSupport.MarshJSON(uint(s)) } /* Ranking ranks a set of Stats by a specified RankingCritera. Use RankStats to create a Ranking. When using Ginkgo, you can register Rankings as Report Entries via AddReportEntry. This will emit a formatted table representing the Stats in rank-order when Ginkgo generates the report. */ type Ranking struct { Criteria RankingCriteria Stats []Stats } /* RankStats creates a new ranking of the passed-in stats according to the passed-in criteria. */ func RankStats(criteria RankingCriteria, stats ...Stats) Ranking { sort.Slice(stats, func(i int, j int) bool { switch criteria { case LowerMeanIsBetter: return stats[i].FloatFor(StatMean) < stats[j].FloatFor(StatMean) case HigherMeanIsBetter: return stats[i].FloatFor(StatMean) > stats[j].FloatFor(StatMean) case LowerMedianIsBetter: return stats[i].FloatFor(StatMedian) < stats[j].FloatFor(StatMedian) case HigherMedianIsBetter: return stats[i].FloatFor(StatMedian) > stats[j].FloatFor(StatMedian) case LowerMinIsBetter: return stats[i].FloatFor(StatMin) < stats[j].FloatFor(StatMin) case HigherMinIsBetter: return stats[i].FloatFor(StatMin) > stats[j].FloatFor(StatMin) case LowerMaxIsBetter: return stats[i].FloatFor(StatMax) < stats[j].FloatFor(StatMax) case HigherMaxIsBetter: return stats[i].FloatFor(StatMax) > stats[j].FloatFor(StatMax) } return false }) out := Ranking{ Criteria: criteria, Stats: stats, } return out } /* Winner returns the Stats with the most optimal rank based on the specified ranking criteria. For example, if the RankingCriteria is LowerMaxIsBetter then the Stats with the lowest value or duration for StatMax will be returned as the "winner" */ func (c Ranking) Winner() Stats { if len(c.Stats) == 0 { return Stats{} } return c.Stats[0] } func (c Ranking) report(enableStyling bool) string { if len(c.Stats) == 0 { return "Empty Ranking" } t := table.NewTable() t.TableStyle.EnableTextStyling = enableStyling t.AppendRow(table.R( table.C("Experiment"), table.C("Name"), table.C("N"), table.C("Min"), table.C("Median"), table.C("Mean"), table.C("StdDev"), table.C("Max"), table.Divider("="), "{{bold}}", )) for idx, stats := range c.Stats { name := stats.MeasurementName if stats.Units != "" { name = name + " [" + stats.Units + "]" } experimentName := stats.ExperimentName style := stats.Style if idx == 0 { style = "{{bold}}" + style name += "\n*Winner*" experimentName += "\n*Winner*" } r := table.R(style) t.AppendRow(r) r.AppendCell(table.C(experimentName), table.C(name)) r.AppendCell(stats.cells()...) } out := fmt.Sprintf("Ranking Criteria: %s\n", c.Criteria) if enableStyling { out = "{{bold}}" + out + "{{/}}" } out += t.Render() return out } /* ColorableString generates a styled report that includes a table of the rank-ordered Stats It is called automatically by Ginkgo's reporting infrastructure when the Ranking is registered as a ReportEntry via AddReportEntry. */ func (c Ranking) ColorableString() string { return c.report(true) } /* String generates an unstyled report that includes a table of the rank-ordered Stats */ func (c Ranking) String() string { return c.report(false) }
gmeasure/rank.go
0.795539
0.421492
rank.go
starcoder
package glm import ( "fmt" "math" ) // VecFunc is a function with two float64 array arguments. type VecFunc func([]float64, []float64) // Link specifies a GLM link function. type Link struct { Name string TypeCode LinkType // Link calculates the link function (usually mapping the mean // value to the linear predictor). Link VecFunc // InvLink calculates the inverse of the link function // (usually mapping the linear predictor to the mean value). InvLink VecFunc // Deriv calculates the derivative of the link function. Deriv VecFunc // Deriv2 calculates the second derivative of the link function. Deriv2 VecFunc } // LinkType is used to specify a GLM link function. type LinkType uint8 // LogLink, ... are used to specify GLM link functions. const ( LogLink LinkType = iota IdentityLink LogitLink CloglogLink RecipLink RecipSquaredLink PowerLink ) // NewLink returns a link function object corresponding to the given // name. Supported values are log, identity, cloglog, logit, recip, // and recipsquared. func NewLink(link LinkType) *Link { switch link { case LogLink: return &logLink case IdentityLink: return &idLink case CloglogLink: return &cLogLogLink case LogitLink: return &logitLink case RecipLink: return &recipLink case RecipSquaredLink: return &recipSquaredLink default: msg := fmt.Sprintf("Link unknown: %v\n", link) panic(msg) } } var logLink = Link{ Name: "Log", TypeCode: LogLink, Link: logFunc, InvLink: expFunc, Deriv: logDerivFunc, Deriv2: logDeriv2Func, } var idLink = Link{ Name: "Identity", TypeCode: IdentityLink, Link: idFunc, InvLink: idFunc, Deriv: idDerivFunc, Deriv2: idDeriv2Func, } var cLogLogLink = Link{ Name: "CLogLog", TypeCode: CloglogLink, Link: cloglogFunc, InvLink: cloglogInvFunc, Deriv: cloglogDerivFunc, Deriv2: cloglogDeriv2Func, } var logitLink = Link{ Name: "Logit", TypeCode: LogitLink, Link: logitFunc, InvLink: expitFunc, Deriv: logitDerivFunc, Deriv2: logitDeriv2Func, } var recipLink = Link{ Name: "Recip", TypeCode: RecipLink, Link: genPowFunc(-1, 1), InvLink: genPowFunc(-1, 1), Deriv: genPowFunc(-2, -1), Deriv2: genPowFunc(-3, 2), } var recipSquaredLink = Link{ Name: "RecipSquared", TypeCode: RecipSquaredLink, Link: genPowFunc(-2, 1), InvLink: genPowFunc(-0.5, 1), Deriv: genPowFunc(-3, -2), Deriv2: genPowFunc(-4, 6), } // NewPowerLink returns the power link eta = mu^pw. If // pw = 0 returns the log link. func NewPowerLink(pw float64) *Link { if pw == 0 { return &logLink } return &Link{ Name: fmt.Sprintf("PowerLink(%f)", pw), TypeCode: PowerLink, Link: genPowFunc(pw, 1), InvLink: genPowFunc(1/pw, 1), Deriv: genPowFunc(pw-1, pw), Deriv2: genPowFunc(pw-2, pw*(pw-1)), } } func logFunc(x []float64, y []float64) { for i := range x { y[i] = math.Log(x[i]) } } func logDerivFunc(x []float64, y []float64) { for i := range x { y[i] = 1 / x[i] } } func logDeriv2Func(x []float64, y []float64) { for i := range x { y[i] = -1 / (x[i] * x[i]) } } func expFunc(x []float64, y []float64) { for i := range x { y[i] = math.Exp(x[i]) } } func logitFunc(x []float64, y []float64) { for i := range x { r := x[i] / (1 - x[i]) y[i] = math.Log(r) } } func logitDerivFunc(x []float64, y []float64) { for i := range x { y[i] = 1 / (x[i] * (1 - x[i])) } } func logitDeriv2Func(x []float64, y []float64) { for i := range x { v := x[i] * (1 - x[i]) y[i] = (2*x[i] - 1) / (v * v) } } func expitFunc(x []float64, y []float64) { for i := range x { y[i] = 1 / (1 + math.Exp(-x[i])) } } func idFunc(x []float64, y []float64) { // Assumes lengths match copy(y, x) } func idDerivFunc(x []float64, y []float64) { one(y) } func idDeriv2Func(x []float64, y []float64) { zero(y) } func cloglogFunc(x []float64, y []float64) { for i, v := range x { y[i] = math.Log(-math.Log(1 - v)) } } func cloglogDerivFunc(x []float64, y []float64) { for i, v := range x { y[i] = 1 / ((v - 1) * math.Log(1-v)) } } func cloglogDeriv2Func(x []float64, y []float64) { for i, v := range x { f := math.Log(1 - v) r := -1 / ((1 - v) * (1 - v) * f) y[i] = r * (1 + 1/f) } } func cloglogInvFunc(x []float64, y []float64) { for i, v := range x { y[i] = 1 - math.Exp(-math.Exp(v)) } } func genPowFunc(p float64, s float64) VecFunc { return func(x []float64, y []float64) { for i := range x { y[i] = s * math.Pow(x[i], p) } } }
glm/links.go
0.724091
0.415136
links.go
starcoder
package decoders import ( "errors" "fmt" "github.com/wader/fq/format/avro/schema" "github.com/wader/fq/pkg/decode" ) func decodeMapFn(s schema.SimplifiedSchema) (DecodeFn, error) { if s.Values == nil { return nil, errors.New("map schema must have values") } // Maps are encoded as a series of blocks. Each block consists of a long count value, followed by that many // key/value pairs. A block with count zero indicates the end of the map. Each item is encoded per the map's // value schema. // If a block's count is negative, its absolute value is used, and the count is followed immediately by a long // block size indicating the number of bytes in the block. This block size permits fast skipping through data, // e.g., when projecting a record to a subset of its fields. // The blocked representation permits one to read and write maps larger than can be buffered in memory, since one // can start writing items without knowing the full length of the map. // This is the exact same as the array decoder, with the value being a KV record, so we just use the array decoder subSchema := schema.SimplifiedSchema{ Type: schema.ARRAY, Items: &schema.SimplifiedSchema{ Type: schema.RECORD, Fields: []schema.Field{ { Name: "key", Type: schema.SimplifiedSchema{Type: schema.STRING}, }, { Name: "value", Type: *s.Values, }, }, }, } subFn, err := DecodeFnForSchema(subSchema) if err != nil { return nil, fmt.Errorf("decode map: %w", err) } return func(s string, d *decode.D) any { val := make(map[string]any) rawV := subFn(s, d) rawSlice, ok := rawV.([]any) if !ok { d.Fatalf("decode map: expected array of interfaces, got %v", rawV) return nil } for _, rawEntry := range rawSlice { entry, ok := rawEntry.(map[string]any) if !ok { d.Fatalf("decode map: expected map, got %T", rawEntry) } rawKey, ok := entry["key"] if !ok { d.Fatalf("decode map: expected key in map %v", entry) } value, ok := entry["value"] if !ok { d.Fatalf("decode map: expected value in map %v", entry) } key, ok := rawKey.(string) if !ok { d.Fatalf("decode map: expected string key in map %v", entry) } val[key] = value } return val }, nil }
format/avro/decoders/map.go
0.640186
0.400808
map.go
starcoder
package jwt import ( "errors" "log" ) /* 7.1. Creating a JWT To create a JWT, the following steps are performed. The order of the steps is not significant in cases where there are no dependencies between the inputs and outputs of the steps. 1. Create a JWT Claims Set containing the desired claims. Note that whitespace is explicitly allowed in the representation and no canonicalization need be performed before encoding. 2. Let the Message be the octets of the UTF-8 representation of the JWT Claims Set. 3. Create a JOSE Header containing the desired set of Header Parameters. The JWT MUST conform to either the [JWS] or [JWE] specification. Note that whitespace is explicitly allowed in the representation and no canonicalization need be performed before encoding. 4. Depending upon whether the JWT is a JWS or JWE, there are two cases: * If the JWT is a JWS, create a JWS using the Message as the JWS Payload; all steps specified in [JWS] for creating a JWS MUST be followed. * Else, if the JWT is a JWE, create a JWE using the Message as the plaintext for the JWE; all steps specified in [JWE] for creating a JWE MUST be followed. 5. If a nested signing or encryption operation will be performed, let the Message be the JWS or JWE, and return to Step 3, using a "cty" (content type) value of "JWT" in the new JOSE Header created in that step. 6. Otherwise, let the resulting JWT be the JWS or JWE. */ func (t *Token) Encode() ([]byte, error){ _, err := t.Header.ToBase64() if err != nil { return nil, err } _, err = t.Payload.ToBase64() if err != nil { return nil, err } algorithm, ok := t.Header.Properties["alg"].(AlgorithmType); if !ok { algorithmStr, ok := t.Header.Properties["alg"].(string); if ok { algorithm = AlgorithmType(algorithmStr) } } tokenType, err := DetermineTokenType(algorithm) if err != nil { return nil, err } switch tokenType { case JWS: return t.Sign() case JWE: log.Fatal("JWE Not Implemented") default: //TODO: If you get here, CUSTOM has been chosen for the algorithm, which means the developer consuming this API will be implementing the SignFunc/EncryptFunc } return nil, errors.New("unable to encode - please check algorithm") }
encode.go
0.579162
0.643035
encode.go
starcoder
package calculator import ( "fmt" "math" ) var functions = map[string]interface{}{ "abs": math.Abs, "acos": math.Acos, "acosh": math.Acosh, "asin": math.Asin, "asinh": math.Asinh, "atan": math.Atan, "atan2": math.Atan2, "atanh": math.Atanh, "cbrt": math.Cbrt, "ceil": math.Ceil, "copysign": math.Copysign, "cos": math.Cos, "cosh": math.Cosh, "dim": math.Dim, "erf": math.Erf, "erfc": math.Erfc, "erfcinv": math.Erfcinv, // Go 1.10+ "erfinv": math.Erfinv, // Go 1.10+ "exp": math.Exp, "exp2": math.Exp2, "expm1": math.Expm1, "fma": math.FMA, // Go 1.14+ "floor": math.Floor, "gamma": math.Gamma, "hypot": math.Hypot, "j0": math.J0, "j1": math.J1, "log": math.Log, "log10": math.Log10, "log1p": math.Log1p, "log2": math.Log2, "logb": math.Logb, "max": math.Max, "min": math.Min, "mod": math.Mod, "nan": math.NaN, "nextafter": math.Nextafter, "pow": math.Pow, "remainder": math.Remainder, "round": math.Round, // Go 1.10+ "roundtoeven": math.RoundToEven, // Go 1.10+ "sin": math.Sin, "sinh": math.Sinh, "sqrt": math.Sqrt, "tan": math.Tan, "tanh": math.Tanh, "trunc": math.Trunc, "y0": math.Y0, "y1": math.Y1, } func call(funcName string, args []float64) (float64, error) { f, ok := functions[funcName] if !ok { return 0, fmt.Errorf("unknown function %s", funcName) } switch f := f.(type) { case func() float64: return f(), nil case func(float64) float64: return f(args[0]), nil case func(float64, float64) float64: return f(args[0], args[1]), nil case func(float64, float64, float64) float64: return f(args[0], args[1], args[2]), nil default: return 0, fmt.Errorf("invalid function %s", funcName) } } func calculate(n *node) (float64, error) { switch n.kind { case addNode: left, err := calculate(n.left) if err != nil { return 0, err } right, err := calculate(n.right) if err != nil { return 0, err } return left + right, nil case subNode: left, err := calculate(n.left) if err != nil { return 0, err } right, err := calculate(n.right) if err != nil { return 0, err } return left - right, nil case mulNode: left, err := calculate(n.left) if err != nil { return 0, err } right, err := calculate(n.right) if err != nil { return 0, err } return left * right, nil case divNode: left, err := calculate(n.left) if err != nil { return 0, err } right, err := calculate(n.right) if err != nil { return 0, err } return left / right, nil case numNode: return n.val, nil case funcNode: args := []float64{} for _, arg := range n.args { val, err := calculate(arg) if err != nil { return 0, err } args = append(args, val) } return call(n.funcName, args) } return 0, fmt.Errorf("unknown node type: %s", n.kind) } // Calculate calculates expr func Calculate(expr string) (float64, error) { tokens, err := tokenize(expr) if err != nil { return 0, err } p := newParser(tokens) n, err := p.parse() if err != nil { return 0, err } return calculate(n) }
calculator.go
0.517571
0.434941
calculator.go
starcoder
package convert import ( "fmt" "reflect" spb "google.golang.org/protobuf/types/known/structpb" ) // Map2pbStruct convert map to pbstruct // ref: https://devnote.pro/posts/10000050901242 func Map2pbStruct(m map[string]interface{}) *spb.Struct { size := len(m) if size == 0 { return nil } fields := make(map[string]*spb.Value, size) for k, v := range m { fields[k] = InterfaceToValue(v) } return &spb.Struct{ Fields: fields, } } func MapBool2pbStruct(m map[string]map[string]bool) *spb.Struct { size := len(m) if size == 0 { return nil } fields := make(map[string]*spb.Value, size) for k, v := range m { fields[k] = InterfaceToValue(v) } return &spb.Struct{ Fields: fields, } } // InterfaceToValue func InterfaceToValue(v interface{}) *spb.Value { switch v := v.(type) { case nil: return nil case bool: return &spb.Value{ Kind: &spb.Value_BoolValue{ BoolValue: v, }, } case int: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case int8: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case int32: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case int64: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case uint: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case uint8: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case uint32: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case uint64: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case float32: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v), }, } case float64: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: v, }, } case string: return &spb.Value{ Kind: &spb.Value_StringValue{ StringValue: v, }, } case error: return &spb.Value{ Kind: &spb.Value_StringValue{ StringValue: v.Error(), }, } default: // 回退为其他类型 return toValue(reflect.ValueOf(v)) } } func toValue(v reflect.Value) *spb.Value { switch v.Kind() { case reflect.Bool: return &spb.Value{ Kind: &spb.Value_BoolValue{ BoolValue: v.Bool(), }, } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v.Int()), }, } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: float64(v.Uint()), }, } case reflect.Float32, reflect.Float64: return &spb.Value{ Kind: &spb.Value_NumberValue{ NumberValue: v.Float(), }, } case reflect.Ptr: if v.IsNil() { return nil } return toValue(reflect.Indirect(v)) case reflect.Array, reflect.Slice: size := v.Len() if size == 0 { return nil } values := make([]*spb.Value, size) for i := 0; i < size; i++ { values[i] = toValue(v.Index(i)) } return &spb.Value{ Kind: &spb.Value_ListValue{ ListValue: &spb.ListValue{ Values: values, }, }, } case reflect.Struct: t := v.Type() size := v.NumField() if size == 0 { return nil } fields := make(map[string]*spb.Value, size) for i := 0; i < size; i++ { name := t.Field(i).Name if len(name) > 0 && 'A' <= name[0] && name[0] <= 'Z' { fields[name] = toValue(v.Field(i)) } } if len(fields) == 0 { return nil } return &spb.Value{ Kind: &spb.Value_StructValue{ StructValue: &spb.Struct{ Fields: fields, }, }, } case reflect.Map: keys := v.MapKeys() if len(keys) == 0 { return nil } fields := make(map[string]*spb.Value, len(keys)) for _, k := range keys { if k.Kind() == reflect.String { fields[k.String()] = toValue(v.MapIndex(k)) } } if len(fields) == 0 { return nil } return &spb.Value{ Kind: &spb.Value_StructValue{ StructValue: &spb.Struct{ Fields: fields, }, }, } default: // 最后排序 return &spb.Value{ Kind: &spb.Value_StringValue{ StringValue: fmt.Sprint(v), }, } } }
bcs-services/bcs-project/internal/util/convert/convert.go
0.517083
0.527317
convert.go
starcoder
package cellshandler import ( "regexp" "strconv" "strings" "github.com/juanPabloMiceli/visual-simd-debugger/backend/xmmhandler" ) //CellData is the data of the cell that is received from the frontend type CellData struct { ID int `json:"id"` Code string `json:"code"` } //CellsData has the data of every cell received from the frontend as well as the //requests each cell has to ask type CellsData struct { Data []CellData `json:"CellsData"` Requests []XmmRequests HiddenRegs []HiddenInCell } type HiddenInCell []int //XMMFormat contains the printing format for every XMM type XMMFormat struct { DefaultDataFormat []string DefaultPrintingFormat []string } //XmmRequest has all the information required to get the data from ptrace. type XmmRequest struct { XmmNumber int XmmID string DataFormat string PrintFormat string } //XmmRequests is a slice containing al XmmRequest in a cell type XmmRequests []XmmRequest //NewCellsData creates a new CellsData func NewCellsData() CellsData { return CellsData{ Data: make([]CellData, 0), Requests: make([]XmmRequests, 0), } } func NewXMMFormat() XMMFormat { defaultDataFormat := make([]string, xmmhandler.XMMREGISTERS) defaultPrintingFormat := make([]string, xmmhandler.XMMREGISTERS) for i := range defaultDataFormat { defaultDataFormat[i] = xmmhandler.INT8STRING defaultPrintingFormat[i] = xmmhandler.SIGNEDFORMAT } return XMMFormat{ DefaultDataFormat: defaultDataFormat, DefaultPrintingFormat: defaultPrintingFormat, } } //CellsData2SourceCode converts Cells Data to source code func (obj *CellsData) CellsData2SourceCode() string { sourceCode := "" for _, cellData := range obj.Data { sourceCode += cellData.Code } return sourceCode } //HandleCellsData edit cells code content such that the cells to source code convertion is direct func (obj *CellsData) HandleCellsData(xmmFormat *XMMFormat) bool { obj.toLowerCase() obj.getAllHiddenRegs() obj.handleAllXmmRequests(xmmFormat) if !obj.hasCode() { return true } obj.addDataSection() obj.addTextSection() obj.removeUserBreakpoints() obj.addCellsBreakpoints() obj.addExitSyscall() return false } func (obj *CellsData) getAllHiddenRegs() { r := regexp.MustCompile(`(( |\t)+)?;(( |\t)+)?hide(( |\t)+)?(xmm(?P<xmmNumber>[0-9]|1[0-5]))\b`) for cellIndex := range obj.Data { obj.HiddenRegs = append(obj.HiddenRegs, make(HiddenInCell, 0)) obj.getCellHiddenRegs(r, cellIndex) } } func (obj *CellsData) getCellHiddenRegs(r *regexp.Regexp, cellIndex int) { matches := r.FindAllStringSubmatch(obj.Data[cellIndex].Code, -1) for _, match := range matches { obj.getHiddenReg(r, match, cellIndex) } } func containsInt(elem int, s []int) bool { for _, current := range s { if current == elem { return true } } return false } func (obj *CellsData) getHiddenReg(r *regexp.Regexp, match []string, cellIndex int) { values := GetGroupValues(r, match) xmmNumber, _ := strconv.Atoi(values["xmmNumber"]) if !containsInt(xmmNumber, obj.HiddenRegs[cellIndex]) { obj.HiddenRegs[cellIndex] = append(obj.HiddenRegs[cellIndex], xmmNumber) } } func (obj *CellsData) hasCode() bool { for i, data := range obj.Data { if i > 0 { if len(data.Code) > 0 { return true } } } return false } func (obj *CellsData) toLowerCase() { for index := range obj.Data { obj.Data[index].Code = strings.ToLower(obj.Data[index].Code) } } //GetGroupValues returns a map with each value found in the regexp match func GetGroupValues(r *regexp.Regexp, match []string) map[string]string { values := make(map[string]string) for i, name := range r.SubexpNames() { values[name] = match[i] } return values } //XmmID2Number receives a string with the format "xmm<number>" and returns the number as an int func XmmID2Number(xmmID string) int { runes := []rune(xmmID) xmmSafeString := string(runes[3:]) xmmNumber, _ := strconv.Atoi(xmmSafeString) return xmmNumber } func (obj *CellsData) handleAllXmmRequests(xmmFormat *XMMFormat) { r := regexp.MustCompile(`(( |\t)+)?;(( |\t)+)?(print|p)(( |\t)+)?(?P<printFormat>\/(d|x|t|u))?(( |\t)+)?(?P<xmmID>xmm([0-9]|1[0-5]))\.(?P<dataFormat>v16_int8|v8_int16|v4_int32|v2_int64|v4_float|v2_double)`) for cellIndex := range obj.Data { obj.Requests = append(obj.Requests, make(XmmRequests, 0)) obj.handleCellXmmRequests(r, cellIndex, xmmFormat) } } func (obj *CellsData) handleCellXmmRequests(r *regexp.Regexp, cellIndex int, xmmFormat *XMMFormat) { matches := r.FindAllStringSubmatch(obj.Data[cellIndex].Code, -1) for _, match := range matches { obj.handleXmmRequest(r, match, cellIndex, xmmFormat) } } func (obj *CellsData) handleXmmRequest(r *regexp.Regexp, match []string, cellIndex int, xmmFormat *XMMFormat) { var xmmRequest XmmRequest values := GetGroupValues(r, match) xmmRequest.XmmID = strings.ToUpper(values["xmmID"]) xmmRequest.XmmNumber = XmmID2Number(xmmRequest.XmmID) xmmRequest.DataFormat = values["dataFormat"] xmmRequest.PrintFormat = values["printFormat"] xmmFormat.DefaultDataFormat[xmmRequest.XmmNumber] = xmmRequest.DataFormat if !containsInt(xmmRequest.XmmNumber, obj.HiddenRegs[cellIndex]) { obj.Requests[cellIndex] = append(obj.Requests[cellIndex], xmmRequest) } } func (obj *CellsData) addDataSection() { obj.Data[0].Code = "section .data\n" + obj.Data[0].Code } func (obj *CellsData) addTextSection() { var startText string startText += "\nglobal _start\n" startText += "section .text\n" startText += "_start:\n" obj.Data[1].Code = startText + obj.Data[1].Code } func (obj *CellsData) removeUserBreakpoints() { for index, cellData := range obj.Data { if strings.Contains(cellData.Code, "int 3") { obj.Data[index].Code = strings.ReplaceAll(cellData.Code, "int 3", "") } } } func (obj *CellsData) addCellsBreakpoints() { for index := range obj.Data { if index > 0 { obj.Data[index].Code += "\nint 3\n" } } } func (obj *CellsData) addExitSyscall() { var exitText string exitText += "mov rax, 60\n" exitText += "mov rdi, 0\n" exitText += "syscall\n" var lastIndex = len(obj.Data) - 1 obj.Data[lastIndex].Code += exitText }
backend/cellshandler/cellshandler.go
0.520009
0.416085
cellshandler.go
starcoder
package calc import ( "math/big" "strings" "github.com/ALTree/bigfloat" complex "github.com/pointlander/c0mpl3x" ) var prec uint = 1024 // ValueType is a value type type ValueType int const ( // ValueTypeMatrix is a matrix value type ValueTypeMatrix ValueType = iota // ValueTypeExpression is an expression value type ValueTypeExpression ) // Value is a value type Value struct { ValueType ValueType Matrix *complex.Matrix Expression *Node } // Eval evaluates the expression func (c *Calculator) Eval() Value { return c.Rulee(c.AST()) } // Rulee is a root expresion func (c *Calculator) Rulee(node *node32) Value { node = node.up for node != nil { switch node.pegRule { case rulee1: return c.Rulee1(node) } node = node.next } return Value{} } // Rulee1 deals with addation or subtraction func (c *Calculator) Rulee1(node *node32) Value { node = node.up var a Value for node != nil { switch node.pegRule { case rulee2: a = c.Rulee2(node) case ruleadd: node = node.next b := c.Rulee2(node) a.Matrix.Add(a.Matrix, b.Matrix) case ruleminus: node = node.next b := c.Rulee2(node) a.Matrix.Sub(a.Matrix, b.Matrix) } node = node.next } return a } // Rulee2 deals with multiplication, division, or modulus func (c *Calculator) Rulee2(node *node32) Value { node = node.up var a Value for node != nil { switch node.pegRule { case rulee3: a = c.Rulee3(node) case rulemultiply: node = node.next b := c.Rulee3(node) a.Matrix.Mul(a.Matrix, b.Matrix) case ruledivide: node = node.next b := c.Rulee3(node) a.Matrix.Div(a.Matrix, b.Matrix) case rulemodulus: node = node.next b := c.Rulee3(node) if a.Matrix.Values[0][0].A.Denom().Cmp(big.NewInt(1)) == 0 && b.Matrix.Values[0][0].A.Denom().Cmp(big.NewInt(1)) == 0 { a.Matrix.Values[0][0].A.Num().Mod(a.Matrix.Values[0][0].A.Num(), b.Matrix.Values[0][0].A.Num()) } } node = node.next } return a } // Rulee3 deals with exponentiation func (c *Calculator) Rulee3(node *node32) Value { node = node.up var a Value for node != nil { switch node.pegRule { case rulee4: a = c.Rulee4(node) case ruleexponentiation: node = node.next b := c.Rulee4(node) a.Matrix.Pow(a.Matrix, &b.Matrix.Values[0][0]) } node = node.next } return a } // Rulee4 negates a number func (c *Calculator) Rulee4(node *node32) Value { node = node.up minus := false for node != nil { switch node.pegRule { case rulevalue: a := c.Rulevalue(node) if minus { a.Matrix.Neg(a.Matrix) } return a case ruleminus: minus = true } node = node.next } return Value{} } // Rulevalue evaluates the value func (c *Calculator) Rulevalue(node *node32) Value { node = node.up for node != nil { switch node.pegRule { case rulematrix: return c.Rulematrix(node) case ruleimaginary: a := complex.NewRational(big.NewRat(1, 1), big.NewRat(0, 1)) node := node.up for node != nil { switch node.pegRule { case ruledecimal: a.A.SetString(strings.TrimSpace(string(c.buffer[node.begin:node.end]))) case rulenotation: b := complex.NewRational(big.NewRat(1, 1), big.NewRat(0, 1)) b.A.SetString(strings.TrimSpace(string(c.buffer[node.up.begin:node.up.end]))) c := complex.NewRational(big.NewRat(10, 1), big.NewRat(0, 1)) x := complex.NewFloat(big.NewFloat(0).SetPrec(prec), big.NewFloat(0).SetPrec(prec)) x.SetRat(c) y := complex.NewFloat(big.NewFloat(0).SetPrec(prec), big.NewFloat(0).SetPrec(prec)) y.SetRat(b) x.Pow(x, y).Rat(b) a.Mul(a, b) } node = node.next } a.A, a.B = a.B, a.A b := complex.NewMatrix(prec) b.Values = [][]complex.Rational{[]complex.Rational{*a}} return Value{ ValueType: ValueTypeMatrix, Matrix: &b, } case rulenumber: a := complex.NewRational(big.NewRat(1, 1), big.NewRat(0, 1)) node := node.up for node != nil { switch node.pegRule { case ruledecimal: a.A.SetString(strings.TrimSpace(string(c.buffer[node.begin:node.end]))) case rulenotation: b := complex.NewRational(big.NewRat(1, 1), big.NewRat(0, 1)) b.A.SetString(strings.TrimSpace(string(c.buffer[node.up.begin:node.up.end]))) c := complex.NewRational(big.NewRat(10, 1), big.NewRat(0, 1)) x := complex.NewFloat(big.NewFloat(0).SetPrec(prec), big.NewFloat(0).SetPrec(prec)) x.SetRat(c) y := complex.NewFloat(big.NewFloat(0).SetPrec(prec), big.NewFloat(0).SetPrec(prec)) y.SetRat(b) x.Pow(x, y).Rat(b) a.Mul(a, b) } node = node.next } b := complex.NewMatrix(prec) b.Values = [][]complex.Rational{[]complex.Rational{*a}} return Value{ ValueType: ValueTypeMatrix, Matrix: &b, } case ruleexp1: node := node.up for node != nil { if node.pegRule == rulee1 { a := c.Rulee1(node) a.Matrix.Exp(a.Matrix) return a } node = node.next } case ruleexp2: node := node.up for node != nil { if node.pegRule == rulevalue { a := c.Rulevalue(node) a.Matrix.Exp(a.Matrix) return a } node = node.next } case rulenatural: a := complex.NewRational(big.NewRat(1, 1), big.NewRat(0, 1)) b := complex.NewMatrix(prec) b.Values = [][]complex.Rational{[]complex.Rational{*a}} return Value{ ValueType: ValueTypeMatrix, Matrix: b.Exp(&b), } case rulepi: a := big.NewRat(1, 1) bigfloat.PI(prec).Rat(a) b := complex.NewRational(a, big.NewRat(0, 1)) c := complex.NewMatrix(prec) c.Values = [][]complex.Rational{[]complex.Rational{*b}} return Value{ ValueType: ValueTypeMatrix, Matrix: &c, } case ruleprec: node := node.up for node != nil { if node.pegRule == rulee1 { a := c.Rulee1(node) prec = uint(a.Matrix.Values[0][0].A.Num().Uint64()) return a } node = node.next } case rulesimplify: node := node.up for node != nil { if node.pegRule == rulee1 { return c.Rulesimplify(node) } node = node.next } case rulederivative: node := node.up for node != nil { if node.pegRule == rulee1 { return c.Rulederivative(node) } node = node.next } case rulelog: node := node.up for node != nil { if node.pegRule == rulee1 { a := c.Rulee1(node) a.Matrix.Log(a.Matrix) return a } node = node.next } case rulesqrt: node := node.up for node != nil { if node.pegRule == rulee1 { a := c.Rulee1(node) a.Matrix.Sqrt(a.Matrix) return a } node = node.next } case rulecos: node := node.up for node != nil { if node.pegRule == rulee1 { a := c.Rulee1(node) a.Matrix.Cos(a.Matrix) return a } node = node.next } case rulesin: node := node.up for node != nil { if node.pegRule == rulee1 { a := c.Rulee1(node) a.Matrix.Sin(a.Matrix) return a } node = node.next } case ruletan: node := node.up for node != nil { if node.pegRule == rulee1 { a := c.Rulee1(node) a.Matrix.Tan(a.Matrix) return a } node = node.next } case rulesub: return c.Rulesub(node) } node = node.next } return Value{} } // Rulematrix computes the matrix func (c *Calculator) Rulematrix(node *node32) Value { node = node.up x := complex.NewMatrix(prec) x.Values = make([][]complex.Rational, 1) for node != nil { switch node.pegRule { case rulee1: a, end := c.Rulee1(node), len(x.Values)-1 if len(a.Matrix.Values) == 1 && len(a.Matrix.Values[0]) == 1 { x.Values[end] = append(x.Values[end], a.Matrix.Values[0][0]) break } panic("matrix within matrix not allowed") case rulerow: x.Values = append(x.Values, make([]complex.Rational, 0, 8)) } node = node.next } return Value{ ValueType: ValueTypeMatrix, Matrix: &x, } } // Convert converts to an expression func (c *Calculator) Convert(node *node32) Value { var ( convert func(node *node32) (a *Node) convertValue func(node *node32) (a *Node) ) convertValue = func(node *node32) (a *Node) { node = node.up for node != nil { switch node.pegRule { case rulevalue: a = convertValue(node) case ruleminus: a = &Node{ Operation: OperationNegate, Left: convertValue(node), } case rulevariable: a = &Node{ Operation: OperationVariable, Value: strings.TrimSpace(string(c.buffer[node.begin:node.end])), } case ruleimaginary: node := node.up a = &Node{ Operation: OperationImaginary, } for node != nil { switch node.pegRule { case ruledecimal: a.Value = strings.TrimSpace(string(c.buffer[node.begin:node.end])) case rulenotation: a.Left = &Node{ Operation: OperationImaginary, Value: a.Value, } a.Operation = OperationNotation a.Value = "" a.Right = &Node{ Operation: OperationNumber, Value: strings.TrimSpace(string(c.buffer[node.up.begin:node.up.end])), } } node = node.next } return a case rulenumber: node := node.up a = &Node{ Operation: OperationNumber, } for node != nil { switch node.pegRule { case ruledecimal: a.Value = strings.TrimSpace(string(c.buffer[node.begin:node.end])) case rulenotation: a.Left = &Node{ Operation: OperationNumber, Value: a.Value, } a.Operation = OperationNotation a.Value = "" a.Right = &Node{ Operation: OperationNumber, Value: strings.TrimSpace(string(c.buffer[node.up.begin:node.up.end])), } } node = node.next } return a case ruleexp1: node := node.up for node != nil { if node.pegRule == rulee1 { a = &Node{ Operation: OperationNaturalExponentiation, Left: convert(node), } return a } node = node.next } case ruleexp2: node := node.up for node != nil { if node.pegRule == rulevalue { a = &Node{ Operation: OperationNaturalExponentiation, Left: convert(node), } return a } node = node.next } case rulenatural: a = &Node{ Operation: OperationNatural, } return a case rulepi: a = &Node{ Operation: OperationPI, } return a case rulelog: node := node.up for node != nil { if node.pegRule == rulee1 { a = &Node{ Operation: OperationNaturalLogarithm, Left: convert(node), } return a } node = node.next } case rulesqrt: node := node.up for node != nil { if node.pegRule == rulee1 { a = &Node{ Operation: OperationSquareRoot, Left: convert(node), } return a } node = node.next } case rulecos: node := node.up for node != nil { if node.pegRule == rulee1 { a = &Node{ Operation: OperationCosine, Left: convert(node), } return a } node = node.next } case rulesin: node := node.up for node != nil { if node.pegRule == rulee1 { a = &Node{ Operation: OperationSine, Left: convert(node), } return a } node = node.next } case ruletan: node := node.up for node != nil { if node.pegRule == rulee1 { a = &Node{ Operation: OperationTangent, Left: convert(node), } return a } node = node.next } case rulesub: node := node.up for node != nil { if node.pegRule == rulee1 { return convert(node) } node = node.next } } node = node.next } return a } convert = func(node *node32) (a *Node) { node = node.up for node != nil { switch node.pegRule { case rulee2, rulee3: a = convert(node) case ruleadd: node = node.next a = &Node{ Operation: OperationAdd, Left: a, Right: convert(node), } case ruleminus: node = node.next a = &Node{ Operation: OperationSubtract, Left: a, Right: convert(node), } case rulemultiply: node = node.next a = &Node{ Operation: OperationMultiply, Left: a, Right: convert(node), } case ruledivide: node = node.next a = &Node{ Operation: OperationDivide, Left: a, Right: convert(node), } case rulemodulus: node = node.next a = &Node{ Operation: OperationModulus, Left: a, Right: convert(node), } case rulee4: a = convertValue(node) case ruleexponentiation: node = node.next a = &Node{ Operation: OperationExponentiation, Left: a, Right: convertValue(node), } } node = node.next } return a } return Value{ ValueType: ValueTypeExpression, Expression: convert(node), } } // Rulesimplify simplifies the expression func (c *Calculator) Rulesimplify(node *node32) Value { expression := c.Convert(node).Expression if expression != nil { expression = expression.Simplify() } return Value{ ValueType: ValueTypeExpression, Expression: expression, } } // Rulederivative computes the symbolic derivative of a number func (c *Calculator) Rulederivative(node *node32) Value { expression := c.Convert(node).Expression derivative := expression.Derivative() if derivative != nil { derivative = derivative.Simplify() } return Value{ ValueType: ValueTypeExpression, Expression: derivative, } } // Rulesub computes the subexpression func (c *Calculator) Rulesub(node *node32) Value { node = node.up for node != nil { switch node.pegRule { case rulee1: return c.Rulee1(node) } node = node.next } return Value{} }
calculator.go
0.663233
0.554109
calculator.go
starcoder
package graphsample2 import "github.com/wangyoucao577/algorithms_practice/graph" /* This sample directed graph comes from "Introduction to Algorithms - Third Edition" 22.1 V = 6 (node count) E = 8 (edge count) define directed graph G(V,E) as below: u(0) -> v(1) w(2) ↓ ↗ ↓ ↙ ↓ x(3) <- y(4) z(5) -> ↑ ↓ <- NOTE: node `z` has a spin edge pointer to itself. */ const ( nodeCount = 6 directedGraph = true ) type nodeIDNameConverter struct { orderedNodesName []string nodeNameToIDMap map[string]graph.NodeID } // define fixed nodes order in the graph, then we use the `index` as nodeID for search, // will be easier to implement by code. // node name only for print. var nodeConverter = nodeIDNameConverter{ []string{"u", "v", "w", "x", "y", "z"}, map[string]graph.NodeID{}, // will be inited during import } // initialization during package import func init() { for i, v := range nodeConverter.orderedNodesName { nodeConverter.nodeNameToIDMap[v] = graph.NodeID(i) } } // IDToName convert NodeID to human readable name func IDToName(i graph.NodeID) string { if i == graph.InvalidNodeID { return "InvalidNodeID" } return nodeConverter.orderedNodesName[i] } // NameToID convert node human readable name to NodeID func NameToID(name string) graph.NodeID { return nodeConverter.nodeNameToIDMap[name] } // AdjacencyListGraphSample return the adjacency list based graph sample instance func AdjacencyListGraphSample() graph.Graph { sample := graph.NewAdjacencyListGraph(nodeCount, directedGraph) return initializeGraphEdges(sample) } // AdjacencyMatrixGraphSample return the adjacency matrix based graph sample instance func AdjacencyMatrixGraphSample() graph.Graph { sample := graph.NewAdjacencyMatrixGraph(nodeCount, directedGraph) return initializeGraphEdges(sample) } func initializeGraphEdges(g graph.Graph) graph.Graph { g.AddEdge(0, 1) g.AddEdge(0, 3) g.AddEdge(1, 4) g.AddEdge(2, 4) g.AddEdge(2, 5) g.AddEdge(3, 1) g.AddEdge(4, 3) g.AddEdge(5, 5) return g }
graphsamples/graphsample2/sample2.go
0.729231
0.465752
sample2.go
starcoder
package ckks import ( "fmt" "math" "math/cmplx" "github.com/ldsec/lattigo/v2/ckks/bettersine" "github.com/ldsec/lattigo/v2/rlwe" "github.com/ldsec/lattigo/v2/utils" ) // Bootstrapper is a struct to stores a memory pool the plaintext matrices // the polynomial approximation and the keys for the bootstrapping. type Bootstrapper struct { *evaluator BootstrappingParameters *BootstrappingKey params Parameters dslots int // Number of plaintext slots after the re-encoding logdslots int encoder Encoder // Encoder prescale float64 // Q[0]/(Q[0]/|m|) postscale float64 // Qi sineeval/(Q[0]/|m|) sinescale float64 // Qi sineeval sqrt2pi float64 // (1/2pi)^{-2^r} scFac float64 // 2^{r} sineEvalPoly *ChebyshevInterpolation // Coefficients of the Chebyshev Interpolation of sin(2*pi*x) or cos(2*pi*x/r) arcSinePoly *Poly // Coefficients of the Taylor series of arcsine(x) coeffsToSlotsDiffScale complex128 // Matrice rescaling slotsToCoeffsDiffScale complex128 // Matrice rescaling pDFT []*PtDiagMatrix // Matrice vectors pDFTInv []*PtDiagMatrix // Matrice vectors rotKeyIndex []int // a list of the required rotation keys } func sin2pi2pi(x complex128) complex128 { return cmplx.Sin(6.283185307179586*x) / 6.283185307179586 } func cos2pi(x complex128) complex128 { return cmplx.Cos(6.283185307179586 * x) } // NewBootstrapper creates a new Bootstrapper. func NewBootstrapper(params Parameters, btpParams *BootstrappingParameters, btpKey BootstrappingKey) (btp *Bootstrapper, err error) { if btpParams.SinType == SinType(Sin) && btpParams.SinRescal != 0 { return nil, fmt.Errorf("cannot use double angle formul for SinType = Sin -> must use SinType = Cos") } btp = newBootstrapper(params, btpParams) btp.BootstrappingKey = &BootstrappingKey{btpKey.Rlk, btpKey.Rtks} if err = btp.CheckKeys(); err != nil { return nil, fmt.Errorf("invalid bootstrapping key: %w", err) } btp.evaluator = btp.evaluator.WithKey(rlwe.EvaluationKey{Rlk: btpKey.Rlk, Rtks: btpKey.Rtks}).(*evaluator) return btp, nil } // newBootstrapper is a constructor of "dummy" bootstrapper to enable the generation of bootstrapping-related constants // without providing a bootstrapping key. To be replaced by a proper factorization of the bootstrapping pre-computations. func newBootstrapper(params Parameters, btpParams *BootstrappingParameters) (btp *Bootstrapper) { btp = new(Bootstrapper) btp.params = params btp.BootstrappingParameters = *btpParams.Copy() btp.dslots = params.Slots() btp.logdslots = params.LogSlots() if params.LogSlots() < params.MaxLogSlots() { btp.dslots <<= 1 btp.logdslots++ } btp.prescale = math.Exp2(math.Round(math.Log2(float64(params.Q()[0]) / btp.MessageRatio))) btp.sinescale = math.Exp2(math.Round(math.Log2(btp.SineEvalModuli.ScalingFactor))) btp.postscale = btp.sinescale / btp.MessageRatio btp.encoder = NewEncoder(params) btp.evaluator = NewEvaluator(params, rlwe.EvaluationKey{}).(*evaluator) // creates an evaluator without keys for genDFTMatrices btp.genSinePoly() btp.genDFTMatrices() btp.ctxpool = NewCiphertext(params, 1, params.MaxLevel(), 0) return btp } // CheckKeys checks if all the necessary keys are present func (btp *Bootstrapper) CheckKeys() (err error) { if btp.Rlk == nil { return fmt.Errorf("relinearization key is nil") } if btp.Rtks == nil { return fmt.Errorf("rotation key is nil") } rotMissing := []int{} for _, i := range btp.rotKeyIndex { galEl := btp.params.GaloisElementForColumnRotationBy(int(i)) if _, generated := btp.Rtks.Keys[galEl]; !generated { rotMissing = append(rotMissing, i) } } if len(rotMissing) != 0 { return fmt.Errorf("rotation key(s) missing: %d", rotMissing) } return nil } // AddMatrixRotToList adds the rotations neede to evaluate pVec to the list rotations func AddMatrixRotToList(pVec *PtDiagMatrix, rotations []int, slots int, repack bool) []int { if pVec.naive { for j := range pVec.Vec { if !utils.IsInSliceInt(j, rotations) { rotations = append(rotations, j) } } } else { var index int for j := range pVec.Vec { N1 := pVec.N1 index = ((j / N1) * N1) if repack { // Sparse repacking, occurring during the first DFT matrix of the CoeffsToSlots. index &= 2*slots - 1 } else { // Other cases index &= slots - 1 } if index != 0 && !utils.IsInSliceInt(index, rotations) { rotations = append(rotations, index) } index = j & (N1 - 1) if index != 0 && !utils.IsInSliceInt(index, rotations) { rotations = append(rotations, index) } } } return rotations } func (btp *Bootstrapper) genDFTMatrices() { a := real(btp.sineEvalPoly.a) b := real(btp.sineEvalPoly.b) n := float64(btp.params.N()) qDiff := float64(btp.params.Q()[0]) / math.Exp2(math.Round(math.Log2(float64(btp.params.Q()[0])))) // Change of variable for the evaluation of the Chebyshev polynomial + cancelling factor for the DFT and SubSum + evantual scaling factor for the double angle formula btp.coeffsToSlotsDiffScale = complex(math.Pow(2.0/((b-a)*n*btp.scFac*qDiff), 1.0/float64(btp.CtSDepth(false))), 0) // Rescaling factor to set the final ciphertext to the desired scale btp.slotsToCoeffsDiffScale = complex(math.Pow((qDiff*btp.params.Scale())/btp.postscale, 1.0/float64(btp.StCDepth(false))), 0) // CoeffsToSlots vectors btp.pDFTInv = btp.BootstrappingParameters.GenCoeffsToSlotsMatrix(btp.coeffsToSlotsDiffScale, btp.encoder) // SlotsToCoeffs vectors btp.pDFT = btp.BootstrappingParameters.GenSlotsToCoeffsMatrix(btp.slotsToCoeffsDiffScale, btp.encoder) // List of the rotation key values to needed for the bootstrapp btp.rotKeyIndex = []int{} //SubSum rotation needed X -> Y^slots rotations for i := btp.params.LogSlots(); i < btp.params.MaxLogSlots(); i++ { if !utils.IsInSliceInt(1<<i, btp.rotKeyIndex) { btp.rotKeyIndex = append(btp.rotKeyIndex, 1<<i) } } // Coeffs to Slots rotations for _, pVec := range btp.pDFTInv { btp.rotKeyIndex = AddMatrixRotToList(pVec, btp.rotKeyIndex, btp.params.Slots(), false) } // Slots to Coeffs rotations for i, pVec := range btp.pDFT { btp.rotKeyIndex = AddMatrixRotToList(pVec, btp.rotKeyIndex, btp.params.Slots(), (i == 0) && (btp.params.LogSlots() < btp.params.MaxLogSlots())) } } func (btp *Bootstrapper) genSinePoly() { K := int(btp.SinRange) deg := int(btp.SinDeg) btp.scFac = float64(int(1 << btp.SinRescal)) if btp.ArcSineDeg > 0 { btp.sqrt2pi = 1.0 coeffs := make([]complex128, btp.ArcSineDeg+1) coeffs[1] = 0.15915494309189535 for i := 3; i < btp.ArcSineDeg+1; i += 2 { coeffs[i] = coeffs[i-2] * complex(float64(i*i-4*i+4)/float64(i*i-i), 0) } btp.arcSinePoly = NewPoly(coeffs) } else { btp.sqrt2pi = math.Pow(0.15915494309189535, 1.0/btp.scFac) } if btp.SinType == Sin { btp.sineEvalPoly = Approximate(sin2pi2pi, -complex(float64(K)/btp.scFac, 0), complex(float64(K)/btp.scFac, 0), deg) } else if btp.SinType == Cos1 { btp.sineEvalPoly = new(ChebyshevInterpolation) btp.sineEvalPoly.coeffs = bettersine.Approximate(K, deg, btp.MessageRatio, int(btp.SinRescal)) btp.sineEvalPoly.maxDeg = btp.sineEvalPoly.Degree() btp.sineEvalPoly.a = complex(float64(-K)/btp.scFac, 0) btp.sineEvalPoly.b = complex(float64(K)/btp.scFac, 0) btp.sineEvalPoly.lead = true } else if btp.SinType == Cos2 { btp.sineEvalPoly = Approximate(cos2pi, -complex(float64(K)/btp.scFac, 0), complex(float64(K)/btp.scFac, 0), deg) } else { panic("Bootstrapper -> invalid sineType") } for i := range btp.sineEvalPoly.coeffs { btp.sineEvalPoly.coeffs[i] *= complex(btp.sqrt2pi, 0) } }
ckks/bootstrapper.go
0.70912
0.438064
bootstrapper.go
starcoder
package imageflux import ( "crypto/hmac" "crypto/sha256" "encoding/base64" "fmt" "image" "image/color" "net/url" "strconv" "strings" "sync" ) var bufPool = sync.Pool{ New: func() interface{} { buf := make([]byte, 0, 32) return &buf }, } // Image is an image hosted on ImageFlux. type Image struct { Path string Proxy *Proxy Config *Config } // Config is configure of image. type Config struct { // Width is width in pixel of the scaled image. Width int // Height is height in pixel of the scaled image. Height int // DisableEnlarge disables enlarge. DisableEnlarge bool // AspectMode is aspect mode. AspectMode AspectMode // Clip is a position in pixel of clipping area. Clip image.Rectangle // ClipRatio is a position in ratio of clipping area. // The coordinates of the rectangle are divided by ClipMax.X or ClipMax.Y. ClipRatio image.Rectangle // ClipMax is the denominators of ClipRatio. ClipMax image.Point // Origin is the position of the image origin. Origin Origin // Background is background color. Background color.Color // Rotate rotates the image. Rotate Rotate Through Through // Overlay Parameters. Overlays []Overlay // Output Parameters. Format Format Quality int DisableOptimization bool Unsharp Unsharp Blur Blur } // Overlay is the configure of an overlay image. type Overlay struct { // URL is an url for overlay image. URL string // Width is width in pixel of the scaled image. Width int // Height is height in pixel of the scaled image. Height int // DisableEnlarge disables enlarge. DisableEnlarge bool // AspectMode is aspect mode. AspectMode AspectMode // Clip is a position in pixel of clipping area. Clip image.Rectangle // ClipRatio is a position in ratio of clipping area. // The coordinates of the rectangle are divided by ClipMax.X or ClipMax.Y. ClipRatio image.Rectangle // ClipMax is the denominators of ClipRatio. ClipMax image.Point // Origin is the position of the image origin. Origin Origin // Background is background color. Background color.Color // Rotate rotates the image. Rotate Rotate // Offset is an offset in pixel of overlay image. Offset image.Point // OffsetRatio is an offset in ratio of overlay image. // The coordinates of the rectangle are divided by OffsetMax.X or OffsetMax.Y. OffsetRatio image.Point // OffsetMax is the denominators of OffsetRatio. OffsetMax image.Point // OverlayOrigin is the postion of the overlay image origin. OverlayOrigin Origin } // Unsharp is an unsharp filter config. type Unsharp struct { Radius int Sigma float64 Gain float64 Threshold float64 } func (u Unsharp) append(buf []byte) []byte { buf = strconv.AppendInt(buf, int64(u.Radius), 10) buf = append(buf, 'x') buf = strconv.AppendFloat(buf, u.Sigma, 'f', -1, 64) if u.Gain != 0 && u.Threshold != 0 { buf = append(buf, '+') buf = strconv.AppendFloat(buf, u.Gain, 'f', -1, 64) buf = append(buf, '+') buf = strconv.AppendFloat(buf, u.Threshold, 'f', -1, 64) } return buf } // Blur is a blur config. type Blur struct { Radius int Sigma float64 } func (b Blur) append(buf []byte) []byte { buf = strconv.AppendInt(buf, int64(b.Radius), 10) buf = append(buf, 'x') buf = strconv.AppendFloat(buf, b.Sigma, 'f', -1, 64) return buf } // AspectMode is aspect mode. type AspectMode int const ( // AspectModeDefault is the default value of aspect mode. AspectModeDefault AspectMode = iota // AspectModeScale holds the the aspect ratio of the input image, // and scales to fit in the specified size. AspectModeScale // AspectModeForceScale ignores the aspect ratio of the input image. AspectModeForceScale // AspectModeCrop holds the the aspect ratio of the input image, // and crops the image. AspectModeCrop // AspectModePad holds the the aspect ratio of the input image, // and fills the unfilled portion with the specified background color. AspectModePad ) // Origin is the origin. type Origin int const ( // OriginDefault is default origin. OriginDefault Origin = iota // OriginTopLeft is top-left OriginTopLeft // OriginTopCenter is top-center OriginTopCenter // OriginTopRight is top-right OriginTopRight // OriginMiddleLeft is middle-left OriginMiddleLeft // OriginMiddleCenter is middle-center OriginMiddleCenter // OriginMiddleRight is middle-right OriginMiddleRight // OriginBottomLeft is bottom-left OriginBottomLeft // OriginBottomCenter is bottom-center OriginBottomCenter // OriginBottomRight is bottom-right OriginBottomRight ) func (o Origin) String() string { switch o { case OriginDefault: return "default" case OriginTopLeft: return "top-left" case OriginTopCenter: return "top-center" case OriginTopRight: return "top-right" case OriginMiddleLeft: return "middle-left" case OriginMiddleCenter: return "middle-center" case OriginMiddleRight: return "middle-right" case OriginBottomLeft: return "bottom-left" case OriginBottomCenter: return "bottom-center" case OriginBottomRight: return "bottom-right" } return "" } // Format is the format of the output image. type Format string const ( // FormatAuto encodes the image by the same format with the input image. FormatAuto Format = "auto" // FormatJPEG encodes the image as a JPEG. FormatJPEG Format = "jpg" // FormatPNG encodes the image as a PNG. FormatPNG Format = "png" // FormatGIF encodes the image as a GIF. FormatGIF Format = "gif" // FormatWebPFromJPEG encodes the image as a WebP. // The input image should be a JPEG. FormatWebPFromJPEG Format = "webp:jpeg" // FormatWebPFromPNG encodes the image as a WebP. // The input image should be a PNG. FormatWebPFromPNG Format = "webp:png" ) func (f Format) String() string { return string(f) } // Rotate rotates the image. type Rotate int const ( // RotateDefault is the default value of Rotate. It is same as RotateTopLeft. RotateDefault Rotate = iota // RotateTopLeft does not anything. RotateTopLeft // RotateTopRight flips the image left and right. RotateTopRight // RotateBottomRight rotates the image 180 degrees. RotateBottomRight // RotateBottomLeft flips the image upside down. RotateBottomLeft // RotateLeftTop mirrors the image around the diagonal axis. RotateLeftTop // RotateRightTop rotates the image left 90 degrees. RotateRightTop // RotateRightBottom rotates the image 180 degrees and mirrors the image around the diagonal axis. RotateRightBottom // RotateLeftBottom rotates the image right 90 degrees. RotateLeftBottom // RotateAuto parses the Orientation of the Exif information and rotates the image. RotateAuto Rotate = -1 ) func (r Rotate) String() string { switch r { case RotateDefault: return "default" case RotateTopLeft: return "top-left" case RotateTopRight: return "top-right" case RotateBottomRight: return "bottom-right" case RotateBottomLeft: return "bottom-left" case RotateLeftTop: return "left-top" case RotateRightTop: return "right-top" case RotateRightBottom: return "right-bottom" case RotateLeftBottom: return "left-bottom" case RotateAuto: return "auto" } return "" } // Through is an image format list for skipping converting. type Through int const ( // ThroughJPEG skips converting JPEG images. ThroughJPEG Through = 1 << iota // ThroughPNG skips converting PNG images. ThroughPNG // ThroughGIF skips converting GIF images. ThroughGIF ) func (t Through) String() string { var buf [12]byte return string(t.append(buf[:])) } func (t Through) append(buf []byte) []byte { if t == 0 { return buf } if (t & ThroughJPEG) != 0 { buf = append(buf, "jpg:"...) } if (t & ThroughPNG) != 0 { buf = append(buf, "png:"...) } if (t & ThroughGIF) != 0 { buf = append(buf, "gif:"...) } return buf[:len(buf)-1] } func (c *Config) String() string { if c == nil { return "" } buf := bufPool.Get().(*[]byte) *buf = c.append((*buf)[:0]) str := string(*buf) bufPool.Put(buf) return str } func (c *Config) append(buf []byte) []byte { var zr image.Rectangle var zp image.Point if c == nil { return buf } l := len(buf) if c.Width != 0 { buf = append(buf, 'w', '=') buf = strconv.AppendInt(buf, int64(c.Width), 10) buf = append(buf, ',') } if c.Height != 0 { buf = append(buf, 'h', '=') buf = strconv.AppendInt(buf, int64(c.Height), 10) buf = append(buf, ',') } if c.DisableEnlarge { buf = append(buf, 'u', '=', '0', ',') } if c.AspectMode != AspectModeDefault { buf = append(buf, 'a', '=') buf = strconv.AppendInt(buf, int64(c.AspectMode-1), 10) buf = append(buf, ',') } if c.Clip != zr { buf = append(buf, 'c', '=') buf = strconv.AppendInt(buf, int64(c.Clip.Min.X), 10) buf = append(buf, ':') buf = strconv.AppendInt(buf, int64(c.Clip.Min.Y), 10) buf = append(buf, ':') buf = strconv.AppendInt(buf, int64(c.Clip.Max.X), 10) buf = append(buf, ':') buf = strconv.AppendInt(buf, int64(c.Clip.Max.Y), 10) buf = append(buf, ',') } if c.ClipRatio != zr && c.ClipMax != zp { x1 := float64(c.ClipRatio.Min.X) / float64(c.ClipMax.X) y1 := float64(c.ClipRatio.Min.Y) / float64(c.ClipMax.Y) x2 := float64(c.ClipRatio.Max.X) / float64(c.ClipMax.X) y2 := float64(c.ClipRatio.Max.Y) / float64(c.ClipMax.Y) buf = append(buf, 'c', 'r', '=') buf = strconv.AppendFloat(buf, x1, 'f', -1, 64) buf = append(buf, ':') buf = strconv.AppendFloat(buf, y1, 'f', -1, 64) buf = append(buf, ':') buf = strconv.AppendFloat(buf, x2, 'f', -1, 64) buf = append(buf, ':') buf = strconv.AppendFloat(buf, y2, 'f', -1, 64) buf = append(buf, ',') } if c.Origin != OriginDefault { buf = append(buf, 'g', '=') buf = strconv.AppendInt(buf, int64(c.Origin), 10) buf = append(buf, ',') } if c.Background != nil { r, g, b, a := c.Background.RGBA() if a == 0xffff { buf = append(buf, 'b', '=') buf = appendByte(buf, byte(r>>8)) buf = appendByte(buf, byte(g>>8)) buf = appendByte(buf, byte(b>>8)) buf = append(buf, ',') } else if a == 0 { buf = append(buf, "b=000000,"...) } else { c := fmt.Sprintf("b=%02x%02x%02x%02x,", r>>8, g>>8, b>>8, a>>8) buf = append(buf, c...) } } if c.Rotate != RotateDefault { if c.Rotate == RotateAuto { buf = append(buf, "r=auto,"...) } else { buf = append(buf, "r="...) buf = strconv.AppendInt(buf, int64(c.Rotate), 10) buf = append(buf, ',') } } if c.Through != 0 { buf = append(buf, "through="...) buf = c.Through.append(buf) buf = append(buf, ',') } if len(c.Overlays) > 0 { for _, overlay := range c.Overlays { buf = append(buf, 'l', '=', '(') buf = overlay.append(buf) buf = append(buf, ',') buf = append(buf[:len(buf)-1], ')', ',') } } if c.Format != "" { buf = append(buf, 'f', '=') buf = append(buf, c.Format...) buf = append(buf, ',') } if c.Quality != 0 { buf = append(buf, 'q', '=') buf = strconv.AppendInt(buf, int64(c.Quality), 10) buf = append(buf, ',') } if c.DisableOptimization { buf = append(buf, 'o', '=', '0', ',') } if c.Unsharp.Radius != 0 { buf = append(buf, "unsharp="...) buf = c.Unsharp.append(buf) buf = append(buf, ',') } if c.Blur.Radius != 0 { buf = append(buf, "blur="...) buf = c.Blur.append(buf) buf = append(buf, ',') } if len(buf) != l { buf = buf[:len(buf)-1] } return buf } func appendByte(buf []byte, b byte) []byte { const digits = "0123456789abcdef" return append(buf, digits[b>>4], digits[b&0x0F]) } func (a AspectMode) String() string { switch a { case AspectModeDefault: return "default" case AspectModeScale: return "scale" case AspectModeForceScale: return "force-scale" case AspectModePad: return "pad" } return "" } // SignedURL returns the URL of the image with the signature. func (img *Image) SignedURL() string { path, s := img.pathAndSign() if s == "" { return "https://" + img.Proxy.Host + path } if strings.HasPrefix(path, "/c/") { return "https://" + img.Proxy.Host + "/c/sig=" + s + "," + strings.TrimPrefix(path, "/c/") } return "https://" + img.Proxy.Host + "/c/sig=" + s + path } // Sign returns the signature. func (img *Image) Sign() string { _, s := img.pathAndSign() return s } func (img *Image) pathAndSign() (string, string) { pbuf := bufPool.Get().(*[]byte) buf := (*pbuf)[:0] buf = append(buf, "/c/"...) buf = img.Config.append(buf) if len(buf) == len("/c/") { buf = buf[:0] } if len(img.Path) == 0 || img.Path[0] != '/' { buf = append(buf, '/') } buf = append(buf, img.Path...) path := string(buf) if img.Proxy.Secret == "" { *pbuf = buf bufPool.Put(pbuf) return path, "" } mac := hmac.New(sha256.New, []byte(img.Proxy.Secret)) mac.Write(buf) buf = mac.Sum(buf[:0]) buf2 := make([]byte, len("1.")+base64.URLEncoding.EncodedLen(len(buf))) buf2[0] = '1' buf2[1] = '.' base64.URLEncoding.Encode(buf2[2:], buf) *pbuf = buf bufPool.Put(pbuf) return path, string(buf2[:]) } func (img *Image) String() string { pbuf := bufPool.Get().(*[]byte) buf := (*pbuf)[:0] buf = append(buf, "https://"...) buf = append(buf, img.Proxy.Host...) buf = append(buf, "/c/"...) buf = img.Config.append(buf) if len(img.Path) == 0 || img.Path[0] != '/' { buf = append(buf, '/') } buf = append(buf, img.Path...) str := string(buf) *pbuf = buf bufPool.Put(pbuf) return str } func (o Overlay) String() string { return string(o.append([]byte{})) } func (o Overlay) append(buf []byte) []byte { var zr image.Rectangle var zp image.Point l := len(buf) if o.Width != 0 { buf = append(buf, 'w', '=') buf = strconv.AppendInt(buf, int64(o.Width), 10) buf = append(buf, ',') } if o.Height != 0 { buf = append(buf, 'h', '=') buf = strconv.AppendInt(buf, int64(o.Height), 10) buf = append(buf, ',') } if o.DisableEnlarge { buf = append(buf, 'u', '=', '0', ',') } if o.AspectMode != AspectModeDefault { buf = append(buf, 'a', '=') buf = strconv.AppendInt(buf, int64(o.AspectMode-1), 10) buf = append(buf, ',') } if o.Clip != zr { buf = append(buf, 'c', '=') buf = strconv.AppendInt(buf, int64(o.Clip.Min.X), 10) buf = append(buf, ':') buf = strconv.AppendInt(buf, int64(o.Clip.Min.Y), 10) buf = append(buf, ':') buf = strconv.AppendInt(buf, int64(o.Clip.Max.X), 10) buf = append(buf, ':') buf = strconv.AppendInt(buf, int64(o.Clip.Max.Y), 10) buf = append(buf, ',') } if o.ClipRatio != zr && o.ClipMax != zp { x1 := float64(o.ClipRatio.Min.X) / float64(o.ClipMax.X) y1 := float64(o.ClipRatio.Min.Y) / float64(o.ClipMax.Y) x2 := float64(o.ClipRatio.Max.X) / float64(o.ClipMax.X) y2 := float64(o.ClipRatio.Max.Y) / float64(o.ClipMax.Y) buf = append(buf, 'c', 'r', '=') buf = strconv.AppendFloat(buf, x1, 'f', -1, 64) buf = append(buf, ':') buf = strconv.AppendFloat(buf, y1, 'f', -1, 64) buf = append(buf, ':') buf = strconv.AppendFloat(buf, x2, 'f', -1, 64) buf = append(buf, ':') buf = strconv.AppendFloat(buf, y2, 'f', -1, 64) buf = append(buf, ',') } if o.Origin != OriginDefault { buf = append(buf, 'g', '=') buf = strconv.AppendInt(buf, int64(o.Origin), 10) buf = append(buf, ',') } if o.Background != nil { r, g, b, a := o.Background.RGBA() if a == 0xffff { buf = append(buf, 'b', '=') buf = appendByte(buf, byte(r>>8)) buf = appendByte(buf, byte(g>>8)) buf = appendByte(buf, byte(b>>8)) buf = append(buf, ',') } else if a == 0 { buf = append(buf, "b=000000,"...) } else { c := fmt.Sprintf("b=%02x%02x%02x%02x,", r>>8, g>>8, b>>8, a>>8) buf = append(buf, c...) } } if o.Rotate != RotateDefault { if o.Rotate == RotateAuto { buf = append(buf, "r=auto,"...) } else { buf = append(buf, "r="...) buf = strconv.AppendInt(buf, int64(o.Rotate), 10) buf = append(buf, ',') } } if o.Offset != zp { buf = append(buf, 'x', '=') buf = strconv.AppendInt(buf, int64(o.Offset.X), 10) buf = append(buf, ',', 'y', '=') buf = strconv.AppendInt(buf, int64(o.Offset.Y), 10) buf = append(buf, ',') } if o.OffsetRatio != zp && o.OffsetMax != zp { x := float64(o.OffsetRatio.X) / float64(o.OffsetMax.X) y := float64(o.OffsetRatio.Y) / float64(o.OffsetMax.Y) buf = append(buf, 'x', 'r', '=') buf = strconv.AppendFloat(buf, x, 'f', -1, 64) buf = append(buf, ',', 'y', 'r', '=') buf = strconv.AppendFloat(buf, y, 'f', -1, 64) buf = append(buf, ',') } if o.OverlayOrigin != OriginDefault { buf = append(buf, 'l', 'g', '=') buf = strconv.AppendInt(buf, int64(o.OverlayOrigin), 10) buf = append(buf, ',') } if len(buf) > l && buf[len(buf)-1] == ',' { buf = buf[:len(buf)-1] } buf = append(buf, "%2f"...) buf = append(buf, url.QueryEscape(o.URL)...) return buf }
image.go
0.762866
0.45744
image.go
starcoder
package spn import ( "crypto/rand" "github.com/OpenWhiteBox/primitives/encoding" "github.com/OpenWhiteBox/primitives/gfmatrix" "github.com/OpenWhiteBox/primitives/number" ) // incrementalMatrices implements succint operations over a slice of incremental matrices. type incrementalMatrices []gfmatrix.IncrementalMatrix // NewIncrementalMatrices returns a new slice of x n-by-n incremental matrices. func newIncrementalMatrices(x, n int) (ims incrementalMatrices) { ims = make([]gfmatrix.IncrementalMatrix, x) for i, _ := range ims { ims[i] = gfmatrix.NewIncrementalMatrix(n) } return } // SufficientlyDefined returns true if every incremental matrix is sufficiently defined. The must all have a // 9-dimensional nullspace or smallter. This way, it is small enough to search, but not so small that we have nowhere to // look for solutions. func (ims incrementalMatrices) SufficientlyDefined() bool { for _, im := range ims { if im.Len() < 247 { return false } } return true } // Matrices returns a slice of matrices, one for each incremental matrix. func (ims incrementalMatrices) Matrices() (out []gfmatrix.Matrix) { out = make([]gfmatrix.Matrix, len(ims)) for i, im := range ims { out[i] = im.Matrix() } return out } // randomLinearCombination returns a random linear combination of a set of basis vectors. func randomLinearCombination(basis []gfmatrix.Row) gfmatrix.Row { coeffs := make([]byte, len(basis)) rand.Read(coeffs) v := gfmatrix.NewRow(basis[0].Size()) for i, c_i := range coeffs { v = v.Add(basis[i].ScalarMul(number.ByteFieldElem(c_i))) } return v } // findPermutation takes a set of vectors and finds a linear combination of them that gives a permutation vector. func findPermutation(basis []gfmatrix.Row) gfmatrix.Row { for true { v := randomLinearCombination(basis) if v[:256].IsPermutation() { return v } } return nil } // newSBox takes a permutation vector as input and returns its corresponding S-Box. It inverts the S-Box if backwards is // true (because the permutation vector we found was for the inverse S-box). func newSBox(v gfmatrix.Row, backwards bool) (out encoding.SBox) { for i, v_i := range v[0:256] { out.EncKey[i] = byte(v_i) } for i, j := range out.EncKey { out.DecKey[j] = byte(i) } if backwards { // Reverse EncKey and DecKey if we recover S^-1 out.EncKey, out.DecKey = out.DecKey, out.EncKey } return } // RecoverSBoxes implements a specific variant of the Cube attack to remove the trailing S-box layer of the given // cipher. It uses the plaintexts generated by generator. func RecoverSBoxes(cipher encoding.Block, generator func() [][16]byte) (last encoding.ConcatenatedBlock, rest encoding.Block) { ims := newIncrementalMatrices(16, 256) for attempt := 0; attempt < 2000 && !ims.SufficientlyDefined(); attempt++ { pts := generator() cts := make([][16]byte, len(pts)) for i, pt := range pts { cts[i] = cipher.Encode(pt) } for pos := 0; pos < 16; pos++ { row := gfmatrix.NewRow(256) for _, ct := range cts { row[ct[pos]] = row[ct[pos]].Add(0x01) } ims[pos].Add(row) } } if !ims.SufficientlyDefined() { panic("Cube attack failed to find enough linear relations in the S-boxes.") } for pos, m := range ims.Matrices() { last[pos] = newSBox(findPermutation(m.NullSpace()), true) } return last, encoding.ComposedBlocks{cipher, encoding.InverseBlock{last}} }
cryptanalysis/spn/sbox.go
0.849893
0.432243
sbox.go
starcoder
package golem import ( "math" "math/rand" ) func MinAndMaxKeyOfBayesProbMap(bpm map[float64]map[string]float64) (float64,float64) { mini,maxi := math.Inf(1), math.Inf(-1) for k,_ := range bpm { if k < mini { mini = k } if k > maxi { maxi = k } } return mini, maxi } /* */ func SampleSubrangesForRange(targetRange *Pair, subRange *Pair, numberOfSubranges int, output []*Pair, ratio int, initial bool) []*Pair { if len(output) >= numberOfSubranges { return output } switch { case initial: for i := 0; i < ratio; i++ { sz := (targetRange.b.(float64) - targetRange.a.(float64)) / float64(ratio) p := ChooseValidRangeGivenSize(targetRange, sz) output = append(output, p) } nextChoice := RandomIntS(0,ratio) return SampleSubrangesForRange(targetRange, output[nextChoice], numberOfSubranges, output, ratio, false) default: // left of partition stl := subRange.a.(float64) - targetRange.a.(float64) sz := stl / float64(ratio) p := &Pair{a: subRange.a.(float64) - sz, b: subRange.a.(float64)} output = append(output,p) nextChoice := p p2 := &Pair{a: subRange.a.(float64) -sz, b: subRange.b.(float64)} output = append(output,p2) if rand.Float32() < 0.5 { nextChoice = p2 } // right of partition stl = targetRange.b.(float64) - subRange.b.(float64) sz = stl / float64(ratio) p3 := &Pair{a: subRange.b.(float64), b: subRange.b.(float64) + sz} output = append(output,p3) if rand.Float32() < 0.5 { nextChoice = p3 } p4 := &Pair{a: subRange.a.(float64), b: subRange.b.(float64) + sz} output = append(output,p4) if rand.Float32() < 0.5 { nextChoice = p4 } return SampleSubrangesForRange(targetRange, nextChoice, numberOfSubranges, output, ratio, false) } return output } // CAUTION: does not perform error-checking func ChooseValidRangeGivenSize(newRange *Pair, size float64) *Pair { for { start := RandomFloat64(newRange.a.(float64), newRange.b.(float64)) if start + size <= newRange.b.(float64) { return &Pair{a: start, b: start + size} } } }
golem/golem_base/bayes_prob_extensions.go
0.587825
0.406862
bayes_prob_extensions.go
starcoder
package listx type IList interface { // Len is the number of elements in the collection. Len() int // Swap swaps the elements with indexes i and j. Swap(i, j int) // Removes all of the elements from this list (optional operation). Clear() // Appends the elements to the end of this list (optional operation). Add(ele ...interface{}) (suc bool) // Inserts the specified elements at the specified position in this list (optional operation). AddAt(index int, ele ...interface{}) (suc bool) // Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation) AddAll(index int, list IList) (suc bool) // Removes the element at the specified position in this list (optional operation). RemoveAt(index int) (ele interface{}, suc bool) // Removes some elements at the specified position in this list (optional operation). RemoveMultiAt(index int, amount int) (ele []interface{}, suc bool) // Removes the last element at from this list (optional operation). RemoveLast() (ele interface{}, suc bool) // Removes some elements from this list started at the last position. RemoveLastMulti(amount int) (ele []interface{}, suc bool) // Removes the first element at from this list (optional operation). RemoveFirst() (ele interface{}, suc bool) // Removes some elements from this list started at the first position. RemoveFirstMulti(amount int) (ele []interface{}, suc bool) // Returns the element at the specified position in this list. Get(index int) (ele interface{}, ok bool) // Returns some elements in this list started at the specified position. GetMulti(index int, amount int) (ele []interface{}, ok bool) // Returns some elements in this list started at the specified position. GetMultiLast(lastIndex int, amount int) (ele []interface{}, ok bool) // Returns all elements in this list. GetAll() []interface{} // Returns the first element of this list. First() (ele interface{}, ok bool) // Returns some elements in this list started at the first position. FirstMulti(amount int) (ele []interface{}, ok bool) // Returns the last element of this list. Last() (ele interface{}, ok bool) // Returns some elements in this list started at the last position. LastMulti(amount int) (ele []interface{}, ok bool) // Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. IndexOf(ele interface{}) (index int, ok bool) // Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. LastIndexOf(ele interface{}) (index int, ok bool) // Returns true if this list contains the specified element. Contains(ele interface{}) (contains bool) // Performs the given action for each element of the list ForEach(each func(index int, ele interface{}) (stop bool)) // Performs the given action for each element of the list ForEachLast(each func(index int, ele interface{}) (stop bool)) }
lang/listx/list.go
0.534127
0.422266
list.go
starcoder
package graphic import "github.com/go-gl/gl/v2.1/gl" // SGNode scenegraph node type SGNode interface { update(delta float64) render() findChilds(search interface{}) []interface{} addChild(child *SGNode) } // SceneGraph helper struct type SceneGraph struct { } // Scene helper struct type Scene struct { } // NewScene helper struct func NewScene() *Scene { s := &Scene{} return s } var dd float32 // Update updates the scene with delta time func (s *Scene) Update(dt float64) { gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) gl.MatrixMode(gl.MODELVIEW) gl.LoadIdentity() gl.Translatef(0, 0, -3.0) gl.Rotatef(dd, 1, 0, 0) gl.Rotatef(dd, 0, 1, 0) dd += float32(dt) * 10 //rotationX += 0.5 //rotationY += 0.5 //gl.BindTexture(gl.TEXTURE_2D, texture) gl.Color4f(1, 1, 1, 1) gl.Begin(gl.QUADS) gl.Normal3f(0, 0, 1) gl.TexCoord2f(0, 0) gl.Vertex3f(-1, -1, 1) gl.TexCoord2f(1, 0) gl.Vertex3f(1, -1, 1) gl.TexCoord2f(1, 1) gl.Vertex3f(1, 1, 1) gl.TexCoord2f(0, 1) gl.Vertex3f(-1, 1, 1) gl.Normal3f(0, 0, -1) gl.TexCoord2f(1, 0) gl.Vertex3f(-1, -1, -1) gl.TexCoord2f(1, 1) gl.Vertex3f(-1, 1, -1) gl.TexCoord2f(0, 1) gl.Vertex3f(1, 1, -1) gl.TexCoord2f(0, 0) gl.Vertex3f(1, -1, -1) gl.Normal3f(0, 1, 0) gl.TexCoord2f(0, 1) gl.Vertex3f(-1, 1, -1) gl.TexCoord2f(0, 0) gl.Vertex3f(-1, 1, 1) gl.TexCoord2f(1, 0) gl.Vertex3f(1, 1, 1) gl.TexCoord2f(1, 1) gl.Vertex3f(1, 1, -1) gl.Normal3f(0, -1, 0) gl.TexCoord2f(1, 1) gl.Vertex3f(-1, -1, -1) gl.TexCoord2f(0, 1) gl.Vertex3f(1, -1, -1) gl.TexCoord2f(0, 0) gl.Vertex3f(1, -1, 1) gl.TexCoord2f(1, 0) gl.Vertex3f(-1, -1, 1) gl.Normal3f(1, 0, 0) gl.TexCoord2f(1, 0) gl.Vertex3f(1, -1, -1) gl.TexCoord2f(1, 1) gl.Vertex3f(1, 1, -1) gl.TexCoord2f(0, 1) gl.Vertex3f(1, 1, 1) gl.TexCoord2f(0, 0) gl.Vertex3f(1, -1, 1) gl.Normal3f(-1, 0, 0) gl.TexCoord2f(0, 0) gl.Vertex3f(-1, -1, -1) gl.TexCoord2f(1, 0) gl.Vertex3f(-1, -1, 1) gl.TexCoord2f(1, 1) gl.Vertex3f(-1, 1, 1) gl.TexCoord2f(0, 1) gl.Vertex3f(-1, 1, -1) gl.End() }
lib/graphic/scene.go
0.61451
0.420719
scene.go
starcoder
package clang // #include "./clang-c/Index.h" // #include "go-clang.h" import "C" import ( "reflect" "unsafe" ) /* Contains the results of code-completion. This data structure contains the results of code completion, as produced by clang_codeCompleteAt(). Its contents must be freed by clang_disposeCodeCompleteResults. */ type CodeCompleteResults struct { c *C.CXCodeCompleteResults } /* Retrieve the number of fix-its for the given completion index. Calling this makes sense only if CXCodeComplete_IncludeCompletionsWithFixIts option was set. Parameter results The structure keeping all completion results Parameter completion_index The index of the completion \return The number of fix-its which must be applied before the completion at completion_index can be applied */ func (ccr *CodeCompleteResults) CompletionNumFixIts(completionIndex uint32) uint32 { return uint32(C.clang_getCompletionNumFixIts(ccr.c, C.uint(completionIndex))) } /* Fix-its that *must* be applied before inserting the text for the corresponding completion. By default, clang_codeCompleteAt() only returns completions with empty fix-its. Extra completions with non-empty fix-its should be explicitly requested by setting CXCodeComplete_IncludeCompletionsWithFixIts. For the clients to be able to compute position of the cursor after applying fix-its, the following conditions are guaranteed to hold for replacement_range of the stored fix-its: - Ranges in the fix-its are guaranteed to never contain the completion point (or identifier under completion point, if any) inside them, except at the start or at the end of the range. - If a fix-it range starts or ends with completion point (or starts or ends after the identifier under completion point), it will contain at least one character. It allows to unambiguously recompute completion point after applying the fix-it. The intuition is that provided fix-its change code around the identifier we complete, but are not allowed to touch the identifier itself or the completion point. One example of completions with corrections are the ones replacing '.' with '->' and vice versa: std::unique_ptr<std::vector<int>> vec_ptr; In 'vec_ptr.^', one of the completions is 'push_back', it requires replacing '.' with '->'. In 'vec_ptr->^', one of the completions is 'release', it requires replacing '->' with '.'. Parameter results The structure keeping all completion results Parameter completion_index The index of the completion Parameter fixit_index The index of the fix-it for the completion at completion_index Parameter replacement_range The fix-it range that must be replaced before the completion at completion_index can be applied Returns The fix-it string that must replace the code at replacement_range before the completion at completion_index can be applied */ func (ccr *CodeCompleteResults) CompletionFixIt(completionIndex uint32, fixitIndex uint32) (SourceRange, string) { var replacementRange SourceRange o := cxstring{C.clang_getCompletionFixIt(ccr.c, C.uint(completionIndex), C.uint(fixitIndex), &replacementRange.c)} defer o.Dispose() return replacementRange, o.String() } // Free the given set of code-completion results. func (ccr *CodeCompleteResults) Dispose() { C.clang_disposeCodeCompleteResults(ccr.c) } // Determine the number of diagnostics produced prior to the location where code completion was performed. func (ccr *CodeCompleteResults) NumDiagnostics() uint32 { return uint32(C.clang_codeCompleteGetNumDiagnostics(ccr.c)) } /* Retrieve a diagnostic associated with the given code completion. Parameter Results the code completion results to query. Parameter Index the zero-based diagnostic number to retrieve. Returns the requested diagnostic. This diagnostic must be freed via a call to clang_disposeDiagnostic(). */ func (ccr *CodeCompleteResults) Diagnostic(index uint32) Diagnostic { return Diagnostic{C.clang_codeCompleteGetDiagnostic(ccr.c, C.uint(index))} } /* Determines what completions are appropriate for the context the given code completion. Parameter Results the code completion results to query Returns the kinds of completions that are appropriate for use along with the given code completion results. */ func (ccr *CodeCompleteResults) Contexts() uint64 { return uint64(C.clang_codeCompleteGetContexts(ccr.c)) } /* Returns the cursor kind for the container for the current code completion context. The container is only guaranteed to be set for contexts where a container exists (i.e. member accesses or Objective-C message sends); if there is not a container, this function will return CXCursor_InvalidCode. Parameter Results the code completion results to query Parameter IsIncomplete on return, this value will be false if Clang has complete information about the container. If Clang does not have complete information, this value will be true. Returns the container kind, or CXCursor_InvalidCode if there is not a container */ func (ccr *CodeCompleteResults) ContainerKind() (uint32, CursorKind) { var isIncomplete C.uint o := CursorKind(C.clang_codeCompleteGetContainerKind(ccr.c, &isIncomplete)) return uint32(isIncomplete), o } /* Returns the USR for the container for the current code completion context. If there is not a container for the current context, this function will return the empty string. Parameter Results the code completion results to query Returns the USR for the container */ func (ccr *CodeCompleteResults) ContainerUSR() string { o := cxstring{C.clang_codeCompleteGetContainerUSR(ccr.c)} defer o.Dispose() return o.String() } /* Returns the currently-entered selector for an Objective-C message send, formatted like "initWithFoo:bar:". Only guaranteed to return a non-empty string for CXCompletionContext_ObjCInstanceMessage and CXCompletionContext_ObjCClassMessage. Parameter Results the code completion results to query Returns the selector (or partial selector) that has been entered thus far for an Objective-C message send. */ func (ccr *CodeCompleteResults) Selector() string { o := cxstring{C.clang_codeCompleteGetObjCSelector(ccr.c)} defer o.Dispose() return o.String() } // The code-completion results. func (ccr CodeCompleteResults) Results() []CompletionResult { var s []CompletionResult gos_s := (*reflect.SliceHeader)(unsafe.Pointer(&s)) gos_s.Cap = int(ccr.c.NumResults) gos_s.Len = int(ccr.c.NumResults) gos_s.Data = uintptr(unsafe.Pointer(ccr.c.Results)) return s } // The number of code-completion results stored in the Results array. func (ccr CodeCompleteResults) NumResults() uint32 { return uint32(ccr.c.NumResults) }
clang/codecompleteresults_gen.go
0.577257
0.407039
codecompleteresults_gen.go
starcoder
package main import ( "github.com/ByteArena/box2d" "github.com/wdevore/RangerGo/api" "github.com/wdevore/RangerGo/engine/rendering" ) // CircleComponent is a box type CircleComponent struct { visual api.INode b2Body *box2d.B2Body scale float64 categoryBits uint16 // I am a... maskBits uint16 // I can collide with a... } // NewCircleComponent constructs a component func NewCircleComponent(name string, parent api.INode) *CircleComponent { o := new(CircleComponent) o.visual = NewCircleNode(name, parent.World(), parent) o.visual.SetID(1003) cn := o.visual.(*CircleNode) cn.Configure(12, 1.0) return o } // Configure component func (c *CircleComponent) Configure(scale float64, categoryBits, maskBits uint16, b2World *box2d.B2World) { c.scale = scale c.categoryBits = categoryBits c.maskBits = maskBits buildCircle(c, b2World) } // SetColor sets the visual's color func (c *CircleComponent) SetColor(color api.IPalette) { gr := c.visual.(*CircleNode) gr.SetColor(color) } // SetPosition sets component's location. func (c *CircleComponent) SetPosition(x, y float64) { c.visual.SetPosition(x, y) c.b2Body.SetTransform(box2d.MakeB2Vec2(x, y), c.b2Body.GetAngle()) } // Update component func (c *CircleComponent) Update() { if c.b2Body.IsActive() { pos := c.b2Body.GetPosition() c.visual.SetPosition(pos.X, pos.Y) rot := c.b2Body.GetAngle() c.visual.SetRotation(rot) } } // ------------------------------------------------------ // Physics control // ------------------------------------------------------ // EnableGravity enables/disables gravity for this component func (c *CircleComponent) EnableGravity(enable bool) { if enable { c.b2Body.SetGravityScale(-9.8) } else { c.b2Body.SetGravityScale(0.0) } } // Reset configures the component back to defaults func (c *CircleComponent) Reset(x, y float64) { c.visual.SetPosition(x, y) c.b2Body.SetTransform(box2d.MakeB2Vec2(x, y), 0.0) c.b2Body.SetLinearVelocity(box2d.MakeB2Vec2(0.0, 0.0)) c.b2Body.SetAngularVelocity(0.0) c.b2Body.SetAwake(true) } // ApplyForce applies linear force to box center func (c *CircleComponent) ApplyForce(dirX, dirY float64) { c.b2Body.ApplyForce(box2d.B2Vec2{X: dirX, Y: dirY}, c.b2Body.GetWorldCenter(), true) } // ApplyImpulse applies linear impulse to box center func (c *CircleComponent) ApplyImpulse(dirX, dirY float64) { c.b2Body.ApplyLinearImpulse(box2d.B2Vec2{X: dirX, Y: dirY}, c.b2Body.GetWorldCenter(), true) } // ApplyImpulseToCorner applies linear impulse to 1,1 box corner // As the box rotates the 1,1 corner rotates which means impulses // could change the rotation to either CW or CCW. func (c *CircleComponent) ApplyImpulseToCorner(dirX, dirY float64) { c.b2Body.ApplyLinearImpulse(box2d.B2Vec2{X: dirX, Y: dirY}, c.b2Body.GetWorldPoint(box2d.B2Vec2{X: 1.0, Y: 1.0}), true) } // ApplyTorque applies torgue to box center func (c *CircleComponent) ApplyTorque(torgue float64) { c.b2Body.ApplyTorque(torgue, true) } // ApplyAngularImpulse applies angular impulse to box center func (c *CircleComponent) ApplyAngularImpulse(impulse float64) { c.b2Body.ApplyAngularImpulse(impulse, true) } // ------------------------------------------------------ // Physics feedback // ------------------------------------------------------ // HandleBeginContact processes BeginContact events func (c *CircleComponent) HandleBeginContact(nodeA, nodeB api.INode) bool { n, ok := nodeA.(*CircleNode) if !ok { n, ok = nodeB.(*CircleNode) } if ok { n.SetColor(rendering.NewPaletteInt64(rendering.Aqua)) } return false } // HandleEndContact processes EndContact events func (c *CircleComponent) HandleEndContact(nodeA, nodeB api.INode) bool { n, ok := nodeA.(*CircleNode) if !ok { n, ok = nodeB.(*CircleNode) } if ok { n.SetColor(rendering.NewPaletteInt64(rendering.Orange)) } return false } func buildCircle(c *CircleComponent, b2World *box2d.B2World) { // A body def used to create bodies bDef := box2d.MakeB2BodyDef() bDef.Type = box2d.B2BodyType.B2_dynamicBody // An instance of a body to contain Fixture c.b2Body = b2World.CreateBody(&bDef) c.visual.SetScale(1.0 * c.scale) gb := c.visual.(*CircleNode) gb.SetColor(rendering.NewPaletteInt64(rendering.Orange)) // Every Fixture has a shape b2Shape := box2d.MakeB2CircleShape() b2Shape.SetRadius(c.scale) fd := box2d.MakeB2FixtureDef() fd.Shape = &b2Shape fd.Density = 1.0 fd.UserData = c.visual fd.Filter.CategoryBits = c.categoryBits fd.Filter.MaskBits = c.maskBits c.b2Body.CreateFixtureFromDef(&fd) // attach Fixture to body }
examples/physics/intermediate/callback_listening/circle_component.go
0.751192
0.512022
circle_component.go
starcoder
package nexpose // Finding is the json struct representation of a vulnerabilities existence // on an asset in nexpose type Finding struct { // The identifier of the vulnerability. ID string `json:"id"` // The number of vulnerable occurrences of the vulnerability. This does not include `invulnerable` instances. Instances int32 `json:"instances"` // Hypermedia links to corresponding or related resources. Links []Link `json:"links,omitempty"` // The vulnerability check results for the finding. Multiple instances may be present if one or more checks fired, or a check has multiple independent results. Results []struct { // The identifier of the vulnerability check. CheckID string `json:"checkId,omitempty"` // If the result is vulnerable with exceptions applied, the identifier(s) of the exceptions actively applied to the result. Exceptions []int32 `json:"exceptions,omitempty"` // An additional discriminating key used to uniquely identify between multiple instances of results on the same finding. ID string `json:"key,omitempty"` // Hypermedia links to corresponding or related resources. Links []Link `json:"links,omitempty"` // The port of the service the result was discovered on. Port int32 `json:"port,omitempty"` // The proof explaining why the result was found vulnerable. The proof may container embedded HTML formatting markup. Proof string `json:"proof,omitempty"` // The protocol of the service the result was discovered on. Protocol string `json:"protocol,omitempty"` // The date and time the result was first recorded, in the ISO8601 format. If the result changes status this value is the date and time of the status change. Since string `json:"since,omitempty"` // The status of the vulnerability check result. Status string `json:"status"` } `json:"results,omitempty"` // The date and time the finding was was first recorded, in the ISO8601 format. // If the result changes status this value is the date and time of the status change. Since string `json:"since,omitempty"` // The status of the finding. Status string `json:"status"` }
json_finding.go
0.734881
0.414899
json_finding.go
starcoder
package dxt import ( "bytes" "encoding/binary" "errors" "github.com/galaco/dxt/common" "image" "image/color" ) // Dxt5 // Dxt5 Image fulfills the standard golang image interface. // It also fulfils a slightly more specialised Dxt interface in the package. type Dxt5 struct { Header Header Pix []uint8 Stride int Rect image.Rectangle } // ColorModel // Returns the color Model for the image (always RGBA) // Fulfills the requirements for the image interface func (p *Dxt5) ColorModel() color.Model { return color.RGBAModel } // Bounds // Returns image boundaries // Fulfills the requirements for the image interface func (p *Dxt5) Bounds() image.Rectangle { return p.Rect } // At // Returns generic Color data for a single pixel at location x,y // Fulfills the requirements for the image interface func (p *Dxt5) At(x, y int) color.Color { return p.RGBAAt(x, y) } // RGBAAt // Returns colour.RGBA information for a single pixel at location x,y // Fulfills the requirements for the image interface func (p *Dxt5) RGBAAt(x, y int) color.RGBA { if !(image.Point{x, y}.In(p.Rect)) { return color.RGBA{} } i := p.PixOffset(x, y) return color.RGBA{R: p.Pix[i+0], G: p.Pix[i+1], B: p.Pix[i+2], A: p.Pix[i+3]} } // PixOffset // Returns the offset into image data of an x,y coordinate // Fulfills the requirements for the image interface func (p *Dxt5) PixOffset(x, y int) int { return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4 } // Set // Set the Color at a given x,y coordinate // Fulfills the requirements for the image interface func (p *Dxt5) Set(x, y int, c color.Color) { if !(image.Point{x, y}.In(p.Rect)) { return } i := p.PixOffset(x, y) c1 := color.RGBAModel.Convert(c).(color.RGBA) p.Pix[i+0] = c1.R p.Pix[i+1] = c1.G p.Pix[i+2] = c1.B p.Pix[i+3] = c1.A } // Decompress // Decompresses and populates the image from packed dxt5 data func (p *Dxt5) Decompress(packed []byte, withHeader bool) error { var rgba []color.RGBA var err error if withHeader { var header Header err = binary.Read(bytes.NewBuffer(packed[:128]), binary.LittleEndian, &header) if err != nil { return err } if header.Id != 0x20534444 { return errors.New("dds format identifier mismatch") } p.Header = header rgba, err = decompressDxt5(packed[128:], p.Rect.Dx(), p.Rect.Dy()) if err != nil { return err } } else { rgba, err = decompressDxt5(packed, p.Rect.Dx(), p.Rect.Dy()) if err != nil { return err } } for i, c := range rgba { i *= 4 p.Pix[i] = c.R p.Pix[i+1] = c.G p.Pix[i+2] = c.B p.Pix[i+3] = c.A } return nil } // NewDxt5 // Create a new Dxt5 image func NewDxt5(r image.Rectangle) *Dxt5 { w, h := r.Dx(), r.Dy() buf := make([]uint8, 4*w*h) return &Dxt5{ Header: Header{}, Pix: buf, Stride: 4 * w, Rect: r, } } // decompressDxt5 // Decompress a Dxt5 compressed slice of bytes. // Decompresses block by block // Width and Height are required, as this information is impossible to derive with // 100% accuracy (e.g. 256x1024 cannot be distinguished from 512x512) from raw alone func decompressDxt5(packed []byte, width int, height int) ([]color.RGBA, error) { unpacked := make([]color.RGBA, width*height) blockCountX := int((width + 3) / blockSize) blockCountY := int((height + 3) / blockSize) offset := 0 for j := 0; j < blockCountY; j++ { for i := 0; i < blockCountX; i++ { if err := decompressDxt5Block(packed[offset+(i*16):], i*blockSize, j*blockSize, width, unpacked); err != nil { return nil, err } } offset += blockCountX * 16 } return unpacked, nil } // decompressDxt5Block // decompress a single dxt5 compressed block. // A single decompressed block is 4x4 pixels located at x,y location in the resultant image func decompressDxt5Block(packed []byte, offsetX int, offsetY int, width int, unpacked []color.RGBA) error { var alpha0, alpha1 uint8 err := binary.Read(bytes.NewBuffer(packed[:1]), binary.LittleEndian, &alpha0) if err != nil { return err } err = binary.Read(bytes.NewBuffer(packed[1:2]), binary.LittleEndian, &alpha1) if err != nil { return err } var bits [6]uint8 err = binary.Read(bytes.NewBuffer(packed[2:8]), binary.LittleEndian, &bits) if err != nil { return err } alphaCode1 := uint32(bits[2]) | (uint32(bits[3]) << 8) | (uint32(bits[4]) << 16) | (uint32(bits[5]) << 24) alphaCode2 := uint16(bits[0]) | (uint16(bits[1]) << 8) // Construct colours to transform between var c0, c1 uint16 err = binary.Read(bytes.NewBuffer(packed[8:10]), binary.LittleEndian, &c0) if err != nil { return err } err = binary.Read(bytes.NewBuffer(packed[10:12]), binary.LittleEndian, &c1) if err != nil { return err } colour0 := common.Rgb565toargb8888(c0) colour1 := common.Rgb565toargb8888(c1) var code uint32 err = binary.Read(bytes.NewBuffer(packed[12:16]), binary.LittleEndian, &code) if err != nil { return err } for j := 0; j < blockSize; j++ { for i := 0; i < blockSize; i++ { alphaCodeIndex := uint(3 * (4*j + i)) var alphaCode int if alphaCodeIndex <= 12 { alphaCode = int((alphaCode2 >> alphaCodeIndex) & 0x07) } else if alphaCodeIndex == 15 { alphaCode = int((uint32(alphaCode2) >> 15) | ((alphaCode1 << 1) & 0x06)) } else { // alphaCodeIndex >= 18 && alphaCodeIndex <= 45 alphaCode = int((alphaCode1 >> (alphaCodeIndex - 16)) & 0x07) } var finalAlpha uint8 if alphaCode == 0 { finalAlpha = alpha0 } else if alphaCode == 1 { finalAlpha = alpha1 } else { if alpha0 > alpha1 { finalAlpha = ((8-uint8(alphaCode))*alpha0 + (uint8(alphaCode)-1)*alpha1) / 7 } else { if alphaCode == 6 { finalAlpha = 0 } else if alphaCode == 7 { finalAlpha = 255 } else { finalAlpha = ((6-uint8(alphaCode))*alpha0 + (uint8(alphaCode)-1)*alpha1) / 5 } } } colorCode := (code >> uint32(2*(4*j+i))) & 0x03 var finalColour color.RGBA switch colorCode { case 0: finalColour = colour0 case 1: finalColour = colour1 case 2: finalColour = color.RGBA{ R: (2*colour0.R + colour1.R) / 3, G: (2*colour0.G + colour1.G) / 3, B: (2*colour0.B + colour1.B) / 3, } case 3: finalColour = color.RGBA{ R: (colour0.R + 2*colour1.R) / 3, G: (colour0.G + 2*colour1.G) / 3, B: (colour0.B + 2*colour1.B) / 3, } } if finalAlpha != 255 { a := 0 a -= 2 } // Set alpha finalColour.A = finalAlpha if offsetX+i < width { unpacked[(offsetY+j)*width+(offsetX+i)] = finalColour } } } return nil }
dxt5.go
0.749271
0.442877
dxt5.go
starcoder
package graph import "fmt" type duplicateNodeError struct { nodeID NodeID } func (e duplicateNodeError) Error() string { return fmt.Sprintf("node with id %d has already been added", e.nodeID) } type duplicateEdgeError struct { fromID NodeID toID NodeID } func (e duplicateEdgeError) Error() string { return fmt.Sprintf("edge from %d to %d has already been added", e.fromID, e.toID) } type redundantEdgeError struct { nodeID NodeID } func (e redundantEdgeError) Error() string { return fmt.Sprintf("edge from %d to %d is redundant", e.nodeID, e.nodeID) } type nodeNotFoundError struct { nodeID NodeID } func (e nodeNotFoundError) Error() string { return fmt.Sprintf("node with id %d could not be found", e.nodeID) } type multipleValuesForNodeError struct { nodeID NodeID } func (e multipleValuesForNodeError) Error() string { return fmt.Sprintf("multiple values provided for node with id %d", e.nodeID) } type multipleValuesForEdgeError struct { fromID NodeID toID NodeID } func (e multipleValuesForEdgeError) Error() string { return fmt.Sprintf("multiple values provided for edge from %d to %d", e.fromID, e.toID) } type edgeNotFoundError struct { fromID NodeID toID NodeID } func (e edgeNotFoundError) Error() string { return fmt.Sprintf("edge from %d to %d could not be found", e.fromID, e.toID) } type noValueFoundInNodeError struct { nodeID NodeID } func (e noValueFoundInNodeError) Error() string { return fmt.Sprintf("no value found in node with id %d", e.nodeID) } type noValueFoundInEdgeError struct { fromID NodeID toID NodeID } func (e noValueFoundInEdgeError) Error() string { return fmt.Sprintf("no value found in edge from %d to %d", e.fromID, e.toID) } type cannotUseForDirectedGraphError struct { methodName string } func (e cannotUseForDirectedGraphError) Error() string { return fmt.Sprintf("cannot use %s on directed graph", e.methodName) } type cannotUseForUndirectedGraphError struct { methodName string } func (e cannotUseForUndirectedGraphError) Error() string { return fmt.Sprintf("cannot use %s on undirected graph", e.methodName) }
graph/error.go
0.668339
0.443359
error.go
starcoder
package packed // Efficient sequential read/write of packed integers. type BulkOperationPacked6 struct { *BulkOperationPacked } func newBulkOperationPacked6() BulkOperation { return &BulkOperationPacked6{newBulkOperationPacked(6)} } func (op *BulkOperationPacked6) decodeLongToInt(blocks []int64, values []int32, iterations int) { blocksOffset, valuesOffset := 0, 0 for i := 0; i < iterations; i ++ { block0 := blocks[blocksOffset]; blocksOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 58)); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 52) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 46) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 40) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 34) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 28) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 22) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 16) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 10) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block0) >> 4) & 63); valuesOffset++ block1 := blocks[blocksOffset]; blocksOffset++ values[valuesOffset] = int32(((block0 & 15) << 2) | (int64(uint64(block1) >> 62))); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 56) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 50) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 44) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 38) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 32) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 26) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 20) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 14) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 8) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block1) >> 2) & 63); valuesOffset++ block2 := blocks[blocksOffset]; blocksOffset++ values[valuesOffset] = int32(((block1 & 3) << 4) | (int64(uint64(block2) >> 60))); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 54) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 48) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 42) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 36) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 30) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 24) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 18) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 12) & 63); valuesOffset++ values[valuesOffset] = int32(int64(uint64(block2) >> 6) & 63); valuesOffset++ values[valuesOffset] = int32(block2 & 63); valuesOffset++ } } func (op *BulkOperationPacked6) decodeByteToInt(blocks []byte, values []int32, iterations int) { blocksOffset, valuesOffset := 0, 0 for i := 0; i < iterations; i ++ { byte0 := blocks[blocksOffset] blocksOffset++ values[valuesOffset] = int32( int64(uint8(byte0) >> 2)) valuesOffset++ byte1 := blocks[blocksOffset] blocksOffset++ values[valuesOffset] = int32((int64(byte0 & 3) << 4) | int64(uint8(byte1) >> 4)) valuesOffset++ byte2 := blocks[blocksOffset] blocksOffset++ values[valuesOffset] = int32((int64(byte1 & 15) << 2) | int64(uint8(byte2) >> 6)) valuesOffset++ values[valuesOffset] = int32( int64(byte2) & 63) valuesOffset++ } } func (op *BulkOperationPacked6) decodeLongToLong(blocks []int64, values []int64, iterations int) { blocksOffset, valuesOffset := 0, 0 for i := 0; i < iterations; i ++ { block0 := blocks[blocksOffset]; blocksOffset++ values[valuesOffset] = int64(uint64(block0) >> 58); valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 52) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 46) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 40) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 34) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 28) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 22) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 16) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 10) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block0) >> 4) & 63; valuesOffset++ block1 := blocks[blocksOffset]; blocksOffset++ values[valuesOffset] = ((block0 & 15) << 2) | (int64(uint64(block1) >> 62)); valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 56) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 50) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 44) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 38) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 32) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 26) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 20) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 14) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 8) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block1) >> 2) & 63; valuesOffset++ block2 := blocks[blocksOffset]; blocksOffset++ values[valuesOffset] = ((block1 & 3) << 4) | (int64(uint64(block2) >> 60)); valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 54) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 48) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 42) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 36) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 30) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 24) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 18) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 12) & 63; valuesOffset++ values[valuesOffset] = int64(uint64(block2) >> 6) & 63; valuesOffset++ values[valuesOffset] = block2 & 63; valuesOffset++ } } func (op *BulkOperationPacked6) decodeByteToLong(blocks []byte, values []int64, iterations int) { blocksOffset, valuesOffset := 0, 0 for i := 0; i < iterations; i ++ { byte0 := blocks[blocksOffset] blocksOffset++ values[valuesOffset] = int64( int64(uint8(byte0) >> 2)) valuesOffset++ byte1 := blocks[blocksOffset] blocksOffset++ values[valuesOffset] = int64((int64(byte0 & 3) << 4) | int64(uint8(byte1) >> 4)) valuesOffset++ byte2 := blocks[blocksOffset] blocksOffset++ values[valuesOffset] = int64((int64(byte1 & 15) << 2) | int64(uint8(byte2) >> 6)) valuesOffset++ values[valuesOffset] = int64( int64(byte2) & 63) valuesOffset++ } }
vendor/github.com/balzaczyy/golucene/core/util/packed/bulkOperation6.go
0.546012
0.728628
bulkOperation6.go
starcoder
package datadog import ( "encoding/json" "time" ) // UsageDBMHour Database Monitoring usage for a given organization for a given hour. type UsageDBMHour struct { // The total number of Database Monitoring host hours from the start of the given hour’s month until the given hour. DbmHostCount *int64 `json:"dbm_host_count,omitempty"` // The total number of normalized Database Monitoring queries from the start of the given hour’s month until the given hour. DbmQueriesCount *int64 `json:"dbm_queries_count,omitempty"` // The hour for the usage. Hour *time.Time `json:"hour,omitempty"` // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct UnparsedObject map[string]interface{} `json:-` } // NewUsageDBMHour instantiates a new UsageDBMHour 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 NewUsageDBMHour() *UsageDBMHour { this := UsageDBMHour{} return &this } // NewUsageDBMHourWithDefaults instantiates a new UsageDBMHour 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 NewUsageDBMHourWithDefaults() *UsageDBMHour { this := UsageDBMHour{} return &this } // GetDbmHostCount returns the DbmHostCount field value if set, zero value otherwise. func (o *UsageDBMHour) GetDbmHostCount() int64 { if o == nil || o.DbmHostCount == nil { var ret int64 return ret } return *o.DbmHostCount } // GetDbmHostCountOk returns a tuple with the DbmHostCount field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *UsageDBMHour) GetDbmHostCountOk() (*int64, bool) { if o == nil || o.DbmHostCount == nil { return nil, false } return o.DbmHostCount, true } // HasDbmHostCount returns a boolean if a field has been set. func (o *UsageDBMHour) HasDbmHostCount() bool { if o != nil && o.DbmHostCount != nil { return true } return false } // SetDbmHostCount gets a reference to the given int64 and assigns it to the DbmHostCount field. func (o *UsageDBMHour) SetDbmHostCount(v int64) { o.DbmHostCount = &v } // GetDbmQueriesCount returns the DbmQueriesCount field value if set, zero value otherwise. func (o *UsageDBMHour) GetDbmQueriesCount() int64 { if o == nil || o.DbmQueriesCount == nil { var ret int64 return ret } return *o.DbmQueriesCount } // GetDbmQueriesCountOk returns a tuple with the DbmQueriesCount field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *UsageDBMHour) GetDbmQueriesCountOk() (*int64, bool) { if o == nil || o.DbmQueriesCount == nil { return nil, false } return o.DbmQueriesCount, true } // HasDbmQueriesCount returns a boolean if a field has been set. func (o *UsageDBMHour) HasDbmQueriesCount() bool { if o != nil && o.DbmQueriesCount != nil { return true } return false } // SetDbmQueriesCount gets a reference to the given int64 and assigns it to the DbmQueriesCount field. func (o *UsageDBMHour) SetDbmQueriesCount(v int64) { o.DbmQueriesCount = &v } // GetHour returns the Hour field value if set, zero value otherwise. func (o *UsageDBMHour) GetHour() time.Time { if o == nil || o.Hour == nil { var ret time.Time return ret } return *o.Hour } // GetHourOk returns a tuple with the Hour field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *UsageDBMHour) GetHourOk() (*time.Time, bool) { if o == nil || o.Hour == nil { return nil, false } return o.Hour, true } // HasHour returns a boolean if a field has been set. func (o *UsageDBMHour) HasHour() bool { if o != nil && o.Hour != nil { return true } return false } // SetHour gets a reference to the given time.Time and assigns it to the Hour field. func (o *UsageDBMHour) SetHour(v time.Time) { o.Hour = &v } func (o UsageDBMHour) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.UnparsedObject != nil { return json.Marshal(o.UnparsedObject) } if o.DbmHostCount != nil { toSerialize["dbm_host_count"] = o.DbmHostCount } if o.DbmQueriesCount != nil { toSerialize["dbm_queries_count"] = o.DbmQueriesCount } if o.Hour != nil { toSerialize["hour"] = o.Hour } return json.Marshal(toSerialize) } func (o *UsageDBMHour) UnmarshalJSON(bytes []byte) (err error) { raw := map[string]interface{}{} all := struct { DbmHostCount *int64 `json:"dbm_host_count,omitempty"` DbmQueriesCount *int64 `json:"dbm_queries_count,omitempty"` Hour *time.Time `json:"hour,omitempty"` }{} err = json.Unmarshal(bytes, &all) if err != nil { err = json.Unmarshal(bytes, &raw) if err != nil { return err } o.UnparsedObject = raw return nil } o.DbmHostCount = all.DbmHostCount o.DbmQueriesCount = all.DbmQueriesCount o.Hour = all.Hour return nil } type NullableUsageDBMHour struct { value *UsageDBMHour isSet bool } func (v NullableUsageDBMHour) Get() *UsageDBMHour { return v.value } func (v *NullableUsageDBMHour) Set(val *UsageDBMHour) { v.value = val v.isSet = true } func (v NullableUsageDBMHour) IsSet() bool { return v.isSet } func (v *NullableUsageDBMHour) Unset() { v.value = nil v.isSet = false } func NewNullableUsageDBMHour(val *UsageDBMHour) *NullableUsageDBMHour { return &NullableUsageDBMHour{value: val, isSet: true} } func (v NullableUsageDBMHour) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableUsageDBMHour) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/v1/datadog/model_usage_dbm_hour.go
0.779741
0.486332
model_usage_dbm_hour.go
starcoder
// +build go1.14,!go1.15 package symbols import ( "gonum.org/v1/plot/palette" "image/color" "reflect" ) func init() { Symbols["gonum.org/v1/plot/palette"] = map[string]reflect.Value{ // function, constant and variable definitions "Blue": reflect.ValueOf(palette.Blue), "Cyan": reflect.ValueOf(palette.Cyan), "ErrNaN": reflect.ValueOf(&palette.ErrNaN).Elem(), "ErrOverflow": reflect.ValueOf(&palette.ErrOverflow).Elem(), "ErrUnderflow": reflect.ValueOf(&palette.ErrUnderflow).Elem(), "Green": reflect.ValueOf(palette.Green), "HSVAModel": reflect.ValueOf(&palette.HSVAModel).Elem(), "Heat": reflect.ValueOf(palette.Heat), "Magenta": reflect.ValueOf(palette.Magenta), "Radial": reflect.ValueOf(palette.Radial), "Rainbow": reflect.ValueOf(palette.Rainbow), "Red": reflect.ValueOf(palette.Red), "Reverse": reflect.ValueOf(palette.Reverse), "Yellow": reflect.ValueOf(palette.Yellow), // type definitions "ColorMap": reflect.ValueOf((*palette.ColorMap)(nil)), "DivergingColorMap": reflect.ValueOf((*palette.DivergingColorMap)(nil)), "DivergingPalette": reflect.ValueOf((*palette.DivergingPalette)(nil)), "HSVA": reflect.ValueOf((*palette.HSVA)(nil)), "Hue": reflect.ValueOf((*palette.Hue)(nil)), "Palette": reflect.ValueOf((*palette.Palette)(nil)), // interface wrapper definitions "_ColorMap": reflect.ValueOf((*_gonum_org_v1_plot_palette_ColorMap)(nil)), "_DivergingColorMap": reflect.ValueOf((*_gonum_org_v1_plot_palette_DivergingColorMap)(nil)), "_DivergingPalette": reflect.ValueOf((*_gonum_org_v1_plot_palette_DivergingPalette)(nil)), "_Palette": reflect.ValueOf((*_gonum_org_v1_plot_palette_Palette)(nil)), } } // _gonum_org_v1_plot_palette_ColorMap is an interface wrapper for ColorMap type type _gonum_org_v1_plot_palette_ColorMap struct { WAlpha func() float64 WAt func(a0 float64) (color.Color, error) WMax func() float64 WMin func() float64 WPalette func(colors int) palette.Palette WSetAlpha func(a0 float64) WSetMax func(a0 float64) WSetMin func(a0 float64) } func (W _gonum_org_v1_plot_palette_ColorMap) Alpha() float64 { return W.WAlpha() } func (W _gonum_org_v1_plot_palette_ColorMap) At(a0 float64) (color.Color, error) { return W.WAt(a0) } func (W _gonum_org_v1_plot_palette_ColorMap) Max() float64 { return W.WMax() } func (W _gonum_org_v1_plot_palette_ColorMap) Min() float64 { return W.WMin() } func (W _gonum_org_v1_plot_palette_ColorMap) Palette(colors int) palette.Palette { return W.WPalette(colors) } func (W _gonum_org_v1_plot_palette_ColorMap) SetAlpha(a0 float64) { W.WSetAlpha(a0) } func (W _gonum_org_v1_plot_palette_ColorMap) SetMax(a0 float64) { W.WSetMax(a0) } func (W _gonum_org_v1_plot_palette_ColorMap) SetMin(a0 float64) { W.WSetMin(a0) } // _gonum_org_v1_plot_palette_DivergingColorMap is an interface wrapper for DivergingColorMap type type _gonum_org_v1_plot_palette_DivergingColorMap struct { WAlpha func() float64 WAt func(a0 float64) (color.Color, error) WConvergePoint func() float64 WMax func() float64 WMin func() float64 WPalette func(colors int) palette.Palette WSetAlpha func(a0 float64) WSetConvergePoint func(a0 float64) WSetMax func(a0 float64) WSetMin func(a0 float64) } func (W _gonum_org_v1_plot_palette_DivergingColorMap) Alpha() float64 { return W.WAlpha() } func (W _gonum_org_v1_plot_palette_DivergingColorMap) At(a0 float64) (color.Color, error) { return W.WAt(a0) } func (W _gonum_org_v1_plot_palette_DivergingColorMap) ConvergePoint() float64 { return W.WConvergePoint() } func (W _gonum_org_v1_plot_palette_DivergingColorMap) Max() float64 { return W.WMax() } func (W _gonum_org_v1_plot_palette_DivergingColorMap) Min() float64 { return W.WMin() } func (W _gonum_org_v1_plot_palette_DivergingColorMap) Palette(colors int) palette.Palette { return W.WPalette(colors) } func (W _gonum_org_v1_plot_palette_DivergingColorMap) SetAlpha(a0 float64) { W.WSetAlpha(a0) } func (W _gonum_org_v1_plot_palette_DivergingColorMap) SetConvergePoint(a0 float64) { W.WSetConvergePoint(a0) } func (W _gonum_org_v1_plot_palette_DivergingColorMap) SetMax(a0 float64) { W.WSetMax(a0) } func (W _gonum_org_v1_plot_palette_DivergingColorMap) SetMin(a0 float64) { W.WSetMin(a0) } // _gonum_org_v1_plot_palette_DivergingPalette is an interface wrapper for DivergingPalette type type _gonum_org_v1_plot_palette_DivergingPalette struct { WColors func() []color.Color WCriticalIndex func() (low int, high int) } func (W _gonum_org_v1_plot_palette_DivergingPalette) Colors() []color.Color { return W.WColors() } func (W _gonum_org_v1_plot_palette_DivergingPalette) CriticalIndex() (low int, high int) { return W.WCriticalIndex() } // _gonum_org_v1_plot_palette_Palette is an interface wrapper for Palette type type _gonum_org_v1_plot_palette_Palette struct { WColors func() []color.Color } func (W _gonum_org_v1_plot_palette_Palette) Colors() []color.Color { return W.WColors() }
pkg/internal/runtime/symbols/go1_14_gonum.org_v1_plot_palette.go
0.622918
0.447158
go1_14_gonum.org_v1_plot_palette.go
starcoder
package aoc import ( "fmt" "math" ) // Point is a two dimensional point defined by x and y coordinates type Point struct { X, Y int } var EightNeighbourOffsets = []Point{ Point{X: -1, Y: -1}, Point{X: 0, Y: -1}, Point{X: 1, Y: -1}, Point{X: -1, Y: 0} /* */, Point{X: 1, Y: 0}, Point{X: -1, Y: 1}, Point{X: 0, Y: 1}, Point{X: 1, Y: 1}, } var FourNeighbourOffsets = []Point{ Point{X: 0, Y: -1}, Point{X: -1, Y: 0}, Point{X: 1, Y: 0}, Point{X: 0, Y: 1}, } func (p Point) String() string { return fmt.Sprintf("%d,%d", p.X, p.Y) } func (p *Point) In(d Direction) Point { return Point{p.X + d.Dx, p.Y + d.Dy} } // Neighbours returns the four neighbours of a point func (p Point) Neighbours() []Point { return []Point{ Point{p.X, p.Y - 1}, Point{p.X - 1, p.Y}, Point{p.X + 1, p.Y}, Point{p.X, p.Y + 1}} } // Neighbours8 returns the eight neighbours of a point func (p Point) Neighbours8() []Point { return []Point{ Point{p.X - 1, p.Y - 1}, Point{p.X + 0, p.Y - 1}, Point{p.X + 1, p.Y - 1}, Point{p.X - 1, p.Y + 0}, Point{p.X + 1, p.Y + 0}, Point{p.X - 1, p.Y + 1}, Point{p.X + 0, p.Y + 1}, Point{p.X + 1, p.Y + 1}, } } // ManhattanDistance returns the Manhattan distance between a 2d point // and another 2d point func (p Point) ManhattanDistance(o Point) int { return Abs(p.X-o.X) + Abs(p.Y-o.Y) } func (p Point) Size() float64 { return math.Sqrt(float64(p.X)*float64(p.X) + float64(p.Y)*float64(p.Y)) } func (p *Point) Norm(o *Point) *Point { r := Point{0,0} if p.X > o.X { r.X = -1 } else if p.X < o.X { r.X = 1 } if p.Y > o.Y { r.Y = -1 } else if p.Y < o.Y { r.Y = 1 } return &r } type Point3D struct { X, Y, Z int } func (p Point3D) String() string { return fmt.Sprintf("%d,%d,%d", p.X, p.Y, p.Z) } func (p Point3D) ManhattanDistance(o Point3D) int { return Abs(p.X-o.X) + Abs(p.Y-o.Y) + Abs(p.Z-o.Z) } func (p Point3D) Size() float64 { return math.Sqrt(float64(p.X)*float64(p.X) + float64(p.Y)*float64(p.Y) + float64(p.Z)*float64(p.Z)) } type PointPair struct { P1 *Point P2 *Point } func (pp* PointPair) String() string { return fmt.Sprintf("%s -> %s\n", pp.P1, pp.P2) } func (pp* PointPair) Norm() *Point { return pp.P1.Norm(pp.P2) }
lib-go/point.go
0.860955
0.763858
point.go
starcoder
package filter import ( "errors" "image" "math" "strconv" "github.com/jangler/imp/util" ) var imposeHelp = `impose <layer> <file> [<x> <y>] Layer the working image on top of another image or vice versa. Possible values for 'layer' are over and under. Coordinates x and y may be given to offset the working image relative to the other image. If coordinates are not given, they default to zero and the images are aligned at their top-left corners.` func imposeFunc(img *image.RGBA, args []string) (*image.RGBA, []string) { if len(args) < 2 { util.Die(errors.New(imposeHelp)) } order := args[0] if order != "over" && order != "under" { util.Die(errors.New(imposeHelp)) } imposeImg := util.ReadImage(args[1]) var xOffset, yOffset int64 if len(args) >= 4 { var err error xOffset, err = strconv.ParseInt(args[2], 10, 0) if err == nil { yOffset, err = strconv.ParseInt(args[3], 10, 0) if err == nil { args = args[4:] } else { xOffset, yOffset = 0, 0 args = args[2:] } } else { xOffset = 0 args = args[2:] } } else { args = args[2:] } b1, b2 := img.Bounds(), imposeImg.Bounds() x1 := int(math.Min(0, float64(xOffset))) x2 := int(math.Max(float64(b2.Dx()), float64(b1.Dx()+int(xOffset)))) y1 := int(math.Min(0, float64(yOffset))) y2 := int(math.Max(float64(b2.Dy()), float64(b1.Dy()+int(yOffset)))) width, height := x2-x1, y2-y1 newImg := image.NewRGBA(image.Rect(0, 0, width, height)) if order == "over" { util.DrawImg(imposeImg, newImg, int(math.Max(0, float64(-xOffset))), int(math.Max(0, float64(-yOffset)))) util.DrawImg(img, newImg, int(math.Max(0, float64(xOffset))), int(math.Max(0, float64(yOffset)))) } else { util.DrawImg(img, newImg, int(math.Max(0, float64(xOffset))), int(math.Max(0, float64(yOffset)))) util.DrawImg(imposeImg, newImg, int(math.Max(0, float64(-xOffset))), int(math.Max(0, float64(-yOffset)))) } return newImg, args } func init() { addFilter(&Filter{"impose", imposeHelp, imposeFunc}) }
filter/impose.go
0.650689
0.475423
impose.go
starcoder
package main import "fmt" /* Given an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. Example 1: Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"] Output: ["eat","oath"] Example 2: Input: board = [["a","b"],["c","d"]], words = ["abcb"] Output: [] Constraints: m == board.length n == board[i].length 1 <= m, n <= 12 board[i][j] is a lowercase English letter. 1 <= words.length <= 3 * 104 1 <= words[i].length <= 10 words[i] consists of lowercase English letters. All the strings of words are unique. */ type TrieNode struct { isEndOfWord bool children map[rune]TrieNode } func DefaultTrieNode() TrieNode { return TrieNode{ isEndOfWord: false, children: make(map[rune]TrieNode), } } func DefaultTrie() *TrieNode { return &TrieNode{isEndOfWord: false, children: make(map[rune]TrieNode)} } func (trie *TrieNode) Insert(word string) *TrieNode { currentNode := *trie for index, letter := range word { if _, ok := currentNode.children[letter]; !ok { node := DefaultTrieNode() node.isEndOfWord = index == len(word)-1 currentNode.children[letter] = node } currentNode = currentNode.children[letter] } return trie } func (trie *TrieNode) Contains(word string) bool { currentNode := *trie for _, letter := range word { if _, ok := currentNode.children[letter]; !ok { return false } currentNode = currentNode.children[letter] } return currentNode.isEndOfWord } func (trie *TrieNode) NodeContainsCharacter(character rune) bool { _, ok := trie.children[character] return ok } func keys(m map[string]bool) []string { out := make([]string, 0, len(m)) for key := range m { out = append(out, key) } return out } // time O(rows * columns * 4 ^ rows * colums) // 4 because there are 4 directions we can to go in theboard // 4 ^ rows * columns is how long a dfs can take // rows * columns because we are doing it starting from each row and column func findWords(board [][]rune, words []string) []string { type position struct { i int j int } trie := DefaultTrie() for _, word := range words { trie.Insert(word) } wordsThatCanBeBuiltFromBoard := make(map[string]bool) visitedPositions := make(map[position]bool) var dfs func(i int, j int, currentWord string, currentNode TrieNode) rows := len(board) columns := len(board[0]) dfs = func(i int, j int, currentWord string, currentNode TrieNode) { if i < 0 || i >= rows || j < 0 || j >= columns { return } currentCharacter := board[i][j] if !currentNode.NodeContainsCharacter(currentCharacter) { return } currentNode = currentNode.children[currentCharacter] currentWord += string(currentCharacter) currentPosition := position{i, j} visitedPositions[currentPosition] = true if currentNode.isEndOfWord { wordsThatCanBeBuiltFromBoard[currentWord] = true } dfs(i-1, j, currentWord, currentNode) dfs(i+1, j, currentWord, currentNode) dfs(i, j-1, currentWord, currentNode) dfs(i, j+1, currentWord, currentNode) visitedPositions[currentPosition] = false } for i := 0; i < rows; i++ { for j := 0; j < columns; j++ { dfs(i, j, "", *trie) } } return keys(wordsThatCanBeBuiltFromBoard) } func main() { trie := DefaultTrie(). Insert("hello"). Insert("world"). Insert("one"). Insert("two"). Insert("three") fmt.Println(trie.Contains("hello")) fmt.Println(trie.Contains("hel")) fmt.Println(trie.Contains("world")) fmt.Println(trie.Contains("hello")) }
golang/algorithms/others/word_search_2/main.go
0.622918
0.511351
main.go
starcoder
package vida import ( "bytes" "fmt" "math/rand" "time" ) // Bytes models a dynamic mutable array of bytes. type Bytes struct { Value []byte } // Value Interface func (b *Bytes) TypeName() string { return "Bytes" } func (b *Bytes) Description() string { return string(b.Value) } func (b *Bytes) Equals(other Value) bool { if value, ok := other.(*Bytes); ok { return bytes.Equal(b.Value, value.Value) } return false } func (b *Bytes) BinaryOp(op byte, rhs Value) (Value, error) { switch rhs := rhs.(type) { case *Bytes: switch op { case TKAdd: return &Bytes{Value: append(b.Value, rhs.Value...)}, nil default: return nil, TypeErrorInBinaryOperator(KindDescription[op], b, rhs) } default: return nil, TypeErrorInBinaryOperator(KindDescription[op], b, rhs) } } func (b *Bytes) PrefixOp(op byte) (Value, error) { return nil, OperatorNotDefined(op, b) } func (b *Bytes) IsIterable() bool { return true } func (b *Bytes) MakeIterator() Iterator { return NewBytesIterator(b, false) } func (b *Bytes) IsHashable() bool { return false } func (b *Bytes) MakeHashKey() HashKey { return HashKey{} } func (b *Bytes) IsValueSemantics() bool { return false } func (b *Bytes) HasMethods() bool { return true } func (b *Bytes) GetMethod(name string) (Value, bool, error) { if method, ok := BytesInterface[name]; ok { return method, true, nil } return nil, false, MethodNotDefined(name, b) } func (b *Bytes) Clone() Value { return &Bytes{Value: append([]byte{}, b.Value...)} } // Interface subscript operator. func (b *Bytes) SubscriptGet(index Value) (Value, error) { switch idx := index.(type) { case IntegerNumber: i, length := idx.ToInt(), Int(len(b.Value)) switch { case i >= -length && i < length: switch { case i < 0: return Byte(b.Value[i+length]), nil default: return Byte(b.Value[i]), nil } default: return nil, IndexOutOfRangeError(length, i) } default: return nil, ValueIsNotAnIndexError(index) } } func (b *Bytes) SubscriptSet(index, value Value) error { if numericValue, ok := value.(IntegerNumber); ok { switch idx := index.(type) { case IntegerNumber: i, length := idx.ToInt(), Int(len(b.Value)) switch { case i >= -length && i < length: switch { case i < 0: b.Value[i+length] = byte(numericValue.ToInt()) default: b.Value[i] = byte(numericValue.ToInt()) } return nil default: return IndexOutOfRangeError(length, i) } default: return ValueIsNotAnIndexError(index) } } return BytesChangeMustBeWithNumericTypesOnly() } // Interface Slice operator. func (b *Bytes) SliceGet(sliceType UInt32, low, high Value) (Value, error) { lidx, okL := low.(IntegerNumber) hidx, okH := high.(IntegerNumber) if !okL || !okH { if !okL { return nil, ValueIsNotAnIndexError(low) } return nil, ValueIsNotAnIndexError(high) } var l, h Int length := Int(len(b.Value)) switch sliceType { case exprColon: l, h = lidx.ToInt(), length case colonExpr: h = hidx.ToInt() case exprColonExpr: l, h = lidx.ToInt(), hidx.ToInt() case onlyColon: h = length default: return nil, NeverShouldHaveHappened("wrong sliceType in Bytes SliceGet") } if l >= -length && l <= length && h >= -length && h <= length { if l < 0 { l += length } if h < 0 { h += length } if l <= h { return &Bytes{Value: b.Value[l:h]}, nil } else { return nil, IndexOutOfRangeError(length, l) } } else { if !(l >= -length && l <= length) { return nil, IndexOutOfRangeError(length, l) } else { return nil, IndexOutOfRangeError(length, h) } } } func (b *Bytes) SliceSet(sliceType UInt32, low, high, value Value) error { if numericValue, ok := value.(IntegerNumber); ok { lidx, okL := low.(IntegerNumber) hidx, okH := high.(IntegerNumber) if !okL || !okH { if !okL { return ValueIsNotAnIndexError(low) } return ValueIsNotAnIndexError(high) } var l, h Int length := Int(len(b.Value)) switch sliceType { case exprColon: l, h = lidx.ToInt(), length case colonExpr: h = hidx.ToInt() case exprColonExpr: l, h = lidx.ToInt(), hidx.ToInt() case onlyColon: h = length default: return NeverShouldHaveHappened("wrong sliceType in Bytes SliceSet") } if l >= -length && l <= length && h >= -length && h <= length { if l < 0 { l += length } if h < 0 { h += length } if l <= h { for i := l; i < h; i++ { b.Value[i] = byte(numericValue.ToInt()) } return nil } else { return IndexOutOfRangeError(length, l) } } else { if !(l >= -length && l <= length) { return IndexOutOfRangeError(length, l) } else { return IndexOutOfRangeError(length, h) } } } return BytesChangeMustBeWithNumericTypesOnly() } // BytesInterface is the collection of methods for the type Bytes. var BytesInterface = Namespace{ "isEmpty": GFunction{Name: "isEmpty", Value: bytesIsEmpty}, "length": GFunction{Name: "length", Value: bytesLength}, "clear": GFunction{Name: "clear", Value: bytesClear}, "contains": GFunction{Name: "contains", Value: bytesContains}, "clone": GFunction{Name: "clone", Value: bytesClone}, "remove": GFunction{Name: "remove", Value: bytesRemove}, "randomElement": GFunction{Name: "randomElement", Value: bytesRandomElement}, "makeIterator": GFunction{Name: "makeIterator", Value: bytesMakeIterator}, } func bytesIsEmpty(args ...Value) (Value, error) { if len(args) == 1 { return Bool(len(args[0].(*Bytes).Value) == 0), nil } return nil, fmt.Errorf("expected %v arguments and got %v", 0, len(args)) } func bytesLength(args ...Value) (Value, error) { if len(args) == 1 { b := args[0].(*Bytes) return Int(len(b.Value)), nil } return nil, fmt.Errorf("expected %v arguments and got %v", 0, len(args)) } func bytesClear(args ...Value) (Value, error) { if len(args) == 1 { b := args[0].(*Bytes) b.Value = b.Value[:0] return b, nil } return nil, fmt.Errorf("expected %v arguments and got %v", 0, len(args)) } func bytesContains(args ...Value) (Value, error) { if len(args) == 2 { b := args[0].(*Bytes) if numeric, ok := args[1].(IntegerNumber); ok { value := byte(numeric.ToInt()) for _, v := range b.Value { if v == value { return True, nil } } return False, nil } return False, nil } return nil, fmt.Errorf("expected %v argument and got %v", 1, len(args)) } func bytesClone(args ...Value) (Value, error) { if len(args) == 1 { b := args[0].(*Bytes) return b.Clone(), nil } return nil, fmt.Errorf("expected %v arguments and got %v", 0, len(args)) } func bytesRemove(args ...Value) (Value, error) { if len(args) == 2 { b := args[0].(*Bytes) if numeric, ok := args[1].(IntegerNumber); ok { length, elem, index, found := len(b.Value), byte(numeric.ToInt()), 0, false for i, v := range b.Value { if v == elem { found, index = true, i break } } if found { copy(b.Value[index:], b.Value[index+1:]) b.Value = b.Value[:length-1] } return b, nil } return b, nil } return nil, fmt.Errorf("expected %v argument and got %v", 1, len(args)) } func bytesRandomElement(args ...Value) (Value, error) { if len(args) == 1 { b := args[0].(*Bytes) if len(b.Value) == 0 { return NilValue, nil } rand.Seed(time.Now().UnixNano()) return Byte(b.Value[rand.Int63n(int64(len(b.Value)))]), nil } return nil, fmt.Errorf("expected %v arguments and got %v", 0, len(args)) } func bytesMakeIterator(args ...Value) (Value, error) { if len(args) == 1 { b := args[0].(*Bytes) return NewBytesIterator(b, false), nil } return nil, fmt.Errorf("expected %v arguments and got %v", 0, len(args)) }
vida/bytes.go
0.737253
0.442938
bytes.go
starcoder
package test import ( "strings" "github.com/ihcsim/wikiracer/errors" "github.com/ihcsim/wikiracer/internal/wiki" ) const separator = "|" // MockWiki is an in-memory wiki type MockWiki struct { pages map[string]*wiki.Page } // NewMockWiki returns a new instance of MockWiki func NewMockWiki() *MockWiki { testData := map[string]*wiki.Page{ "1984 Summer Olympics": &wiki.Page{ID: 2000, Title: "1984 Summer Olympics", Namespace: 0, Links: []string{"7-Eleven", "Afghanistan"}}, "2010 Winter Olympics": &wiki.Page{ID: 2009, Title: "2010 Winter Olympics", Namespace: 0, Links: []string{"1984 Summer Olympics"}}, "7-Eleven": &wiki.Page{ID: 2001, Title: "7-Eleven", Namespace: 0, Links: []string{"Big C", "Calgary", "Eurocash"}}, "Afghanistan": &wiki.Page{ID: 2002, Title: "Afghanistan", Namespace: 0, Links: []string{}}, "Alexander the Great": &wiki.Page{ID: 1000, Title: "Alexander the Great", Namespace: 0, Links: []string{"Apepi", "Greek language", "Diodotus I"}}, "Apepi": &wiki.Page{ID: 1005, Title: "Apepi", Namespace: 0}, "Big C": &wiki.Page{ID: 2003, Title: "Big C", Namespace: 0, Links: []string{"Vancouver"}}, "Calgary": &wiki.Page{ID: 2004, Title: "Calgary", Namespace: 0}, "Eurocash": &wiki.Page{ID: 2005, Title: "Eurocash", Namespace: 0, Links: []string{"Małpka Express", "Tea"}}, "Diodotus I": &wiki.Page{ID: 1007, Title: "Diodotus I", Namespace: 0}, "Fruit anatomy": &wiki.Page{ID: 1001, Title: "Fruit anatomy", Namespace: 0, Links: []string{"Segment"}}, "Greek language": &wiki.Page{ID: 1002, Title: "Greek language", Namespace: 0, Links: []string{"Fruit anatomy"}}, "Małpka Express": &wiki.Page{ID: 2006, Title: "Małpka Express", Namespace: 0}, "<NAME>": &wiki.Page{ID: 1006, Title: "<NAME>", Namespace: 0}, "<NAME>": &wiki.Page{ID: 1003, Title: "<NAME>", Namespace: 0, Links: []string{"<NAME>", "1984 Summer Olympics"}}, "Segment": &wiki.Page{ID: 1004, Title: "Segment", Namespace: 0, Links: []string{"Vancouver"}}, "Tea": &wiki.Page{ID: 2007, Title: "Tea", Namespace: 0}, "Vancouver": &wiki.Page{ID: 2008, Title: "Vancouver", Namespace: 0, Links: []string{"2010 Winter Olympics"}}, } return &MockWiki{pages: testData} } // FindPages returns the page with the given title, if it exists. // Otherwise, it returns a 'page not found' error. func (m *MockWiki) FindPages(titles, nextBatch string) ([]*wiki.Page, error) { pages := []*wiki.Page{} for _, title := range strings.Split(titles, separator) { page, exist := m.pages[title] if !exist { return nil, errors.PageNotFound{wiki.Page{Title: title}} } pages = append(pages, page) } return pages, nil }
test/mock_wiki.go
0.577257
0.410313
mock_wiki.go
starcoder
package world // GameMode represents a game mode that may be assigned to a player. Upon joining the world, players will be // given the default game mode that the world holds. // Game modes specify the way that a player interacts with and plays in the world. type GameMode interface { // AllowsEditing specifies if a player with this GameMode can edit the World it's in. AllowsEditing() bool // AllowsTakingDamage specifies if a player with this GameMode can take damage from other entities. AllowsTakingDamage() bool // CreativeInventory specifies if a player with this GameMode has access to the creative inventory. CreativeInventory() bool // HasCollision specifies if a player with this GameMode can collide with blocks or entities in the world. HasCollision() bool // AllowsFlying specifies if a player with this GameMode can fly freely. AllowsFlying() bool // AllowsInteraction specifies if a player with this GameMode can interact with the world through entities or if it // can use items in the world. AllowsInteraction() bool // Visible specifies if a player with this GameMode can be visible to other players. If false, the player will be // invisible under any circumstance. Visible() bool } // GameModeSurvival represents the survival game mode: Players with this game mode have limited supplies and // can break blocks using only the right tools. type GameModeSurvival struct{} // AllowsEditing ... func (GameModeSurvival) AllowsEditing() bool { return true } // AllowsTakingDamage ... func (GameModeSurvival) AllowsTakingDamage() bool { return true } // CreativeInventory ... func (GameModeSurvival) CreativeInventory() bool { return false } // HasCollision ... func (GameModeSurvival) HasCollision() bool { return true } // AllowsFlying ... func (GameModeSurvival) AllowsFlying() bool { return false } // AllowsInteraction ... func (GameModeSurvival) AllowsInteraction() bool { return true } // Visible ... func (GameModeSurvival) Visible() bool { return true } // GameModeCreative represents the creative game mode: Players with this game mode have infinite blocks and // items and can break blocks instantly. Players with creative mode can also fly. type GameModeCreative struct{} // AllowsEditing ... func (GameModeCreative) AllowsEditing() bool { return true } // AllowsTakingDamage ... func (GameModeCreative) AllowsTakingDamage() bool { return false } // CreativeInventory ... func (GameModeCreative) CreativeInventory() bool { return true } // HasCollision ... func (GameModeCreative) HasCollision() bool { return true } // AllowsFlying ... func (GameModeCreative) AllowsFlying() bool { return true } // AllowsInteraction ... func (GameModeCreative) AllowsInteraction() bool { return true } // Visible ... func (GameModeCreative) Visible() bool { return true } // GameModeAdventure represents the adventure game mode: Players with this game mode cannot edit the world // (placing or breaking blocks). type GameModeAdventure struct{} // AllowsEditing ... func (GameModeAdventure) AllowsEditing() bool { return false } // AllowsTakingDamage ... func (GameModeAdventure) AllowsTakingDamage() bool { return true } // CreativeInventory ... func (GameModeAdventure) CreativeInventory() bool { return false } // HasCollision ... func (GameModeAdventure) HasCollision() bool { return true } // AllowsFlying ... func (GameModeAdventure) AllowsFlying() bool { return false } // AllowsInteraction ... func (GameModeAdventure) AllowsInteraction() bool { return true } // Visible ... func (GameModeAdventure) Visible() bool { return true } // GameModeSpectator represents the spectator game mode: Players with this game mode cannot interact with the // world and cannot be seen by other players. GameModeSpectator players can fly, like creative mode, and can // move through blocks. type GameModeSpectator struct{} // AllowsEditing ... func (GameModeSpectator) AllowsEditing() bool { return false } // AllowsTakingDamage ... func (GameModeSpectator) AllowsTakingDamage() bool { return false } // CreativeInventory ... func (GameModeSpectator) CreativeInventory() bool { return true } // HasCollision ... func (GameModeSpectator) HasCollision() bool { return false } // AllowsFlying ... func (GameModeSpectator) AllowsFlying() bool { return true } // AllowsInteraction ... func (GameModeSpectator) AllowsInteraction() bool { return true } // Visible ... func (GameModeSpectator) Visible() bool { return false }
server/world/game_mode.go
0.82176
0.626696
game_mode.go
starcoder
package plot import "math" // Length defines canvas space size. type Length = float64 // Point describes a canvas position or offset. type Point struct{ X, Y Length } // nanPoint describes a missing or invalid point. var nanPoint = Point{ X: math.NaN(), Y: math.NaN(), } // P is a convenience func for creating a point. func P(x, y Length) Point { return Point{x, y} } // Empty returns whether the point is (0, 0) func (a Point) Empty() bool { return a == Point{} } // Neg negates the point coordinates. func (a Point) Neg() Point { return Point{-a.X, -a.Y} } // Add calculates a + b. func (a Point) Add(b Point) Point { return Point{a.X + b.X, a.Y + b.Y} } // Sub calculates a - b. func (a Point) Sub(b Point) Point { return Point{a.X - b.X, a.Y - b.Y} } // Min returns the min coordinates of a and b. func (a Point) Min(b Point) Point { return Point{math.Min(a.X, b.X), math.Min(a.Y, b.Y)} } // Max returns the max coordinates of a and b. func (a Point) Max(b Point) Point { return Point{math.Max(a.X, b.X), math.Max(a.Y, b.Y)} } // Scale scales the point by v. func (a Point) Scale(v float64) Point { return Point{a.X * v, a.Y * v} } // XY returns x and y coordinates. func (a Point) XY() (x, y Length) { return a.X, a.Y } // Rect defines a position. type Rect struct{ Min, Max Point } // R is a convenience func for creating a rectangle. func R(x0, y0, x1, y1 Length) Rect { return Rect{Point{x0, y0}, Point{x1, y1}} } // Zero returns rect such that the top-left corner is at (0, 0) func (r Rect) Zero() Rect { return Rect{Point{0, 0}, r.Max.Sub(r.Min)} } // Empty returns whether the rectangle is empty. func (r Rect) Empty() bool { return r.Min.Empty() && r.Max.Empty() } // Size returns the size of the rect. func (r Rect) Size() Point { return r.Max.Sub(r.Min) } // Offset moves the given rectangle. func (r Rect) Offset(by Point) Rect { return Rect{r.Min.Add(by), r.Max.Add(by)} } // Shrink shrinks the rect by the sides. func (r Rect) Shrink(radius Point) Rect { return Rect{r.Min.Add(radius), r.Max.Sub(radius)} } // UnitLocation converts relative position to rect bounds. func (r Rect) UnitLocation(u Point) Point { return Point{ X: lerpUnit(u.X, r.Min.X, r.Max.X), Y: lerpUnit(u.Y, r.Min.Y, r.Max.Y), } } // Inset shrinks the rect by the given rect. func (r Rect) Inset(by Rect) Rect { return Rect{r.Min.Add(by.Min), r.Max.Sub(by.Max)} } // Points returns corners of the rectangle. func (r Rect) Points() []Point { return []Point{ r.Min, Point{r.Min.X, r.Max.Y}, r.Max, Point{r.Max.X, r.Min.Y}, r.Min, } } // Column returns a i-th column when the rect is split into count columns. func (r Rect) Column(i, count int) Rect { if count == 0 { return r } x0 := r.Min.X + float64(i)*(r.Max.X-r.Min.X)/float64(count) x1 := r.Min.X + float64(i+1)*(r.Max.X-r.Min.X)/float64(count) return R(x0, r.Min.Y, x1, r.Max.Y) } // Row returns a i-th row when the rect is split into count rows. func (r Rect) Row(i, count int) Rect { if count == 0 { return r } y0 := r.Min.Y + float64(i)*(r.Max.Y-r.Min.Y)/float64(count) y1 := r.Min.Y + float64(i+1)*(r.Max.Y-r.Min.Y)/float64(count) return R(r.Min.X, y0, r.Max.X, y1) } // Convenience functions // Ps creates points from pairs. func Ps(cs ...Length) []Point { if len(cs)%2 != 0 { panic("must give x, y pairs") } ps := make([]Point, len(cs)/2) for i := range ps { ps[i] = Point{cs[i*2], cs[i*2+1]} } return ps } // Points creates a slice of points by combining two slices. // If x or y is nil, then it will enumerate them with indices. func Points(x, y []float64) []Point { n := len(x) if n < len(y) { n = len(y) } points := make([]Point, 0, n) for i := 0; i < n; i++ { var p Point if i < len(x) { p.X = x[i] } else { p.X = float64(i) } if i < len(y) { p.Y = y[i] } else { p.Y = float64(i) } points = append(points, p) } return points }
geom.go
0.927585
0.741066
geom.go
starcoder
package ast import ( "bytes" "strings" "Gengo/token" ) // Node A single node in the AST. type Node interface { TokenLiteral() string String() string } // Statement represents a statement node. type Statement interface { Node // Used to help the compiler tell the difference between a Statement and an Expression. statementNode() } // Expression represents an expression node. type Expression interface { Node expressionNode() } // Program consists of an array of statement nodes. type Program struct { Statements []Statement } // TokenLiteral The literal value of the token. Used only for debugging and testing. func (p *Program) TokenLiteral() string { if len(p.Statements) > 0 { return p.Statements[0].TokenLiteral() } return "" } func (p *Program) String() string { var out bytes.Buffer for _, s := range p.Statements { out.WriteString(s.String()) } return out.String() } // LetStatement Are used to assign a value to an identifier. type LetStatement struct { Token token.Token Name *Identifier Value Expression } // TokenLiteral The literal value of the token. func (ls *LetStatement) TokenLiteral() string { return ls.Token.Literal } func (ls *LetStatement) String() string { var out bytes.Buffer out.WriteString(ls.TokenLiteral() + " " + ls.Name.String() + " = ") if ls.Value != nil { out.WriteString(ls.Value.String()) } out.WriteString(";") return out.String() } func (ls *LetStatement) statementNode() {} // Identifier The name a value is assigned to. type Identifier struct { Token token.Token Value string } // TokenLiteral The literal value of the token. func (i *Identifier) TokenLiteral() string { return i.Token.Literal } func (i *Identifier) String() string { return i.Value } func (i *Identifier) expressionNode() {} // StringLiteral The value of a string. type StringLiteral struct { Token token.Token Value string } // TokenLiteral The literal value of the token. func (sl *StringLiteral) TokenLiteral() string { return sl.Token.Literal } func (sl *StringLiteral) String() string { return sl.Token.Literal } func (sl *StringLiteral) expressionNode() {} // ReturnStatement Used to return a value from a function. type ReturnStatement struct { Token token.Token ReturnValue Expression } // TokenLiteral The literal value of the token. func (rs *ReturnStatement) TokenLiteral() string { return rs.Token.Literal } func (rs *ReturnStatement) String() string { var out bytes.Buffer out.WriteString(rs.TokenLiteral() + " ") if rs.ReturnValue != nil { out.WriteString(rs.ReturnValue.String()) } out.WriteString(";") return out.String() } func (rs *ReturnStatement) statementNode() {} // ExpressionStatement An expression is something that returns a value. type ExpressionStatement struct { Token token.Token // first token of the expression Expression Expression } // TokenLiteral The literal value of the token. func (es *ExpressionStatement) TokenLiteral() string { return es.Token.Literal } func (es *ExpressionStatement) String() string { if es.Expression != nil { return es.Expression.String() } return "" } func (es *ExpressionStatement) statementNode() {} // IntegerLiteral A literal integer type IntegerLiteral struct { Token token.Token Value int64 } // TokenLiteral The literal value of the token. func (il *IntegerLiteral) TokenLiteral() string { return il.Token.Literal } func (il *IntegerLiteral) String() string { return il.Token.Literal } func (il *IntegerLiteral) expressionNode() { } // FloatLiteral A literal float type FloatLiteral struct { Token token.Token Value float64 } // TokenLiteral The literal value of the token. func (fl *FloatLiteral) TokenLiteral() string { return fl.Token.Literal } func (fl *FloatLiteral) String() string { return fl.Token.Literal } func (fl *FloatLiteral) expressionNode() { } // PrefixExpression Prefixes an expression. Like `-5`, `!true`, `-add(1,2)` type PrefixExpression struct { Token token.Token Operator string Right Expression } // TokenLiteral The literal value of the token. func (pe *PrefixExpression) TokenLiteral() string { return pe.Token.Literal } func (pe *PrefixExpression) String() string { return "(" + pe.Operator + pe.Right.String() + ")" } func (pe *PrefixExpression) expressionNode() {} // InfixExpression An infix expression. type InfixExpression struct { Token token.Token // The operator token, e.g. + Left Expression Operator string Right Expression } // TokenLiteral The literal value of the token. func (oe *InfixExpression) TokenLiteral() string { return oe.Token.Literal } func (oe *InfixExpression) String() string { return "(" + oe.Left.String() + " " + oe.Operator + " " + oe.Right.String() + ")" } func (oe *InfixExpression) expressionNode() {} // Boolean A boolean value. type Boolean struct { Token token.Token Value bool } // TokenLiteral The literal value of the token. func (b *Boolean) TokenLiteral() string { return b.Token.Literal } func (b *Boolean) String() string { return b.Token.Literal } func (b *Boolean) expressionNode() {} // IfExpression An if expression. type IfExpression struct { Token token.Token // the 'if' token Condition Expression Consequence *BlockStatement Alternative *BlockStatement } // TokenLiteral The literal value of the token. func (ie *IfExpression) TokenLiteral() string { return ie.Token.Literal } func (ie *IfExpression) String() string { var out bytes.Buffer out.WriteString("if (" + ie.Condition.String() + ")") out.WriteString(" { " + ie.Consequence.String() + " }") if ie.Alternative != nil { out.WriteString(" else { " + ie.Alternative.String() + " }") } return out.String() } func (ie *IfExpression) expressionNode() {} // BlockStatement A block of code. type BlockStatement struct { Token token.Token // the { token Statements []Statement } // TokenLiteral The literal value of the token. func (bs *BlockStatement) TokenLiteral() string { return bs.Token.Literal } func (bs *BlockStatement) String() string { var out bytes.Buffer for _, s := range bs.Statements { out.WriteString(s.String()) } return out.String() } func (bs *BlockStatement) statementNode() {} // FunctionLiteral A function literal. type FunctionLiteral struct { Token token.Token // The 'fn' token Parameters []*Identifier Body *BlockStatement } // TokenLiteral The literal value of the token. func (fl *FunctionLiteral) TokenLiteral() string { return fl.Token.Literal } func (fl *FunctionLiteral) String() string { var out bytes.Buffer var params []string for _, p := range fl.Parameters { params = append(params, p.String()) } out.WriteString(fl.TokenLiteral()) out.WriteString("(") out.WriteString(strings.Join(params, ", ")) out.WriteString(") { ") out.WriteString(fl.Body.String()) out.WriteString(" }") return out.String() } func (fl *FunctionLiteral) expressionNode() {} // CallExpression A call expression. type CallExpression struct { Token token.Token // the '(' token Function Expression // Identifier or FunctionLiteral Arguments []Expression } // TokenLiteral The literal value of the token. func (ce *CallExpression) TokenLiteral() string { return ce.Token.Literal } func (ce *CallExpression) String() string { var out bytes.Buffer var args []string for _, a := range ce.Arguments { args = append(args, a.String()) } out.WriteString(ce.Function.String()) out.WriteString("(") out.WriteString(strings.Join(args, ", ")) out.WriteString(")") return out.String() } func (ce *CallExpression) expressionNode() {} // ArrayLiteral An array literal. type ArrayLiteral struct { Token token.Token // the '[' token Elements []Expression } // TokenLiteral The literal value of the token. func (al *ArrayLiteral) TokenLiteral() string { return al.Token.Literal } func (al *ArrayLiteral) String() string { var elements []string for _, el := range al.Elements { elements = append(elements, el.String()) } return "[" + strings.Join(elements, ", ") + "]" } func (al *ArrayLiteral) expressionNode() {} // HashLiteral A hash literal. type HashLiteral struct { Token token.Token // the '{' token Pairs map[Expression]Expression } // TokenLiteral The literal value of the token. func (hl *HashLiteral) TokenLiteral() string { return hl.Token.Literal } func (hl *HashLiteral) String() string { var pairs []string for key, value := range hl.Pairs { pairs = append(pairs, key.String()+":"+value.String()) } return "{" + strings.Join(pairs, ", ") + "}" } func (hl *HashLiteral) expressionNode() {} // IndexExpression An expression to get a value in an array. type IndexExpression struct { Token token.Token // the [ token Left Expression Index Expression } // TokenLiteral The literal value of the token. func (ie *IndexExpression) TokenLiteral() string { return ie.Token.Literal } func (ie *IndexExpression) String() string { return "(" + ie.Left.String() + "[" + ie.Index.String() + "])" } func (ie *IndexExpression) expressionNode() {}
ast/ast.go
0.771757
0.487673
ast.go
starcoder
// Package day22 solves AoC 2018 day 22. package day22 import ( "container/heap" "fmt" "github.com/fis/aoc/glue" "github.com/fis/aoc/util" ) func init() { glue.RegisterSolver(2018, 22, glue.LineSolver(solve)) } func solve(lines []string) ([]string, error) { var depth, tX, tY int if len(lines) != 2 { return nil, fmt.Errorf("expected 2 lines, got %d", len(lines)) } else if _, err := fmt.Sscanf(lines[0], "depth: %d", &depth); err != nil { return nil, fmt.Errorf("bad depth line: %s: %w", lines[0], err) } else if _, err := fmt.Sscanf(lines[1], "target: %d,%d", &tX, &tY); err != nil { return nil, fmt.Errorf("bad target line: %s: %w", lines[1], err) } cave := newCave(depth, tX, tY) part1 := cave.totalRisk() part2 := cave.shortestPath() return glue.Ints(part1, part2), nil } type cave struct { depth int tX, tY int erosionCache map[util.P]int } type rType int const ( rocky rType = 0 wet rType = 1 narrow rType = 2 ) func newCave(depth, tX, tY int) *cave { return &cave{depth: depth, tX: tX, tY: tY, erosionCache: make(map[util.P]int)} } func (c *cave) erosion(x, y int) int { switch { case x == 0 && y == 0, x == c.tX && y == c.tY: return c.depth % 20183 case y == 0: return (16807*x + c.depth) % 20183 case x == 0: return (48271*y + c.depth) % 20183 default: if cached, ok := c.erosionCache[util.P{x, y}]; ok { return cached } e := (c.erosion(x-1, y)*c.erosion(x, y-1) + c.depth) % 20183 c.erosionCache[util.P{x, y}] = e return e } } func (c *cave) rType(x, y int) rType { return rType(c.erosion(x, y) % 3) } func (c *cave) totalRisk() (risk int) { for y := 0; y <= c.tY; y++ { for x := 0; x <= c.tX; x++ { risk += int(c.rType(x, y)) } } return risk } type tool int const ( noTool tool = iota climbingGear torch ) func (t tool) compatible(r rType) bool { switch r { case rocky: return t == climbingGear || t == torch case wet: return t == noTool || t == climbingGear case narrow: return t == noTool || t == torch } return false } type state struct { at util.P equip tool } type path struct { s state d int hd int } type pathq []path func (c *cave) shortestPath() int { from := state{at: util.P{0, 0}, equip: torch} to := state{at: util.P{c.tX, c.tY}, equip: torch} dist := map[state]int{from: 0} fringe := pathq{{s: from, d: 0, hd: util.DistM(from.at, to.at)}} for len(fringe) > 0 { p := heap.Pop(&fringe).(path) if p.s == to { return p.d } if od := dist[p.s]; od < p.d { continue // path no longer relevant } for _, q := range p.s.at.Neigh() { if q.X < 0 || q.Y < 0 || !p.s.equip.compatible(c.rType(q.X, q.Y)) { continue } qp := path{s: state{at: q, equip: p.s.equip}, d: p.d + 1, hd: p.d + 1 + util.DistM(q, to.at)} if od, ok := dist[qp.s]; ok && od <= qp.d { continue } dist[qp.s] = qp.d heap.Push(&fringe, qp) } for t := noTool; t <= torch; t++ { if !t.compatible(c.rType(p.s.at.X, p.s.at.Y)) { continue } tp := path{s: state{at: p.s.at, equip: t}, d: p.d + 7, hd: p.d + 7 + util.DistM(p.s.at, to.at)} if od, ok := dist[tp.s]; ok && od <= tp.d { continue } dist[tp.s] = tp.d heap.Push(&fringe, tp) } } return -1 // can't get there from here } func (q pathq) Len() int { return len(q) } func (q pathq) Less(i, j int) bool { return q[i].hd < q[j].hd } func (q pathq) Swap(i, j int) { q[i], q[j] = q[j], q[i] } func (q *pathq) Push(x interface{}) { *q = append(*q, x.(path)) } func (q *pathq) Pop() interface{} { old, n := *q, len(*q) path := old[n-1] *q = old[0 : n-1] return path }
2018/day22/day22.go
0.636579
0.407923
day22.go
starcoder
package values // Unifier can be used to verify whether a list of values has equal entries. type Unifier struct { state unifierState } // NewUnifier returns a new instance. func NewUnifier() Unifier { return Unifier{state: unifierInitState{}} } // UnifierFor returns a unifier for a single value. func UnifierFor(value interface{}) Unifier { unifier := NewUnifier() unifier.Add(value) return unifier } // Add unifies the given value to the current state. // The given value must be comparable. func (u *Unifier) Add(value interface{}) { u.state = u.state.add(value) } // Unified returns the result of the unification. // If all values that were added to the unifier were equal, then the first // added value will be returned. Otherwise, nil will be returned. func (u *Unifier) Unified() interface{} { return u.state.unified() } // IsUnique returns true if the unifier has received only equal values. func (u Unifier) IsUnique() bool { return u.state.isUnique() } // IsEmpty returns true if the unifier has not received any value. func (u Unifier) IsEmpty() bool { return (u.state == nil) || u.state.isEmpty() } type unifierState interface { add(value interface{}) unifierState unified() interface{} isUnique() bool isEmpty() bool } type unifierInitState struct{} func (state unifierInitState) add(value interface{}) unifierState { return unifierMatchedState{value: value} } func (state unifierInitState) unified() interface{} { return nil } func (state unifierInitState) isUnique() bool { return false } func (state unifierInitState) isEmpty() bool { return true } type unifierMatchedState struct { value interface{} } func (state unifierMatchedState) add(value interface{}) unifierState { if state.value == value { return state } return unifierMismatchedState{} } func (state unifierMatchedState) unified() interface{} { return state.value } func (state unifierMatchedState) isUnique() bool { return true } func (state unifierMatchedState) isEmpty() bool { return false } type unifierMismatchedState struct{} func (state unifierMismatchedState) add(value interface{}) unifierState { return state } func (state unifierMismatchedState) unified() interface{} { return nil } func (state unifierMismatchedState) isUnique() bool { return false } func (state unifierMismatchedState) isEmpty() bool { return false }
editor/values/Unifier.go
0.884408
0.558327
Unifier.go
starcoder
package pkg import ( wr "github.com/mroth/weightedrand" "math/rand" "time" ) // OptimizeType describes an optimization type type OptimizeType string const ( Load OptimizeType = "Load" Network OptimizeType = "Network" Latency OptimizeType = "Latency" ) // StrategyOptions describes the quorum system strategy options. type StrategyOptions struct { // Optimize defines the target optimization. Optimize OptimizeType // LoadLimit defines the limit on the load limit. LoadLimit *float64 // NetworkLimit defines the limit on the network limit. NetworkLimit *float64 // LatencyLimit defines the limit on the latency. LatencyLimit *float64 // ReadFraction defines the workflow distribution for the read operations. ReadFraction Distribution // WriteFraction defines the workflow distribution for the write operations. WriteFraction Distribution // F r ∈ R is F-resilient for some integer f if despite removing // any f nodes from r, r is still a read quorum F uint } // Strategy defines a strategy related to a QuorumSystem. type Strategy struct { Qs QuorumSystem SigmaR Sigma SigmaW Sigma nodeToReadProbability map[Node]Probability nodeToWriteProbability map[Node]Probability } // Sigma defines the probabilities of a specific Strategy. Each Expr (quorum) has a probability of being choose associated. type Sigma struct { Values []SigmaRecord } // SigmaRecord defines as ExprSet that represents a quorum and the probability of being chosen. type SigmaRecord struct { Quorum ExprSet Probability Probability } // NewStrategy returns a new Strategy given a QuorumSystem and the Sigma related to the read/writes. func NewStrategy(quorumSystem QuorumSystem, sigmaR Sigma, sigmaW Sigma) Strategy { newStrategy := Strategy{SigmaR: sigmaR, SigmaW: sigmaW, Qs: quorumSystem} xReadProbability := make(map[Node]float64) for _, sr := range sigmaR.Values { for q := range sr.Quorum { xReadProbability[q.(Node)] += sr.Probability } } xWriteProbability := make(map[Node]float64) for _, sr := range sigmaW.Values { for q := range sr.Quorum { xWriteProbability[q.(Node)] += sr.Probability } } newStrategy.nodeToWriteProbability = xWriteProbability newStrategy.nodeToReadProbability = xReadProbability return newStrategy } // GetReadQuorum returns a ExprSet representing a quorum of the strategy. // The method return the quorum based on its probability. func (s Strategy) GetReadQuorum() ExprSet { rand.Seed(time.Now().UTC().UnixNano()) // always seed random! criteria := make([]wr.Choice, 0) weightSum := 0.0 for _, w := range s.SigmaR.Values { weightSum += w.Probability } for _, sigmaRecord := range s.SigmaR.Values { criteria = append(criteria, wr.Choice{Item: sigmaRecord.Quorum, Weight: uint(sigmaRecord.Probability * 10)}) } chooser, _ := wr.NewChooser(criteria...) result := chooser.Pick().(ExprSet) return result } // GetWriteQuorum returns a ExprSet representing a quorum of the strategy. // The method return the quorum based on its probability. func (s Strategy) GetWriteQuorum() ExprSet { rand.Seed(time.Now().UTC().UnixNano()) // always seed random! criteria := make([]wr.Choice, 0) weightSum := 0.0 for _, w := range s.SigmaW.Values { weightSum += w.Probability } for _, sigmaRecord := range s.SigmaW.Values { criteria = append(criteria, wr.Choice{Item: sigmaRecord.Quorum, Weight: uint(sigmaRecord.Probability * 10)}) } chooser, _ := wr.NewChooser(criteria...) result := chooser.Pick().(ExprSet) return result } // Load calculates and returns the load of the strategy given a read and write distribution. func (s Strategy) Load(rf *Distribution, wf *Distribution) (float64, error) { d, err := canonicalizeReadsWrites(rf, wf) if err != nil { return 0, err } sum := 0.0 for fr, p := range d { sum += p * s.getMaxLoad(fr) } return sum, nil } // Capacity calculates and returns the capacity of the strategy given a read and write distribution. func (s Strategy) Capacity(rf *Distribution, wf *Distribution) (float64, error) { d, err := canonicalizeReadsWrites(rf, wf) if err != nil { return -1, err } sum := 0.0 for fr, p := range d { sum += p * 1.0 / s.getMaxLoad(fr) } return sum, nil } // NetworkLoad calculates and returns the network load of the strategy given a read and write Distribution. func (s Strategy) NetworkLoad(rf *Distribution, wf *Distribution) (float64, error) { d, err := canonicalizeReadsWrites(rf, wf) if err != nil { return -1, err } frsum := 0.0 for fr, p := range d { frsum += p * fr } reads := 0.0 for _, sigma := range s.SigmaR.Values { reads += frsum * float64(len(sigma.Quorum)) * sigma.Probability } writes := 0.0 for _, sigma := range s.SigmaW.Values { writes += (1 - frsum) * float64(len(sigma.Quorum)) * sigma.Probability } total := reads + writes return total, nil } // Latency calculates and returns the latency of the strategy given a read and write Distribution. func (s Strategy) Latency(rf *Distribution, wf *Distribution) (float64, error) { d, err := canonicalizeReadsWrites(rf, wf) if err != nil { return -1, err } frsum := 0.0 for fr, p := range d { frsum += p * fr } reads := 0.0 for _, rq := range s.SigmaR.Values { nodes := make([]Node, 0) for n := range rq.Quorum { nodes = append(nodes, s.Qs.GetNodeByName(n.String())) } v, err := s.Qs.readQuorumLatency(nodes) if err != nil { return -1, err } reads += float64(v) * rq.Probability } writes := 0.0 for _, wq := range s.SigmaW.Values { nodes := make([]Node, 0) for n := range wq.Quorum { nodes = append(nodes, s.Qs.GetNodeByName(n.String())) } v, err := s.Qs.writeQuorumLatency(nodes) if err != nil { return -1, err } writes += float64(v) * wq.Probability } total := frsum*reads + (1-frsum)*writes return total, nil } // NodeLoad returns the load of a specific Node given a read and write Distribution. func (s Strategy) NodeLoad(node Node, rf *Distribution, wf *Distribution) (float64, error) { d, err := canonicalizeReadsWrites(rf, wf) if err != nil { return -1, err } sum := 0.0 for fr, p := range d { sum += p * s.getNodeLoad(node, fr) } return sum, nil } // NodeUtilization returns the utilization of a specific Node given a read and write Distribution. func (s Strategy) NodeUtilization(node Node, rf *Distribution, wf *Distribution) (*float64, error) { d, err := canonicalizeReadsWrites(rf, wf) if err != nil { return nil, err } sum := 0.0 for fr, p := range d { sum += p * s.nodeUtilization(node, fr) } return &sum, nil } // NodeThroughput returns the throughput of a specific Node given a read and write Distribution. func (s Strategy) NodeThroughput(node Node, rf *Distribution, wf *Distribution) (*float64, error) { d, err := canonicalizeReadsWrites(rf, wf) if err != nil { return nil, err } sum := 0.0 for fr, p := range d { sum += p * s.nodeThroughput(node, fr) } return &sum, nil } func (s Strategy) String() string { return "TODO" } // getMaxLoad returns the max load of the strategy for a specific fraction. func (s Strategy) getMaxLoad(fr float64) float64 { max := 0.0 for n := range s.Qs.GetNodes() { if s.getNodeLoad(n, fr) > max { max = s.getNodeLoad(n, fr) } } return max } // getNodeLoad returns the load of a node for a given probability. func (s Strategy) getNodeLoad(node Node, fr float64) float64 { fw := 1 - fr return fr*s.nodeToReadProbability[node]/float64(*node.ReadCapacity) + fw*s.nodeToWriteProbability[node]/float64(*node.WriteCapacity) } func (s Strategy) nodeUtilization(node Node, fr float64) float64 { return s.getNodeLoad(node, fr) / s.getMaxLoad(fr) } func (s Strategy) nodeThroughput(node Node, fr float64) float64 { capacity := 1 / s.getMaxLoad(fr) fw := 1 - fr return capacity * (fr*s.nodeToReadProbability[node] + fw*s.nodeToWriteProbability[node]) } func initializeStrategyOptions(initOptions StrategyOptions) func(options *StrategyOptions) error { init := func(options *StrategyOptions) error { options.Optimize = initOptions.Optimize options.LatencyLimit = initOptions.LatencyLimit options.NetworkLimit = initOptions.NetworkLimit options.LoadLimit = initOptions.LoadLimit options.F = initOptions.F options.ReadFraction = initOptions.ReadFraction options.WriteFraction = initOptions.WriteFraction return nil } return init }
pkg/strategy.go
0.848376
0.608245
strategy.go
starcoder
package arrays import ( "math" "strconv" ) func Includes(arr []int, val int) bool { for i := 0; i < len(arr); i++ { if arr[i] == val { return true } } return false } func Remove(arr []int, i int) []int { return append(arr[:i], arr[i+1:]...) } func Sum(arr []float64) float64 { var s float64 for i := 0; i < len(arr); i++ { s += arr[i] } return s } func SumInt(arr []int) int { var s int for i := 0; i < len(arr); i++ { s += arr[i] } return s } func EuclideanDistance(a, b []float64) float64 { var s float64 if len(a) != len(b) { panic("vectors not equal size") } for i := range a { s += math.Pow(a[i]-b[i], 2) } return math.Sqrt(s) } func floatArrayToString(a []float64) string { var s string for i := range a { s += strconv.FormatFloat(a[i], 'E', -1, 64) if i < len(a)-1 { s += "," } } return s } func IdentityMatrix(n int) [][]float64 { var matrix = make([][]float64, n) for i := 0; i < n; i++ { row := make([]float64, n) row[i] = 1 matrix[i] = row } return matrix } func MiddleVector(a, b []float64) []float64 { middle := make([]float64, len(a)) for i := range a { middle[i] = (a[i] + b[i]) / 2 } return middle } func Normalise(a []float64) []float64 { s := Sum(a) var normalised = make([]float64, len(a)) for i := range a { normalised[i] = a[i] / s } return normalised } //DistributedTriangleVectors creates a n*m matrix where n = objectives and m = population size. //The algorithm creates new vertices in the n dimensional space until the row number is bigger than m. //With this approach an even distribution is not always possible, but a good distribution can be reached. func DistributedTriangleVectors(objectives, populationSize int) [][]float64 { vertices := IdentityMatrix(objectives) calculated := map[string]bool{} for i := range vertices { calculated[floatArrayToString(vertices[i])] = true } for len(vertices) < populationSize { k := len(vertices) for i := 0; i < k; i++ { for j := i; j < k; j++ { if i != j { vertex := MiddleVector(vertices[i], vertices[j]) if calculated[floatArrayToString(vertex)] == true { continue } else { calculated[floatArrayToString(vertex)] = true vertices = append(vertices, vertex) } } } } } return vertices } //UniformDistributedVectors generates a set of uniformly distributed vectors func UniformDistributedVectors(m, H int) []Vector { buf := make([]int, m) var result []Vector for true { vector := Vector{Size: m} vector.Zeros() for i := 0; i < m-1; i++ { vector.Set(i, float64(buf[i+1]-buf[i])/float64(H)) } vector.Set(m-1, float64(H-buf[m-1])/float64(H)) result = append(result, vector) var p int for p = m - 1; p != 0 && buf[p] == H; p-- { } if p == 0 { break } buf[p]++ for p = p + 1; p != m; p++ { buf[p] = buf[p-1] } } return result[1 : len(result)-1] } //NearestNeighbour calculates the closest T vectors for vector i in the set arr. //NOTE the implementation makes the assumption that the vector i is it's own closest neighbour. //The MOEA/D framework also makes this assumption func NearestNeighbour(arr []Vector, i, T int) []int { neighbourIndexes := make([]int, T) for x := range neighbourIndexes { neighbourIndexes[x] = -1 } for x := 0; x < T; x++ { distance := math.MaxFloat64 index := -1 for j := range arr { dist := arr[i].Dist(arr[j]) if dist < distance && !Includes(neighbourIndexes, j) { distance = dist index = j } } neighbourIndexes[x] = index } return neighbourIndexes } func Middle(a, b []float64) []float64 { middle := make([]float64, len(a)) for i := range a { middle[i] = (a[i] + b[i]) / 2 } return middle } // Zeros2DFloat64 creates a new 2D array with dimension defined by outerlength and innerlength. All values are set to 0 func Zeros2DFloat64(outerLength, innerLength int) [][]float64 { arr := make([][]float64, outerLength) for i := range arr { arr[i] = make([]float64, innerLength) } return arr } func IncreasingIntsN(n int) []int { array := make([]int, n) for i := 0; i < n; i++ { array[i] = i } return array } func EqualInterval(length int, min, max float64) (interval [][]float64) { for i := 0; i < length; i++ { interval = append(interval, []float64{min, max}) } return interval } func Min(floats ...float64) (min float64) { min = math.MaxFloat64 for _, f := range floats { min = math.Min(f, min) } return min }
arrays/arrays.go
0.655997
0.441011
arrays.go
starcoder
package cfg import "github.com/gofoji/foji/stringlist" // Merge merges all properties from an ancestor Config. func (c Config) Merge(from Config) Config { c.Formats = c.Formats.Merge(from.Formats) c.Files = c.Files.Merge(from.Files) c.Processes = c.Processes.Merge(from.Processes).ApplyFormat(c.Formats) return c } // ApplyFormat merges linked format into each process config. func (pp Processes) ApplyFormat(formats Processes) Processes { for key, p := range pp { f, ok := formats[p.Format] if ok { p = p.Merge(f) } pp[key] = p } return pp } // Merge merges all properties from an ancestor Processes. func (pp Processes) Merge(from Processes) Processes { out := pp if out == nil { out = Processes{} } else { for key, p := range pp { p.ID = key out[key] = p } } for key, p := range from { to, ok := out[key] if ok { to = to.Merge(p) } else { to = p } to.ID = key out[key] = to } return out } // mergeOutputs merges all output lists, and has the special function to treat "-" as an empty array. func mergeOutputs(to, from stringlist.StringMap) stringlist.StringMap { if len(to) == 0 { return from } if len(to) == 1 { // Special case to disable inherited output if _, ok := to["-"]; ok { return stringlist.StringMap{} } } return to } // Merge merges all properties from an ancestor Output. func (o Output) Merge(from Output) Output { result := o if result == nil { result = Output{} } for k, v := range from { result[k] = mergeOutputs(result[k], v) } return result } // Merge merges all properties from an ancestor Process. func (p Process) Merge(from Process) Process { if p.Case == "" { p.Case = from.Case } if p.Format == "" { p.Format = from.Format } if len(p.Post) == 0 { p.Post = from.Post } if len(p.Resources) == 0 { p.Resources = from.Resources } p.Files = p.Files.Merge(from.Files) p.Output = p.Output.Merge(from.Output) p.Maps = p.Maps.Merge(from.Maps) p.Params = p.Params.Merge(from.Params) return p } // Merge merges all properties from an ancestor Maps. func (m Maps) Merge(from Maps) Maps { m.Type = MergeTypesMaps(from.Type, m.Type) m.Nullable = MergeTypesMaps(from.Nullable, m.Nullable) m.Name = MergeTypesMaps(from.Name, m.Name) m.Case = MergeTypesMaps(from.Case, m.Case) return m } // Merge merges all properties from an ancestor ParamMap. func (pp ParamMap) Merge(from ParamMap) ParamMap { out := pp if out == nil { out = ParamMap{} } for key, p := range from { _, ok := out[key] if !ok { out[key] = p } } return out } // Merge merges all properties from an ancestor FileInputMap. func (ff FileInputMap) Merge(from FileInputMap) FileInputMap { out := ff if out == nil { out = FileInputMap{} } for key, p := range from { _, ok := out[key] if !ok { out[key] = p } } return out } // Merge merges all properties from an ancestor FileInput. func (f FileInput) Merge(from FileInput) FileInput { if len(f.Files) > 0 || len(f.Filter) > 0 || len(f.Rewrite) > 0 { return f } return from } // Merge merges all properties from an ancestor TypeMap. func MergeTypesMaps(maps ...stringlist.StringMap) stringlist.StringMap { result := stringlist.StringMap{} for _, m := range maps { for k, v := range m { result[k] = v } } return result }
cfg/merge.go
0.739422
0.437403
merge.go
starcoder
package blockchain const erc20ABI = `[ { "constant": false, "inputs": [ { "name": "_spender", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "approve", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "totalSupply", "outputs": [ { "name": "supply", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_from", "type": "address" }, { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "decimals", "outputs": [ { "name": "digits", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "_owner", "type": "address" } ], "name": "balanceOf", "outputs": [ { "name": "balance", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "_value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "name": "success", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "_owner", "type": "address" }, { "name": "_spender", "type": "address" } ], "name": "allowance", "outputs": [ { "name": "remaining", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "_owner", "type": "address" }, { "indexed": true, "name": "_spender", "type": "address" }, { "indexed": false, "name": "_value", "type": "uint256" } ], "name": "Approval", "type": "event" } ]`
common/blockchain/erc20_abi.go
0.645008
0.474205
erc20_abi.go
starcoder
package day12 import ( "bufio" "fmt" "math" "os" "regexp" "strconv" ) type position struct { vals [3]int } func newPos(x, y, z int) position { return position{[3]int{x, y, z}} } func (p position) String() string { return fmt.Sprintf("<x=%v, y=%v, z=%v>", p.vals[0], p.vals[1], p.vals[2]) } func (p position) equals(other position) bool { for i, val := range p.vals { if val != other.vals[i] { return false } } return true } func (p position) axisEquals(other position, axis int) bool { return p.vals[axis] == other.vals[axis] } type velocity struct { vals [3]int } func newVel(x, y, z int) velocity { return velocity{[3]int{x, y, z}} } func (v velocity) String() string { return fmt.Sprintf("<x=%v, y=%v, z=%v>", v.vals[0], v.vals[1], v.vals[2]) } func (v velocity) equals(other velocity) bool { for i, val := range v.vals { if val != other.vals[i] { return false } } return true } func (v velocity) axisEquals(other velocity, axis int) bool { return v.vals[axis] == other.vals[axis] } type moon struct { pos *position vel *velocity } func (m *moon) String() string { return fmt.Sprintf("pos=%v, vel=%v", *m.pos, *m.vel) } func (m *moon) equals(other *moon) bool { return m.pos.equals(*other.pos) && m.vel.equals(*other.vel) } func (m *moon) axisEquals(other *moon, axis int) bool { return m.pos.axisEquals(*other.pos, axis) && m.vel.axisEquals(*other.vel, axis) } func newMoon(pos position) *moon { vel := newVel(0, 0, 0) return &moon{&pos, &vel} } func (m *moon) gravitate(other *moon) { for i, val := range m.pos.vals { m.vel.vals[i] += relate(val, other.pos.vals[i]) } } func relate(this, other int) int { if this > other { return -1 } if this < other { return 1 } return 0 } func (m *moon) move() { for i, val := range m.vel.vals { m.pos.vals[i] += val } } func (m *moon) getEnergy() int { pot := addAbs(m.pos.vals) kin := addAbs(m.vel.vals) return pot * kin } func addAbs(vals [3]int) int { fx, fy, fz := float64(vals[0]), float64(vals[1]), float64(vals[2]) return int(math.Abs(fx) + math.Abs(fy) + math.Abs(fz)) } func run(fname string, steps int) (int, error) { moons, err := read(fname) if err != nil { return -1, err } for i := 0; i < steps; i++ { fmt.Printf("After %v steps\n", i) for _, m := range moons { fmt.Printf("%v\n", m) } for a, m := range moons { for b, o := range moons { if a == b { continue } m.gravitate(o) } } for _, m := range moons { m.move() } fmt.Println("") } fmt.Printf("After %v steps\n", steps) for _, m := range moons { fmt.Printf("%v\n", m) } rval := 0 for _, m := range moons { rval += m.getEnergy() } return rval, nil } func copyMoons(moons []*moon) []*moon { rval := make([]*moon, len(moons)) for i, m := range moons { rval[i] = newMoon(*m.pos) } return rval } func equal(moons, originals []*moon) bool { for i, m := range moons { if !m.equals(originals[i]) { return false } } return true } func axisEqual(moons, originals []*moon, axis int) bool { for i, m := range moons { if !m.axisEquals(originals[i], axis) { return false } } return true } func getAxisCycle(moons, originals []*moon, axis int) int64 { rval := int64(0) for !axisEqual(moons, originals, axis) || rval == 0 { for a, m := range moons { for b, o := range moons { if a == b { continue } m.vel.vals[axis] += relate(m.pos.vals[axis], o.pos.vals[axis]) } } for _, m := range moons { m.pos.vals[axis] += m.vel.vals[axis] } rval++ } return rval } func gcd(x, y int64) int64 { for y != 0 { x, y = y, x%y } return x } func lcm(x, y int64, others ...int64) int64 { rval := x * y / gcd(x, y) for _, val := range others { rval = lcm(rval, val) } return rval } func getCycle(fname string) (int64, error) { moons, err := read(fname) if err != nil { return -1, err } cycles := [3]int64{0, 0, 0} for i := 0; i < len(cycles); i++ { clones := copyMoons(moons) cycles[i] = getAxisCycle(clones, moons, i) } return lcm(cycles[0], cycles[1], cycles[2]), nil } func read(fname string) ([]*moon, error) { in, err := os.Open(fname) if err != nil { return nil, err } defer in.Close() re := regexp.MustCompile("^<x=(-?[0-9]+), y=(-?[0-9]+), z=(-?[0-9]+)>.*$") var rval []*moon scanner := bufio.NewScanner(in) for scanner.Scan() { line := scanner.Text() groups := re.FindStringSubmatch(line) if groups == nil { continue } fmt.Printf("groups: %v\n", groups) x, err := strconv.Atoi(groups[1]) if err != nil { return nil, err } y, err := strconv.Atoi(groups[2]) if err != nil { return nil, err } z, err := strconv.Atoi(groups[3]) if err != nil { return nil, err } rval = append(rval, newMoon(newPos(x, y, z))) } return rval, nil }
pkg/day12/moons.go
0.581303
0.409191
moons.go
starcoder
package bloomFilter import ( "ProbabilisticDataStructures/utils" "math" "github.com/bits-and-blooms/bitset" "github.com/spaolacci/murmur3" ) // BloomFilter is the struct that represents a Bloom Filter type BloomFilter struct { n uint m uint k uint e float64 bits *bitset.BitSet } // New creates a new Bloom Filter with size m and k hash functions func New(m uint, k uint) BloomFilter { n := computeCapacity(m, k) e := computeError(m, k, n) return newBF(n, e, m, k) } // NewFromSizeAndError creates a new Bloom Filter that can hold n elements with e false positive error func NewFromSizeAndError(n uint, e float64) BloomFilter { sizeM := computeSizeM(n, e) sizeK := computeSizeK(n, sizeM) return newBF(n, e, sizeM, sizeK) } // Insert inserts element into BF. Computational time: O(k) func (b *BloomFilter) Insert(element []byte) { positions := b.computeKHashPositions(element) for _, pos := range positions { b.bits.Set(pos) } } // Lookup returns true if element may belong to the BF and false if element does not belong to the BF. Computational time: O(k) func (b BloomFilter) Lookup(element []byte) bool { positions := b.computeKHashPositions(element) for _, pos := range positions { if !b.bits.Test(pos) { return false } } return true } // TotalSize returns an estimation (in bytes) of the size of the array that represents BF. func (b BloomFilter) TotalSize() uint { if b.m % utils.ByteSize == 0 { return b.m/utils.ByteSize } return b.m/utils.ByteSize + 1 } func newBF(n uint, e float64, m uint, k uint) BloomFilter { return BloomFilter{ n: n, e: e, m: m, k: k, bits: bitset.New(m), } } func (b BloomFilter) computeKHashPositions(element []byte) []uint { positions := make([]uint, 0) for i := uint(0); i < b.k; i++ { pos := computeHash(element, uint32(i)) % b.m positions = append(positions, pos) } return positions } func computeHash(element []byte, seed uint32) uint { return uint(murmur3.Sum64WithSeed(element, seed)) } func computeCapacity(m uint, k uint) uint { return uint(math.Floor(float64(m) / (float64(k)) * math.Log(2))) } func computeError(m uint, k uint, n uint) float64 { return math.Pow(1-math.Pow(math.E, -float64(k)*float64(n)/float64(m)), float64(k)) } func computeSizeM(n uint, error float64) uint { return uint(math.Ceil(-(float64(n) * math.Log(error)) / (math.Log(2) * math.Log(2)))) } func computeSizeK(n uint, sizeM uint) uint { return uint(math.Ceil((float64(sizeM) / float64(n)) * math.Log(2))) }
bloomFilter/bloomFilter.go
0.862844
0.512449
bloomFilter.go
starcoder
package main import ( . "github.com/mmcloughlin/avo/build" . "github.com/mmcloughlin/avo/operand" ) func main() { Package("github.com/mmcloughlin/avo/examples/returns") TEXT("Interval", NOSPLIT, "func(start, size uint64) (uint64, uint64)") Doc( "Interval returns the (start, end) of an interval with the given start and size.", "Demonstrates multiple unnamed return values.", ) start := Load(Param("start"), GP64()) size := Load(Param("size"), GP64()) end := size ADDQ(start, end) Store(start, ReturnIndex(0)) Store(end, ReturnIndex(1)) RET() TEXT("Butterfly", NOSPLIT, "func(x0, x1 float64) (y0, y1 float64)") Doc( "Butterfly performs a 2-dimensional butterfly operation: computes (x0+x1, x0-x1).", "Demonstrates multiple named return values.", ) x0 := Load(Param("x0"), XMM()) x1 := Load(Param("x1"), XMM()) y0, y1 := XMM(), XMM() MOVSD(x0, y0) ADDSD(x1, y0) MOVSD(x0, y1) SUBSD(x1, y1) Store(y0, Return("y0")) Store(y1, Return("y1")) RET() TEXT("Septuple", NOSPLIT, "func(byte) [7]byte") Doc( "Septuple returns an array of seven of the given byte.", "Demonstrates returning array values.", ) b := Load(ParamIndex(0), GP8()) for i := 0; i < 7; i++ { Store(b, ReturnIndex(0).Index(i)) } RET() TEXT("CriticalLine", NOSPLIT, "func(t float64) complex128") Doc( "CriticalLine returns the complex value 0.5 + it on Riemann's critical line.", "Demonstrates returning complex values.", ) t := Load(Param("t"), XMM()) half := XMM() MOVSD(ConstData("half", F64(0.5)), half) Store(half, ReturnIndex(0).Real()) Store(t, ReturnIndex(0).Imag()) RET() TEXT("NewStruct", NOSPLIT, "func(w uint16, p [2]float64, q uint64) Struct") Doc( "NewStruct initializes a Struct value.", "Demonstrates returning struct values.", ) w := Load(Param("w"), GP16()) x := Load(Param("p").Index(0), XMM()) y := Load(Param("p").Index(1), XMM()) q := Load(Param("q"), GP64()) Store(w, ReturnIndex(0).Field("Word")) Store(x, ReturnIndex(0).Field("Point").Index(0)) Store(y, ReturnIndex(0).Field("Point").Index(1)) Store(q, ReturnIndex(0).Field("Quad")) RET() Generate() }
examples/returns/asm.go
0.680454
0.42931
asm.go
starcoder
package mlpack /* #cgo CFLAGS: -I./capi -Wall #cgo LDFLAGS: -L. -lmlpack_go_kfn #include <capi/kfn.h> #include <stdlib.h> */ import "C" import "gonum.org/v1/gonum/mat" type KfnOptionalParam struct { Algorithm string Epsilon float64 InputModel *kfnModel K int LeafSize int Percentage float64 Query *mat.Dense RandomBasis bool Reference *mat.Dense Seed int TreeType string TrueDistances *mat.Dense TrueNeighbors *mat.Dense Verbose bool } func KfnOptions() *KfnOptionalParam { return &KfnOptionalParam{ Algorithm: "dual_tree", Epsilon: 0, InputModel: nil, K: 0, LeafSize: 20, Percentage: 1, Query: nil, RandomBasis: false, Reference: nil, Seed: 0, TreeType: "kd", TrueDistances: nil, TrueNeighbors: nil, Verbose: false, } } /* This program will calculate the k-furthest-neighbors of a set of points. You may specify a separate set of reference points and query points, or just a reference set which will be used as both the reference and query set. For example, the following will calculate the 5 furthest neighbors of eachpoint in input and store the distances in distances and the neighbors in neighbors: // Initialize optional parameters for Kfn(). param := mlpack.KfnOptions() param.K = 5 param.Reference = input distances, neighbors, _ := mlpack.Kfn(param) The output files are organized such that row i and column j in the neighbors output matrix corresponds to the index of the point in the reference set which is the j'th furthest neighbor from the point in the query set with index i. Row i and column j in the distances output file corresponds to the distance between those two points. Input parameters: - Algorithm (string): Type of neighbor search: 'naive', 'single_tree', 'dual_tree', 'greedy'. Default value 'dual_tree'. - Epsilon (float64): If specified, will do approximate furthest neighbor search with given relative error. Must be in the range [0,1). Default value 0. - InputModel (kfnModel): Pre-trained kFN model. - K (int): Number of furthest neighbors to find. Default value 0. - LeafSize (int): Leaf size for tree building (used for kd-trees, vp trees, random projection trees, UB trees, R trees, R* trees, X trees, Hilbert R trees, R+ trees, R++ trees, and octrees). Default value 20. - Percentage (float64): If specified, will do approximate furthest neighbor search. Must be in the range (0,1] (decimal form). Resultant neighbors will be at least (p*100) % of the distance as the true furthest neighbor. Default value 1. - Query (mat.Dense): Matrix containing query points (optional). - RandomBasis (bool): Before tree-building, project the data onto a random orthogonal basis. - Reference (mat.Dense): Matrix containing the reference dataset. - Seed (int): Random seed (if 0, std::time(NULL) is used). Default value 0. - TreeType (string): Type of tree to use: 'kd', 'vp', 'rp', 'max-rp', 'ub', 'cover', 'r', 'r-star', 'x', 'ball', 'hilbert-r', 'r-plus', 'r-plus-plus', 'oct'. Default value 'kd'. - TrueDistances (mat.Dense): Matrix of true distances to compute the effective error (average relative error) (it is printed when -v is specified). - TrueNeighbors (mat.Dense): Matrix of true neighbors to compute the recall (it is printed when -v is specified). - Verbose (bool): Display informational messages and the full list of parameters and timers at the end of execution. Output parameters: - distances (mat.Dense): Matrix to output distances into. - neighbors (mat.Dense): Matrix to output neighbors into. - outputModel (kfnModel): If specified, the kFN model will be output here. */ func Kfn(param *KfnOptionalParam) (*mat.Dense, *mat.Dense, kfnModel) { resetTimers() enableTimers() disableBacktrace() disableVerbose() restoreSettings("k-Furthest-Neighbors Search") // Detect if the parameter was passed; set if so. if param.Algorithm != "dual_tree" { setParamString("algorithm", param.Algorithm) setPassed("algorithm") } // Detect if the parameter was passed; set if so. if param.Epsilon != 0 { setParamDouble("epsilon", param.Epsilon) setPassed("epsilon") } // Detect if the parameter was passed; set if so. if param.InputModel != nil { setKFNModel("input_model", param.InputModel) setPassed("input_model") } // Detect if the parameter was passed; set if so. if param.K != 0 { setParamInt("k", param.K) setPassed("k") } // Detect if the parameter was passed; set if so. if param.LeafSize != 20 { setParamInt("leaf_size", param.LeafSize) setPassed("leaf_size") } // Detect if the parameter was passed; set if so. if param.Percentage != 1 { setParamDouble("percentage", param.Percentage) setPassed("percentage") } // Detect if the parameter was passed; set if so. if param.Query != nil { gonumToArmaMat("query", param.Query) setPassed("query") } // Detect if the parameter was passed; set if so. if param.RandomBasis != false { setParamBool("random_basis", param.RandomBasis) setPassed("random_basis") } // Detect if the parameter was passed; set if so. if param.Reference != nil { gonumToArmaMat("reference", param.Reference) setPassed("reference") } // Detect if the parameter was passed; set if so. if param.Seed != 0 { setParamInt("seed", param.Seed) setPassed("seed") } // Detect if the parameter was passed; set if so. if param.TreeType != "kd" { setParamString("tree_type", param.TreeType) setPassed("tree_type") } // Detect if the parameter was passed; set if so. if param.TrueDistances != nil { gonumToArmaMat("true_distances", param.TrueDistances) setPassed("true_distances") } // Detect if the parameter was passed; set if so. if param.TrueNeighbors != nil { gonumToArmaUmat("true_neighbors", param.TrueNeighbors) setPassed("true_neighbors") } // Detect if the parameter was passed; set if so. if param.Verbose != false { setParamBool("verbose", param.Verbose) setPassed("verbose") enableVerbose() } // Mark all output options as passed. setPassed("distances") setPassed("neighbors") setPassed("output_model") // Call the mlpack program. C.mlpackKfn() // Initialize result variable and get output. var distancesPtr mlpackArma distances := distancesPtr.armaToGonumMat("distances") var neighborsPtr mlpackArma neighbors := neighborsPtr.armaToGonumUmat("neighbors") var outputModel kfnModel outputModel.getKFNModel("output_model") // Clear settings. clearSettings() // Return output(s). return distances, neighbors, outputModel }
kfn.go
0.677261
0.512998
kfn.go
starcoder
package bimg /* #cgo pkg-config: vips #include "vips/vips.h" */ import "C" import "errors" const ( // Quality defines the default JPEG quality to be used. Quality = 75 ) // maxSize defines maximum pixels width or height supported. var maxSize = 16383 // MaxSize returns maxSize. func MaxSize() int { return maxSize } // SetMaxSize sets maxSize. func SetMaxsize(s int) error { if s <= 0 { return errors.New("Size must be higher than zero.") } maxSize = s return nil } // Gravity represents the image gravity value. type Gravity int const ( // GravityCentre represents the centre value used for image gravity orientation. GravityCentre Gravity = iota // GravityNorth represents the north value used for image gravity orientation. GravityNorth // GravityEast represents the east value used for image gravity orientation. GravityEast // GravitySouth represents the south value used for image gravity orientation. GravitySouth // GravityWest represents the west value used for image gravity orientation. GravityWest // GravitySmart enables libvips Smart Crop algorithm for image gravity orientation. GravitySmart ) // Interpolator represents the image interpolation value. type Interpolator int const ( // Bicubic interpolation value. Bicubic Interpolator = iota // Bilinear interpolation value. Bilinear // Nohalo interpolation value. Nohalo // Nearest neighbour interpolation value. Nearest ) var interpolations = map[Interpolator]string{ Bicubic: "bicubic", Bilinear: "bilinear", Nohalo: "nohalo", Nearest: "nearest", } func (i Interpolator) String() string { return interpolations[i] } // Angle represents the image rotation angle value. type Angle int const ( // D0 represents the rotation angle 0 degrees. D0 Angle = 0 // D45 represents the rotation angle 45 degrees. D45 Angle = 45 // D90 represents the rotation angle 90 degrees. D90 Angle = 90 // D135 represents the rotation angle 135 degrees. D135 Angle = 135 // D180 represents the rotation angle 180 degrees. D180 Angle = 180 // D235 represents the rotation angle 235 degrees. D235 Angle = 235 // D270 represents the rotation angle 270 degrees. D270 Angle = 270 // D315 represents the rotation angle 315 degrees. D315 Angle = 315 ) // Direction represents the image direction value. type Direction int const ( // Horizontal represents the orizontal image direction value. Horizontal Direction = C.VIPS_DIRECTION_HORIZONTAL // Vertical represents the vertical image direction value. Vertical Direction = C.VIPS_DIRECTION_VERTICAL ) // Interpretation represents the image interpretation type. // See: https://libvips.github.io/libvips/API/current/VipsImage.html#VipsInterpretation type Interpretation int const ( // InterpretationError points to the libvips interpretation error type. InterpretationError Interpretation = C.VIPS_INTERPRETATION_ERROR // InterpretationMultiband points to its libvips interpretation equivalent type. InterpretationMultiband Interpretation = C.VIPS_INTERPRETATION_MULTIBAND // InterpretationBW points to its libvips interpretation equivalent type. InterpretationBW Interpretation = C.VIPS_INTERPRETATION_B_W // InterpretationCMYK points to its libvips interpretation equivalent type. InterpretationCMYK Interpretation = C.VIPS_INTERPRETATION_CMYK // InterpretationRGB points to its libvips interpretation equivalent type. InterpretationRGB Interpretation = C.VIPS_INTERPRETATION_RGB // InterpretationSRGB points to its libvips interpretation equivalent type. InterpretationSRGB Interpretation = C.VIPS_INTERPRETATION_sRGB // InterpretationRGB16 points to its libvips interpretation equivalent type. InterpretationRGB16 Interpretation = C.VIPS_INTERPRETATION_RGB16 // InterpretationGREY16 points to its libvips interpretation equivalent type. InterpretationGREY16 Interpretation = C.VIPS_INTERPRETATION_GREY16 // InterpretationScRGB points to its libvips interpretation equivalent type. InterpretationScRGB Interpretation = C.VIPS_INTERPRETATION_scRGB // InterpretationLAB points to its libvips interpretation equivalent type. InterpretationLAB Interpretation = C.VIPS_INTERPRETATION_LAB // InterpretationXYZ points to its libvips interpretation equivalent type. InterpretationXYZ Interpretation = C.VIPS_INTERPRETATION_XYZ ) // Extend represents the image extend mode, used when the edges // of an image are extended, you can specify how you want the extension done. // See: https://libvips.github.io/libvips/API/current/libvips-conversion.html#VIPS-EXTEND-BACKGROUND:CAPS type Extend int const ( // ExtendBlack extend with black (all 0) pixels mode. ExtendBlack Extend = C.VIPS_EXTEND_BLACK // ExtendCopy copy the image edges. ExtendCopy Extend = C.VIPS_EXTEND_COPY // ExtendRepeat repeat the whole image. ExtendRepeat Extend = C.VIPS_EXTEND_REPEAT // ExtendMirror mirror the whole image. ExtendMirror Extend = C.VIPS_EXTEND_MIRROR // ExtendWhite extend with white (all bits set) pixels. ExtendWhite Extend = C.VIPS_EXTEND_WHITE // ExtendBackground with colour from the background property. ExtendBackground Extend = C.VIPS_EXTEND_BACKGROUND // ExtendLast extend with last pixel. ExtendLast Extend = C.VIPS_EXTEND_LAST ) // WatermarkFont defines the default watermark font to be used. var WatermarkFont = "sans 10" // Color represents a traditional RGB color scheme. type Color struct { R, G, B uint8 } // ColorBlack is a shortcut to black RGB color representation. var ColorBlack = Color{0, 0, 0} // Watermark represents the text-based watermark supported options. type Watermark struct { Width int DPI int Margin int Opacity float32 NoReplicate bool Text string Font string Background Color } // WatermarkImage represents the image-based watermark supported options. type WatermarkImage struct { Left int Top int Buf []byte Opacity float32 } // GaussianBlur represents the gaussian image transformation values. type GaussianBlur struct { Sigma float64 MinAmpl float64 } // Sharpen represents the image sharp transformation options. type Sharpen struct { Radius int X1 float64 Y2 float64 Y3 float64 M1 float64 M2 float64 } // Options represents the supported image transformation options. type Options struct { Height int Width int AreaHeight int AreaWidth int Top int Left int Quality int Compression int Zoom int Crop bool SmartCrop bool // Deprecated, use: bimg.Options.Gravity = bimg.GravitySmart Enlarge bool Embed bool Flip bool Flop bool Force bool NoAutoRotate bool NoProfile bool Interlace bool StripMetadata bool Trim bool Lossless bool Extend Extend Rotate Angle Background Color Gravity Gravity Watermark Watermark WatermarkImage WatermarkImage Type ImageType Interpolator Interpolator Interpretation Interpretation GaussianBlur GaussianBlur Sharpen Sharpen Threshold float64 Gamma float64 Brightness float64 Contrast float64 OutputICC string InputICC string Palette bool // Speed defines the AVIF encoders CPU effort. Valid values are: // 0-8 for AVIF encoding. // 0-9 for PNG encoding. Speed int // private fields autoRotateOnly bool }
options.go
0.684159
0.431764
options.go
starcoder