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 algo
import (
"fmt"
)
const (
VERTEX_NOT_FOUND = Vertex("vertex not found")
)
type Vertex string
type Graph struct {
adjacent map[Vertex][]Vertex
visited map[Vertex]struct{}
}
func NewGraph() *Graph {
g := &Graph{
adjacent: make(map[Vertex][]Vertex),
visited: make(map[Vertex]struct{}),
}
return g
}
func (g *Graph) AddVertex(vertex Vertex) {
g.adjacent[vertex] = nil
}
func (g *Graph) AddEdge(vertex1, vertex2 Vertex) error {
if _, ok := g.adjacent[vertex1]; !ok {
return fmt.Errorf("unable to create edge: vertex %v does not exist", vertex1)
}
g.adjacent[vertex1] = append(g.adjacent[vertex1], vertex2)
g.adjacent[vertex2] = append(g.adjacent[vertex2], vertex1)
return nil
}
func (g Graph) DFSrecursive(startVertex, searchValue Vertex) Vertex {
if startVertex == searchValue {
return startVertex
}
g.visited[startVertex] = struct{}{}
for _, adjacent := range g.adjacent[startVertex] {
_, ok := g.visited[adjacent]
if !ok {
result := g.DFSrecursive(adjacent, searchValue)
if result == searchValue {
return result
}
}
}
return VERTEX_NOT_FOUND
}
func (g Graph) BFS(startVertex, searchValue Vertex) Vertex {
if startVertex == searchValue {
return startVertex
}
queue := NewQueue()
g.visited[startVertex] = struct{}{}
queue.Enqueue(string(startVertex))
for len(*queue) > 0 {
current_vertex, err := queue.Dequeue()
if err != nil {
fmt.Println(err)
}
if Vertex(current_vertex) == searchValue {
return Vertex(current_vertex)
}
for _, adjacent := range g.adjacent[Vertex(current_vertex)] {
_, ok := g.visited[adjacent]
if !ok {
g.visited[adjacent] = struct{}{}
queue.Enqueue(string(adjacent))
}
}
}
return VERTEX_NOT_FOUND
}
type ShortestDistanceGraph struct {
Verticies []*WeightedVertex
DistanceMap map[string]int
PreviousWeightedVertexMap map[string]string
Unvisited []string
Visited map[string]struct{}
}
func NewShortestDistanceGraph() *ShortestDistanceGraph {
s := &ShortestDistanceGraph{
DistanceMap: make(map[string]int),
PreviousWeightedVertexMap: make(map[string]string),
Visited: make(map[string]struct{}),
}
return s
}
func (s *ShortestDistanceGraph) AddVertex(vertex *WeightedVertex) {
s.Verticies = append(s.Verticies, vertex)
}
func (s ShortestDistanceGraph) GetShortestDistance(startVertex WeightedVertex, endVertex WeightedVertex) []string {
s.DistanceMap[startVertex.Value] = 0
current_vertex := startVertex
for current_vertex.Value != "" {
s.Visited[current_vertex.Value] = struct{}{}
}
return []string{}
}
type WeightedVertex struct {
Value string
Adjacent map[*WeightedVertex]int
}
func NewWeightedVertex(value string) *WeightedVertex {
w := &WeightedVertex{
Value: value,
Adjacent: make(map[*WeightedVertex]int),
}
return w
}
func (w *WeightedVertex) AddAdjacentVertex(vertex *WeightedVertex, weight int) {
w.Adjacent[vertex] = weight
} | graph.go | 0.673836 | 0.457621 | graph.go | starcoder |
package bst
import (
"fmt"
"math"
)
type Node struct {
value string
left *Node
right *Node
}
type BST struct {
nodeCount int
root *Node
}
func (b *BST) IsEmpty() bool {
return b.nodeCount == 0
}
func (b *BST) Size() int {
return b.nodeCount
}
func (b *BST) Add(value string) bool {
if b.Contains(value) {
return false
}
b.root = b.add(b.root, value)
b.nodeCount++
return true
}
func (b *BST) add(node *Node, value string) *Node {
if node == nil {
node = &Node{value: value}
}
if value > node.value {
node.right = b.add(node.right, value)
}
if value < node.value {
node.left = b.add(node.left, value)
}
return node
}
func (b *BST) Contains(value string) bool {
return b.contains(b.root, value)
}
func (b *BST) contains(node *Node, value string) bool {
if node == nil {
return false
}
if value > node.value {
return b.contains(node.right, value)
}
if value < node.value {
return b.contains(node.left, value)
}
return true
}
func (b *BST) Remove(value string) bool {
if b.Contains(value) {
b.root = b.remove(b.root, value)
b.nodeCount--
return true
}
return false
}
func (b *BST) remove(node *Node, value string) *Node {
if node == nil {
return nil
}
if value > node.value {
node.right = b.remove(node.right, value)
} else if value < node.value {
node.left = b.remove(node.left, value)
} else {
if node.left == nil {
return node.right
}
if node.right == nil {
return node.left
}
tmp := b.findMax(node.left)
node.value = tmp.value
node.right = b.remove(node.right, tmp.value)
}
return node
}
func (b *BST) Height() int {
return b.height(b.root)
}
func (b *BST) height(node *Node) int {
if node == nil {
return 0
}
return int(math.Max(float64(b.height(node.left)), float64(b.height(node.right)))) + 1
}
func (b *BST) findMin(node *Node) *Node {
if node.left == nil {
return node
}
return b.findMin(node.left)
}
func (b *BST) findMax(node *Node) *Node {
if node.right == nil {
return node
}
return b.findMax(node.right)
}
func (b *BST) PreOrder() {
b.preOrder(b.root)
}
func (b *BST) preOrder(node *Node) {
if node == nil {
return
}
fmt.Println(node.value)
b.preOrder(node.left)
b.preOrder(node.right)
}
func (b *BST) InOrder() {
b.inOrder(b.root)
}
func (b *BST) inOrder(node *Node) {
if node == nil {
return
}
b.inOrder(node.left)
fmt.Println(node.value)
b.inOrder(node.right)
}
func (b *BST) LevelOrder() {
b.levelOrder(b.root)
}
func (b *BST) levelOrder(node *Node) {
var queue []*Node
queue = append(queue, node)
for len(queue) != 0 {
dequeue := queue[0]
queue = queue[1:]
fmt.Println(dequeue.value)
if dequeue.left != nil {
queue = append(queue, dequeue.left)
}
if dequeue.right != nil {
queue = append(queue, dequeue.right)
}
}
} | ds/bst/bst.go | 0.518302 | 0.469216 | bst.go | starcoder |
package zfloat
import (
"errors"
"fmt"
"reflect"
"strconv"
)
type Slice []float64
func GetAny(i interface{}) (float64, error) {
switch i.(type) {
case bool:
if i.(bool) {
return 1, nil
}
return 0, nil
case int:
return float64(i.(int)), nil
case int8:
return float64(i.(int8)), nil
case int16:
return float64(i.(int16)), nil
case int32:
return float64(i.(int32)), nil
case int64:
return float64(i.(int64)), nil
case uint:
return float64(i.(uint)), nil
case uint8:
return float64(i.(uint8)), nil
case uint16:
return float64(i.(uint16)), nil
case uint32:
return float64(i.(uint32)), nil
case uint64:
return float64(i.(uint64)), nil
case float32:
return float64(i.(float32)), nil
case float64:
return float64(i.(float64)), nil
case string:
f, err := strconv.ParseFloat(i.(string), 64)
return f, err
}
val := reflect.ValueOf(i)
switch val.Kind() {
case reflect.Bool:
if i.(bool) {
return 1, nil
}
return 0, nil
case reflect.Int:
return float64(val.Int()), nil
case reflect.Int8:
return float64(val.Int()), nil
case reflect.Int16:
return float64(val.Int()), nil
case reflect.Int32:
return float64(val.Int()), nil
case reflect.Int64:
return float64(val.Int()), nil
case reflect.Uint:
return float64(val.Int()), nil
case reflect.Uint8:
return float64(val.Int()), nil
case reflect.Uint16:
return float64(val.Int()), nil
case reflect.Uint32:
return float64(val.Int()), nil
case reflect.Uint64:
return float64(val.Int()), nil
case reflect.Float32:
return float64(val.Float()), nil
case reflect.Float64:
return float64(val.Float()), nil
case reflect.String:
n, err := strconv.ParseFloat(val.String(), 64)
return n, err
default:
return 0, errors.New(fmt.Sprint("bad type:", reflect.TypeOf(i)))
}
}
func SetAny(any interface{}, f float64) error {
// zlog.Info("SetAnyF:", reflect.ValueOf(any).Type())
switch atype := any.(type) {
case *float32:
*atype = float32(f)
case *float64:
*any.(*float64) = f
case bool:
*any.(*bool) = (f != 0)
case int:
*any.(*int) = int(f)
case int8:
*any.(*int8) = int8(f)
case int16:
*any.(*int16) = int16(f)
case int32:
*any.(*int32) = int32(f)
case int64:
*any.(*int64) = int64(f)
case uint:
*any.(*uint) = uint(f)
case uint8:
*any.(*uint8) = uint8(f)
case uint16:
*any.(*uint16) = uint16(f)
case uint32:
*any.(*uint32) = uint32(f)
case uint64:
*any.(*uint64) = uint64(f)
default:
return errors.New(fmt.Sprint("bad type:", reflect.TypeOf(any)))
}
return nil
}
func IsInSlice(n float64, slice []float64) bool {
for _, s := range slice {
if s == n {
return true
}
}
return false
}
func AddToSet(slice *[]float64, n float64) bool {
if !IsInSlice(n, *slice) {
*slice = append(*slice, n)
return true
}
return false
}
func Max32(a, b float32) float32 {
if a > b {
return a
}
return b
}
func Min32(a, b float32) float32 {
if a < b {
return a
}
return b
}
func Minimize32(a *float32, b float32) bool {
if *a < b {
return false
}
*a = b
return true
}
func Maximize32(a *float32, b float32) bool {
if *a > b {
return false
}
*a = b
return true
}
func Minimize(a *float64, b float64) bool {
if *a < b {
return false
}
*a = b
return true
}
func Maximize(a *float64, b float64) bool {
if *a > b {
return false
}
*a = b
return true
}
func Float64Max(a, b float64) float64 {
if a > b {
return a
}
return b
}
func Float64Min(a, b float64) float64 {
if a < b {
return a
}
return b
}
// GetItem makes Slice worth with MenuView MenuItems interface
func (s Slice) GetItem(i int) (id, name string, value interface{}) {
if i >= len(s) {
return "", "", nil
}
n := s[i]
str := strconv.FormatFloat(n, 'f', -1, 64)
return str, str, n
}
func (s Slice) Count() int {
return len(s)
}
func (s Slice) Minimum() float64 {
var min float64
for i, n := range s {
if i == 0 || min > n {
min = n
}
}
return min
}
func Clamped(v, min, max float64) float64 {
if v < min {
v = min
}
if v > max {
v = max
}
return v
}
func Clamped32(v, min, max float32) float32 {
if v < min {
v = min
}
if v > max {
v = max
}
return v
}
// MixedValueAtT returns the mix beween the values t lies within using MixedValueAtIndex
// t is 0-1, corresponding to 0 as 100% of [0] and 1 as 100% the last slice element.
func MixedValueAtT(slice []float64, t float64) float64 {
return MixedValueAtIndex(slice, float64(len(slice)-1)*t)
}
// MixedValueAtIndex returns a mix of the value before and after index;
// So if index is 4.25, it will return a mix of 75% [4] and 25% [5]
func MixedValueAtIndex(slice []float64, index float64) float64 {
if index < 0.0 {
return slice[0]
}
if index >= float64(len(slice))-1 {
return slice[len(slice)-1]
}
n := index
f := (index - n)
var v = slice[int(n)] * (1 - f)
if int(n) < len(slice) {
v += slice[int(n+1)] * f
return v
}
if len(slice) > 0 {
return slice[len(slice)-1]
}
return 0
} | zfloat/zfloat.go | 0.597373 | 0.459379 | zfloat.go | starcoder |
package utils
import (
"fmt"
"sync/atomic"
)
// AtomicInt64
type AtomicInt64 int64
// CreateAtomicInt64 with initial value
func CreateAtomicInt64(initialValue int64) *AtomicInt64 {
a := AtomicInt64(initialValue)
return &a
}
// GetAtomic
func (a *AtomicInt64) GetAtomic() int64 {
return int64(*a)
}
// SetAtomic
func (a *AtomicInt64) SetAtomic(newValue int64) {
atomic.StoreInt64((*int64)(a), newValue)
}
// GetAndSetAtomic return current and set new
func (a *AtomicInt64) GetAndSetAtomic(newValue int64) int64 {
for {
current := a.GetAtomic()
if a.CompareAndSet(current, newValue) {
return current
}
}
}
// GetNewAndSetAtomic set new and return new
func (a *AtomicInt64) GetNewAndSetAtomic(newValue int64) int64 {
for {
current := a.GetAtomic()
if a.CompareAndSet(current, newValue) {
return newValue
}
}
}
// CompareAndSet
func (a *AtomicInt64) CompareAndSet(expect, update int64) bool {
return atomic.CompareAndSwapInt64((*int64)(a), expect, update)
}
// GetOldAndIncrement return current and add 1 to atomic
func (a *AtomicInt64) GetOldAndIncrement() int64 {
for {
current := a.GetAtomic()
next := current + 1
if a.CompareAndSet(current, next) {
return current
}
}
}
// GetOldAndDecrement return current and minus 1 to atomic
func (a *AtomicInt64) GetOldAndDecrement() int64 {
for {
current := a.GetAtomic()
next := current - 1
if a.CompareAndSet(current, next) {
return current
}
}
}
// GetOldAndAdd return current and add delta to atomic
func (a *AtomicInt64) GetOldAndAdd(delta int64) int64 {
for {
current := a.GetAtomic()
next := current + delta
if a.CompareAndSet(current, next) {
return current
}
}
}
// IncrementAndGetNew
func (a *AtomicInt64) IncrementAndGetNew() int64 {
for {
current := a.GetAtomic()
next := current + 1
if a.CompareAndSet(current, next) {
return next
}
}
}
// DecrementAndGetNew
func (a *AtomicInt64) DecrementAndGetNew() int64 {
for {
current := a.GetAtomic()
next := current - 1
if a.CompareAndSet(current, next) {
return next
}
}
}
// AddAndGetNew
func (a *AtomicInt64) AddAndGetNew(delta int64) int64 {
for {
current := a.GetAtomic()
next := current + delta
if a.CompareAndSet(current, next) {
return next
}
}
}
func (a *AtomicInt64) String() string {
return fmt.Sprintf("%d", a.GetAtomic())
}
// AtomicInt32
type AtomicInt32 int32
// CreateAtomicInt32
func CreateAtomicInt32(initialValue int32) *AtomicInt32 {
a := AtomicInt32(initialValue)
return &a
}
// GetAtomic
func (a *AtomicInt32) GetAtomic() int32 {
return int32(*a)
}
// SetAtomic
func (a *AtomicInt32) SetAtomic(newValue int32) {
// replace stored value by newValue
atomic.StoreInt32((*int32)(a), newValue)
}
// GetAndSetAtomic
func (a *AtomicInt32) GetAndSetAtomic(newValue int32) int32 {
for {
current := a.GetAtomic()
if a.CompareAndSet(current, newValue) {
return current
}
}
}
// CompareAndSet
func (a *AtomicInt32) CompareAndSet(expect, update int32) bool {
return atomic.CompareAndSwapInt32((*int32)(a), expect, update)
}
// GetOldAndIncrement
func (a *AtomicInt32) GetOldAndIncrement() int32 {
for {
current := a.GetAtomic()
next := current + 1
if a.CompareAndSet(current, next) {
return current
}
}
}
// GetOldAndDecrement
func (a *AtomicInt32) GetOldAndDecrement() int32 {
for {
current := a.GetAtomic()
next := current - 1
if a.CompareAndSet(current, next) {
return current
}
}
}
// GetOldAndAdd
func (a *AtomicInt32) GetOldAndAdd(delta int32) int32 {
for {
current := a.GetAtomic()
next := current + delta
if a.CompareAndSet(current, next) {
return current
}
}
}
// IncrementAndGetNew
func (a *AtomicInt32) IncrementAndGetNew() int32 {
for {
current := a.GetAtomic()
next := current + 1
if a.CompareAndSet(current, next) {
return next
}
}
}
// DecrementAndGetNew
func (a *AtomicInt32) DecrementAndGetNew() int32 {
for {
current := a.GetAtomic()
next := current - 1
if a.CompareAndSet(current, next) {
return next
}
}
}
// AddAndGetNew
func (a *AtomicInt32) AddAndGetNew(delta int32) int32 {
for {
current := a.GetAtomic()
next := current + delta
if a.CompareAndSet(current, next) {
return next
}
}
}
func (a *AtomicInt32) String() string {
return fmt.Sprintf("%d", a.GetAtomic())
} | utils/atomic.go | 0.59843 | 0.432123 | atomic.go | starcoder |
package vm
import (
"commaql/vm/values"
)
type VM struct {
// Table Context Registers
// 0: Main register (all queries are executed with this context)
// 1: Working register for joins, sub-queries, etc
tcr [2]tableContext
// Limit and Iterator Registers
// Used for maintaining scan position within contexts.
lim uint
itr uint
// Row register
row []values.Value
stack stack
ip uint
}
func NewVM() VM {
return VM{
tcr: [2]tableContext{},
stack: stack{meta: []values.Value{}},
ip: 0,
}
}
func binaryOp(left, right values.Value, opCode OpCode) values.Value {
if leftNum, ok := left.(values.Number); ok {
if rightNum, ok := right.(values.Number); ok {
switch opCode {
case OpAdd:
return values.NewNumberFromValue(leftNum.Meta + rightNum.Meta)
case OpSubtract:
return values.NewNumberFromValue(leftNum.Meta - rightNum.Meta)
case OpMultiply:
return values.NewNumberFromValue(leftNum.Meta * rightNum.Meta)
case OpDivide:
return values.NewNumberFromValue(leftNum.Meta / rightNum.Meta)
case OpEquals:
return values.NewBooleanFromValue(leftNum.Meta == rightNum.Meta)
case OpNotEquals:
return values.NewBooleanFromValue(leftNum.Meta != rightNum.Meta)
case OpGreaterEquals:
return values.NewBooleanFromValue(leftNum.Meta >= rightNum.Meta)
case OpGreaterThan:
return values.NewBooleanFromValue(leftNum.Meta > rightNum.Meta)
case OpLessEquals:
return values.NewBooleanFromValue(leftNum.Meta <= rightNum.Meta)
case OpLessThan:
return values.NewBooleanFromValue(leftNum.Meta < rightNum.Meta)
}
}
}
if leftVal, ok := left.(values.Boolean); ok {
if rightVal, ok := right.(values.Boolean); ok {
switch opCode {
case OpAnd:
return values.NewBooleanFromValue(leftVal.Meta && rightVal.Meta)
case OpOr:
return values.NewBooleanFromValue(leftVal.Meta || rightVal.Meta)
case OpEquals:
return values.NewBooleanFromValue(leftVal.Meta == rightVal.Meta)
case OpNotEquals:
return values.NewBooleanFromValue(leftVal.Meta != rightVal.Meta)
}
}
}
if leftVal, ok := left.(values.String); ok {
if rightVal, ok := right.(values.String); ok {
switch opCode {
case OpAdd:
return values.NewString(leftVal.Meta + rightVal.Meta)
case OpEquals:
return values.NewBooleanFromValue(leftVal.Meta == rightVal.Meta)
case OpNotEquals:
return values.NewBooleanFromValue(leftVal.Meta != rightVal.Meta)
}
}
}
panic("UnsupportedOperation")
}
func (vm *VM) Run(bc Bytecode) ResultSet {
readArg := func() OpCode {
vm.ip++
return bc.Blob[vm.ip]
}
for vm.ip = 0; vm.ip < uint(len(bc.Blob)); vm.ip++ {
opCode := bc.Blob[vm.ip]
switch opCode {
case OpLoadConst:
vm.stack.push(bc.ConstantsPool[readArg()])
case OpAdd:
fallthrough
case OpSubtract:
fallthrough
case OpMultiply:
fallthrough
case OpDivide:
fallthrough
case OpAnd:
fallthrough
case OpOr:
fallthrough
case OpGreaterThan:
fallthrough
case OpGreaterEquals:
fallthrough
case OpLessThan:
fallthrough
case OpLessEquals:
fallthrough
case OpEquals:
fallthrough
case OpNotEquals:
leftOperand := vm.stack.pop()
rightOperand := vm.stack.pop()
res := binaryOp(leftOperand, rightOperand, opCode)
vm.stack.push(res)
case OpLoadTable:
// OpLoadTable table_ctx_idx table_ctx_register_idx
tableCtx := bc.TableContext[readArg()]
vm.tcr[readArg()] = newTableContext(tableCtx)
case OpSelectColumn:
vm.tcr[readArg()].markColumnSelected(readArg())
case OpScan:
rows := vm.tcr[0].table.RowCount()
vm.lim = rows
vm.itr = 0
case OpLoadNextRow:
tab := vm.tcr[0].table
vm.row, _ = tab.GetRow(vm.itr)
vm.itr++
case OpLoadVal:
vm.stack.push(vm.row[readArg()])
case OpJumpIfScan:
// -1 to offset for the loop counter increment before the next iteration
jumpOffset := uint(readArg()) - 1
//fmt.Printf("Jumping to %s\n", GetOpCodeInfo(bc.Blob[jumpOffset+1]).PrintableName)
if vm.itr < vm.lim {
vm.ip = jumpOffset
} else {
vm.itr = 0
vm.lim = 0
}
case OpSelectRowIfTrue:
if vm.stack.pop().(values.Boolean).Meta {
vm.tcr[0].markRowSelected(vm.itr - 1)
}
default:
panic("instruction not implemented: " + GetOpCodeInfo(opCode).PrintableName)
}
}
return vm.tcr[0].toResultSet()
} | vm/vm.go | 0.50293 | 0.450118 | vm.go | starcoder |
package camera
import "C"
import (
"github.com/faiface/pixel"
"gotracer/vmath"
"math"
)
// Camera defocus is a camera that has support for defocus blur.
type CameraDefocus struct {
Camera
// Lens radius affects how much the rays can drift from the center.
LensRadius float64
// Lens aperture.
Aperture float64
// Distance to be in perfect focus of the camera.
FocusDistance float64
U *vmath.Vector3
V *vmath.Vector3
W *vmath.Vector3
}
// Create camera from bouding box
func NewCameraDefocus (bounds pixel.Rect, position *vmath.Vector3, lookAt *vmath.Vector3, up *vmath.Vector3, fov float64, aperture float64, focusDistance float64) *CameraDefocus {
var c = new(CameraDefocus)
var size = bounds.Size()
c.Aperture = aperture
c.FocusDistance = focusDistance
c.Fov = fov
c.AspectRatio = size.X / size.Y
c.Position = position
c.LookAt = lookAt
c.Up = up
c.UpdateViewport()
return c
}
// Create camera from bouding box
func NewCameraDefocusBounds(bounds pixel.Rect) *CameraDefocus {
var c = new(CameraDefocus)
var size = bounds.Size()
c.Fov = 90
c.AspectRatio = size.X / size.Y
c.Position = vmath.NewVector3(-0.15, 0.2, 0.15)
c.LookAt = vmath.NewVector3(0.0, 0.0, 0.0)
c.Up = vmath.NewVector3(0.0, 1.0, 0.0)
c.Aperture = 0.0
var direction = c.Position.Clone()
direction.Sub(c.LookAt)
c.FocusDistance = direction.Length()
c.UpdateViewport()
return c
}
// UpdateViewport camera projection properties.
func (c *CameraDefocus) UpdateViewport() {
var fovRad = c.Fov * (math.Pi / 180.0)
var halfHeight = math.Tan(fovRad / 2.0)
var halfWidth = c.AspectRatio * halfHeight
var direction = c.Position.Clone()
direction.Sub(c.LookAt)
c.LensRadius = c.Aperture / 2.0
c.W = direction.UnitVector()
c.U = vmath.Cross(c.Up, c.W).UnitVector()
c.V = vmath.Cross(c.W, c.U)
var u = c.U.Clone()
var v = c.V.Clone()
var w = c.W.Clone()
u.MulScalar(halfWidth * c.FocusDistance)
v.MulScalar(halfHeight * c.FocusDistance)
w.MulScalar(c.FocusDistance)
c.LowerLeftCorner = c.Position.Clone()
c.LowerLeftCorner.Sub(u)
c.LowerLeftCorner.Sub(v)
c.LowerLeftCorner.Sub(w)
c.Horizontal = u.Clone()
c.Horizontal.MulScalar(2.0)
c.Vertical = v.Clone()
c.Vertical.MulScalar(2.0)
}
// Get a ray from this camera, from a normalized UV screen coordinate.
func (c *CameraDefocus) GetRay(u float64, v float64) *vmath.Ray {
var rd = vmath.RandomInUnitDisk()
rd.MulScalar(c.LensRadius)
var offset = c.U.Clone()
offset.MulScalar(rd.X)
var vclone = c.V.Clone()
vclone.MulScalar(rd.Y)
offset.Add(vclone)
var hor = c.Horizontal.Clone()
hor.MulScalar(u)
var vert = c.Vertical.Clone()
vert.MulScalar(v)
var direction = c.LowerLeftCorner.Clone()
direction.Add(hor)
direction.Add(vert)
direction.Sub(c.Position)
direction.Sub(offset)
offset.Add(c.Position)
return vmath.NewRay(offset, direction)
}
// Copy data from another camera object
func (c *CameraDefocus) Copy(o *CameraDefocus) {
c.Fov = o.Fov
c.AspectRatio = o.AspectRatio
c.Position.Copy(o.Position)
c.LookAt.Copy(o.LookAt)
c.Up.Copy(o.Up)
c.Aperture = o.Aperture
c.FocusDistance = o.FocusDistance
}
// Clone the camera object
func (o *CameraDefocus) Clone() *CameraDefocus {
var c = new(CameraDefocus)
c.Fov = o.Fov
c.AspectRatio = o.AspectRatio
c.Position = o.Position.Clone()
c.LookAt = o.LookAt.Clone()
c.Up = o.Up.Clone()
c.Aperture = o.Aperture
c.FocusDistance = o.FocusDistance
c.UpdateViewport()
return c
} | camera/camera_defocus.go | 0.760917 | 0.507141 | camera_defocus.go | starcoder |
package day18
import (
"fmt"
"strconv"
)
var HEAD *Node
type Node struct {
left, right, parent *Node
depth int
val int
}
func (node *Node) String() string {
if node.isSimple() {
return fmt.Sprintf("%d", node.val)
}
return fmt.Sprintf("[%v,%v]", node.left, node.right)
}
func (node *Node) isSimple() bool {
return node.left == nil && node.right == nil
}
func (node *Node) isLeft() bool {
if node.parent == nil {
return true
}
return node.parent.left == node
}
func (node *Node) leftMost() *Node {
if node.isSimple() {
return node
}
return node.left.leftMost()
}
func (node *Node) rightMost() *Node {
if node.isSimple() {
return node
}
return node.right.rightMost()
}
func (node *Node) leftMostInRight() *Node {
if node.parent == nil {
return nil
}
if node.parent.right != node {
if node.parent.right.isSimple() {
return node.parent.right
}
return node.parent.right.leftMost()
} else {
return node.parent.leftMostInRight()
}
}
func (node *Node) rightMostInLeft() *Node {
if node.parent == nil {
return nil
}
if node.parent.left != node {
if node.parent.left.isSimple() {
return node.parent.left
}
return node.parent.left.rightMost()
} else {
return node.parent.rightMostInLeft()
}
}
func (n *Node) join(other *Node) *Node {
if n.parent != nil || other.parent != nil {
panic("not a root node")
}
parent := &Node{
left: n,
right: other,
}
n.parent = parent
other.parent = parent
nodes := make([]*Node, 0)
nodes = append(nodes, n)
nodes = append(nodes, other)
for len(nodes) > 0 {
node := nodes[0]
nodes = nodes[1:]
node.depth += 1
if node.left != nil {
nodes = append(nodes, node.left)
}
if node.right != nil {
nodes = append(nodes, node.right)
}
node = nil
}
return parent
}
func (node *Node) explode() *Node {
if node.isSimple() {
return node
}
right := node.leftMostInRight()
if right != nil {
right.val += node.right.val
}
left := node.rightMostInLeft()
if left != nil {
left.val += node.left.val
}
new_node := &Node{parent: node.parent, val: 0, depth: node.depth}
node = nil
return new_node
}
func (node *Node) split() *Node {
if node.val < 10 {
return node
}
parent := &Node{
parent: node.parent,
depth: node.depth,
}
left := &Node{
val: node.val / 2,
parent: parent,
depth: node.depth + 1,
}
right := &Node{
val: (node.val + 1)/2,
parent: parent,
depth: node.depth + 1,
}
parent.left = left
parent.right = right
node = nil
return parent
}
func findExploding(nodes []*Node) *Node {
for _, node := range nodes {
if node.depth > 4 {
return node.parent
}
}
return nil
}
func findSpilt(nodes []*Node) *Node {
for _, node := range nodes {
if node.val >= 10 {
return node
}
}
return nil
}
func (main *Node) explore() {
nodes := main.flatten()
modified := true
for modified {
modified = false
node := findExploding(nodes)
if node == nil {
node = findSpilt(nodes)
if node != nil {
parent := node.parent
if node.isLeft() {
parent.left = node.split()
} else {
parent.right = node.split()
}
node = nil
modified = true
}
} else {
parent := node.parent
if node.isLeft() {
parent.left = node.explode()
} else {
parent.right = node.explode()
}
node = nil
modified = true
}
if modified {
nodes = main.flatten()
}
}
}
func (node *Node) value() int {
sum := 0
if node.left.isSimple() {
sum += 3 * node.left.val
} else {
sum += 3 * node.left.value()
}
if node.right.isSimple() {
sum += 2 * node.right.val
} else {
sum += 2 * node.right.value()
}
return sum
}
func(node *Node) flatten() (nodes []*Node) {
if node.left.isSimple() {
nodes = append(nodes, node.left)
} else {
nodes = append(nodes, node.left.flatten()...)
}
if node.right.isSimple() {
nodes = append(nodes, node.right)
} else {
nodes = append(nodes, node.right.flatten()...)
}
return
}
type stream struct {
s string
idx int
}
func (s *stream) next() string {
if s.idx >= len(s.s) {
return ""
}
c := s.s[s.idx]
s.idx++
return string(c)
}
func newStream(s string) *stream {
return &stream{
s: s,
idx: 0,
}
}
func newNode(s string) (*Node, error) {
return processPair(newStream(s), nil, 0)
}
func processPair(s *stream, parent *Node, depth int) (*Node, error) {
val := s.next()
var err error
switch val {
case "[":
node := &Node{
depth: depth,
parent: parent,
}
node.left, err = processPair(s, node, depth+1)
if err != nil {
return nil, err
}
s.next()
node.right, err = processPair(s, node, depth+1)
if err != nil {
return nil, err
}
s.next()
return node, nil
default:
v, err := strconv.Atoi(val)
if err != nil {
return nil, err
}
node := &Node{
depth: depth,
parent: parent,
val: v,
}
return node, nil
}
} | day18/utils.go | 0.546738 | 0.418875 | utils.go | starcoder |
Memory Sections
A memory section is a contiguous region of real memory. The access attributes
control it's usage (read.write, executable, misaligned access). Loading an ELF
file will typically create a number of sections with appropriate attributes.
*/
//-----------------------------------------------------------------------------
package mem
import "encoding/binary"
//-----------------------------------------------------------------------------
// Section is a contiguous region of real memory.
type Section struct {
name string // section name
attr Attribute // bitmask of attributes
start, end uint // address range
mem []uint8 // memory array
}
// NewSection allocates and returns a memory chunk.
func NewSection(name string, start, size uint, attr Attribute) *Section {
mem := make([]uint8, size)
return &Section{
name: name,
attr: attr,
start: start,
end: start + size - 1,
mem: mem,
}
}
// SetAttr sets the attributes for this memory section.
func (m *Section) SetAttr(attr Attribute) {
m.attr = attr
}
// Info returns the information for this region.
func (m *Section) Info() *RegionInfo {
return &RegionInfo{
name: m.name,
start: m.start,
end: m.end,
attr: m.attr,
}
}
// In returns true if the adr, size is entirely within the memory chunk.
func (m *Section) In(adr, size uint) bool {
end := adr + size - 1
return (adr >= m.start) && (end <= m.end)
}
// RdIns reads a 32-bit instruction from memory.
func (m *Section) RdIns(adr uint) (uint, error) {
return uint(binary.LittleEndian.Uint32(m.mem[adr-m.start:])), rdInsError(adr, m.attr, m.name)
}
// Rd64 reads a 64-bit data value from memory.
func (m *Section) Rd64(adr uint) (uint64, error) {
return binary.LittleEndian.Uint64(m.mem[adr-m.start:]), rdError(adr, m.attr, m.name, 8)
}
// Rd32 reads a 32-bit data value from memory.
func (m *Section) Rd32(adr uint) (uint32, error) {
return binary.LittleEndian.Uint32(m.mem[adr-m.start:]), rdError(adr, m.attr, m.name, 4)
}
// Rd16 reads a 16-bit data value from memory.
func (m *Section) Rd16(adr uint) (uint16, error) {
return binary.LittleEndian.Uint16(m.mem[adr-m.start:]), rdError(adr, m.attr, m.name, 2)
}
// Rd8 reads an 8-bit data value from memory.
func (m *Section) Rd8(adr uint) (uint8, error) {
return m.mem[adr-m.start], rdError(adr, m.attr, m.name, 1)
}
// Wr64 writes a 64-bit data value to memory.
func (m *Section) Wr64(adr uint, val uint64) error {
err := wrError(adr, m.attr, m.name, 8)
if err == nil {
binary.LittleEndian.PutUint64(m.mem[adr-m.start:], val)
}
return err
}
// Wr32 writes a 32-bit data value to memory.
func (m *Section) Wr32(adr uint, val uint32) error {
err := wrError(adr, m.attr, m.name, 4)
if err == nil {
binary.LittleEndian.PutUint32(m.mem[adr-m.start:], val)
}
return err
}
// Wr16 writes a 16-bit data value to memory.
func (m *Section) Wr16(adr uint, val uint16) error {
err := wrError(adr, m.attr, m.name, 2)
if err == nil {
binary.LittleEndian.PutUint16(m.mem[adr-m.start:], val)
}
return err
}
// Wr8 writes an 8-bit data value to memory.
func (m *Section) Wr8(adr uint, val uint8) error {
err := wrError(adr, m.attr, m.name, 1)
if err == nil {
m.mem[adr-m.start] = val
}
return err
}
//----------------------------------------------------------------------------- | mem/section.go | 0.79649 | 0.491273 | section.go | starcoder |
package scl
import (
"bufio"
"fmt"
"io"
"math"
"strconv"
"strings"
)
// A Scale is a sequence of pitches that can be applied relative to a base frequency.
type Scale struct {
Description string
Pitches []Pitch
}
// Freqs returns one octave of frequencies in the scale, starting at and including
// the given base frequency.
func (s Scale) Freqs(base float64) []float64 {
f := make([]float64, len(s.Pitches)+1)
f[0] = base
for i, p := range s.Pitches {
f[i+1] = p.Freq(base)
}
return f
}
// Pitch represents one scale pitch.
type Pitch interface {
// Freq returns the pitch frequency relative to the given base.
Freq(base float64) float64
String() string
}
// A RatioPitch is a pitch which is the ratio of two integers.
type RatioPitch struct {
N, D int64
}
func (p RatioPitch) String() string {
return fmt.Sprintf("%d/%d", p.N, p.D)
}
func (p RatioPitch) Freq(f float64) float64 {
return float64(p.N) * f / float64(p.D)
}
// A CentsPitch represents a pitch given in units of cents.
type CentsPitch float64
func (p CentsPitch) String() string {
return fmt.Sprintf("%f", p)
}
func (p CentsPitch) Freq(f float64) float64 {
return f * math.Exp2(float64(p)/1200.0)
}
// Read reads a Scale from the given reader.
// The input is assumed to be a file in scl format and is consumed until EOF is reached.
func Read(r io.Reader) (Scale, error) {
var (
scale Scale
readDesc bool
readNum bool
numPitches int64
err error
)
s := bufio.NewScanner(r)
for i := 1; s.Scan(); i++ {
line := s.Text()
if strings.HasPrefix(line, "!") {
continue
} else if !readDesc {
scale.Description = line
readDesc = true
} else if !readNum {
line = strings.TrimSpace(line)
numPitches, err = strconv.ParseInt(line, 10, 64)
if err != nil {
return scale, fmt.Errorf("malformed number of pitches: %s", line)
}
readNum = true
} else {
pitch, err := parsePitch(line)
if err != nil {
fmt.Errorf("Parse error on line %d: %s", i, err)
}
scale.Pitches = append(scale.Pitches, pitch)
}
}
if len(scale.Pitches) != int(numPitches) {
return scale, fmt.Errorf("read %d pitches but expected %d", len(scale.Pitches), numPitches)
}
return scale, s.Err()
}
// Write writes a scale to the given writer in scl format.
// If name is a non-empty string it is written in a comment at the beginning of the output,
// as is customary in .scl files.
func Write(w io.Writer, s Scale, name string) error {
if name != "" {
_, err := fmt.Fprintf(w, "! %s\n!\n", name)
if err != nil {
return err
}
}
_, err := fmt.Fprintln(w, s.Description)
if err != nil {
return err
}
_, err = fmt.Fprintf(w, " %d\n", len(s.Pitches))
if err != nil {
return err
}
for _, p := range s.Pitches {
_, err := fmt.Fprintf(w, " %s\n", p)
if err != nil {
return err
}
}
return nil
}
func parsePitch(s string) (Pitch, error) {
s = strings.Fields(s)[0]
if strings.ContainsRune(s, '.') {
v, err := strconv.ParseFloat(s, 64)
return CentsPitch(v), err
}
var (
p = RatioPitch{1, 1}
parts = strings.Split(s, "/")
err error
)
switch len(parts) {
case 2:
d, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return p, err
}
p.D = d
fallthrough
case 1:
n, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return p, err
}
p.N = n
default:
err = fmt.Errorf("malformed pitch ratio: %s", s)
}
if p.N <= 0 || p.D <= 0 {
err = fmt.Errorf("malformed pitch ratio: %s", s)
}
return p, err
} | scl.go | 0.689933 | 0.402392 | scl.go | starcoder |
package dom
import (
"encoding/json"
"reflect"
"strings"
"unicode"
"github.com/murlokswarm/app"
"github.com/pkg/errors"
)
// Mapping represents a component method or field descriptor.
type Mapping struct {
// The component identifier.
CompoID string
// A dot separated string that points to a component field or method.
FieldOrMethod string
// The JSON value to map to a field or method's first argument.
JSONValue string
// A string that describes a field that may required override.
Override string
pipeline []string
index int
}
// Map performs the mapping to the given component.
func (m *Mapping) Map(c app.Compo) (f func(), err error) {
if m.pipeline, err = pipeline(m.FieldOrMethod); err != nil {
return nil, err
}
return m.mapTo(reflect.ValueOf(c))
}
func (m *Mapping) currentPipeline() []string {
return m.pipeline[m.index:]
}
func (m *Mapping) target() string {
return m.pipeline[m.index]
}
func (m *Mapping) fullTarget() string {
return strings.Join(m.pipeline[:m.index+1], ".")
}
func (m *Mapping) mapTo(value reflect.Value) (func(), error) {
switch value.Kind() {
case reflect.Ptr:
return m.mapToPointer(value)
case reflect.Struct:
return m.mapToStruct(value)
case reflect.Map:
return m.mapToMap(value)
case reflect.Slice, reflect.Array:
return m.mapToSlice(value)
case reflect.Func:
return m.mapToFunction(value)
default:
return m.mapToValue(value)
}
}
func (m *Mapping) mapToPointer(ptr reflect.Value) (func(), error) {
if len(m.currentPipeline()) == 0 {
return m.mapToValue(ptr)
}
if !isExported(m.target()) {
return nil, errors.Errorf("%s is mapped to an unexported method", m.fullTarget())
}
method := ptr.MethodByName(m.target())
if method.IsValid() {
m.index++
return m.mapTo(method)
}
return m.mapTo(ptr.Elem())
}
func (m *Mapping) mapToStruct(structure reflect.Value) (func(), error) {
if len(m.currentPipeline()) == 0 {
return m.mapToValue(structure)
}
if !isExported(m.target()) {
return nil, errors.Errorf(
"%s is mapped to unexported field or method",
m.fullTarget(),
)
}
if method := structure.MethodByName(m.target()); method.IsValid() {
m.index++
return m.mapTo(method)
}
field := structure.FieldByName(m.target())
if !field.IsValid() {
return nil, errors.Errorf(
"%s is mapped to a nonexistent field or method",
m.fullTarget(),
)
}
m.index++
return m.mapTo(field)
}
func (m *Mapping) mapToMap(mapv reflect.Value) (func(), error) {
if len(m.currentPipeline()) == 0 {
return m.mapToValue(mapv)
}
if isExported(m.target()) {
if method := mapv.MethodByName(m.target()); method.IsValid() {
m.index++
return m.mapTo(method)
}
}
return nil, errors.Errorf(
"%s is mapped to a map value",
m.fullTarget(),
)
}
func (m *Mapping) mapToSlice(slice reflect.Value) (func(), error) {
if len(m.currentPipeline()) == 0 {
return m.mapToValue(slice)
}
if isExported(m.target()) {
if method := slice.MethodByName(m.target()); method.IsValid() {
m.index++
return m.mapTo(method)
}
}
return nil, errors.Errorf(
"%s is mapped to a slice value",
m.fullTarget(),
)
}
func (m *Mapping) mapToFunction(fn reflect.Value) (func(), error) {
if len(m.currentPipeline()) != 0 {
return nil, errors.Errorf(
"%s is mapped to a unsuported method",
m.fullTarget(),
)
}
typ := fn.Type()
if typ.NumIn() > 1 {
return nil, errors.Errorf(
"%s is mapped to func that have more than 1 arg",
m.pipeline,
)
}
if typ.NumIn() == 0 {
return func() {
fn.Call(nil)
}, nil
}
arg := reflect.New(typ.In(0))
if err := json.Unmarshal([]byte(m.JSONValue), arg.Interface()); err != nil {
return nil, errors.Wrapf(err, "%s:", m.pipeline)
}
return func() {
fn.Call([]reflect.Value{arg.Elem()})
}, nil
}
func (m *Mapping) mapToValue(value reflect.Value) (func(), error) {
if len(m.currentPipeline()) == 0 {
newValue := reflect.New(value.Type())
if err := json.Unmarshal([]byte(m.JSONValue), newValue.Interface()); err != nil {
return nil, errors.Wrapf(err, "%s:", m.pipeline)
}
value.Set(newValue.Elem())
return nil, nil
}
if !isExported(m.target()) {
return nil, errors.Errorf(
"%s is mapped to a unsuported method",
m.fullTarget(),
)
}
method := value.MethodByName(m.target())
if !method.IsValid() {
return nil, errors.Errorf(
"%s is mapped to a undefined method",
m.fullTarget(),
)
}
m.index++
return m.mapTo(method)
}
func pipeline(fieldOrMethod string) ([]string, error) {
if len(fieldOrMethod) == 0 {
return nil, errors.New("empty")
}
p := strings.Split(fieldOrMethod, ".")
for _, e := range p {
if len(e) == 0 {
return nil, errors.Errorf("%s: contains an empty element", fieldOrMethod)
}
}
return p, nil
}
func isExported(fieldOrMethod string) bool {
return !unicode.IsLower(rune(fieldOrMethod[0]))
} | internal/dom/map.go | 0.655005 | 0.455441 | map.go | starcoder |
package tort
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
)
// StringAssertions are tests around string values.
type StringAssertions struct {
Assertions
name string
str string
}
// String identifies a string variable value and returns test functions for its values.
func (assert Assertions) String(value string) StringAssertions {
assert.t.Helper()
return StringAssertions{
Assertions: assert,
name: "string",
str: value,
}
}
// String identifies a string field on a struct. If the field isn't present, or isn't a string,
// generates an error.
func (assert StructAssertions) String(field string) StringAssertions {
assert.t.Helper()
name := fmt.Sprintf("%s.%s", assert.Type(), field)
property := assert.Field(field)
if property.Kind() != reflect.String {
assert.Fatal("field %s is not a string", name)
}
return StringAssertions{
Assertions: assert.Assertions,
name: name,
str: property.String(),
}
}
// String looks up an element in a slice expecting it to be a string.
func (assert SliceAssertions) String(idx int) StringAssertions {
assert.t.Helper()
name := strconv.Itoa(idx)
property := assert.Element(idx)
if property.Kind() != reflect.String {
assert.Fatal("element %d is not a string", idx)
}
return StringAssertions{
Assertions: assert.Assertions,
name: name,
str: property.String(),
}
}
// Blank generates an error if the string is not empty with something other than whitespace.
func (assert StringAssertions) Blank() {
assert.t.Helper()
if strings.TrimSpace(assert.str) != "" {
assert.Failed(`%s is not blank; is "%s"`, assert.name, assert.str)
}
}
// NotBlank generates an error if the string is empty or contains only whitespace.
func (assert StringAssertions) NotBlank() {
assert.t.Helper()
if strings.TrimSpace(assert.str) == "" {
assert.Failed(`%s is blank"`, assert.name)
}
}
// IsBlank is an alias for Blank.
func (assert StringAssertions) IsBlank() {
assert.t.Helper()
if strings.TrimSpace(assert.str) != "" {
assert.Failed(`%s is not blank; is "%s"`, assert.name, assert.str)
}
}
// IsNotBlank is an alias for NotBlank.
func (assert StringAssertions) IsNotBlank() {
assert.t.Helper()
if strings.TrimSpace(assert.str) == "" {
assert.Failed(`%s is blank"`, assert.name)
}
}
// Empty generates an error if the string contains any characters, including whitespace.
func (assert StringAssertions) Empty() {
assert.t.Helper()
if assert.str != "" {
assert.Failed(`%s is not empty; is "%s"`, assert.name, assert.str)
}
}
// NotEmpty generates an error if the string does not contain any characters, including whitespace.
func (assert StringAssertions) NotEmpty() {
assert.t.Helper()
if assert.str == "" {
assert.Failed(`%s is empty"`, assert.name)
}
}
// Equals generates an error if the string value isn't the same as other.
func (assert StringAssertions) Equals(other string) {
assert.t.Helper()
if assert.str != other {
assert.Failed(`expected %s to be "%s" but it was "%s"`, assert.name, other, assert.str)
}
}
// NotEquals generates an error if the string value is the same as the other.
func (assert StringAssertions) NotEquals(other string) {
assert.t.Helper()
if assert.str == other {
assert.Failed(`expected %s to not be "%s"`, assert.name, other)
}
}
// Contains generates an error if the other value isn't present somewhere in the string.
func (assert StringAssertions) Contains(other string) {
assert.t.Helper()
if !strings.Contains(assert.str, other) {
assert.Failed(`expected %s to contain "%s" (is "%s")`, assert.name, other, assert.str)
}
}
// NotContains generates an error if the other value is present somewhere in the string.
func (assert StringAssertions) NotContains(other string) {
assert.t.Helper()
if strings.Contains(assert.str, other) {
assert.Failed(`expected %s to not contain "%s" (is "%s")`, assert.name, other, assert.str)
}
}
// Matches generates an error if the string value doesn't match the regular expression.
func (assert StringAssertions) Matches(expr string) {
assert.t.Helper()
matched, err := regexp.MatchString(expr, assert.str)
if err != nil {
assert.Fatal(`invalid regular expression "%s"`, expr)
}
if !matched {
assert.Failed(`expected %s to match "%s" (is %s)`, assert.name, expr, assert.str)
}
}
// NotMatches generates an error if the string value matches the regular expression.
func (assert StringAssertions) NotMatches(expr string) {
assert.t.Helper()
matched, err := regexp.MatchString(expr, assert.str)
if err != nil {
assert.Fatal(`invalid regular expression "%s"`, expr)
}
if matched {
assert.Failed(`expected %s not to match "%s" (is %s)`, assert.name, expr, assert.str)
}
} | strings.go | 0.774199 | 0.730891 | strings.go | starcoder |
package bexpr
import (
"reflect"
"strconv"
)
// CoerceInt conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int`
func CoerceInt(value string) (interface{}, error) {
i, err := strconv.ParseInt(value, 0, 0)
return int(i), err
}
// CoerceInt8 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int8`
func CoerceInt8(value string) (interface{}, error) {
i, err := strconv.ParseInt(value, 0, 8)
return int8(i), err
}
// CoerceInt16 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int16`
func CoerceInt16(value string) (interface{}, error) {
i, err := strconv.ParseInt(value, 0, 16)
return int16(i), err
}
// CoerceInt32 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int32`
func CoerceInt32(value string) (interface{}, error) {
i, err := strconv.ParseInt(value, 0, 32)
return int32(i), err
}
// CoerceInt64 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int64`
func CoerceInt64(value string) (interface{}, error) {
i, err := strconv.ParseInt(value, 0, 64)
return int64(i), err
}
// CoerceUint conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int`
func CoerceUint(value string) (interface{}, error) {
i, err := strconv.ParseUint(value, 0, 0)
return uint(i), err
}
// CoerceUint8 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int8`
func CoerceUint8(value string) (interface{}, error) {
i, err := strconv.ParseUint(value, 0, 8)
return uint8(i), err
}
// CoerceUint16 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int16`
func CoerceUint16(value string) (interface{}, error) {
i, err := strconv.ParseUint(value, 0, 16)
return uint16(i), err
}
// CoerceUint32 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int32`
func CoerceUint32(value string) (interface{}, error) {
i, err := strconv.ParseUint(value, 0, 32)
return uint32(i), err
}
// CoerceUint64 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `int64`
func CoerceUint64(value string) (interface{}, error) {
i, err := strconv.ParseUint(value, 0, 64)
return uint64(i), err
}
// CoerceBool conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into a `bool`
func CoerceBool(value string) (interface{}, error) {
return strconv.ParseBool(value)
}
// CoerceFloat32 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `float32`
func CoerceFloat32(value string) (interface{}, error) {
// ParseFloat always returns a float64 but ensures
// it can be converted to a float32 without changing
// its value
f, err := strconv.ParseFloat(value, 32)
return float32(f), err
}
// CoerceFloat64 conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into an `float64`
func CoerceFloat64(value string) (interface{}, error) {
return strconv.ParseFloat(value, 64)
}
// CoerceString conforms to the FieldValueCoercionFn signature
// and can be used to convert the raw string value of
// an expression into a `string`
func CoerceString(value string) (interface{}, error) {
return value, nil
}
var primitiveCoercionFns = map[reflect.Kind]FieldValueCoercionFn{
reflect.Bool: CoerceBool,
reflect.Int: CoerceInt,
reflect.Int8: CoerceInt8,
reflect.Int16: CoerceInt16,
reflect.Int32: CoerceInt32,
reflect.Int64: CoerceInt64,
reflect.Uint: CoerceUint,
reflect.Uint8: CoerceUint8,
reflect.Uint16: CoerceUint16,
reflect.Uint32: CoerceUint32,
reflect.Uint64: CoerceUint64,
reflect.Float32: CoerceFloat32,
reflect.Float64: CoerceFloat64,
reflect.String: CoerceString,
} | vendor/github.com/hashicorp/go-bexpr/coerce.go | 0.778776 | 0.616849 | coerce.go | starcoder |
package stateindex
import (
"errors"
"math"
)
const (
hextable = "0123456789abcdef"
reverseOrder = '0'
normalOrder = '1'
)
// EncodeInt64 encodes a given int64 value to a hexadecimal representation to
// preserve the order of actual value, i.e., -100 < -10 < 0 < 100 < 1000
func EncodeInt64(n int64) string {
if n < 0 {
return encodeReverseOrderVarUint64(-uint64(n))
}
return encodeOrderPreservingVarUint64(uint64(n))
}
// encodeOrderPreservingVarUint64 returns a string-representation for a uint64 number such that
// all zero-bits starting bytes are trimmed in order to reduce the length of the array
// For preserving the order in a default bytes-comparison, first byte contains the type of
// encoding and the second byte contains the number of remaining bytes.
func encodeOrderPreservingVarUint64(n uint64) string {
var bytePosition int
for bytePosition = 0; bytePosition <= 7; bytePosition++ {
if byte(n>>(56-(bytePosition*8))) != 0x00 {
break
}
}
size := int8(8 - bytePosition)
encodedBytes := make([]byte, encodedLen(int(size)+1))
b := byte(size)
// given that size will never be greater than 8, we use the first
// byte to denote the normal order encoding
encodedBytes[0] = normalOrder
encodedBytes[1] = hextable[b]
j := 2
for r := bytePosition; r <= 7; r++ {
b = byte(n >> (56 - (r * 8)))
encodedBytes[j] = hextable[b>>4]
encodedBytes[j+1] = hextable[b&0x0f]
j += 2
}
return string(encodedBytes)
}
// encodeReverseOrderVarUint64 returns a string-representation for a uint64 number such that
// the number is first subtracted from MaxUint64 and then all the leading 0xff bytes
// are trimmed and replaced by the number of such trimmed bytes. This helps in reducing the size.
// In the byte order comparison this encoding ensures that EncodeReverseOrderVarUint64(A) > EncodeReverseOrderVarUint64(B),
// If B > A
func encodeReverseOrderVarUint64(n uint64) string {
n = math.MaxUint64 - n
var bytePosition int
for bytePosition = 0; bytePosition <= 7; bytePosition++ {
if byte(n>>(56-(bytePosition*8))) != 0xff {
break
}
}
size := int8(8 - bytePosition)
encodedBytes := make([]byte, encodedLen(int(size)+1))
b := byte(bytePosition)
// given that size will never be greater than 8, we use the first
// byte to denote the reverse order encoding
encodedBytes[0] = reverseOrder
encodedBytes[1] = hextable[b]
j := 2
for r := bytePosition; r <= 7; r++ {
b = byte(n >> (56 - (r * 8)))
encodedBytes[j] = hextable[b>>4]
encodedBytes[j+1] = hextable[b&0x0f]
j += 2
}
return string(encodedBytes)
}
func decodeInt64(s string) (int64, error) {
n, o, err := decodeVarUint64(s)
if err != nil {
return 0, err
}
switch o {
case normalOrder:
return int64(n), nil
default:
return -int64(n), nil
}
}
func decodeVarUint64(s string) (uint64, int32, error) {
bs := []byte(s)
encodingType := bs[0]
switch encodingType {
case normalOrder:
bs[0] = '0'
n, err := decodeOrderPreservingVarUint64(bs)
if err != nil {
return 0, 0, err
}
return n, normalOrder, nil
case reverseOrder:
bs[0] = '0'
n, err := decodeReverseOrderVarUint64(bs)
if err != nil {
return 0, 0, err
}
return n, reverseOrder, nil
default:
return 0, 0, errors.New("unexpected prefix [" + string(bs[0]) + "]")
}
}
// decodeOrderPreservingVarUint64 decodes the number from the string obtained from method 'EncodeOrderPreservingVarUint64'.
// It returns the decoded number and error if any occurred during the decoding process.
func decodeOrderPreservingVarUint64(bs []byte) (uint64, error) {
sizeByte, err := convertHexAtLocationToBinary(bs, 0)
if err != nil {
return 0, err
}
size := int(sizeByte)
var v uint64
for i := 7; i >= 8-size; i-- {
location := (size - (7 - i)) * 2 // 2 character per hex
b, err := convertHexAtLocationToBinary(bs, location)
if err != nil {
return 0, err
}
v = v | uint64(b)<<(56-(i*8))
}
return v, nil
}
// decodeReverseOrderVarUint64 decodes the number from the string obtained from function 'encodeReverseOrderVarUint64'.
func decodeReverseOrderVarUint64(bs []byte) (uint64, error) {
bytePosition, err := convertHexAtLocationToBinary(bs, 0)
if err != nil {
return 0, err
}
size := 8 - int(bytePosition)
var v uint64
var i int
for i = 7; i >= 8-size; i-- {
location := (size - (7 - i)) * 2 // 2 character per hex
b, err := convertHexAtLocationToBinary(bs, location)
if err != nil {
return 0, err
}
v = v | uint64(b)<<(56-(i*8))
}
for j := i; j >= 0; j-- {
v = v | uint64(0xff)<<(56-(j*8))
}
return math.MaxUint64 - v, nil
}
func convertHexAtLocationToBinary(b []byte, location int) (byte, error) {
firstChar, err := fromHexChar(b[location])
if err != nil {
return 0, err
}
secondChar, err := fromHexChar(b[location+1])
if err != nil {
return 0, err
}
return (firstChar << 4) | secondChar, nil
}
// EncodedLen returns the length of an encoding of n source bytes.
// Specifically, it returns n * 2.
func encodedLen(n int) int { return n * 2 }
// fromHexChar converts a hex character into its value
func fromHexChar(c byte) (byte, error) {
switch {
case '0' <= c && c <= '9':
return c - '0', nil
case 'a' <= c && c <= 'f':
return c - 'a' + 10, nil
case 'A' <= c && c <= 'F':
return c - 'A' + 10, nil
default:
return 0, errors.New("invalid hex character [" + string(c) + "]")
}
} | internal/stateindex/encoding.go | 0.775009 | 0.454714 | encoding.go | starcoder |
package switchboard
// Supply needs to be implemented by any type acting as a supplier.
// Must be safe for concurrent use by multiple goroutines.
type Supply interface {
Estimate(demand Demand, choicesMade []Choice) (Choice, error)
}
// Demand is an empty interface that denotes a demand.
type Demand interface {
}
// Choice represents the fulfillment of a Demand with a particular Supply with
// its corresponding cost.
type Choice struct {
supply Supply
demand Demand
cost float64
attributes map[string]interface{}
}
// Supply returns the supply associated with the current choice
func (choice Choice) Supply() Supply {
return choice.supply
}
// Demand returns the demand associated with the current choice
func (choice Choice) Demand() Demand {
return choice.demand
}
// Cost returns the cost associated with the current choice
func (choice Choice) Cost() float64 {
return choice.cost
}
// Get retrieves the associated value from the attribute map
func (choice Choice) Get(key string) interface{} {
return choice.attributes[key]
}
// NewChoice build a new choice from the given supply, demand, cost and attributes.
func NewChoice(supply Supply, demand Demand, cost float64, attributes map[string]interface{}) (choice Choice) {
choice.supply = supply
choice.demand = demand
choice.cost = cost
choice.attributes = make(map[string]interface{})
for k, v := range attributes {
choice.attributes[k] = v
}
return
}
// Player evaluates a board and chooses a new board using a built-in strategy.
type Player func(board Board) (chosenBoard Board)
// GreedyPlayer is a fast player that just chooses the best available choice,
// resulting in a local minima.
func GreedyPlayer() Player {
return func(board Board) Board {
currentBestBoard := board
for _, choice := range board.availableChoices() {
candidateBoard := board.choose(choice)
if board.comparator(currentBestBoard, candidateBoard) {
currentBestBoard = candidateBoard
}
}
return currentBestBoard
}
}
// Explorer evaluates a board to determine whether its choices are worth
// exploring further. Must be safe for concurrent use by multiple goroutines.
type Explorer func(board Board) bool
// BruteForceExplorer forces the exploration of every possible board
func BruteForceExplorer() Explorer {
return func(board Board) bool { return true }
}
// GoalTransformer allows transformation of choice scores to determine the goal
// of the exploration
type GoalTransformer func(cost float64) float64
// Maximize provides a GoalTransformer which helps find the board with the
// highest total cost
func Maximize() GoalTransformer {
return func(cost float64) float64 { return cost }
}
// Minimize provides a GoalTransformer which helps find the board with the
// lowest total cost
func Minimize() GoalTransformer {
return func(cost float64) float64 { return cost * -1 }
}
// BoardComparator returns true if board2 is better than board1.
type BoardComparator func(board1, board2 Board) bool
// PrioritizeWorkDone gives first priority to the number of choices made - it
// can be used when it's more important to fulfill as much demand as possible
// than to just meet the cost goals
func PrioritizeWorkDone(transformer GoalTransformer) BoardComparator {
return func(b1, b2 Board) bool {
if len(b1.ChoicesMade()) == len(b2.ChoicesMade()) {
if transformer(b2.Cost()) > transformer(b1.Cost()) {
return true
}
} else {
if len(b2.ChoicesMade()) > len(b1.ChoicesMade()) {
return true
}
}
return false
}
}
// PrioritizeTotalCost simply targets a board with the given cost goal
func PrioritizeTotalCost(transformer GoalTransformer) BoardComparator {
return func(b1, b2 Board) bool {
return transformer(b2.Cost()) > transformer(b1.Cost())
}
} | switchboard.go | 0.844569 | 0.611237 | switchboard.go | starcoder |
package game
import (
"fmt"
)
const (
KeepPlaying int = iota
Draw
Win
)
// Contains the state of the game.
type Game struct {
Board [3][3]byte
Turn byte
}
// Creates a new game. i may either be a [3][3]byte, which represents an existing
// game (this is useful for testing), or nil, in which case a Game with a zeroed
// board is returned.
func NewGame(i interface{}) *Game {
switch v := i.(type) {
case [3][3]byte:
return &Game{
Board: v,
Turn: 'X',
}
default:
return &Game{
Board: [3][3]byte{},
Turn: 'X',
}
}
}
// Changes the state of the game by saying which square the current player has
// chosen to place an X or an O.
func (g *Game) PlayTurn(x, y int) error {
if x < 0 || x > 2 || y < 0 || y > 2 {
return fmt.Errorf("x %d y %d is not valid; must be in range 0-2", x, y)
}
if g.Board[y][x] != 0 {
return fmt.Errorf("square %d,%d is already occupied", x, y)
}
g.Board[y][x] = g.Turn
if g.Turn == 'X' {
g.Turn = 'O'
} else {
g.Turn = 'X'
}
return nil
}
// Returns either KeepPlaying, Draw, or Win in first argument.
// If the first argument is equal to Win, a WinInfo structure is
// returned in the second argument; otherwise, the second argument is nil.
func (g *Game) CheckWin() (int, WinInfo) {
// test for win condition
wc_array := [8][3][2]int{
[3][2]int{
[2]int{0, 0},
[2]int{0, 1},
[2]int{0, 2},
},
[3][2]int{
[2]int{1, 0},
[2]int{1, 1},
[2]int{1, 2},
},
[3][2]int{
[2]int{2, 0},
[2]int{2, 1},
[2]int{2, 2},
},
[3][2]int{
[2]int{0, 0},
[2]int{1, 0},
[2]int{2, 0},
},
[3][2]int{
[2]int{0, 1},
[2]int{1, 1},
[2]int{2, 1},
},
[3][2]int{
[2]int{0, 2},
[2]int{1, 2},
[2]int{2, 2},
},
[3][2]int{
[2]int{0, 0},
[2]int{1, 1},
[2]int{2, 2},
},
[3][2]int{
[2]int{0, 2},
[2]int{1, 1},
[2]int{2, 0},
},
}
for _, letter := range [2]byte{'X', 'O'} {
for _, wc := range wc_array {
win := true
for _, coords := range wc {
if g.Board[coords[1]][coords[0]] != letter {
win = false
}
}
if win {
return Win, MuhWin{
letter: g.Board[wc[0][1]][wc[0][0]],
squares: wc,
}
}
}
}
// test for draw condition
draw := true
for _, row := range g.Board {
for _, square := range row{
if square == 0 {
draw = false
break
}
}
}
if draw {
return Draw, nil
}
// neither win nor draw
return KeepPlaying, nil
} | game/game.go | 0.651022 | 0.498413 | game.go | starcoder |
package cryptopals
import (
"bytes"
"crypto/rsa"
"math/big"
)
type challenge47 struct {
}
type oracleFunc func([]byte) bool
type interval struct {
a *big.Int
b *big.Int
}
func (challenge47) mulEncrypt(s, e, n, c *big.Int) []byte {
x := new(big.Int).Exp(s, e, n)
return x.Mul(c, x).Mod(x, n).Bytes()
}
func (challenge47) union(M []interval, m interval) []interval {
if m.a.Cmp(m.b) > 0 {
return M
}
var result []interval
for i, mi := range M {
if mi.b.Cmp(m.a) < 0 {
result = append(result, mi)
} else if m.b.Cmp(mi.a) < 0 {
return append(append(result, m), M[i:]...)
} else {
m = interval{a: min(mi.a, m.a), b: max(mi.b, m.b)}
}
}
return append(result, m)
}
func (x challenge47) DecryptRsaPaddingOracleSimple(pub *rsa.PublicKey, ciphertext []byte, oracle oracleFunc) []byte {
e, c0, s := big.NewInt(int64(pub.E)), new(big.Int).SetBytes(ciphertext), new(big.Int)
k := big.NewInt(int64(pub.N.BitLen() / 8))
one, two, three, eight := big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(8)
B := new(big.Int).Sub(k, two)
B = B.Mul(eight, B).Exp(two, B, nil)
twoB, threeB := new(big.Int).Mul(two, B), new(big.Int).Mul(three, B)
M := []interval{{a: twoB, b: new(big.Int).Sub(threeB, one)}}
// Step 2: Searching for PKCS conforming messages.
for i := 1; ; i++ {
if i == 1 { // Step 2a: Starting the search.
for s = ceil(pub.N, threeB); !oracle(x.mulEncrypt(s, e, pub.N, c0)); s = s.Add(s, one) {
}
} else if len(M) > 1 { // Step 2.b: Searching with more than one interval left.
for s = s.Add(s, one); !oracle(x.mulEncrypt(s, e, pub.N, c0)); s = s.Add(s, one) {
}
} else { // Step 2.c: Searching with one interval left.
a, b, found := M[0].a, M[0].b, false
r := new(big.Int).Mul(b, s)
r = ceil(r.Sub(r, twoB).Mul(two, r), pub.N)
for ; !found; r = r.Add(r, one) {
sMin := new(big.Int).Mul(r, pub.N)
sMin = ceil(sMin.Add(twoB, sMin), b)
sMax := new(big.Int).Mul(r, pub.N)
sMax = sMax.Add(threeB, sMax).Div(sMax, a)
for s = sMin; s.Cmp(sMax) <= 0; s = s.Add(s, one) {
if oracle(x.mulEncrypt(s, e, pub.N, c0)) {
found = true
break
}
}
}
}
var Mi []interval
// Step 3: Narrowing the set of solutions.
for _, m := range M {
rMin := new(big.Int).Mul(m.a, s)
rMin = ceil(rMin.Sub(rMin, threeB).Add(rMin, one), pub.N)
rMax := new(big.Int).Mul(m.b, s)
rMax = rMax.Sub(rMax, twoB).Div(rMax, pub.N)
for r := rMin; r.Cmp(rMax) <= 0; r = r.Add(r, one) {
a := new(big.Int).Mul(r, pub.N)
a = max(m.a, ceil(a.Add(twoB, a), s))
b := new(big.Int).Mul(r, pub.N)
b = min(m.b, floor(b.Add(threeB, b).Sub(b, one), s))
mi := interval{a: a, b: b}
Mi = x.union(Mi, mi)
}
}
M = Mi
// Step 4: Computing the solution.
if len(M) == 1 && M[0].a.Cmp(M[0].b) == 0 {
padded := M[0].a.Bytes()
index := bytes.IndexByte(padded, 0)
return padded[index+1:]
}
}
} | challenge47.go | 0.650356 | 0.553686 | challenge47.go | starcoder |
package gdsp
import (
"math"
"sort"
)
// Min returns the minimum value from a vector.
func Min(v Vector) float64 {
if len(v) == 0 {
return 0.0
}
minValue := math.MaxFloat64
for _, r := range v {
if r < minValue {
minValue = r
}
}
return minValue
}
// Max returns the maximum value from a vector.
func Max(v Vector) float64 {
if len(v) == 0 {
return 0.0
}
maxValue := -math.MaxFloat64
for _, r := range v {
if r > maxValue {
maxValue = r
}
}
return maxValue
}
// MinReal returns the minimum value from a slice of floats.
func MinReal(v VectorComplex) float64 {
if len(v) == 0 {
return 0.0
}
minValue := math.MaxFloat64
for _, c := range v {
if real(c) < minValue {
minValue = real(c)
}
}
return minValue
}
// MaxReal returns the maximum value from a slice of floats.
func MaxReal(v VectorComplex) float64 {
if len(v) == 0 {
return 0.0
}
maxValue := -math.MaxFloat64
for _, c := range v {
if real(c) > maxValue {
maxValue = real(c)
}
}
return maxValue
}
// MinImag returns the minimum value from a slice of floats.
func MinImag(v VectorComplex) float64 {
if len(v) == 0 {
return 0.0
}
minValue := math.MaxFloat64
for _, c := range v {
if imag(c) < minValue {
minValue = imag(c)
}
}
return minValue
}
// MaxImag returns the maximum value from a slice of floats.
func MaxImag(v VectorComplex) float64 {
if len(v) == 0 {
return 0.0
}
maxValue := -math.MaxFloat64
for _, c := range v {
if imag(c) > maxValue {
maxValue = imag(c)
}
}
return maxValue
}
// Mean returns the mean of the elements of v.
func Mean(v Vector) float64 {
return VESum(v) / float64(len(v))
}
// Median returns the median of the elements of v.
func Median(v Vector) float64 {
vc := v.Copy()
sort.Float64s(vc)
if len(v)%2 == 0 {
v1 := v[len(v)/2]
v2 := v[len(v)/2+1]
return (v1 + v2) / 2.0
}
return vc[(len(vc)-1)+1]
}
// StdDev returns the standard deviation of the elements of v.
func StdDev(v Vector) float64 {
s := 0.0
m := Mean(v)
for _, r := range v {
x := r - m
s += x * x
}
return math.Sqrt(s / float64(len(v)-1))
}
// Normalize normalizes the given vector.
func Normalize(v Vector) Vector {
nv := MakeVector(0.0, len(v))
s := StdDev(v)
m := Mean(v)
for i, r := range v {
nv[i] = (r - m) / s
}
return nv
}
// NormalizeStrict normalizes a vector using the max and min elements.
func NormalizeStrict(v Vector) (Vector, []float64) {
maxValue := Max(v)
minValue := Min(v)
difference := maxValue - minValue
nv := MakeVector(0.0, len(v))
for i, r := range v {
x := 0.0
if difference != 0.0 {
x = (r - minValue) / difference
}
nv[i] = x
}
return nv, []float64{minValue, maxValue}
}
// NormalizeStrictC normalizes a complex-valued vector.
func NormalizeStrictC(v VectorComplex) (VectorComplex, []float64) {
real := v.Real()
imag := v.Imag()
nReal, rLimits := NormalizeStrict(real)
nImag, iLimits := NormalizeStrict(imag)
vc := MakeVectorComplexFromSplit(nReal, nImag)
return vc, append(rLimits, iLimits...)
} | stat.go | 0.861887 | 0.491212 | stat.go | starcoder |
package datatable
import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/DATA-DOG/godog/gherkin"
"github.com/jinzhu/copier"
"github.com/tidwall/pretty"
)
// Options defines field options for the DataTable.
type Options struct {
OptionalFields []string
RequiredFields []string
}
// DataTable defines a table with fields names and rows.
type DataTable struct {
fields []string
rows [][]string
options *Options
}
// New creates a new DataTable with given fields. It optionally accepts initial
// rows.
func New(fields []string, rows ...[]string) (*DataTable, error) {
return NewWithOptions(nil, fields, rows...)
}
// NewWithOptions create a new DataTable with options and given fields. It
// optionally accepts inital rows.
func NewWithOptions(options *Options, fields []string, rows ...[]string) (*DataTable, error) {
for _, row := range rows {
if len(row) != len(fields) {
return nil, fmt.Errorf("expected row length of %d, got %d", len(fields), len(row))
}
}
dt := &DataTable{
fields: fields,
rows: rows,
options: options,
}
if err := dt.validateFields(); err != nil {
return nil, err
}
return dt, nil
}
// FromGherkin creates a new DataTable from *gherkin.DataTable
func FromGherkin(dt *gherkin.DataTable) (*DataTable, error) {
return FromGherkinWithOptions(nil, dt)
}
// FromGherkinWithOptions creates a new DataTable from *gherkin.DataTable with options.
func FromGherkinWithOptions(options *Options, dt *gherkin.DataTable) (*DataTable, error) {
if len(dt.Rows) < 2 {
return nil, errors.New("data table must have at least two rows")
}
return NewWithOptions(options, values(dt.Rows[0]), rowValues(dt.Rows[1:])...)
}
// validateFields ensures that required fields are present and there are only
// fields listed in the AllowedFields option if the data table was created with
// options.
func (t *DataTable) validateFields() error {
if t.options == nil {
return nil
}
for _, field := range t.options.RequiredFields {
if !contains(t.fields, field) {
return fmt.Errorf(`data table is missing required field %q`, field)
}
}
if len(t.options.OptionalFields) == 0 {
return nil
}
allowedFields := append(t.options.OptionalFields, t.options.RequiredFields...)
for _, field := range t.fields {
if !contains(allowedFields, field) {
return fmt.Errorf(
`data table contains additional field %q, allowed fields are "%s"`,
field,
strings.Join(allowedFields, `", "`),
)
}
}
return nil
}
// Copy makes a copy of the data table.
func (t *DataTable) Copy() *DataTable {
c := &DataTable{
fields: make([]string, len(t.fields)),
rows: make([][]string, len(t.rows)),
}
copier.Copy(&c.fields, &t.fields)
copier.Copy(&c.rows, &t.rows)
return c
}
// FindRow compares given row with all rows in the data table and returns the
// row index if a matching row is found. Returns -1 if row cannot be found.
func (t *DataTable) FindRow(row []string) int {
for i, r := range t.rows {
if matchValues(r, row) {
return i
}
}
return -1
}
// RemoveRow removes the row at given index.
func (t *DataTable) RemoveRow(index int) {
t.rows = append(t.rows[:index], t.rows[index+1:]...)
}
// AppendRow appends a row to the data table. Will return an error if the
// number of fields does not match the data table's fields.
func (t *DataTable) AppendRow(row []string) error {
if len(row) != len(t.fields) {
return fmt.Errorf("expected row length of %d, got %d", len(t.fields), len(row))
}
t.rows = append(t.rows, row)
return nil
}
// Len returns the row count of the data table.
func (t *DataTable) Len() int {
return len(t.rows)
}
// Fields returns the table fields.
func (t *DataTable) Fields() []string {
return t.fields
}
// Rows transforms the data table rows into a slice of maps and returns it.
// The map keys are the data table's fields for every row.
func (t *DataTable) Rows() []map[string]string {
s := make([]map[string]string, len(t.rows))
for i, row := range t.rows {
m := make(map[string]string)
for j, field := range t.fields {
m[field] = row[j]
}
s[i] = m
}
return s
}
// RowValues returns the row values.
func (t *DataTable) RowValues() [][]string {
return t.rows
}
// PrettyJSON is a convenience function for transforming the data table into
// its prettyprinted json representation. Will panic if json marshalling fails.
func (t *DataTable) PrettyJSON() []byte {
buf, err := json.Marshal(t.Rows())
if err != nil {
panic(err)
}
return pretty.Pretty(buf)
}
// rowValues converts a slice of *gherkin.TableRow into a slice of string
// slices.
func rowValues(rows []*gherkin.TableRow) [][]string {
vals := make([][]string, len(rows))
for i, row := range rows {
vals[i] = values(row)
}
return vals
}
// values converts a *gherkin.TableRow into a slice of strings.
func values(row *gherkin.TableRow) []string {
values := make([]string, len(row.Cells))
for i, cell := range row.Cells {
values[i] = cell.Value
}
return values
}
// matchRow returns true if all values in two string slices match pairwise.
func matchValues(a, b []string) bool {
for i := range a {
if b[i] != a[i] {
return false
}
}
return true
}
// contains returns true if haystack contains needle
func contains(haystack []string, needle string) bool {
for _, element := range haystack {
if element == needle {
return true
}
}
return false
} | datatable/datatable.go | 0.7865 | 0.492981 | datatable.go | starcoder |
package physics
import "github.com/zladovan/gorched/gmath"
// Physics represents very simplistic physical model.
// In this model there are some bodies which can move and fall.
// Optionally body can land on the ground.
// There are no other collisions resolved here instead of landing on the ground.
// If you want to apply physics to your object implement HasBody interface.
// If you want to let your object land on the ground implement Lander interface too.
type Physics struct {
// Gravity holds gravitational acceleration
Gravity float64
// Ground resolves nearest ground y coordinate for position given by x and y
Ground func(x, y int) int
}
// Body is the main object in physical model.
type Body struct {
// Position holds position of body
Position gmath.Vector2f
// Velocity holds velocity of body
Velocity gmath.Vector2f
// Mass holds mass of body
Mass float64
// Locked if is true no physics is applied to this body
Locked bool
}
// HasBody describes some object which can provide physical Body.
type HasBody interface {
Body() *Body
}
// Lander describes some object which is able to land on the ground.
// It should return x coordinates (start, end) relative to body position of the bottom line used for the collision with ground.
type Lander interface {
BottomLine() (int, int)
}
// Apply will update body according to this physical model.
// Velocity will be updated by gravitational accelleration.
// Position will be updated by velocity.
// Position could be trimmed to the ground positions if given object e implements Lander interface too.
func (p *Physics) Apply(e HasBody, dt float64) {
body := e.Body()
y := int(body.Position.Y)
// nothing to update if body is locked
if body.Locked {
return
}
// update velocity by gravity
body.Velocity.Y += p.Gravity * dt * body.Mass
// update position by velocity
body.Position.X += body.Velocity.X * dt
body.Position.Y += body.Velocity.Y * dt
// process landing on the ground if possible
if faller, ok := e.(Lander); ok {
bx1, bx2 := faller.BottomLine()
minx := int(body.Position.X) + bx1
maxx := int(body.Position.X) + bx2
// check collision with bottom line and the ground
for i := minx; i <= maxx; i++ {
groundy := p.Ground(i, y)
if int(body.Position.Y) > groundy {
body.Position.Y = float64(groundy)
body.Velocity.Y = 0
break
}
}
}
} | physics/physics.go | 0.777131 | 0.566828 | physics.go | starcoder |
package autospotting
import (
"math"
"strconv"
)
const (
// The tag names below allow overriding global setting on a per-group level.
// They should follow the format below:
// "autospotting_${overridden_command_line_parameter_name}"
// For example the tag named "autospotting_min_on_demand_number" will override
// the command-line option named "min_on_demand_number", and so on.
// OnDemandPercentageTag is the name of a tag that can be defined on a
// per-group level for overriding maintained on-demand capacity given as a
// percentage of the group's running instances.
OnDemandPercentageTag = "autospotting_min_on_demand_percentage"
// OnDemandNumberLong is the name of a tag that can be defined on a
// per-group level for overriding maintained on-demand capacity given as an
// absolute number.
OnDemandNumberLong = "autospotting_min_on_demand_number"
// BiddingPolicyTag stores the bidding policy for the spot instance
BiddingPolicyTag = "autospotting_bidding_policy"
// SpotPriceBufferPercentageTag stores percentage value above the
// current spot price to place the bid
SpotPriceBufferPercentageTag = "autospotting_spot_price_buffer_percentage"
// AllowedInstanceTypesTag is the name of a tag that can indicate which
// instance types are allowed in the current group
AllowedInstanceTypesTag = "autospotting_allowed_instance_types"
// DisallowedInstanceTypesTag is the name of a tag that can indicate which
// instance types are not allowed in the current group
DisallowedInstanceTypesTag = "autospotting_disallowed_instance_types"
// Default constant values should be defined below:
// DefaultSpotProductDescription stores the default operating system
// to use when looking up spot price history in the market.
DefaultSpotProductDescription = "Linux/UNIX (Amazon VPC)"
// DefaultMinOnDemandValue stores the default on-demand capacity to be kept
// running in a group managed by autospotting.
DefaultMinOnDemandValue = 0
// DefaultSpotPriceBufferPercentage stores the default percentage value
// above the current spot price to place a bid
DefaultSpotPriceBufferPercentage = 10.0
// DefaultBiddingPolicy stores the default bidding policy for
// the spot bid on a per-group level
DefaultBiddingPolicy = "normal"
// DefaultInstanceTerminationMethod is the default value for the instance termination
// method configuration option
DefaultInstanceTerminationMethod = AutoScalingTerminationMethod
// ScheduleTag is the name of the tag set on the AutoScaling Group that
// can override the global value of the Schedule parameter
ScheduleTag = "autospotting_cron_schedule"
// CronScheduleState controls whether to run or not to run during the time interval
// specified in the Schedule variable or its per-group tag overrides. It
// accepts "on|off" as valid values
CronScheduleState = "on"
// CronScheduleStateTag is the name of the tag set on the AutoScaling Group that
// can override the global value of the CronScheduleState parameter
CronScheduleStateTag = "autospotting_cron_schedule_state"
)
// AutoScalingConfig stores some group-specific configurations that can override
// their corresponding global values
type AutoScalingConfig struct {
MinOnDemandNumber int64
MinOnDemandPercentage float64
AllowedInstanceTypes string
DisallowedInstanceTypes string
OnDemandPriceMultiplier float64
SpotPriceBufferPercentage float64
SpotProductDescription string
BiddingPolicy string
TerminationMethod string
// Instance termination method
InstanceTerminationMethod string
// Termination Notification action
TerminationNotificationAction string
CronSchedule string
CronScheduleState string // "on" or "off", dictate whether to run inside the CronSchedule or not
}
func (a *autoScalingGroup) loadPercentageOnDemand(tagValue *string) (int64, bool) {
percentage, err := strconv.ParseFloat(*tagValue, 64)
if err != nil {
logger.Printf("Error with ParseFloat: %s\n", err.Error())
} else if percentage == 0 {
logger.Printf("Loaded MinOnDemand value to %f from tag %s\n", percentage, OnDemandPercentageTag)
return int64(percentage), true
} else if percentage > 0 && percentage <= 100 {
instanceNumber := float64(a.instances.count())
onDemand := int64(math.Floor((instanceNumber * percentage / 100.0) + .5))
logger.Printf("Loaded MinOnDemand value to %d from tag %s\n", onDemand, OnDemandPercentageTag)
return onDemand, true
}
logger.Printf("Ignoring value out of range %f\n", percentage)
return DefaultMinOnDemandValue, false
}
func (a *autoScalingGroup) loadSpotPriceBufferPercentage(tagValue *string) (float64, bool) {
spotPriceBufferPercentage, err := strconv.ParseFloat(*tagValue, 64)
if err != nil {
logger.Printf("Error with ParseFloat: %s\n", err.Error())
return DefaultSpotPriceBufferPercentage, false
} else if spotPriceBufferPercentage <= 0 {
logger.Printf("Ignoring out of range value : %f\n", spotPriceBufferPercentage)
return DefaultSpotPriceBufferPercentage, false
}
logger.Printf("Loaded SpotPriceBufferPercentage value to %f from tag %s\n", spotPriceBufferPercentage, SpotPriceBufferPercentageTag)
return spotPriceBufferPercentage, true
}
func (a *autoScalingGroup) loadNumberOnDemand(tagValue *string) (int64, bool) {
onDemand, err := strconv.Atoi(*tagValue)
if err != nil {
logger.Printf("Error with Atoi: %s\n", err.Error())
} else if onDemand >= 0 && int64(onDemand) <= *a.MaxSize {
logger.Printf("Loaded MinOnDemand value to %d from tag %s\n", onDemand, OnDemandNumberLong)
return int64(onDemand), true
} else {
logger.Printf("Ignoring value out of range %d\n", onDemand)
}
return DefaultMinOnDemandValue, false
}
func (a *autoScalingGroup) getTagValue(keyMatch string) *string {
for _, asgTag := range a.Tags {
if *asgTag.Key == keyMatch {
return asgTag.Value
}
}
return nil
}
func (a *autoScalingGroup) loadConfOnDemand() bool {
tagList := [2]string{OnDemandNumberLong, OnDemandPercentageTag}
loadDyn := map[string]func(*string) (int64, bool){
OnDemandPercentageTag: a.loadPercentageOnDemand,
OnDemandNumberLong: a.loadNumberOnDemand,
}
for _, tagKey := range tagList {
if tagValue := a.getTagValue(tagKey); tagValue != nil {
if _, ok := loadDyn[tagKey]; ok {
if newValue, done := loadDyn[tagKey](tagValue); done {
a.minOnDemand = newValue
return done
}
}
}
debug.Println("Couldn't find tag", tagKey)
}
return false
}
func (a *autoScalingGroup) loadBiddingPolicy(tagValue *string) (string, bool) {
biddingPolicy := *tagValue
if biddingPolicy != "aggressive" {
return DefaultBiddingPolicy, false
}
logger.Printf("Loaded BiddingPolicy value with %s from tag %s\n", biddingPolicy, BiddingPolicyTag)
return biddingPolicy, true
}
func (a *autoScalingGroup) LoadCronSchedule() {
tagValue := a.getTagValue(ScheduleTag)
if tagValue != nil {
logger.Printf("Loaded CronSchedule value %v from tag %v\n", *tagValue, ScheduleTag)
a.config.CronSchedule = *tagValue
return
}
debug.Println("Couldn't find tag", ScheduleTag, "on the group", a.name, "using the default configuration")
a.config.CronSchedule = a.region.conf.CronSchedule
}
func (a *autoScalingGroup) LoadCronScheduleState() {
tagValue := a.getTagValue(CronScheduleStateTag)
if tagValue != nil {
logger.Printf("Loaded CronScheduleState value %v from tag %v\n", *tagValue, CronScheduleStateTag)
a.config.CronScheduleState = *tagValue
return
}
debug.Println("Couldn't find tag", CronScheduleStateTag, "on the group", a.name, "using the default configuration")
a.config.CronScheduleState = a.region.conf.CronScheduleState
}
func (a *autoScalingGroup) loadConfSpot() bool {
tagValue := a.getTagValue(BiddingPolicyTag)
if tagValue == nil {
debug.Println("Couldn't find tag", BiddingPolicyTag)
return false
}
if newValue, done := a.loadBiddingPolicy(tagValue); done {
a.region.conf.BiddingPolicy = newValue
logger.Println("BiddingPolicy =", a.region.conf.BiddingPolicy)
return done
}
return false
}
func (a *autoScalingGroup) loadConfSpotPrice() bool {
tagValue := a.getTagValue(SpotPriceBufferPercentageTag)
if tagValue == nil {
return false
}
newValue, done := a.loadSpotPriceBufferPercentage(tagValue)
if !done {
debug.Println("Couldn't find tag", SpotPriceBufferPercentageTag)
return false
}
a.region.conf.SpotPriceBufferPercentage = newValue
return done
}
// Add configuration of other elements here: prices, whitelisting, etc
func (a *autoScalingGroup) loadConfigFromTags() bool {
resOnDemandConf := a.loadConfOnDemand()
resSpotConf := a.loadConfSpot()
resSpotPriceConf := a.loadConfSpotPrice()
a.LoadCronSchedule()
a.LoadCronScheduleState()
if resOnDemandConf {
logger.Println("Found and applied configuration for OnDemand value")
}
if resSpotConf {
logger.Println("Found and applied configuration for Spot Bid")
}
if resSpotPriceConf {
logger.Println("Found and applied configuration for Spot Price")
}
if resOnDemandConf || resSpotConf || resSpotPriceConf {
return true
}
return false
}
func (a *autoScalingGroup) loadDefaultConfigNumber() (int64, bool) {
onDemand := a.region.conf.MinOnDemandNumber
if onDemand >= 0 && onDemand <= int64(a.instances.count()) {
logger.Printf("Loaded default value %d from conf number.", onDemand)
return onDemand, true
}
logger.Println("Ignoring default value out of range:", onDemand)
return DefaultMinOnDemandValue, false
}
func (a *autoScalingGroup) loadDefaultConfigPercentage() (int64, bool) {
percentage := a.region.conf.MinOnDemandPercentage
if percentage < 0 || percentage > 100 {
logger.Printf("Ignoring default value out of range: %f", percentage)
return DefaultMinOnDemandValue, false
}
instanceNumber := a.instances.count()
onDemand := int64(math.Floor((float64(instanceNumber) * percentage / 100.0) + .5))
logger.Printf("Loaded default value %d from conf percentage.", onDemand)
return onDemand, true
}
func (a *autoScalingGroup) loadDefaultConfig() bool {
done := false
a.minOnDemand = DefaultMinOnDemandValue
if a.region.conf.SpotPriceBufferPercentage <= 0 {
a.region.conf.SpotPriceBufferPercentage = DefaultSpotPriceBufferPercentage
}
if a.region.conf.MinOnDemandNumber != 0 {
a.minOnDemand, done = a.loadDefaultConfigNumber()
}
if !done && a.region.conf.MinOnDemandPercentage != 0 {
a.minOnDemand, done = a.loadDefaultConfigPercentage()
} else {
logger.Println("No default value for on-demand instances specified, skipping.")
}
return done
} | core/autoscaling_configuration.go | 0.668664 | 0.406685 | autoscaling_configuration.go | starcoder |
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func Abs(a int) int {
if (a >= 0) {
return +a
} else {
return -a
}
}
type Point struct {
x, y int
}
func (p Point) ToString() string {
return fmt.Sprintf("Point{ x: %d, y: %d }(dist: %d)", p.x, p.y, p.Distance())
}
func (p Point) Print() {
fmt.Printf("%s\n", p.ToString())
}
func (p Point) Distance() int {
return Abs(p.x) + Abs(p.y)
}
func (p Point) DistanceTo(dp Point) int {
return Segment{
start: p,
end: dp,
}.Length()
}
type Intersection struct {
pt Point
steps1, steps2 int
}
type Segment struct {
start, end Point
}
func (s Segment) Length() int {
if(s.start.x == s.end.x) {
return Abs(s.end.y - s.start.y)
} else {
return Abs(s.end.x - s.start.x)
}
}
func (s Segment) ToString() string {
return fmt.Sprintf("{ %d, %d -> %d, %d }", s.start.x, s.start.y, s.end.x, s.end.y)
}
func ParseLine(line string, out *[]Segment) {
oldPos := Point{ x: 0, y: 0 }
fragments := strings.Split(line, ",")
for i := 0; i < len(fragments); i += 1 {
f := fragments[i]
velocity, _ := strconv.Atoi(f[1:])
xMovement, yMovement := 0, 0
switch(f[0]) {
case 'U': yMovement = -1
case 'R': xMovement = +1
case 'D': yMovement = +1
case 'L': xMovement = -1
}
newPos := Point{
x: oldPos.x + (xMovement * velocity),
y: oldPos.y + (yMovement * velocity),
}
*out = append(*out, Segment{
start: oldPos,
end: newPos,
})
oldPos = newPos
}
}
func Min(a, b int) int {
if a < b {
return a
} else {
return b
}
}
func Max(a, b int) int {
if a > b {
return a
} else {
return b
}
}
func FindIntersection(a, b Segment) *Point {
if(a.start.x == a.end.x) {
// "a" is a vertical segment
if(b.start.x == b.end.x) {
// "b" is a vertical segment
// Two vertical segments could overlap, but let's ignore that for now
return nil
} else {
// "b" is a horizontal segment
minX := Min(b.start.x, b.end.x)
maxX := Max(b.start.x, b.end.x)
if(a.start.x < minX) || (a.start.x > maxX) {
return nil
}
minY := Min(a.start.y, a.end.y)
maxY := Max(a.start.y, a.end.y)
if(b.start.y < minY) || (b.start.y > maxY) {
return nil
}
return &Point{ x: a.start.x, y: b.start.y }
}
} else {
// "a" is a horizontal segment
if(b.start.x == b.end.x) {
// "b" is a vertical segment
minX := Min(a.start.x, a.end.x)
maxX := Max(a.start.x, a.end.x)
if(b.start.x < minX) || (b.start.x > maxX) {
return nil
}
minY := Min(b.start.y, b.end.y)
maxY := Max(b.start.y, b.end.y)
if(a.start.y < minY) || (a.start.y > maxY) {
return nil
}
return &Point{ x: b.start.x, y: a.start.y }
} else {
// "b" is a horizontal segment
// Two horizontal segments could overlap, but let's ignore that for now
return nil
}
}
}
func PrintClosestIntersection(intersections []Intersection) {
minIdx := 0
minDist := intersections[minIdx].pt.Distance()
for idx := 1; idx < len(intersections); idx += 1 {
dist := intersections[idx].pt.Distance()
if dist < minDist {
minIdx = idx
minDist = dist
}
}
fmt.Printf("Closest intersection is #%d\n", minIdx)
intersections[minIdx].pt.Print()
}
func PrintCheapestIntersection(intersections []Intersection) {
minIdx := 0
minCost := intersections[minIdx].steps1 + intersections[minIdx].steps2
for idx := 1; idx < len(intersections); idx += 1 {
cost := intersections[idx].steps1 + intersections[idx].steps2
if cost < minCost {
minIdx = idx
minCost = cost
}
}
fmt.Printf("Cheapest intersection is #%d\n", minIdx)
fmt.Printf("Intersection{ x: %d, y: %d }(Cost: %d)\n", intersections[minIdx].pt.x, intersections[minIdx].pt.y, minCost)
}
func main() {
reader := bufio.NewReader(os.Stdin)
var line string
wire1 := []Segment{}
line, _ = reader.ReadString('\n')
ParseLine(strings.Trim(line, "\n \t"), &wire1)
wire2 := []Segment{}
line, _ = reader.ReadString('\n')
ParseLine(strings.Trim(line, "\n \t"), &wire2)
intersections := []Intersection{}
steps1 := 0
for i := 0; i < len(wire1); i += 1 {
steps2 := 0
for j := 0; j < len(wire2); j += 1 {
cross := FindIntersection(wire1[i], wire2[j])
if cross != nil {
// Omit the intersection at (0, 0)
if (cross.x != 0) || (cross.y != 0) {
intersections = append(intersections, Intersection{
pt: *cross,
steps1: steps1 + cross.DistanceTo(wire1[i].start),
steps2: steps2 + cross.DistanceTo(wire2[j].start),
})
}
}
steps2 += wire2[j].Length()
}
steps1 += wire1[i].Length()
}
PrintClosestIntersection(intersections)
PrintCheapestIntersection(intersections)
} | 2019/day03/wires.go | 0.535584 | 0.400661 | wires.go | starcoder |
package exception
import (
"bytes"
"fmt"
"io"
"os"
"reflect"
"runtime/debug"
"github.com/searKing/golang/go/util/object"
)
const (
/** Message for trying to suppress a null exception. */
NullCauseMessage string = "Cannot suppress a null exception."
/** Message for trying to suppress oneself. */
SelfSuppressionMessage string = "Self-suppression not permitted"
/** Caption for labeling causative exception stack traces */
CauseCaption string = "Caused by: "
/** Caption for labeling suppressed exception stack traces */
SuppressedCaption string = "Suppressed: "
)
var (
/**
* A shared value for an empty stack.
*/
UnassignedStack = make([]byte, 0)
// Setting this static field introduces an acceptable
// initialization dependency on a few java.util classes.
SuppressedSentinel = make([]Throwable, 0)
EmptyThrowableArray = make([]Throwable, 0)
)
type Throwable interface {
GetMessage() string
GetLocalizedMessage() string
GetCause() Throwable
InitCause(cause Throwable) Throwable
String() string
PrintStackTrace()
PrintStackTrace1(writer io.Writer)
PrintEnclosedStackTrace(writer io.Writer, enclosingTrace []byte,
caption string, prefix string, dejaVu map[Throwable]struct{})
fillInStackTrack() Throwable
GetSuppressed() []Throwable
GetStackTrace() []byte
Error() string
}
/**
* The {@code Throwable} class is the superclass of all errors and
* exceptions in the Java language. Only objects that are instances of this
* class (or one of its subclasses) are thrown by the Java Virtual Machine or
* can be thrown by the Java {@code throw} statement. Similarly, only
* this class or one of its subclasses can be the argument type in a
* {@code catch} clause.
*
* For the purposes of compile-time checking of exceptions, {@code
* Throwable} and any subclass of {@code Throwable} that is not also a
* subclass of either {@link RuntimeException} or {@link Error} are
* regarded as checked exceptions.
*
* <p>Instances of two subclasses, {@link java.lang.Error} and
* {@link java.lang.Exception}, are conventionally used to indicate
* that exceptional situations have occurred. Typically, these instances
* are freshly created in the context of the exceptional situation so
* as to include relevant information (such as stack trace data).
*
* <p>A throwable contains a snapshot of the execution stack of its
* thread at the time it was created. It can also contain a message
* string that gives more information about the error. Over time, a
* throwable can {@linkplain Throwable#addSuppressed suppress} other
* throwables from being propagated. Finally, the throwable can also
* contain a <i>cause</i>: another throwable that caused this
* throwable to be constructed. The recording of this causal information
* is referred to as the <i>chained exception</i> facility, as the
* cause can, itself, have a cause, and so on, leading to a "chain" of
* exceptions, each caused by another.
*
* <p>One reason that a throwable may have a cause is that the class that
* throws it is built atop a lower layered abstraction, and an operation on
* the upper layer fails due to a failure in the lower layer. It would be bad
* design to let the throwable thrown by the lower layer propagate outward, as
* it is generally unrelated to the abstraction provided by the upper layer.
* Further, doing so would tie the API of the upper layer to the details of
* its implementation, assuming the lower layer's exception was a checked
* exception. Throwing a "wrapped exception" (i.e., an exception containing a
* cause) allows the upper layer to communicate the details of the failure to
* its caller without incurring either of these shortcomings. It preserves
* the flexibility to change the implementation of the upper layer without
* changing its API (in particular, the set of exceptions thrown by its
* methods).
*
* <p>A second reason that a throwable may have a cause is that the method
* that throws it must conform to a general-purpose interface that does not
* permit the method to throw the cause directly. For example, suppose
* a persistent collection conforms to the {@link java.util.Collection
* Collection} interface, and that its persistence is implemented atop
* {@code java.io}. Suppose the internals of the {@code add} method
* can throw an {@link java.io.IOException IOException}. The implementation
* can communicate the details of the {@code IOException} to its caller
* while conforming to the {@code Collection} interface by wrapping the
* {@code IOException} in an appropriate unchecked exception. (The
* specification for the persistent collection should indicate that it is
* capable of throwing such exceptions.)
*
* <p>A cause can be associated with a throwable in two ways: via a
* constructor that takes the cause as an argument, or via the
* {@link #initCause(Throwable)} method. New throwable classes that
* wish to allow causes to be associated with them should provide constructors
* that take a cause and delegate (perhaps indirectly) to one of the
* {@code Throwable} constructors that takes a cause.
*
* Because the {@code initCause} method is public, it allows a cause to be
* associated with any throwable, even a "legacy throwable" whose
* implementation predates the addition of the exception chaining mechanism to
* {@code Throwable}.
*
* <p>By convention, class {@code Throwable} and its subclasses have two
* constructors, one that takes no arguments and one that takes a
* {@code String} argument that can be used to produce a detail message.
* Further, those subclasses that might likely have a cause associated with
* them should have two more constructors, one that takes a
* {@code Throwable} (the cause), and one that takes a
* {@code String} (the detail message) and a {@code Throwable} (the
* cause).
*
* @author unascribed
* @author <NAME> (Added exception chaining and programmatic access to
* stack trace in 1.4.)
* @jls 11.2 Compile-Time Checking of Exceptions
* @since 1.0
*/
type ThrowableObject struct {
/**
* Specific details about the Throwable. For example, for
* {@code FileNotFoundException}, this contains the name of
* the file that could not be found.
*
* @serial
*/
detailMessage string
/**
* The throwable that caused this throwable to get thrown, or null if this
* throwable was not caused by another throwable, or if the causative
* throwable is unknown. If this field is equal to this throwable itself,
* it indicates that the cause of this throwable has not yet been
* initialized.
*
* @serial
* @since 1.4
*/
cause Throwable
/**
* The stack trace, as returned by {@link #getStackTrace()}.
*
* The field is initialized to a zero-length array. A {@code
* null} value of this field indicates subsequent calls to {@link
* #setStackTrace(StackTraceElement[])} and {@link
* #fillInStackTrace()} will be no-ops.
*
* @serial
* @since 1.4
*/
stackTrace []byte
/**
* The list of suppressed exceptions, as returned by {@link
* #getSuppressed()}. The list is initialized to a zero-element
* unmodifiable sentinel list. When a serialized Throwable is
* read in, if the {@code suppressedExceptions} field points to a
* zero-element list, the field is reset to the sentinel value.
*
* @serial
* @since 1.7
*/
suppressedExceptions []Throwable
}
/**
* Constructs a new throwable with {@code null} as its detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* <p>The {@link #fillInStackTrace()} method is called to initialize
* the stack trace data in the newly created throwable.
*/
func NewThrowable() *ThrowableObject {
return NewThrowable1("")
}
/**
* Constructs a new throwable with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* <p>The {@link #fillInStackTrace()} method is called to initialize
* the stack trace data in the newly created throwable.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
func NewThrowable1(message string) *ThrowableObject {
t := NewThrowable2(message, nil)
t.cause = t
return t
}
/**
* Constructs a new throwable with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this throwable's detail message.
*
* <p>The {@link #fillInStackTrace()} method is called to initialize
* the stack trace data in the newly created throwable.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
func NewThrowable2(message string, cause Throwable) *ThrowableObject {
return NewThrowable4(message, cause, true, true)
}
/**
* Constructs a new throwable with the specified detail message,
* cause, {@linkplain #addSuppressed suppression} enabled or
* disabled, and writable stack trace enabled or disabled. If
* suppression is disabled, {@link #getSuppressed} for this object
* will return a zero-length array and calls to {@link
* #addSuppressed} that would otherwise append an exception to the
* suppressed list will have no effect. If the writable stack
* trace is false, this constructor will not call {@link
* #fillInStackTrace()}, a {@code null} will be written to the
* {@code stackTrace} field, and subsequent calls to {@code
* fillInStackTrace} and {@link
* #setStackTrace(StackTraceElement[])} will not set the stack
* trace. If the writable stack trace is false, {@link
* #getStackTrace} will return a zero length array.
*
* <p>Note that the other constructors of {@code Throwable} treat
* suppression as being enabled and the stack trace as being
* writable. Subclasses of {@code Throwable} should document any
* conditions under which suppression is disabled and document
* conditions under which the stack trace is not writable.
* Disabling of suppression should only occur in exceptional
* circumstances where special requirements exist, such as a
* virtual machine reusing exception objects under low-memory
* situations. Circumstances where a given exception object is
* repeatedly caught and rethrown, such as to implement control
* flow between two sub-systems, is another situation where
* immutable throwable objects would be appropriate.
*
* @param message the detail message.
* @param cause the cause. (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @param enableSuppression whether or not suppression is enabled or disabled
* @param writableStackTrace whether or not the stack trace should be
* writable
*
* @see OutOfMemoryError
* @see NullPointerException
* @see ArithmeticException
* @since 1.7
*/
func NewThrowable4(message string, cause Throwable, enableSuppression, writableStackTrace bool) *ThrowableObject {
t := &ThrowableObject{}
t.init()
if writableStackTrace {
t.fillInStackTrack()
} else {
t.stackTrace = nil
}
t.detailMessage = message
t.cause = cause
if !enableSuppression {
t.suppressedExceptions = nil
}
return t
}
// member variable init as C++
func (t *ThrowableObject) init() {
t.cause = t
t.stackTrace = UnassignedStack
t.suppressedExceptions = SuppressedSentinel
}
func (t *ThrowableObject) Error() string {
return t.GetMessage()
}
/**
* Returns the detail message string of this throwable.
*
* @return the detail message string of this {@code Throwable} instance
* (which may be {@code null}).
*/
func (t *ThrowableObject) GetMessage() string {
return t.detailMessage
}
/**
* Creates a localized description of this throwable.
* Subclasses may override this method in order to produce a
* locale-specific message. For subclasses that do not override this
* method, the default implementation returns the same result as
* {@code getMessage()}.
*
* @return The localized description of this throwable.
* @since 1.1
*/
func (t *ThrowableObject) GetLocalizedMessage() string {
return t.GetMessage()
}
/**
* Returns the cause of this throwable or {@code null} if the
* cause is nonexistent or unknown. (The cause is the throwable that
* caused this throwable to get thrown.)
*
* <p>This implementation returns the cause that was supplied via one of
* the constructors requiring a {@code Throwable}, or that was set after
* creation with the {@link #initCause(Throwable)} method. While it is
* typically unnecessary to override this method, a subclass can override
* it to return a cause set by some other means. This is appropriate for
* a "legacy chained throwable" that predates the addition of chained
* exceptions to {@code Throwable}. Note that it is <i>not</i>
* necessary to override any of the {@code PrintStackTrace} methods,
* all of which invoke the {@code getCause} method to determine the
* cause of a throwable.
*
* @return the cause of this throwable or {@code null} if the
* cause is nonexistent or unknown.
* @since 1.4
*/
func (t *ThrowableObject) GetCause() Throwable {
if t.cause == t {
return nil
}
return t.cause
}
/**
* Initializes the <i>cause</i> of this throwable to the specified value.
* (The cause is the throwable that caused this throwable to get thrown.)
*
* <p>This method can be called at most once. It is generally called from
* within the constructor, or immediately after creating the
* throwable. If this throwable was created
* with {@link #Throwable(Throwable)} or
* {@link #Throwable(String,Throwable)}, this method cannot be called
* even once.
*
* <p>An example of using this method on a legacy throwable type
* without other support for setting the cause is:
*
* <pre>
* try {
* lowLevelOp();
* } catch (LowLevelException le) {
* throw (HighLevelException)
* new HighLevelException().initCause(le); // Legacy constructor
* }
* </pre>
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @return a reference to this {@code Throwable} instance.
* @throws IllegalArgumentException if {@code cause} is this
* throwable. (A throwable cannot be its own cause.)
* @throws IllegalStateException if this throwable was
* created with {@link #Throwable(Throwable)} or
* {@link #Throwable(String,Throwable)}, or this method has already
* been called on this throwable.
* @since 1.4
*/
func (t *ThrowableObject) InitCause(cause Throwable) Throwable {
if t.cause != t {
return NewIllegalStateException2("Can't overwrite cause with "+object.ToString(cause, "a nil"), t)
}
if cause == t {
return NewIllegalArgumentException2("Self-causation not permitted", t)
}
t.cause = cause
return t
}
/**
* Returns a short description of this throwable.
* The result is the concatenation of:
* <ul>
* <li> the {@linkplain Class#getName() name} of the class of this object
* <li> ": " (a colon and a space)
* <li> the result of invoking this object's {@link #getLocalizedMessage}
* method
* </ul>
* If {@code getLocalizedMessage} returns {@code null}, then just
* the class name is returned.
*
* @return a string representation of this throwable.
*/
func (t *ThrowableObject) String() string {
s := object.GetFunc().Name()
message := t.GetLocalizedMessage()
if len(message) != 0 {
return s + ":" + message
}
return s
}
/**
* Prints this throwable and its backtrace to the
* standard error stream. This method prints a stack trace for this
* {@code Throwable} object on the error output stream that is
* the value of the field {@code System.err}. The first line of
* output contains the result of the {@link #toString()} method for
* this object. Remaining lines represent data previously recorded by
* the method {@link #fillInStackTrace()}. The format of this
* information depends on the implementation, but the following
* example may be regarded as typical:
* <blockquote><pre>
* java.lang.NullPointerException
* at MyClass.mash(MyClass.java:9)
* at MyClass.crunch(MyClass.java:6)
* at MyClass.main(MyClass.java:3)
* </pre></blockquote>
* This example was produced by running the program:
* <pre>
* class MyClass {
* public static void main(String[] args) {
* crunch(null);
* }
* static void crunch(int[] a) {
* mash(a);
* }
* static void mash(int[] b) {
* System.out.println(b[0]);
* }
* }
* </pre>
* The backtrace for a throwable with an initialized, non-null cause
* should generally include the backtrace for the cause. The format
* of this information depends on the implementation, but the following
* example may be regarded as typical:
* <pre>
* HighLevelException: MidLevelException: LowLevelException
* at Junk.a(Junk.java:13)
* at Junk.main(Junk.java:4)
* Caused by: MidLevelException: LowLevelException
* at Junk.c(Junk.java:23)
* at Junk.b(Junk.java:17)
* at Junk.a(Junk.java:11)
* ... 1 more
* Caused by: LowLevelException
* at Junk.e(Junk.java:30)
* at Junk.d(Junk.java:27)
* at Junk.c(Junk.java:21)
* ... 3 more
* </pre>
* Note the presence of lines containing the characters {@code "..."}.
* These lines indicate that the remainder of the stack trace for this
* exception matches the indicated number of frames from the bottom of the
* stack trace of the exception that was caused by this exception (the
* "enclosing" exception). This shorthand can greatly reduce the length
* of the output in the common case where a wrapped exception is thrown
* from same method as the "causative exception" is caught. The above
* example was produced by running the program:
* <pre>
* public class Junk {
* public static void main(String args[]) {
* try {
* a();
* } catch(HighLevelException e) {
* e.printStackTrace();
* }
* }
* static void a() throws HighLevelException {
* try {
* b();
* } catch(MidLevelException e) {
* throw new HighLevelException(e);
* }
* }
* static void b() throws MidLevelException {
* c();
* }
* static void c() throws MidLevelException {
* try {
* d();
* } catch(LowLevelException e) {
* throw new MidLevelException(e);
* }
* }
* static void d() throws LowLevelException {
* e();
* }
* static void e() throws LowLevelException {
* throw new LowLevelException();
* }
* }
*
* class HighLevelException extends Exception {
* HighLevelException(Throwable cause) { super(cause); }
* }
*
* class MidLevelException extends Exception {
* MidLevelException(Throwable cause) { super(cause); }
* }
*
* class LowLevelException extends Exception {
* }
* </pre>
* As of release 7, the platform supports the notion of
* <i>suppressed exceptions</i> (in conjunction with the {@code
* try}-with-resources statement). Any exceptions that were
* suppressed in order to deliver an exception are printed out
* beneath the stack trace. The format of this information
* depends on the implementation, but the following example may be
* regarded as typical:
*
* <pre>
* Exception in thread "main" java.lang.Exception: Something happened
* at Foo.bar(Foo.java:10)
* at Foo.main(Foo.java:5)
* Suppressed: Resource$CloseFailException: Resource ID = 0
* at Resource.close(Resource.java:26)
* at Foo.bar(Foo.java:9)
* ... 1 more
* </pre>
* Note that the "... n more" notation is used on suppressed exceptions
* just at it is used on causes. Unlike causes, suppressed exceptions are
* indented beyond their "containing exceptions."
*
* <p>An exception can have both a cause and one or more suppressed
* exceptions:
* <pre>
* Exception in thread "main" java.lang.Exception: Main block
* at Foo3.main(Foo3.java:7)
* Suppressed: Resource$CloseFailException: Resource ID = 2
* at Resource.close(Resource.java:26)
* at Foo3.main(Foo3.java:5)
* Suppressed: Resource$CloseFailException: Resource ID = 1
* at Resource.close(Resource.java:26)
* at Foo3.main(Foo3.java:5)
* Caused by: java.lang.Exception: I did it
* at Foo3.main(Foo3.java:8)
* </pre>
* Likewise, a suppressed exception can have a cause:
* <pre>
* Exception in thread "main" java.lang.Exception: Main block
* at Foo4.main(Foo4.java:6)
* Suppressed: Resource2$CloseFailException: Resource ID = 1
* at Resource2.close(Resource2.java:20)
* at Foo4.main(Foo4.java:5)
* Caused by: java.lang.Exception: Rats, you caught me
* at Resource2$CloseFailException.<init>(Resource2.java:45)
* ... 2 more
* </pre>
*/
func (t *ThrowableObject) PrintStackTrace() {
t.PrintStackTrace1(os.Stderr)
}
/**
* Prints this throwable and its backtrace to the specified print stream.
*
* @param s {@code PrintStream} to use for output
*/
func (t *ThrowableObject) PrintStackTrace1(writer io.Writer) {
// Guard against malicious overrides of Throwable.equals by
// using a Set with identity equality semantics.
var dejaVu = map[Throwable]struct{}{t: {}}
// Print our stack trace
_, _ = writer.Write([]byte(fmt.Sprintln(t)))
trace := t.GetOurStackTrace()
_, _ = writer.Write(t.GetOurStackTrace())
// Print suppressed exceptions, if any
for _, se := range t.GetSuppressed() {
se.PrintEnclosedStackTrace(writer, trace, SuppressedCaption, "\t", dejaVu)
}
// Print cause, if any
ourCause := t.GetCause()
if ourCause != nil {
ourCause.PrintEnclosedStackTrace(writer, trace, CauseCaption, "", dejaVu)
}
}
/**
* Print our stack trace as an enclosed exception for the specified
* stack trace.
*/
func (t *ThrowableObject) PrintEnclosedStackTrace(writer io.Writer, enclosingTrace []byte,
caption string, prefix string, dejaVu map[Throwable]struct{}) {
if _, has := dejaVu[t]; has {
_, _ = writer.Write([]byte(fmt.Sprintln("\t[CIRCULAR REFERENCE:", t, "]")))
return
}
dejaVu[t] = struct{}{}
// Compute number of frames in common between this and enclosing trace
trace := t.GetOurStackTrace()
traces := bytes.Split(trace, []byte{'\n'})
enclosingTraces := bytes.Split(enclosingTrace, []byte{'\n'})
m := len(traces) - 1
n := len(enclosingTraces) - 1
for m >= 0 && n >= 0 && bytes.EqualFold(traces[m], enclosingTraces[n]) {
m--
n--
}
framesInCommon := len(traces) - 1 - m
// Print our stack trace
_, _ = writer.Write([]byte(fmt.Sprintln(prefix+caption, t)))
for i := 0; i <= m; i++ {
_, _ = writer.Write([]byte(fmt.Sprintln(traces[i])))
}
if framesInCommon != 0 {
_, _ = writer.Write([]byte(fmt.Sprintln(prefix, "\t...", framesInCommon, " more")))
}
// Print suppressed exceptions, if any
for _, se := range t.GetSuppressed() {
se.PrintEnclosedStackTrace(writer, trace, SuppressedCaption, prefix+"\t", dejaVu)
}
// Print cause, if any
ourCause := t.GetCause()
if ourCause != nil {
ourCause.PrintEnclosedStackTrace(writer, trace, CauseCaption, prefix, dejaVu)
}
}
/**
* Fills in the execution stack trace. This method records within this
* {@code Throwable} object information about the current state of
* the stack frames for the current thread.
*
* <p>If the stack trace of this {@code Throwable} {@linkplain
* Throwable#Throwable(String, Throwable, boolean, boolean) is not
* writable}, calling this method has no effect.
*
* @return a reference to this {@code Throwable} instance.
* @see java.lang.Throwable#printStackTrace()
*/
func (t *ThrowableObject) fillInStackTrack() Throwable {
if t.stackTrace != nil {
t.stackTrace = UnassignedStack
}
return t
}
/**
* Provides programmatic access to the stack trace information printed by
* {@link #printStackTrace()}. Returns an array of stack trace elements,
* each representing one stack frame. The zeroth element of the array
* (assuming the array's length is non-zero) represents the top of the
* stack, which is the last method invocation in the sequence. Typically,
* this is the point at which this throwable was created and thrown.
* The last element of the array (assuming the array's length is non-zero)
* represents the bottom of the stack, which is the first method invocation
* in the sequence.
*
* <p>Some virtual machines may, under some circumstances, omit one
* or more stack frames from the stack trace. In the extreme case,
* a virtual machine that has no stack trace information concerning
* this throwable is permitted to return a zero-length array from this
* method. Generally speaking, the array returned by this method will
* contain one element for every frame that would be printed by
* {@code printStackTrace}. Writes to the returned array do not
* affect future calls to this method.
*
* @return an array of stack trace elements representing the stack trace
* pertaining to this throwable.
* @since 1.4
*/
func (t *ThrowableObject) GetStackTrace() []byte {
return object.DeepClone(t.GetOurStackTrace()).([]byte)
}
func (t *ThrowableObject) GetOurStackTrace() []byte {
if t.stackTrace == nil {
return UnassignedStack
}
if bytes.Equal(t.stackTrace, UnassignedStack) {
t.stackTrace = debug.Stack()
}
return t.stackTrace
}
/**
* Sets the stack trace elements that will be returned by
* {@link #getStackTrace()} and printed by {@link #printStackTrace()}
* and related methods.
*
* This method, which is designed for use by RPC frameworks and other
* advanced systems, allows the client to override the default
* stack trace that is either generated by {@link #fillInStackTrace()}
* when a throwable is constructed or deserialized when a throwable is
* read from a serialization stream.
*
* <p>If the stack trace of this {@code Throwable} {@linkplain
* Throwable#Throwable(String, Throwable, boolean, boolean) is not
* writable}, calling this method has no effect other than
* validating its argument.
*
* @param stackTrace the stack trace elements to be associated with
* this {@code Throwable}. The specified array is copied by this
* call; changes in the specified array after the method invocation
* returns will have no affect on this {@code Throwable}'s stack
* trace.
*
* @throws NullPointerException if {@code stackTrace} is
* {@code null} or if any of the elements of
* {@code stackTrace} are {@code null}
*
* @since 1.4
*/
func (t *ThrowableObject) SetStackTrace(trace []byte) {
// Validate argument
if len(trace) == 0 {
panic(NewNullPointerException1("stackTrace[]"))
return
}
if t.stackTrace == nil { // Immutable stack
return
}
defensiveCopy := object.DeepClone(trace).([]byte)
t.stackTrace = defensiveCopy
}
/**
* Appends the specified exception to the exceptions that were
* suppressed in order to deliver this exception. This method is
* thread-safe and typically called (automatically and implicitly)
* by the {@code try}-with-resources statement.
*
* <p>The suppression behavior is enabled <em>unless</em> disabled
* {@linkplain #Throwable(String, Throwable, boolean, boolean) via
* a constructor}. When suppression is disabled, this method does
* nothing other than to validate its argument.
*
* <p>Note that when one exception {@linkplain
* #initCause(Throwable) causes} another exception, the first
* exception is usually caught and then the second exception is
* thrown in response. In other words, there is a causal
* connection between the two exceptions.
*
* In contrast, there are situations where two independent
* exceptions can be thrown in sibling code blocks, in particular
* in the {@code try} block of a {@code try}-with-resources
* statement and the compiler-generated {@code finally} block
* which closes the resource.
*
* In these situations, only one of the thrown exceptions can be
* propagated. In the {@code try}-with-resources statement, when
* there are two such exceptions, the exception originating from
* the {@code try} block is propagated and the exception from the
* {@code finally} block is added to the list of exceptions
* suppressed by the exception from the {@code try} block. As an
* exception unwinds the stack, it can accumulate multiple
* suppressed exceptions.
*
* <p>An exception may have suppressed exceptions while also being
* caused by another exception. Whether or not an exception has a
* cause is semantically known at the time of its creation, unlike
* whether or not an exception will suppress other exceptions
* which is typically only determined after an exception is
* thrown.
*
* <p>Note that programmer written code is also able to take
* advantage of calling this method in situations where there are
* multiple sibling exceptions and only one can be propagated.
*
* @param exception the exception to be added to the list of
* suppressed exceptions
* @throws IllegalArgumentException if {@code exception} is this
* throwable; a throwable cannot suppress itself.
* @throws NullPointerException if {@code exception} is {@code null}
* @since 1.7
*/
func (t *ThrowableObject) AddSuppressed(exception Throwable) {
if exception == t {
panic(NewIllegalArgumentException2(SelfSuppressionMessage, exception))
}
if exception == nil {
panic(NewNullPointerException1(NullCauseMessage))
}
if t.suppressedExceptions == nil {
return
}
t.suppressedExceptions = append(t.suppressedExceptions, exception)
}
/**
* Returns an array containing all of the exceptions that were
* suppressed, typically by the {@code try}-with-resources
* statement, in order to deliver this exception.
*
* If no exceptions were suppressed or {@linkplain
* #Throwable(String, Throwable, boolean, boolean) suppression is
* disabled}, an empty array is returned. This method is
* thread-safe. Writes to the returned array do not affect future
* calls to this method.
*
* @return an array containing all of the exceptions that were
* suppressed to deliver this exception.
* @since 1.7
*/
func (t *ThrowableObject) GetSuppressed() []Throwable {
if reflect.DeepEqual(t.suppressedExceptions, SuppressedSentinel) || t.suppressedExceptions == nil {
return EmptyThrowableArray
}
return t.suppressedExceptions
} | go/error/exception/throwable.go | 0.719482 | 0.41324 | throwable.go | starcoder |
package setcover
import "sort"
// set holds the original set elements but also
// a map of elements that are not yet covered in the resulting universe.
type set struct {
index int
elements []int
uncoveredElements map[int]struct{}
}
// newSet generates a new set by initializing the uncovered element map.
func newSet(elements []int, index int) (s set) {
s.index = index
s.elements = elements
s.uncoveredElements = make(map[int]struct{})
for _, element := range elements {
s.uncoveredElements[element] = struct{}{}
}
return
}
// filter removes all elements from the uncovered elements map.
func (s *set) filter(filter map[int]struct{}) {
for element := range filter {
delete(s.uncoveredElements, element)
}
}
// GreedyCoverageIndex returns a minimum set of sets that covers the whole universe by using
// the Greedy Set Coverage Algorithm. The resulting subset will still cover the whole universe but
// its not guaranteed that it's the smallest subset.
func GreedyCoverageIndex(s [][]int) (resultIndex []int) {
// convert sets to sets that use above's struct
sets := make([]set, len(s))
for i, rawSet := range s {
sets[i] = newSet(rawSet, i)
}
for {
// search for the set that covers most elements in the universe
sort.Slice(sets, func(i, j int) bool {
if len(sets[i].uncoveredElements) == len(sets[j].uncoveredElements) {
return len(sets[i].elements) < len(sets[j].elements)
}
return len(sets[i].uncoveredElements) > len(sets[j].uncoveredElements)
})
if len(sets) == 0 || len(sets[0].uncoveredElements) == 0 {
// no more sets or elements in sets -> universe is now covered in result
return
}
// add the biggest set to the universe and remove it from the remaining sets
biggestSet := sets[0]
resultIndex = append(resultIndex, biggestSet.index)
sets = sets[1:]
// remove elements of the biggest set from the remaining sets
for i, set := range sets {
set.filter(biggestSet.uncoveredElements)
sets[i] = set
}
}
}
func GreedyCoverage(s [][]int) (result [][]int) {
indices := GreedyCoverageIndex(s)
result = make([][]int, len(indices))
for i, index := range indices {
result[i] = make([]int, len(s[index]))
copy(result[i], s[index])
}
return
} | setcover.go | 0.625095 | 0.430626 | setcover.go | starcoder |
package set
type Equaler[T any] interface {
Equal(t T) bool
}
// Set defines a mutable set; members can be added
// and removed and the set can be combined with
// itself.
type Set[
self any,
elem Equaler[elem],
] interface {
// New returns a new empty instance of the set.
New() self
// Union sets the contents of the receiver to
// the union of a and b and returns the receiver.
Union(a, b self) self
// Intersect sets the contents of the receiver to
// the union of a and b and returns the receiver.
Intersect(a, b self) self
// Iter returns an iterator that visits each member
// of the set in turn.
Iter() Iter[elem]
// Add adds the given elements to the set.
Add(elem)
// Add removes the given elements to the set.
Remove(elem)
}
type Iter[T any] interface {
Next() bool
Item() T
}
type BitSet struct {
bits []uint64
}
type Int int
func (i Int) Equal(j Int) bool {
return i == j
}
const wbits = 64
func (b *BitSet) New() *BitSet {
return &BitSet{}
}
func (b *BitSet) Union(c, d *BitSet) *BitSet {
if b == nil {
b = new(BitSet)
}
if len(c.bits) < len(d.bits) {
c, d = d, c
}
cbits, dbits := c.bits, d.bits
if len(c.bits) > len(b.bits) {
b.bits = make([]uint64, len(c.bits))
}
for i := range b.bits {
b.bits[i] = cbits[i] | dbits[i]
}
return b
}
func (b *BitSet) Intersect(c, d *BitSet) *BitSet {
if b == nil {
b = new(BitSet)
}
if len(c.bits) > len(d.bits) {
c, d = d, c
}
cbits, dbits := c.bits, d.bits
if len(c.bits) > len(b.bits) {
b.bits = make([]uint64, len(c.bits))
}
for i := range b.bits {
b.bits[i] = cbits[i] & dbits[i]
}
return b
}
func (b *BitSet) Add(x Int) {
index := int(x >> wbits)
if index >= len(b.bits) {
bits := make([]uint64, index+1)
copy(bits, b.bits)
b.bits = bits
}
b.bits[index] |= 1 << (x & (wbits - 1))
}
func (b *BitSet) Remove(x Int) {
panic("unimplemented")
}
func (b *BitSet) Iter() Iter[Int] {
return &bitIter{
bits: b.bits,
index: -1,
}
}
type bitIter struct {
bits []uint64
index int
}
func (iter *bitIter) Next() bool {
panic("unimplemented")
}
func (iter *bitIter) Item() Int {
return Int(iter.index)
}
// Verify that BitSet implements Set.
var _ Set[*BitSet, Int] = (*BitSet)(nil) | set-2014/set.go | 0.804252 | 0.530297 | set.go | starcoder |
package metadata
import (
"blockwatch.cc/tzgo/tezos"
"time"
)
func init() {
LoadSchema(tz21Ns, []byte(tz21Schema), &Tz21{})
}
// https://gitlab.com/tzip/tzip/-/blob/master/proposals/tzip-21/metadata-schema.json
const (
tz21Ns = "tz21"
tz21Schema = `{
"$schema": "http://json-schema.org/draft/2019-09/schema#",
"$id": "https://api.tzstats.com/metadata/schemas/tz21.json",
"$ref": "#/defs/asset",
"title": "Rich Metadata",
"$defs": {
"asset": {
"type": "object",
"additionalProperties": true,
"properties": {
"description": {
"type": "string",
"description": "General notes, abstracts, or summaries about the contents of an asset."
},
"minter": {
"type": "string",
"format": "tzaddress",
"description": "The tz address responsible for minting the asset."
},
"creators": {
"type": "array",
"description": "The primary person, people, or organization(s) responsible for creating the intellectual content of the asset.",
"uniqueItems": true,
"items": {
"type": "string"
}
},
"contributors": {
"type": "array",
"description": "The person, people, or organization(s) that have made substantial creative contributions to the asset.",
"uniqueItems": true,
"items": {
"type": "string"
}
},
"publishers": {
"type": "array",
"description": "The person, people, or organization(s) primarily responsible for distributing or making the asset available to others in its present form.",
"uniqueItems": true,
"items": {
"type": "string"
}
},
"date": {
"type": "string",
"format": "date-time",
"description": "A date associated with the creation or availability of the asset."
},
"blockLevel": {
"type": "integer",
"description": "Chain block level associated with the creation or availability of the asset."
},
"type": {
"type": "string",
"description": "A broad definition of the type of content of the asset."
},
"tags": {
"type": "array",
"description": "A list of tags that describe the subject or content of the asset.",
"uniqueItems": true,
"items": {
"type": "string"
}
},
"genres": {
"type": "array",
"description": "A list of genres that describe the subject or content of the asset.",
"uniqueItems": true,
"items": {
"type": "string"
}
},
"language": {
"type": "string",
"format": "https://tools.ietf.org/html/rfc1766",
"description": "The language of the intellectual content of the asset as defined in RFC 1776."
},
"identifier": {
"type": "string",
"description": "A string or number used to uniquely identify the asset. Ex. URL, URN, UUID, ISBN, etc."
},
"rights": {
"type": "string",
"description": "A statement about the asset rights."
},
"rightUri": {
"type": "string",
"format": "uri-reference",
"description": "Links to a statement of rights."
},
"artifactUri": {
"type": "string",
"format": "uri-reference",
"description": "A URI to the asset."
},
"displayUri": {
"type": "string",
"format": "uri-reference",
"description": "A URI to an image of the asset. Used for display purposes."
},
"thumbnailUri": {
"type": "string",
"format": "uri-reference",
"description": "A URI to an image of the asset for wallets and client applications to have a scaled down image to present to end-users. Reccomened maximum size of 350x350px."
},
"externalUri": {
"type": "string",
"format": "uri-reference",
"description": "A URI with additional information about the subject or content of the asset."
},
"isTransferable": {
"type": "boolean",
"description": "All tokens will be transferable by default to allow end-users to send them to other end-users. However, this field exists to serve in special cases where owners will not be able to transfer the token."
},
"isBooleanAmount": {
"type": "boolean",
"description": "Describes whether an account can have an amount of exactly 0 or 1. (The purpose of this field is for wallets to determine whether or not to display balance information and an amount field when transferring.)"
},
"shouldPreferSymbol": {
"type": "boolean",
"description": "Allows wallets to decide whether or not a symbol should be displayed in place of a name."
},
"formats": {
"type": "array",
"items": {
"$ref": "#/defs/format"
}
},
"attributes": {
"type": "array",
"items": {
"$ref": "#/defs/attribute"
},
"description": "Custom attributes about the subject or content of the asset."
},
"assets": {
"type": "array",
"items": {
"$ref": "#/defs/asset"
},
"description": "Facilitates the description of collections and other types of resources that contain multiple assets."
}
}
},
"format": {
"type": "object",
"additionalProperties": false,
"properties": {
"uri": {
"type": "string",
"format": "uri-reference",
"description": "A URI to the asset represented in this format."
},
"hash": {
"type": "string",
"description": "A checksum hash of the content of the asset in this format."
},
"mimeType": {
"type": "string",
"description": "Media (MIME) type of the format."
},
"fileSize": {
"type": "integer",
"description": "Size in bytes of the content of the asset in this format."
},
"fileName": {
"type": "string",
"description": "Filename for the asset in this format. For display purposes."
},
"duration": {
"type": "string",
"format": "time",
"description": "Time duration of the content of the asset in this format."
},
"dimensions": {
"$ref": "#/defs/dimensions",
"description": "Dimensions of the content of the asset in this format."
},
"dataRate": {
"$ref": "#/defs/dataRate",
"description": "Data rate which the content of the asset in this format was captured at."
}
}
},
"attribute": {
"type": "object",
"additionalProperties": false,
"properties": {
"name": {
"type": "string",
"description": "Name of the attribute."
},
"value": {
"type": "string",
"description": "Value of the attribute."
},
"type": {
"type": "string",
"description": "Type of the value. To be used for display purposes."
}
},
"required": [
"name",
"value"
]
},
"dataRate": {
"type": "object",
"additionalProperties": false,
"properties": {
"value": {
"type": "integer"
},
"unit": {
"type": "string"
}
},
"required": [
"unit",
"value"
]
},
"dimensions": {
"type": "object",
"additionalProperties": false,
"properties": {
"value": {
"type": "string"
},
"unit": {
"type": "string"
}
},
"required": [
"unit",
"value"
]
}
}
}`
)
type Tz21 struct {
Tz21Asset
}
type Tz21Asset struct {
Description string `json:"description"`
Minter tezos.Address `json:"minter"`
Creators []string `json:"creators"`
Contributors []string `json:"contributors"`
Publishers []string `json:"publishers"`
Date time.Time `json:"date"`
BlockLevel int64 `json:"blockLevel"`
Type string `json:"type"`
Tags []string `json:"tags"`
Genres []string `json:"genres"`
Language string `json:"language"`
Identifier string `json:"identifier"`
Rights string `json:"rights"`
RightUri string `json:"rightUri"`
ArtifactUri string `json:"artifactUri"`
DisplayUri string `json:"displayUri"`
ThumbnailUri string `json:"thumbnailUri"`
ExternalUri string `json:"externalUri"`
IsTransferable bool `json:"isTransferable"`
IsBooleanAmount bool `json:"isBooleanAmount"`
ShouldPreferSymbol bool `json:"shouldPreferSymbol"`
Formats []Tz21Format `json:"formats"`
Attributes []Tz21Attribute `json:"attributes"`
Assets []Tz21Asset `json:"assets"`
}
type Tz21Format struct {
Uri string `json:"uri"`
Hash string `json:"hash"`
MimeType string `json:"mimeType"`
FileSize int64 `json:"fileSize"`
FileName string `json:"fileName"`
Duration string `json:"duration"`
Dimensions Tz21Dimension `json:"dimensions"`
DataRate Tz21DataRate `json:"dataRate"`
}
type Tz21Attribute struct {
Name string `json:"name"`
Value string `json:"value"`
Type string `json:"type,omitempty"`
}
type Tz21Dimension struct {
Value string `json:"value"`
Unit string `json:"unit"`
}
type Tz21DataRate struct {
Value string `json:"value"`
Unit string `json:"unit"`
}
func (d Tz21) Namespace() string {
return tz21Ns
}
func (d Tz21) Validate() error {
s, ok := GetSchema(tz21Ns)
if ok {
return s.Validate(d)
}
return nil
} | etl/metadata/tzip21.go | 0.816443 | 0.539408 | tzip21.go | starcoder |
package chain
/*
#include <stdint.h>
void eosio_assert( uint32_t test, const char* msg );
void eosio_assert_message( uint32_t test, const char* msg, uint32_t msg_len );
void eosio_assert_code( uint32_t test, uint64_t code );
void eosio_exit( int32_t code );
uint64_t current_time( void );
char is_feature_activated( const uint8_t* feature_digest ); //checksum 32 bytes
uint64_t get_sender( void );
*/
import "C"
import (
"unsafe"
)
var gRevertEnabled = false
type RevertFunction func(errMsg string)
var gRevertFn RevertFunction
func SetRevertFn(fn RevertFunction) {
gRevertFn = fn
}
func GetRevertFn() RevertFunction {
return gRevertFn
}
func EnableRevert(b bool) {
gRevertEnabled = b
}
func IsRevertEnabled() bool {
return gRevertEnabled
}
func Check(b bool, msg string) {
revert := GetRevertFn()
if revert != nil {
if !b {
revert(msg)
}
return
}
EosioAssert(b, msg)
}
//Aborts processing of this action and unwinds all pending changes if the test condition is true
func Assert(test bool, msg string) {
EosioAssert(test, msg)
}
//Aborts processing of this action and unwinds all pending changes if the test condition is true
func EosioAssert(test bool, msg string) {
_test := uint32(0)
if test {
_test = 1
}
_msg := (*StringHeader)(unsafe.Pointer(&msg))
C.eosio_assert_message(C.uint32_t(_test), (*C.char)(_msg.data), C.uint32_t(len(msg)))
}
//Aborts processing of this action and unwinds all pending changes if the test condition is true
func EosioAssertCode(test bool, code uint64) {
_test := uint32(0)
if test {
_test = 1
}
C.eosio_assert_code(C.uint32_t(_test), C.uint64_t(code))
}
//Returns the time in microseconds from 1970 of the current block
func CurrentTime() TimePoint {
return TimePoint{uint64(C.current_time())}
}
//Returns the time in microseconds from 1970 of the current block
func Now() TimePoint {
return CurrentTime()
}
func NowSeconds() uint32 {
t := CurrentTime().Elapsed / 1000000
return uint32(t)
}
func CurrentTimeSeconds() uint32 {
t := CurrentTime().Elapsed / 1000000
return uint32(t)
}
//Check if specified protocol feature has been activated
func IsFeatureActivated(featureDigest [32]byte) bool {
_featureDigest := (*C.uint8_t)(unsafe.Pointer(&featureDigest[0]))
return C.is_feature_activated(_featureDigest) != 0
}
//Return name of account that sent current inline action
func GetSender() uint64 {
return uint64(C.get_sender())
}
func Exit() {
C.eosio_exit(0)
} | system.go | 0.552781 | 0.405449 | system.go | starcoder |
package ring
// Ring implements a circular buffer. It has one different implementation from
// a standard ring buffer in that most reads are expected to be done from head
// rather than tail.
type Ring struct {
head int // most recent value position
tail int // oldest value position
buff []interface{}
}
// New returns a newly initialized Ring of capacity c.
func New(c int) *Ring {
return &Ring{
head: -1,
tail: 0,
buff: make([]interface{}, c),
}
}
// Capacity returns the current capacity of r.
func (r Ring) Capacity() int {
return len(r.buff)
}
// Enqueue adds value e to the head of r.
func (r *Ring) Enqueue(e interface{}) {
r.set(r.head+1, e)
old := r.head
r.head = r.mod(r.head + 1)
if old != -1 && r.head == r.tail {
r.tail = r.mod(r.tail + 1)
}
}
// Dequeue removes and returns the tail value from r. Returns nil, if r is empty.
func (r *Ring) Dequeue() interface{} {
if r.head == -1 {
return nil
}
v := r.get(r.tail)
if r.tail == r.head {
r.head = -1
r.tail = 0
} else {
r.tail = r.mod(r.tail + 1)
}
return v
}
// Peek returns the value that Dequeue would have returned without acutally
// removing it. If r is empty return nil.
func (r *Ring) Peek() interface{} {
if r.head == -1 {
return nil
}
return r.get(r.head)
}
// PeekN peeks n interface{}s deep into r. If r's capacity is less than n or r
// r contains less than n interface{}s only min(r capacity, r current) is returned.
// The slice returned is copy of r's buffer however the contents of the buffer
// are not copied. If n <= 0 or r is empty, nil is returned.
func (r *Ring) PeekN(n int) []interface{} {
if n <= 0 {
return nil
}
if r.head == -1 {
return nil
}
b := []interface{}{}
i := r.head
for {
b = append(b, r.buff[i])
if i == r.tail || len(b) == n {
break
}
i--
if i < 0 {
i = r.Capacity() - 1
}
}
return b
}
// Tail returns the value that Dequeue would have returned without acutally
// removing it. If r is empty return nil.
func (r *Ring) Tail() interface{} {
if r.head == -1 {
return nil
}
return r.get(r.tail)
}
// sets a value in r at the given unmodified index.
func (r *Ring) set(p int, v interface{}) {
r.buff[r.mod(p)] = v
}
// gets a value in r based at a given unmodified index.
func (r *Ring) get(p int) interface{} {
return r.buff[r.mod(p)]
}
// returns the modified index of an unmodified index
func (r *Ring) mod(p int) int {
return p % r.Capacity()
} | ring.go | 0.857127 | 0.509947 | ring.go | starcoder |
package row
import (
"errors"
"fmt"
"strings"
"unicode/utf8"
)
// Row is a slice of strings.
type Row []string
// ColumnCap holds the number of maximum runs for each column.
type ColumnCap []int
var errItemCountNotEqual = errors.New(`Number of items in the head and body []string must be
equal if there are more than 0 of either of each.`)
// New Row object. Line break will be striped from the strings
// and n whitespace added to the end of the cell.
func New(c ColumnCap, row []string, n uint8) Row {
// trim too long rows
if len(row) > len(c) {
row = row[:len(c)]
}
for i, cell := range row {
cell = purgeRunes(cell)
cell = trimCell(cell, c[i]-int(n))
row[i] = fmt.Sprintf("%s%s", cell, strings.Repeat(" ", int(n)))
}
return Row(row)
}
// trimCell if it is longer than max runes.
func trimCell(cell string, max int) string {
if max < 0 {
max = 0
}
count := utf8.RuneCountInString(cell)
switch {
case count <= max: // do nothing
return cell
case max <= 3: // trim without adding dots
return cell[:max]
default: // trim + dots
return fmt.Sprintf("%s...", cell[:max-3])
}
}
// NewColumnCap calculate ColumnCap for the rows with n whitespace added.
func NewColumnCap(rows [][]string, n uint8) ColumnCap {
c := make(ColumnCap, len(rows[0]))
for _, row := range rows {
for i, cell := range row {
cell = purgeRunes(cell)
count := utf8.RuneCountInString(cell) + int(n)
if count > c[i] {
c[i] = count
}
if c[i] == 0 {
c[i] = 1
}
}
}
return c
}
// ConvRunesPerColumn calculates ColumnCap (incorporate added whitespace n).
func ConvRunesPerColumn(runesPerColumn []int, n uint8) ColumnCap {
c := make(ColumnCap, len(runesPerColumn))
for i, count := range runesPerColumn {
if count <= 0 {
count = 0
}
c[i] = count + int(n)
if c[i] == 0 {
c[i] = 1
}
}
return c
}
func purgeRunes(cell string) string {
cell = strings.Replace(cell, "\n", "", -1)
cell = strings.Replace(cell, "\r", "", -1)
return cell
}
// TrimTextToMaxLength enlarges too short stings.
func TrimTextToMaxLength(s string, n int) string {
size := utf8.RuneCountInString(s)
if size == n {
return s
}
return fmt.Sprintf("%s%s", s, strings.Repeat(" ", n-size))
} | row/row.go | 0.579876 | 0.401277 | row.go | starcoder |
package debt
import "fmt"
// Graph represents the whole relationship between all vertices
type Graph struct {
Vertices map[string]*Vertex
Edges []*EdgeVector
}
// NewEdgeVector creates an edge vector in graph
// and add into the graph
func (g *Graph) NewEdgeVector(id uint64, start, end string, amount int64) *EdgeVector {
startVertex, ok := g.Vertices[start]
if !ok {
return nil
}
endVertex, ok := g.Vertices[end]
if !ok {
return nil
}
edge := &EdgeVector{
ID: id,
Start: startVertex,
End: endVertex,
Amount: amount,
}
g.Edges = append(g.Edges, edge)
return edge
}
func (g Graph) String() string {
var s string
for _, v := range g.Vertices {
s += fmt.Sprintf("%s - ", v.Name)
}
s += "\n"
for i, e := range g.Edges {
s += fmt.Sprintf("%d - %s -> %s: %d\n", i+1, e.Start.Name, e.End.Name, e.Amount)
}
s += "\nRecievers: \n"
for _, v := range g.Receivers() {
s += fmt.Sprintf("%s: %d\n", v.Name, v.CalBalance())
}
s += "\nGivers: \n"
for _, v := range g.Givers() {
s += fmt.Sprintf("%s: %d\n", v.Name, v.CalBalance())
}
return s
}
func (g *Graph) FillVerticesWithEdges() {
for _, e := range g.Edges {
if e.Start.StartOfEdges == nil {
e.Start.StartOfEdges = make(map[uint64]*EdgeVector)
}
e.Start.StartOfEdges[e.ID] = e
if e.End.EndOfEdges == nil {
e.End.EndOfEdges = make(map[uint64]*EdgeVector)
}
e.End.EndOfEdges[e.ID] = e
}
}
func (g Graph) PrintEachVertices() {
var s string
for _, v := range g.Vertices {
s += fmt.Sprintf("%s (%d) \n\t -> ", v.Name, v.CalBalance())
for _, e := range v.StartOfEdges {
s += fmt.Sprintf("%s: %d, ", e.End.Name, e.Amount)
}
s += "\n\t <- "
for _, e := range v.EndOfEdges {
s += fmt.Sprintf("%s: %d, ", e.Start.Name, e.Amount)
}
s += "\n"
}
fmt.Println(s)
}
func (g Graph) Receivers() []*Vertex {
var receivers []*Vertex
for _, v := range g.Vertices {
if v.CalBalance() > 0 {
receivers = append(receivers, v)
}
}
return receivers
}
func (g Graph) Givers() []*Vertex {
var givers []*Vertex
for _, v := range g.Vertices {
if v.CalBalance() < 0 {
givers = append(givers, v)
}
}
return givers
} | debt/graph.go | 0.580352 | 0.493164 | graph.go | starcoder |
package main
import (
"math"
. "github.com/jakecoffman/cp"
"github.com/jakecoffman/cp/examples"
)
var motor *SimpleMotor
func main() {
space := NewSpace()
space.Iterations = 20
space.SetGravity(Vector{0, -500})
var shape *Shape
var a, b Vector
walls := []Vector{
{-320, -240}, {-320, 240},
{320, -240}, {320, 240},
{-320, -240}, {320, -240},
}
for i := 0; i < len(walls)-1; i += 2 {
shape = space.AddShape(NewSegment(space.StaticBody, walls[i], walls[i+1], 0))
shape.SetElasticity(1)
shape.SetFriction(1)
shape.SetFilter(examples.NotGrabbableFilter)
}
offset := 30.0
chassisMass := 2.0
a = Vector{-offset, 0}
b = Vector{offset, 0}
chassis := space.AddBody(NewBody(chassisMass, MomentForSegment(chassisMass, a, b, 0)))
shape = space.AddShape(NewSegment(chassis, a, b, segRadius))
shape.SetFilter(NewShapeFilter(1, ALL_CATEGORIES, ALL_CATEGORIES))
crankMass := 1.0
crankRadius := 13.0
crank := space.AddBody(NewBody(crankMass, MomentForCircle(crankMass, crankRadius, 0, Vector{})))
shape = space.AddShape(NewCircle(crank, crankRadius, Vector{}))
shape.SetFilter(NewShapeFilter(1, ALL_CATEGORIES, ALL_CATEGORIES))
space.AddConstraint(NewPivotJoint2(chassis, crank, Vector{}, Vector{}))
side := 30.0
const numLegs = 2
for i := 0; i < numLegs; i++ {
makeLeg(space, side, offset, chassis, crank, ForAngle(float64(2*i+0)/numLegs*math.Pi).Mult(crankRadius))
makeLeg(space, side, -offset, chassis, crank, ForAngle(float64(2*i+1)/numLegs*math.Pi).Mult(crankRadius))
}
motor = space.AddConstraint(NewSimpleMotor(chassis, crank, 6)).Class.(*SimpleMotor)
examples.Main(space, 1/180.0, update, examples.DefaultDraw)
}
const segRadius = 3.0
func makeLeg(space *Space, side, offset float64, chassis, crank *Body, anchor Vector) {
var a, b Vector
var shape *Shape
legMass := 1.0
// make a leg
a = Vector{}
b = Vector{0, side}
upperLeg := space.AddBody(NewBody(legMass, MomentForSegment(legMass, a, b, 0)))
upperLeg.SetPosition(Vector{offset, 0})
shape = space.AddShape(NewSegment(upperLeg, a, b, segRadius))
shape.SetFilter(NewShapeFilter(1, ALL_CATEGORIES, ALL_CATEGORIES))
space.AddConstraint(NewPivotJoint2(chassis, upperLeg, Vector{offset, 0}, Vector{}))
// lower leg
a = Vector{}
b = Vector{0, -1 * side}
lowerLeg := space.AddBody(NewBody(legMass, MomentForSegment(legMass, a, b, 0)))
lowerLeg.SetPosition(Vector{offset, -side})
shape = space.AddShape(NewSegment(lowerLeg, a, b, segRadius))
shape.SetFilter(NewShapeFilter(1, ALL_CATEGORIES, ALL_CATEGORIES))
shape = space.AddShape(NewCircle(lowerLeg, segRadius*2.0, b))
shape.SetFilter(NewShapeFilter(1, ALL_CATEGORIES, ALL_CATEGORIES))
shape.SetElasticity(0)
shape.SetFriction(1)
space.AddConstraint(NewPinJoint(chassis, lowerLeg, Vector{offset, 0}, Vector{}))
space.AddConstraint(NewGearJoint(upperLeg, lowerLeg, 0, 1))
var constraint *Constraint
diag := math.Sqrt(side*side + offset*offset)
constraint = space.AddConstraint(NewPinJoint(crank, upperLeg, anchor, Vector{0, side}))
constraint.Class.(*PinJoint).Dist = diag
constraint = space.AddConstraint(NewPinJoint(crank, lowerLeg, anchor, Vector{}))
constraint.Class.(*PinJoint).Dist = diag
}
func update(space *Space, dt float64) {
coef := (2.0 + examples.Keyboard.Y) / 3.0
rate := examples.Keyboard.X * 10 * coef
motor.Rate = rate
if rate != 0 {
motor.SetMaxForce(100000)
} else {
motor.SetMaxForce(0)
}
space.Step(dt)
} | examples/theojansen/theojansen.go | 0.63114 | 0.532121 | theojansen.go | starcoder |
package main
import (
"time"
"tetris/consts"
"golang.org/x/exp/shiny/screen"
)
type CurrentTile struct {
MillisForOneStep int64 // how many tiles in one second
CurrentTile []*Tile
LastTick int64
}
func FromNextTile(nextTile []*Tile) *CurrentTile {
c := &CurrentTile{}
c.LastTick = time.Now().UnixNano() / 1000000
c.MillisForOneStep = 500
xDiff := nextTile[0].Rectangle.Min.X - consts.DefaultTilePosX
yDiff := nextTile[0].Rectangle.Min.Y - consts.DefaultTilePosY
for _, t := range nextTile {
t.Rectangle.Min.X -= xDiff
t.Rectangle.Min.Y -= yDiff
t.Rectangle.Max.X -= xDiff
t.Rectangle.Max.Y -= yDiff
}
c.CurrentTile = nextTile
return c
}
func (c *CurrentTile) Draw(buf screen.Buffer) {
for _, t := range c.CurrentTile {
t.Draw(buf)
}
}
func (c *CurrentTile) ToBottomTile() []*Tile {
return c.CurrentTile
}
func (c *CurrentTile) TryWalk() {
now := time.Now().UnixNano() / 1000000
diff := now - c.LastTick
if diff > c.MillisForOneStep {
c.LastTick = now
for _, t := range c.CurrentTile {
t.Rectangle.Max.Y += consts.TileHeight
t.Rectangle.Min.Y += consts.TileHeight
}
return
}
}
func (c *CurrentTile) MoveLeft() {
for _, t := range c.CurrentTile {
if !t.CheckCollision {
continue
}
if t.Rectangle.Min.X <= 3*consts.TileWidth {
return
}
}
for _, t := range c.CurrentTile {
t.Rectangle.Max.X -= consts.TileWidth
t.Rectangle.Min.X -= consts.TileWidth
}
}
func (c *CurrentTile) MoveRight() {
for _, t := range c.CurrentTile {
if !t.CheckCollision {
continue
}
if t.Rectangle.Max.X >= 13*consts.TileWidth {
return
}
}
for _, t := range c.CurrentTile {
t.Rectangle.Max.X += consts.TileWidth
t.Rectangle.Min.X += consts.TileWidth
}
}
func (c *CurrentTile) MoveDown() {
for _, t := range c.CurrentTile {
t.Rectangle.Max.Y += consts.TileHeight
t.Rectangle.Min.Y += consts.TileHeight
}
}
func (c *CurrentTile) RotateLeft() {
/**
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
*/
c.CurrentTile[0].Rectangle.Min.X += 3 * consts.TileWidth
c.CurrentTile[0].Rectangle.Max.X += 3 * consts.TileWidth
c.CurrentTile[1].Rectangle.Min.X += 2 * consts.TileWidth
c.CurrentTile[1].Rectangle.Max.X += 2 * consts.TileWidth
c.CurrentTile[1].Rectangle.Min.Y += 1 * consts.TileHeight
c.CurrentTile[1].Rectangle.Max.Y += 1 * consts.TileHeight
c.CurrentTile[2].Rectangle.Min.X += 1 * consts.TileWidth
c.CurrentTile[2].Rectangle.Max.X += 1 * consts.TileWidth
c.CurrentTile[2].Rectangle.Min.Y += 2 * consts.TileHeight
c.CurrentTile[2].Rectangle.Max.Y += 2 * consts.TileHeight
c.CurrentTile[3].Rectangle.Min.X += 0 * consts.TileWidth
c.CurrentTile[3].Rectangle.Max.X += 0 * consts.TileWidth
c.CurrentTile[3].Rectangle.Min.Y += 3 * consts.TileHeight
c.CurrentTile[3].Rectangle.Max.Y += 3 * consts.TileHeight
c.CurrentTile[4].Rectangle.Min.X += 2 * consts.TileWidth
c.CurrentTile[4].Rectangle.Max.X += 2 * consts.TileWidth
c.CurrentTile[4].Rectangle.Min.Y += -1 * consts.TileHeight
c.CurrentTile[4].Rectangle.Max.Y += -1 * consts.TileHeight
c.CurrentTile[5].Rectangle.Min.X += 1 * consts.TileWidth
c.CurrentTile[5].Rectangle.Max.X += 1 * consts.TileWidth
c.CurrentTile[5].Rectangle.Min.Y += 0 * consts.TileHeight
c.CurrentTile[5].Rectangle.Max.Y += 0 * consts.TileHeight
c.CurrentTile[6].Rectangle.Min.X += 0 * consts.TileWidth
c.CurrentTile[6].Rectangle.Max.X += 0 * consts.TileWidth
c.CurrentTile[6].Rectangle.Min.Y += 1 * consts.TileHeight
c.CurrentTile[6].Rectangle.Max.Y += 1 * consts.TileHeight
c.CurrentTile[7].Rectangle.Min.X += -1 * consts.TileWidth
c.CurrentTile[7].Rectangle.Max.X += -1 * consts.TileWidth
c.CurrentTile[7].Rectangle.Min.Y += 2 * consts.TileHeight
c.CurrentTile[7].Rectangle.Max.Y += 2 * consts.TileHeight
c.CurrentTile[8].Rectangle.Min.X += 1 * consts.TileWidth
c.CurrentTile[8].Rectangle.Max.X += 1 * consts.TileWidth
c.CurrentTile[8].Rectangle.Min.Y += -2 * consts.TileHeight
c.CurrentTile[8].Rectangle.Max.Y += -2 * consts.TileHeight
c.CurrentTile[9].Rectangle.Min.X += 0 * consts.TileWidth
c.CurrentTile[9].Rectangle.Max.X += 0 * consts.TileWidth
c.CurrentTile[9].Rectangle.Min.Y += -1 * consts.TileHeight
c.CurrentTile[9].Rectangle.Max.Y += -1 * consts.TileHeight
c.CurrentTile[10].Rectangle.Min.X += -1 * consts.TileWidth
c.CurrentTile[10].Rectangle.Max.X += -1 * consts.TileWidth
c.CurrentTile[10].Rectangle.Min.Y += 0 * consts.TileHeight
c.CurrentTile[10].Rectangle.Max.Y += 0 * consts.TileHeight
c.CurrentTile[11].Rectangle.Min.X += -2 * consts.TileWidth
c.CurrentTile[11].Rectangle.Max.X += -2 * consts.TileWidth
c.CurrentTile[11].Rectangle.Min.Y += 1 * consts.TileHeight
c.CurrentTile[11].Rectangle.Max.Y += 1 * consts.TileHeight
c.CurrentTile[12].Rectangle.Min.X += 0 * consts.TileWidth
c.CurrentTile[12].Rectangle.Max.X += 0 * consts.TileWidth
c.CurrentTile[12].Rectangle.Min.Y += -3 * consts.TileHeight
c.CurrentTile[12].Rectangle.Max.Y += -3 * consts.TileHeight
c.CurrentTile[13].Rectangle.Min.X += -1 * consts.TileWidth
c.CurrentTile[13].Rectangle.Max.X += -1 * consts.TileWidth
c.CurrentTile[13].Rectangle.Min.Y += -2 * consts.TileHeight
c.CurrentTile[13].Rectangle.Max.Y += -2 * consts.TileHeight
c.CurrentTile[14].Rectangle.Min.X += -2 * consts.TileWidth
c.CurrentTile[14].Rectangle.Max.X += -2 * consts.TileWidth
c.CurrentTile[14].Rectangle.Min.Y += -1 * consts.TileHeight
c.CurrentTile[14].Rectangle.Max.Y += -1 * consts.TileHeight
c.CurrentTile[15].Rectangle.Min.X += -3 * consts.TileWidth
c.CurrentTile[15].Rectangle.Max.X += -3 * consts.TileWidth
c.CurrentTile[15].Rectangle.Min.Y += 0 * consts.TileHeight
c.CurrentTile[15].Rectangle.Max.Y += 0 * consts.TileHeight
newCurrentTile := make([]*Tile, len(c.CurrentTile))
newCurrentTile[0] = NewTileFromOther(c.CurrentTile[12])
newCurrentTile[1] = NewTileFromOther(c.CurrentTile[8])
newCurrentTile[2] = NewTileFromOther(c.CurrentTile[4])
newCurrentTile[3] = NewTileFromOther(c.CurrentTile[0])
newCurrentTile[4] = NewTileFromOther(c.CurrentTile[13])
newCurrentTile[5] = NewTileFromOther(c.CurrentTile[9])
newCurrentTile[6] = NewTileFromOther(c.CurrentTile[5])
newCurrentTile[7] = NewTileFromOther(c.CurrentTile[1])
newCurrentTile[8] = NewTileFromOther(c.CurrentTile[14])
newCurrentTile[9] = NewTileFromOther(c.CurrentTile[10])
newCurrentTile[10] = NewTileFromOther(c.CurrentTile[6])
newCurrentTile[11] = NewTileFromOther(c.CurrentTile[2])
newCurrentTile[12] = NewTileFromOther(c.CurrentTile[15])
newCurrentTile[13] = NewTileFromOther(c.CurrentTile[11])
newCurrentTile[14] = NewTileFromOther(c.CurrentTile[7])
newCurrentTile[15] = NewTileFromOther(c.CurrentTile[3])
c.CurrentTile = newCurrentTile
} | current_tile.go | 0.519521 | 0.461805 | current_tile.go | starcoder |
package vector
import (
"fmt"
"math/cmplx"
"github.com/itsubaki/q/pkg/math/matrix"
)
type Vector []complex128
func New(z ...complex128) Vector {
out := Vector{}
for _, zi := range z {
out = append(out, zi)
}
return out
}
func Zero(n int) Vector {
out := Vector{}
for i := 0; i < n; i++ {
out = append(out, 0)
}
return out
}
func (v Vector) Complex() []complex128 {
return []complex128(v)
}
func (v Vector) Clone() Vector {
clone := Vector{}
for i := 0; i < len(v); i++ {
clone = append(clone, v[i])
}
return clone
}
func (v Vector) Dual() Vector {
out := Vector{}
for i := 0; i < len(v); i++ {
out = append(out, cmplx.Conj(v[i]))
}
return out
}
func (v Vector) Add(w Vector) Vector {
out := Vector{}
for i := 0; i < len(v); i++ {
out = append(out, v[i]+w[i])
}
return out
}
func (v Vector) Mul(z complex128) Vector {
out := Vector{}
for i := range v {
out = append(out, z*v[i])
}
return out
}
func (v Vector) TensorProduct(w Vector) Vector {
out := Vector{}
for i := 0; i < len(v); i++ {
for j := 0; j < len(w); j++ {
out = append(out, v[i]*w[j])
}
}
return out
}
func (v Vector) InnerProduct(w Vector) complex128 {
dual := w.Dual()
out := complex(0, 0)
for i := 0; i < len(v); i++ {
out = out + v[i]*dual[i]
}
return out
}
func (v Vector) OuterProduct(w Vector) matrix.Matrix {
dual := w.Dual()
out := matrix.Matrix{}
for i := 0; i < len(v); i++ {
vv := make([]complex128, 0)
for j := 0; j < len(dual); j++ {
vv = append(vv, v[i]*dual[j])
}
out = append(out, vv)
}
return out
}
func (v Vector) IsOrthogonal(w Vector) bool {
return v.InnerProduct(w) == 0
}
func (v Vector) Norm() complex128 {
return cmplx.Sqrt(v.InnerProduct(v))
}
func (v Vector) IsUnit() bool {
return v.Norm() == 1
}
func (v Vector) Apply(m matrix.Matrix) Vector {
p, q := m.Dimension()
if q != len(v) {
panic(fmt.Sprintf("invalid dimension. p=%d q=%d len(v)=%d", p, q, len(v)))
}
out := Vector{}
for i := 0; i < p; i++ {
tmp := complex(0, 0)
for j := 0; j < q; j++ {
tmp = tmp + m[i][j]*v[j]
}
out = append(out, tmp)
}
return out
}
func (v Vector) Equals(w Vector, eps ...float64) bool {
if len(v) != len(w) {
return false
}
e := epsilon(eps...)
for i := 0; i < len(v); i++ {
if cmplx.Abs(v[i]-w[i]) > e {
return false
}
}
return true
}
func (v Vector) Dimension() int {
return len(v)
}
func (v Vector) Real() []float64 {
out := make([]float64, 0)
for i := range v {
out = append(out, real(v[i]))
}
return out
}
func (v Vector) Imag() []float64 {
out := make([]float64, 0)
for i := range v {
out = append(out, imag(v[i]))
}
return out
}
func TensorProductN(v Vector, n ...int) Vector {
if len(n) < 1 {
return v
}
list := make([]Vector, 0)
for i := 0; i < n[0]; i++ {
list = append(list, v)
}
return TensorProduct(list...)
}
func TensorProduct(v ...Vector) Vector {
out := v[0]
for i := 1; i < len(v); i++ {
out = out.TensorProduct(v[i])
}
return out
}
func epsilon(eps ...float64) float64 {
if len(eps) > 0 {
return eps[0]
}
return 1e-13
} | pkg/math/vector/vector.go | 0.690872 | 0.422683 | vector.go | starcoder |
// Package counter provides functions to generate a frequency histogram of values.
package counter
import (
"sort"
)
// Counter is used for calculating a frequency histogram of strings.
type Counter map[string]int
// New returns a new Counter.
func New() Counter {
return Counter(map[string]int{})
}
// Len returns the current number of unique values.
func (c Counter) Len() int {
return len(c)
}
// Has returns true if the counter contains the value.
func (c Counter) Has(value string) bool {
_, ok := c[value]
return ok
}
// Count returns the current count for a given value.
// Returns 0 if the value has not occured.
func (c Counter) Count(value string) int {
i, ok := c[value]
if ok {
return i
}
return 0
}
// Increment increases the count for a given value by 1.
func (c Counter) Increment(value string) {
if count, ok := c[value]; ok {
c[value] = count + 1
} else {
c[value] = 1
}
}
// All returns all the values as a slice of strings.
// If s is set to true, then the values are sorted in alphabetical order.
func (c Counter) All(s bool) []string {
values := make([]string, 0, len(c))
for v := range c {
values = append(values, v)
}
if s {
sort.SliceStable(values, func(i, j int) bool {
return values[i] < values[j]
})
}
return values
}
// Top returns at most "n" values that have occured at least "min" times as a slice of strings.
// If s is set to true, then the values are sorted in descending order before the "n" values are chosen.
// If you would want to get the single most frequent value then use Top(1, 0, true).
// If you want 2 values that occured at least ten times, but do not care if they are the 2 most frequent values, then use Top(2, 10, false).
func (c Counter) Top(n int, min int, s bool) []string {
if n == 0 {
return make([]string, 0)
}
items := make([]struct {
Value string
Frequency int
}, 0)
for value, frequency := range c {
if frequency >= min {
items = append(items, struct {
Value string
Frequency int
}{Value: value, Frequency: frequency})
}
}
if s {
sort.SliceStable(items, func(i, j int) bool {
return items[i].Frequency > items[j].Frequency
})
}
if n > 0 && n < len(items) {
values := make([]string, 0, n)
for _, item := range items {
values = append(values, item.Value)
}
return values[:n]
}
values := make([]string, 0, len(items))
for _, item := range items {
values = append(values, item.Value)
}
return values
}
// Top returns at most "n" values that have occured at most "max" times as a slice of strings.
// If max is less than zero, then ignore "max" as a threshold.
// If max is set to zero, then the function will return an empty slice of strings.
// If s is set to true, then the values are sorted in ascending order before the "n" values are chosen.
func (c Counter) Bottom(n int, max int, s bool) []string {
if n == 0 {
return make([]string, 0)
}
items := make([]struct {
Value string
Frequency int
}, 0)
for value, frequency := range c {
if max < 0 || frequency <= max {
items = append(items, struct {
Value string
Frequency int
}{Value: value, Frequency: frequency})
}
}
if s {
sort.SliceStable(items, func(i, j int) bool {
return items[i].Frequency < items[j].Frequency
})
}
if n > 0 && n < len(items) {
values := make([]string, 0, n)
for _, item := range items {
values = append(values, item.Value)
}
return values[:n]
}
values := make([]string, 0, len(items))
for _, item := range items {
values = append(values, item.Value)
}
return values
} | pkg/counter/Counter.go | 0.858422 | 0.625438 | Counter.go | starcoder |
package pagerank
import (
"math"
)
// Pagerank is pagerank calculator
type Pagerank struct {
Matrix [][]uint64
Links []uint64
Keymap map[string]uint64
Rekeymap []string
}
// NewPagerank Create a pagerank calculator
func NewPagerank() *Pagerank {
return &Pagerank{
Keymap: map[string]uint64{},
}
}
// Len returns total number of pages
func (pr *Pagerank) Len() int {
return len(pr.Rekeymap)
}
// Link mark a link
func (pr *Pagerank) Link(from, to string) {
fromIndex := pr.keyIndex(from)
toIndex := pr.keyIndex(to)
pr.updateMatrix(fromIndex, toIndex)
pr.updateLinksNum(fromIndex)
}
// Rank calculate rank
func (pr *Pagerank) Rank(followingProb, tolerance float64, resultFunc func(label string, rank float64)) {
size := pr.Len()
invSize := 1.0 / float64(size)
overSize := (1.0 - followingProb) / float64(size)
existLinks := pr.getExistLinks()
result := make([]float64, 0, size)
for i := 0; i != size; i++ {
result = append(result, invSize)
}
for change := 1.0; change >= tolerance; {
newResult := pr.step(followingProb, overSize, existLinks, result)
change = calculateTolerance(result, newResult)
result = newResult
}
for i, v := range result {
resultFunc(pr.Rekeymap[uint64(i)], v)
}
}
// keyIndex
func (pr *Pagerank) keyIndex(key string) uint64 {
index, ok := pr.Keymap[key]
if !ok {
index = uint64(len(pr.Rekeymap))
pr.Rekeymap = append(pr.Rekeymap, key)
pr.Keymap[key] = index
}
return index
}
// updateMatrix
func (pr *Pagerank) updateMatrix(fromAsIndex, toAsIndex uint64) {
if missingSlots := len(pr.Keymap) - len(pr.Matrix); missingSlots > 0 {
pr.Matrix = append(pr.Matrix, make([][]uint64, missingSlots)...)
}
pr.Matrix[toAsIndex] = append(pr.Matrix[toAsIndex], fromAsIndex)
}
// updateLinksNum
func (pr *Pagerank) updateLinksNum(fromAsIndex uint64) {
if missingSlots := len(pr.Keymap) - len(pr.Links); missingSlots > 0 {
pr.Links = append(pr.Links, make([]uint64, missingSlots)...)
}
pr.Links[fromAsIndex] += 1
}
// getExistLinks
func (pr *Pagerank) getExistLinks() []int {
danglingNodes := make([]int, 0, len(pr.Links))
for i, numberOutLinksForI := range pr.Links {
if numberOutLinksForI == 0 {
danglingNodes = append(danglingNodes, i)
}
}
return danglingNodes
}
// step
func (pr *Pagerank) step(followingProb, overSize float64, existLinks []int, result []float64) []float64 {
sumLinks := 0.0
for _, v := range existLinks {
sumLinks += result[v]
}
sumLinks /= float64(len(result))
vsum := 0.0
newResult := make([]float64, len(result))
for i, from := range pr.Matrix {
ksum := 0.0
for _, index := range from {
ksum += result[index] / float64(pr.Links[index])
}
newResult[i] = followingProb*(ksum+sumLinks) + overSize
vsum += newResult[i]
}
for i := range newResult {
newResult[i] /= vsum
}
return newResult
}
// calculateTolerance
func calculateTolerance(result, newResult []float64) float64 {
acc := 0.0
for i, v := range result {
acc += math.Abs(v - newResult[i])
}
return acc
} | pagerank.go | 0.627152 | 0.460835 | pagerank.go | starcoder |
package advent2019
import "strings"
type orbitPoint struct {
Name string
Orbits *orbitPoint
OrbittedBy orbitPoints
}
type orbitPoints []*orbitPoint
func findNode(op *orbitPoint, find string) *orbitPoint {
if op.Name == find {
return op
}
for _, p := range op.OrbittedBy {
if res := findNode(p, find); res != nil && res.Name == find {
return res
}
}
return nil
}
//As I used findNode multiple times over multiple iterations this is a separate function.
func traverse(op *orbitPoint, count int) (*orbitPoint, int) {
tmp := 0
for _, p := range op.OrbittedBy {
_, val := traverse(p, count+1)
tmp += val
}
return op, count + tmp
}
func iteration(uom *orbitPoint, mapItems []string) (missing []string) {
for _, mapItem := range mapItems {
mapPoint := strings.Split(mapItem, ")")
// fmt.Printf("Initial - Given Parent: %s Orbitter: %s / ", mapPoint[0], mapPoint[1])
parent := findNode(uom, mapPoint[0])
if parent != nil {
new := &orbitPoint{
mapPoint[1],
parent,
nil,
}
parent.OrbittedBy = append(parent.OrbittedBy, new)
// fmt.Printf("Result - Returned Parent: %s Orbiter %s\n", parent.Name, new.Name)
} else {
missing = append(missing, mapItem)
}
}
return
}
func getPathFromEndNode(op *orbitPoint) []string {
pointer := op.Orbits
var opa []string
for pointer != nil {
opa = append(opa, pointer.Name)
pointer = pointer.Orbits
}
last := len(opa) - 1
for i := 0; i < len(opa)/2; i++ {
opa[i], opa[last-i] = opa[last-i], opa[i]
}
return opa
}
// Day6Part1 function
func Day6Part1(mapItems []string) int {
//Universal Orbit Map
uom := &orbitPoint{
"COM",
nil,
nil,
}
//Rather than devising some sort of pre-sorting I basically just go over it multiple times to ensure any misses on the first round get picked up on later rounds. I'm sure there is a more efficient way but my sort and other tests didn't really work so...
for len(mapItems) > 0 {
mapItems = iteration(uom, mapItems)
}
_, count := traverse(uom, 0)
return count
}
// Day6Part2 function
func Day6Part2(mapItems []string) int {
//Universal Orbit Map
uom := &orbitPoint{
"COM",
nil,
nil,
}
//Rather than devising some sort of pre-sorting I basically just go over it multiple times to ensure any misses on the first round get picked up on later rounds. I'm sure there is a more efficient way but my sort and other tests didn't really work so...
for len(mapItems) > 0 {
mapItems = iteration(uom, mapItems)
}
san := getPathFromEndNode(findNode(uom, "SAN"))
you := getPathFromEndNode(findNode(uom, "YOU"))
i := 0
countOfSame := 0
for true {
if i < len(you) && i < len(san) {
if you[i] == san[i] {
countOfSame++
}
} else {
break
}
i++
}
return (len(you) - countOfSame) + (len(san) - countOfSame)
} | internal/pkg/advent2019/day6.go | 0.535584 | 0.420659 | day6.go | starcoder |
package htm
import (
//"math"
"bytes"
"github.com/nupic-community/htm/utils"
)
//entries are positions of non-zero values
type SparseEntry struct {
Row int
Col int
}
//Sparse binary matrix stores indexes of non-zero entries in matrix
//to conserve space
type SparseBinaryMatrix struct {
Width int
Height int
entries []SparseEntry
}
//Create new sparse binary matrix of specified size
func NewSparseBinaryMatrix(height, width int) *SparseBinaryMatrix {
m := &SparseBinaryMatrix{}
m.Height = height
m.Width = width
//Intialize with 70% sparsity
//m.entries = make([]SparseEntry, int(math.Ceil(width*height*0.3)))
return m
}
//Create sparse binary matrix from specified dense matrix
func NewSparseBinaryMatrixFromDense(values [][]bool) *SparseBinaryMatrix {
if len(values) < 1 {
panic("No values specified.")
}
m := &SparseBinaryMatrix{}
m.Height = len(values)
m.Width = len(values[0])
for r := 0; r < m.Height; r++ {
m.SetRowFromDense(r, values[r])
}
return m
}
//Create sparse binary matrix from specified dense matrix
func NewSparseBinaryMatrixFromDense1D(values []bool, rows, cols int) *SparseBinaryMatrix {
if len(values) < 1 {
panic("No values specified.")
}
if len(values) != rows*cols {
panic("Invalid size")
}
m := new(SparseBinaryMatrix)
m.Height = rows
m.Width = cols
for r := 0; r < m.Height; r++ {
m.SetRowFromDense(r, values[r*cols:(r*cols)+cols])
}
return m
}
// Creates a sparse binary matrix from specified integer array
// (any values greater than 0 are true)
func NewSparseBinaryMatrixFromInts(values [][]int) *SparseBinaryMatrix {
if len(values) < 1 {
panic("No values specified.")
}
m := &SparseBinaryMatrix{}
m.Height = len(values)
m.Width = len(values[0])
for r := 0; r < m.Height; r++ {
for c := 0; c < m.Width; c++ {
if values[r][c] > 0 {
m.Set(r, c, true)
}
}
}
return m
}
// func NewRandSparseBinaryMatrix() *SparseBinaryMatrix {
// }
// func (sm *SparseBinaryMatrix) Resize(width int, height int) {
// }
//Returns all true/on indices
func (sm *SparseBinaryMatrix) Entries() []SparseEntry {
return sm.entries
}
//Returns flattend dense represenation
func (sm *SparseBinaryMatrix) Flatten() []bool {
result := make([]bool, sm.Height*sm.Width)
for _, val := range sm.entries {
result[(val.Row*sm.Width)+val.Col] = true
}
return result
}
//Get value at col,row position
func (sm *SparseBinaryMatrix) Get(row int, col int) bool {
for _, val := range sm.entries {
if val.Row == row && val.Col == col {
return true
}
}
return false
}
func (sm *SparseBinaryMatrix) delete(row int, col int) {
for idx, val := range sm.entries {
if val.Row == row && val.Col == col {
sm.entries = append(sm.entries[:idx], sm.entries[idx+1:]...)
break
}
}
}
//Set value at row,col position
func (sm *SparseBinaryMatrix) Set(row int, col int, value bool) {
if !value {
sm.delete(row, col)
return
}
if sm.Get(row, col) {
return
}
newEntry := SparseEntry{}
newEntry.Col = col
newEntry.Row = row
sm.entries = append(sm.entries, newEntry)
}
//Replaces specified row with values, assumes values is ordered
//correctly
func (sm *SparseBinaryMatrix) ReplaceRow(row int, values []bool) {
sm.validateRowCol(row, len(values))
for i := 0; i < sm.Width; i++ {
sm.Set(row, i, values[i])
}
}
//Replaces row with true values at specified indices
func (sm *SparseBinaryMatrix) ReplaceRowByIndices(row int, indices []int) {
sm.validateRow(row)
for i := 0; i < sm.Width; i++ {
val := false
for x := 0; x < len(indices); x++ {
if i == indices[x] {
val = true
break
}
}
sm.Set(row, i, val)
}
}
//Returns dense row
func (sm *SparseBinaryMatrix) GetDenseRow(row int) []bool {
sm.validateRow(row)
result := make([]bool, sm.Width)
for i := 0; i < len(sm.entries); i++ {
if sm.entries[i].Row == row {
result[sm.entries[i].Col] = true
}
}
return result
}
//Returns a rows "on" indices
func (sm *SparseBinaryMatrix) GetRowIndices(row int) []int {
result := []int{}
for i := 0; i < len(sm.entries); i++ {
if sm.entries[i].Row == row {
result = append(result, sm.entries[i].Col)
}
}
return result
}
//Sets a sparse row from dense representation
func (sm *SparseBinaryMatrix) SetRowFromDense(row int, denseRow []bool) {
sm.validateRowCol(row, len(denseRow))
for i := 0; i < sm.Width; i++ {
sm.Set(row, i, denseRow[i])
}
}
//In a normal matrix this would be multiplication in binary terms
//we just and then sum the true entries
func (sm *SparseBinaryMatrix) RowAndSum(row []bool) []int {
sm.validateCol(len(row))
result := make([]int, sm.Height)
for _, val := range sm.entries {
if row[val.Col] {
result[val.Row]++
}
}
return result
}
//Returns row indexes with at least 1 true column
func (sm *SparseBinaryMatrix) NonZeroRows() []int {
var result []int
for _, val := range sm.entries {
if !utils.ContainsInt(val.Row, result) {
result = append(result, val.Row)
}
}
return result
}
//Returns # of rows with at least 1 true value
func (sm *SparseBinaryMatrix) TotalTrueRows() int {
var hitRows []int
for _, val := range sm.entries {
if !utils.ContainsInt(val.Row, hitRows) {
hitRows = append(hitRows, val.Row)
}
}
return len(hitRows)
}
//Returns # of cols with at least 1 true value
func (sm *SparseBinaryMatrix) TotalTrueCols() int {
var hitCols []int
for _, val := range sm.entries {
if !utils.ContainsInt(val.Col, hitCols) {
hitCols = append(hitCols, val.Col)
}
}
return len(hitCols)
}
//Returns total true entries
func (sm *SparseBinaryMatrix) TotalNonZeroCount() int {
return len(sm.entries)
}
// Ors 2 matrices
func (sm *SparseBinaryMatrix) Or(sm2 *SparseBinaryMatrix) *SparseBinaryMatrix {
result := NewSparseBinaryMatrix(sm.Height, sm.Width)
for _, val := range sm.entries {
result.Set(val.Row, val.Col, true)
}
for _, val := range sm2.entries {
result.Set(val.Row, val.Col, true)
}
return result
}
//Clears all entries
func (sm *SparseBinaryMatrix) Clear() {
sm.entries = nil
}
//Fills specified row with specified value
func (sm *SparseBinaryMatrix) FillRow(row int, val bool) {
for j := 0; j < sm.Width; j++ {
sm.Set(row, j, val)
}
}
//Copys a matrix
func (sm *SparseBinaryMatrix) Copy() *SparseBinaryMatrix {
if sm == nil {
return nil
}
result := new(SparseBinaryMatrix)
result.Width = sm.Width
result.Height = sm.Height
result.entries = make([]SparseEntry, len(sm.entries))
for idx, val := range sm.entries {
result.entries[idx] = val
}
return result
}
func (sm *SparseBinaryMatrix) ToString() string {
var buffer bytes.Buffer
for r := 0; r < sm.Height; r++ {
for c := 0; c < sm.Width; c++ {
if sm.Get(r, c) {
buffer.WriteByte('1')
} else {
buffer.WriteByte('0')
}
}
buffer.WriteByte('\n')
}
return buffer.String()
}
func (sm *SparseBinaryMatrix) validateCol(col int) {
if col > sm.Width {
panic("Specified row is wider than matrix.")
}
}
func (sm *SparseBinaryMatrix) validateRow(row int) {
if row > sm.Height {
panic("Specified row is out of bounds.")
}
}
func (sm *SparseBinaryMatrix) validateRowCol(row int, col int) {
sm.validateCol(col)
sm.validateRow(row)
} | sparseBinaryMatrix.go | 0.715026 | 0.549882 | sparseBinaryMatrix.go | starcoder |
package split
import "github.com/vjeantet/bitfan/processors/doc"
func (p *processor) Doc() *doc.Processor {
return &doc.Processor{
Name: "split",
ImportPath: "github.com/vjeantet/bitfan/processors/filter-split",
Doc: "The split filter clones an event by splitting one of its fields and placing each value resulting from the split into a clone of the original event. The field being split can either be a string or an array.\n\nAn example use case of this filter is for taking output from the exec input plugin which emits one event for the whole output of a command and splitting that output by newline - making each line an event.\n\nThe end result of each split is a complete copy of the event with only the current split section of the given field changed.",
DocShort: "Splits multi-line messages into distinct events",
Options: &doc.ProcessorOptions{
Doc: "",
Options: []*doc.ProcessorOption{
&doc.ProcessorOption{
Name: "Field",
Alias: "",
Doc: "The field which value is split by the terminator",
Required: false,
Type: "string",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "",
},
&doc.ProcessorOption{
Name: "Target",
Alias: "",
Doc: "The field within the new event which the value is split into. If not set, target field defaults to split field name",
Required: false,
Type: "string",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "",
},
&doc.ProcessorOption{
Name: "Terminator",
Alias: "",
Doc: "The string to split on. This is usually a line terminator, but can be any string\nDefault value is \"\\n\"",
Required: false,
Type: "string",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "",
},
&doc.ProcessorOption{
Name: "processors.CommonOptions",
Alias: ",squash",
Doc: "",
Required: false,
Type: "processors.CommonOptions",
DefaultValue: nil,
PossibleValues: []string{},
ExampleLS: "",
},
},
},
Ports: []*doc.ProcessorPort{
&doc.ProcessorPort{
Default: true,
Name: "PORT_SUCCESS",
Number: 0,
Doc: "",
},
&doc.ProcessorPort{
Default: false,
Name: "PORT_ERROR",
Number: 1,
Doc: "",
},
},
}
} | processors/filter-split/docdoc.go | 0.655005 | 0.447279 | docdoc.go | starcoder |
package twod
import (
"fmt"
)
// Problem describes the situation we wish to optimize
type Problem struct {
Sheet Sheet `json:"sheet"`
Items []Item `json:"items"`
}
// Validate checks if the problem can be solved.
// If this returns an error the problem definitely cannot be solved.
// If this does not return an error it's still possible that the problem has no solution.
func (p *Problem) Validate() error {
for _, i := range p.Items {
if i.Width > p.Sheet.Width {
return &NoSolutionError{i, "item is wider than the sheet"}
}
if 0 < p.Sheet.Height && p.Sheet.Height < i.Height {
return &NoSolutionError{i, "item is taller than the sheet"}
}
}
return nil
}
// Sheet describes the container we want to pack the items on
type Sheet struct {
Width int64 `json:"width"`
// Height is the height of the sheet in units. If zero we'll pack a single infinite sheet
Height int64 `json:"height,omitempty"`
}
// SVG produces an SVG representation of this sheet
func (s *Sheet) SVG() string {
return fmt.Sprintf("<rect width=\"%d\" height=\"%d\" class=\"sheet\" />", s.Height, s.Width)
}
// Item describes a single item we want to pack on a sheet
type Item struct {
Name string `json:"name"`
Width int64 `json:"width"`
Height int64 `json:"height"`
}
// SVG produces an SVG representation of this item
func (i *Item) SVG() string {
return fmt.Sprintf("<rect width=\"%d\" height=\"%d\" class=\"item\"><text>%s</text></rect>", i.Width, i.Height, i.Name)
}
// Solution has the items packed on sheets
type Solution struct {
Sheets []PackedSheet `json:"sheet"`
Cost int64 `json:"cost"`
}
// SVG produces an SVG representation of this item
func (s *Solution) SVG() string {
style := `<style>
svg {
background-color: white;
}
.packed-sheet {
stroke: black;
fill: none;
}
.packed-item {
stroke: red;
fill: none;
}
</style>`
sheets := ""
for i, s := range s.Sheets {
sheets += fmt.Sprintf("<g transform=\"translate(0,%f)\">%s</g>", float32(i)*float32(s.Height)*1.05, s.SVG())
}
var w, h float32
if len(s.Sheets) > 0 {
w = float32(len(s.Sheets)) * float32(s.Sheets[0].Height) * 1.05
h = float32(s.Sheets[0].Width)
}
return fmt.Sprintf("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"%f\" height=\"%f\">%s%s</svg>", w, h, style, sheets)
}
// PackedSheet contains a set of items aranged on a sheet
type PackedSheet struct {
Sheet
Items []PackedItem `json:"items"`
}
// SVG produces an SVG representation of this sheet
func (s *PackedSheet) SVG() string {
sheet := s.Sheet.SVG()
items := ""
for _, i := range s.Items {
items += i.SVG()
}
return fmt.Sprintf("<g class=\"packed-sheet\">%s%s</g>", sheet, items)
}
// PackedItem is an item placed somewhere in space
type PackedItem struct {
Item
OffsetX int64 `json:"x"`
OffsetY int64 `json:"y"`
}
// SVG produces an SVG representation of this item
func (p *PackedItem) SVG() string {
return fmt.Sprintf("<g transform=\"translate(%d,%d)\" class=\"packed-item\">%s</g>", p.OffsetX, p.OffsetY, p.Item.SVG())
}
// NoSolutionError indicates that a problem has no solution
type NoSolutionError struct {
Item Item
Reason string
}
func (e *NoSolutionError) Error() string {
return e.Reason
} | pkg/twod/twod.go | 0.827375 | 0.41745 | twod.go | starcoder |
package shared
import (
"fmt"
"reflect"
"strings"
)
// Intertemplate an interface for manipulating templates.
type Intertemplate interface {
Length() int
GetFieldAt(i int) interface{}
NewTuple() Tuple
}
// Template structure used for matching against tuples.
// Templates is, in princple, a tuple with additional attributes used for pattern matching.
type Template struct {
Fields []interface{}
}
// CreateTemplate creates a template from the variadic fields provided.
// CreateTemplate encapsulates the types of pointer values and are used to provide variable binding.
// Variable binding is used in Pattern matched values such that they can be writen back through the pointers.
func CreateTemplate(fields ...interface{}) Template {
tempfields := make([]interface{}, len(fields))
copy(tempfields, fields)
// Replace pointers with reflect.Type value used to match type.
for i, value := range fields {
if reflect.TypeOf(value).Kind() == reflect.Ptr {
// Encapsulate the parameter with a TypeField.
tempfields[i] = CreateTypeField(reflect.ValueOf(value).Elem().Type())
}
}
template := Template{tempfields}
return template
}
// Length returns the amount of fields of the template.
func (tp *Template) Length() int {
return len((*tp).Fields)
}
// GetFieldAt returns the i'th field of the template.
func (tp *Template) GetFieldAt(i int) interface{} {
return (*tp).Fields[i]
}
// NewTuple returns a new tuple t from the template.
// NewTuple initializes all tuple fields in t with empty values depending on types in the template.
func (tp *Template) NewTuple() (t Tuple) {
param := make([]interface{}, tp.Length())
var element interface{}
for i, _ := range param {
field := tp.GetFieldAt(i)
if field != nil {
if reflect.TypeOf(field) == reflect.TypeOf(TypeField{}) {
tf := reflect.ValueOf(field).Interface().(TypeField)
rt := (tf.GetType()).(reflect.Type)
element = reflect.New(rt).Elem().Interface()
} else {
ptf := reflect.TypeOf(field)
element = reflect.New(ptf).Elem().Interface()
}
} else {
element = field
}
param[i] = element
}
t = CreateTuple(param...)
return t
}
// GetParenthesisType returns a pair of strings that encapsulates the template.
// GetParenthesisType is used in the String() method.
func (tp Template) GetParenthesisType() (string, string) {
return "(", ")"
}
// GetDelimiter returns the delimiter used to seperated the template fields.
// GetParenthesisType is used in the String() method.
func (tp Template) GetDelimiter() string {
return ", "
}
// String returns a print friendly representation of the template.
func (tp Template) String() string {
lp, rp := tp.GetParenthesisType()
delim := tp.GetDelimiter()
strs := make([]string, tp.Length())
for i, _ := range strs {
field := tp.GetFieldAt(i)
if field != nil {
if reflect.TypeOf(field).Kind() == reflect.String {
strs[i] = fmt.Sprintf("%s%s%s", "\"", field, "\"")
} else {
strs[i] = fmt.Sprintf("%v", field)
}
} else {
strs[i] = "nil"
}
}
return fmt.Sprintf("%s%s%s", lp, strings.Join(strs, delim), rp)
} | shared/template.go | 0.603114 | 0.426023 | template.go | starcoder |
package goja
import (
"fmt"
"reflect"
"strconv"
"github.com/dop251/goja/unistring"
)
/*
DynamicObject is an interface representing a handler for a dynamic Object. Such an object can be created
using the Runtime.NewDynamicObject() method.
Note that Runtime.ToValue() does not have any special treatment for DynamicObject. The only way to create
a dynamic object is by using the Runtime.NewDynamicObject() method. This is done deliberately to avoid
silent code breaks when this interface changes.
*/
type DynamicObject interface {
// Get a property value for the key. May return nil if the property does not exist.
Get(key string) Value
// Set a property value for the key. Return true if success, false otherwise.
Set(key string, val Value) bool
// Has should return true if and only if the property exists.
Has(key string) bool
// Delete the property for the key. Returns true on success (note, that includes missing property).
Delete(key string) bool
// Keys returns a list of all existing property keys. There are no checks for duplicates or to make sure
// that the order conforms to https://262.ecma-international.org/#sec-ordinaryownpropertykeys
Keys() []string
}
/*
DynamicArray is an interface representing a handler for a dynamic array Object. Such an object can be created
using the Runtime.NewDynamicArray() method.
Any integer property key or a string property key that can be parsed into an int value (including negative
ones) is treated as an index and passed to the trap methods of the DynamicArray. Note this is different from
the regular ECMAScript arrays which only support positive indexes up to 2^32-1.
DynamicArray cannot be sparse, i.e. hasOwnProperty(num) will return true for num >= 0 && num < Len(). Deleting
such a property will fail. Note that this creates a slight peculiarity because the properties are reported as
configurable (and therefore should be deletable). Reporting them as non-configurable is not an option though
as it breaks an ECMAScript invariant where non-configurable properties cannot disappear.
Note that Runtime.ToValue() does not have any special treatment for DynamicArray. The only way to create
a dynamic array is by using the Runtime.NewDynamicArray() method. This is done deliberately to avoid
silent code breaks when this interface changes.
*/
type DynamicArray interface {
// Len returns the current array length.
Len() int
// Get an item at index idx. Note that idx may be any integer, negative or beyond the current length.
Get(idx int) Value
// Set an item at index idx. Note that idx may be any integer, negative or beyond the current length.
// The expected behaviour when it's beyond length is that the array's length is increased to accommodate
// the item. All elements in the 'new' section of the array should be zeroed.
Set(idx int, val Value) bool
// SetLen is called when the array's 'length' property is changed. If the length is increased all elements in the
// 'new' section of the array should be zeroed.
SetLen(int) bool
}
type baseDynamicObject struct {
val *Object
prototype *Object
}
type dynamicObject struct {
baseDynamicObject
d DynamicObject
}
type dynamicArray struct {
baseDynamicObject
a DynamicArray
}
/*
NewDynamicObject creates an Object backed by the provided DynamicObject handler.
All properties of this Object are Writable, Enumerable and Configurable data properties. Any attempt to define
a property that does not conform to this will fail.
The Object is always extensible and cannot be made non-extensible. Object.preventExtensions() will fail.
The Object's prototype is initially set to Object.prototype, but can be changed using regular mechanisms
(Object.SetPrototype() in Go or Object.setPrototypeOf() in JS).
The Object cannot have own Symbol properties, however its prototype can. If you need an iterator support for
example, you could create a regular object, set Symbol.iterator on that object and then use it as a
prototype. See TestDynamicObjectCustomProto for more details.
Export() returns the original DynamicObject.
This mechanism is similar to ECMAScript Proxy, however because all properties are enumerable and the object
is always extensible there is no need for invariant checks which removes the need to have a target object and
makes it a lot more efficient.
*/
func (r *Runtime) NewDynamicObject(d DynamicObject) *Object {
v := &Object{runtime: r}
o := &dynamicObject{
d: d,
baseDynamicObject: baseDynamicObject{
val: v,
prototype: r.global.ObjectPrototype,
},
}
v.self = o
return v
}
/*
NewDynamicArray creates an array Object backed by the provided DynamicArray handler.
It is similar to NewDynamicObject, the differences are:
- the Object is an array (i.e. Array.isArray() will return true and it will have the length property).
- the prototype will be initially set to Array.prototype.
- the Object cannot have any own string properties except for the 'length'.
*/
func (r *Runtime) NewDynamicArray(a DynamicArray) *Object {
v := &Object{runtime: r}
o := &dynamicArray{
a: a,
baseDynamicObject: baseDynamicObject{
val: v,
prototype: r.global.ArrayPrototype,
},
}
v.self = o
return v
}
func (*dynamicObject) sortLen() int64 {
return 0
}
func (*dynamicObject) sortGet(i int64) Value {
return nil
}
func (*dynamicObject) swap(i int64, i2 int64) {
}
func (*dynamicObject) className() string {
return classObject
}
func (o *baseDynamicObject) getParentStr(p unistring.String, receiver Value) Value {
if proto := o.prototype; proto != nil {
if receiver == nil {
return proto.self.getStr(p, o.val)
}
return proto.self.getStr(p, receiver)
}
return nil
}
func (o *dynamicObject) getStr(p unistring.String, receiver Value) Value {
prop := o.d.Get(p.String())
if prop == nil {
return o.getParentStr(p, receiver)
}
return prop
}
func (o *baseDynamicObject) getParentIdx(p valueInt, receiver Value) Value {
if proto := o.prototype; proto != nil {
if receiver == nil {
return proto.self.getIdx(p, o.val)
}
return proto.self.getIdx(p, receiver)
}
return nil
}
func (o *dynamicObject) getIdx(p valueInt, receiver Value) Value {
prop := o.d.Get(p.String())
if prop == nil {
return o.getParentIdx(p, receiver)
}
return prop
}
func (o *baseDynamicObject) getSym(p *Symbol, receiver Value) Value {
if proto := o.prototype; proto != nil {
if receiver == nil {
return proto.self.getSym(p, o.val)
}
return proto.self.getSym(p, receiver)
}
return nil
}
func (o *dynamicObject) getOwnPropStr(u unistring.String) Value {
return o.d.Get(u.String())
}
func (o *dynamicObject) getOwnPropIdx(v valueInt) Value {
return o.d.Get(v.String())
}
func (*baseDynamicObject) getOwnPropSym(*Symbol) Value {
return nil
}
func (o *dynamicObject) _set(prop string, v Value, throw bool) bool {
if o.d.Set(prop, v) {
return true
}
o.val.runtime.typeErrorResult(throw, "'Set' on a dynamic object returned false")
return false
}
func (o *baseDynamicObject) _setSym(throw bool) {
o.val.runtime.typeErrorResult(throw, "Dynamic objects do not support Symbol properties")
}
func (o *dynamicObject) setOwnStr(p unistring.String, v Value, throw bool) bool {
prop := p.String()
if !o.d.Has(prop) {
if proto := o.prototype; proto != nil {
// we know it's foreign because prototype loops are not allowed
if res, handled := proto.self.setForeignStr(p, v, o.val, throw); handled {
return res
}
}
}
return o._set(prop, v, throw)
}
func (o *dynamicObject) setOwnIdx(p valueInt, v Value, throw bool) bool {
prop := p.String()
if !o.d.Has(prop) {
if proto := o.prototype; proto != nil {
// we know it's foreign because prototype loops are not allowed
if res, handled := proto.self.setForeignIdx(p, v, o.val, throw); handled {
return res
}
}
}
return o._set(prop, v, throw)
}
func (o *baseDynamicObject) setOwnSym(s *Symbol, v Value, throw bool) bool {
if proto := o.prototype; proto != nil {
// we know it's foreign because prototype loops are not allowed
if res, handled := proto.self.setForeignSym(s, v, o.val, throw); handled {
return res
}
}
o._setSym(throw)
return false
}
func (o *baseDynamicObject) setParentForeignStr(p unistring.String, v, receiver Value, throw bool) (res bool, handled bool) {
if proto := o.prototype; proto != nil {
if receiver != proto {
return proto.self.setForeignStr(p, v, receiver, throw)
}
return proto.self.setOwnStr(p, v, throw), true
}
return false, false
}
func (o *dynamicObject) setForeignStr(p unistring.String, v, receiver Value, throw bool) (res bool, handled bool) {
prop := p.String()
if !o.d.Has(prop) {
return o.setParentForeignStr(p, v, receiver, throw)
}
return false, false
}
func (o *baseDynamicObject) setParentForeignIdx(p valueInt, v, receiver Value, throw bool) (res bool, handled bool) {
if proto := o.prototype; proto != nil {
if receiver != proto {
return proto.self.setForeignIdx(p, v, receiver, throw)
}
return proto.self.setOwnIdx(p, v, throw), true
}
return false, false
}
func (o *dynamicObject) setForeignIdx(p valueInt, v, receiver Value, throw bool) (res bool, handled bool) {
prop := p.String()
if !o.d.Has(prop) {
return o.setParentForeignIdx(p, v, receiver, throw)
}
return false, false
}
func (o *baseDynamicObject) setForeignSym(p *Symbol, v, receiver Value, throw bool) (res bool, handled bool) {
if proto := o.prototype; proto != nil {
if receiver != proto {
return proto.self.setForeignSym(p, v, receiver, throw)
}
return proto.self.setOwnSym(p, v, throw), true
}
return false, false
}
func (o *dynamicObject) hasPropertyStr(u unistring.String) bool {
if o.hasOwnPropertyStr(u) {
return true
}
if proto := o.prototype; proto != nil {
return proto.self.hasPropertyStr(u)
}
return false
}
func (o *dynamicObject) hasPropertyIdx(idx valueInt) bool {
if o.hasOwnPropertyIdx(idx) {
return true
}
if proto := o.prototype; proto != nil {
return proto.self.hasPropertyIdx(idx)
}
return false
}
func (o *baseDynamicObject) hasPropertySym(s *Symbol) bool {
if proto := o.prototype; proto != nil {
return proto.self.hasPropertySym(s)
}
return false
}
func (o *dynamicObject) hasOwnPropertyStr(u unistring.String) bool {
return o.d.Has(u.String())
}
func (o *dynamicObject) hasOwnPropertyIdx(v valueInt) bool {
return o.d.Has(v.String())
}
func (*baseDynamicObject) hasOwnPropertySym(_ *Symbol) bool {
return false
}
func (o *baseDynamicObject) checkDynamicObjectPropertyDescr(name fmt.Stringer, descr PropertyDescriptor, throw bool) bool {
if descr.Getter != nil || descr.Setter != nil {
o.val.runtime.typeErrorResult(throw, "Dynamic objects do not support accessor properties")
return false
}
if descr.Writable == FLAG_FALSE {
o.val.runtime.typeErrorResult(throw, "Dynamic object field %q cannot be made read-only", name.String())
return false
}
if descr.Enumerable == FLAG_FALSE {
o.val.runtime.typeErrorResult(throw, "Dynamic object field %q cannot be made non-enumerable", name.String())
return false
}
if descr.Configurable == FLAG_FALSE {
o.val.runtime.typeErrorResult(throw, "Dynamic object field %q cannot be made non-configurable", name.String())
return false
}
return true
}
func (o *dynamicObject) defineOwnPropertyStr(name unistring.String, desc PropertyDescriptor, throw bool) bool {
if o.checkDynamicObjectPropertyDescr(name, desc, throw) {
return o._set(name.String(), desc.Value, throw)
}
return false
}
func (o *dynamicObject) defineOwnPropertyIdx(name valueInt, desc PropertyDescriptor, throw bool) bool {
if o.checkDynamicObjectPropertyDescr(name, desc, throw) {
return o._set(name.String(), desc.Value, throw)
}
return false
}
func (o *baseDynamicObject) defineOwnPropertySym(name *Symbol, desc PropertyDescriptor, throw bool) bool {
o._setSym(throw)
return false
}
func (o *dynamicObject) _delete(prop string, throw bool) bool {
if o.d.Delete(prop) {
return true
}
o.val.runtime.typeErrorResult(throw, "Could not delete property %q of a dynamic object", prop)
return false
}
func (o *dynamicObject) deleteStr(name unistring.String, throw bool) bool {
return o._delete(name.String(), throw)
}
func (o *dynamicObject) deleteIdx(idx valueInt, throw bool) bool {
return o._delete(idx.String(), throw)
}
func (*baseDynamicObject) deleteSym(_ *Symbol, _ bool) bool {
return true
}
func (o *baseDynamicObject) toPrimitiveNumber() Value {
return o.val.genericToPrimitiveNumber()
}
func (o *baseDynamicObject) toPrimitiveString() Value {
return o.val.genericToPrimitiveString()
}
func (o *baseDynamicObject) toPrimitive() Value {
return o.val.genericToPrimitive()
}
func (o *baseDynamicObject) assertCallable() (call func(FunctionCall) Value, ok bool) {
return nil, false
}
func (*baseDynamicObject) assertConstructor() func(args []Value, newTarget *Object) *Object {
return nil
}
func (o *baseDynamicObject) proto() *Object {
return o.prototype
}
func (o *baseDynamicObject) setProto(proto *Object, throw bool) bool {
o.prototype = proto
return true
}
func (o *baseDynamicObject) hasInstance(v Value) bool {
panic(o.val.runtime.NewTypeError("Expecting a function in instanceof check, but got a dynamic object"))
}
func (*baseDynamicObject) isExtensible() bool {
return true
}
func (o *baseDynamicObject) preventExtensions(throw bool) bool {
o.val.runtime.typeErrorResult(throw, "Cannot make a dynamic object non-extensible")
return false
}
type dynamicObjectPropIter struct {
o *dynamicObject
propNames []string
idx int
}
func (i *dynamicObjectPropIter) next() (propIterItem, iterNextFunc) {
for i.idx < len(i.propNames) {
name := i.propNames[i.idx]
i.idx++
if i.o.d.Has(name) {
return propIterItem{name: unistring.NewFromString(name), enumerable: _ENUM_TRUE}, i.next
}
}
return propIterItem{}, nil
}
func (o *dynamicObject) enumerateOwnKeys() iterNextFunc {
keys := o.d.Keys()
return (&dynamicObjectPropIter{
o: o,
propNames: keys,
}).next
}
func (o *dynamicObject) export(ctx *objectExportCtx) interface{} {
return o.d
}
func (o *dynamicObject) exportType() reflect.Type {
return reflect.TypeOf(o.d)
}
func (o *dynamicObject) equal(impl objectImpl) bool {
if other, ok := impl.(*dynamicObject); ok {
return o.d == other.d
}
return false
}
func (o *dynamicObject) ownKeys(all bool, accum []Value) []Value {
keys := o.d.Keys()
if l := len(accum) + len(keys); l > cap(accum) {
oldAccum := accum
accum = make([]Value, len(accum), l)
copy(accum, oldAccum)
}
for _, key := range keys {
accum = append(accum, newStringValue(key))
}
return accum
}
func (*baseDynamicObject) ownSymbols(all bool, accum []Value) []Value {
return accum
}
func (o *dynamicObject) ownPropertyKeys(all bool, accum []Value) []Value {
return o.ownKeys(all, accum)
}
func (*baseDynamicObject) _putProp(name unistring.String, value Value, writable, enumerable, configurable bool) Value {
return nil
}
func (*baseDynamicObject) _putSym(s *Symbol, prop Value) {
}
func (a *dynamicArray) sortLen() int64 {
return int64(a.a.Len())
}
func (a *dynamicArray) sortGet(i int64) Value {
return a.a.Get(int(i))
}
func (a *dynamicArray) swap(i int64, j int64) {
x := a.sortGet(i)
y := a.sortGet(j)
a.a.Set(int(i), y)
a.a.Set(int(j), x)
}
func (a *dynamicArray) className() string {
return classArray
}
func (a *dynamicArray) getStr(p unistring.String, receiver Value) Value {
if p == "length" {
return intToValue(int64(a.a.Len()))
}
if idx, ok := strPropToInt(p); ok {
return a.a.Get(idx)
}
return a.getParentStr(p, receiver)
}
func (a *dynamicArray) getIdx(p valueInt, receiver Value) Value {
if val := a.getOwnPropIdx(p); val != nil {
return val
}
return a.getParentIdx(p, receiver)
}
func (a *dynamicArray) getOwnPropStr(u unistring.String) Value {
if u == "length" {
return &valueProperty{
value: intToValue(int64(a.a.Len())),
writable: true,
}
}
if idx, ok := strPropToInt(u); ok {
return a.a.Get(idx)
}
return nil
}
func (a *dynamicArray) getOwnPropIdx(v valueInt) Value {
return a.a.Get(toIntStrict(int64(v)))
}
func (a *dynamicArray) _setLen(v Value, throw bool) bool {
if a.a.SetLen(toIntStrict(v.ToInteger())) {
return true
}
a.val.runtime.typeErrorResult(throw, "'SetLen' on a dynamic array returned false")
return false
}
func (a *dynamicArray) setOwnStr(p unistring.String, v Value, throw bool) bool {
if p == "length" {
return a._setLen(v, throw)
}
if idx, ok := strPropToInt(p); ok {
return a._setIdx(idx, v, throw)
}
a.val.runtime.typeErrorResult(throw, "Cannot set property %q on a dynamic array", p.String())
return false
}
func (a *dynamicArray) _setIdx(idx int, v Value, throw bool) bool {
if a.a.Set(idx, v) {
return true
}
a.val.runtime.typeErrorResult(throw, "'Set' on a dynamic array returned false")
return false
}
func (a *dynamicArray) setOwnIdx(p valueInt, v Value, throw bool) bool {
return a._setIdx(toIntStrict(int64(p)), v, throw)
}
func (a *dynamicArray) setForeignStr(p unistring.String, v, receiver Value, throw bool) (res bool, handled bool) {
return a.setParentForeignStr(p, v, receiver, throw)
}
func (a *dynamicArray) setForeignIdx(p valueInt, v, receiver Value, throw bool) (res bool, handled bool) {
return a.setParentForeignIdx(p, v, receiver, throw)
}
func (a *dynamicArray) hasPropertyStr(u unistring.String) bool {
if a.hasOwnPropertyStr(u) {
return true
}
if proto := a.prototype; proto != nil {
return proto.self.hasPropertyStr(u)
}
return false
}
func (a *dynamicArray) hasPropertyIdx(idx valueInt) bool {
if a.hasOwnPropertyIdx(idx) {
return true
}
if proto := a.prototype; proto != nil {
return proto.self.hasPropertyIdx(idx)
}
return false
}
func (a *dynamicArray) _has(idx int) bool {
return idx >= 0 && idx < a.a.Len()
}
func (a *dynamicArray) hasOwnPropertyStr(u unistring.String) bool {
if u == "length" {
return true
}
if idx, ok := strPropToInt(u); ok {
return a._has(idx)
}
return false
}
func (a *dynamicArray) hasOwnPropertyIdx(v valueInt) bool {
return a._has(toIntStrict(int64(v)))
}
func (a *dynamicArray) defineOwnPropertyStr(name unistring.String, desc PropertyDescriptor, throw bool) bool {
if a.checkDynamicObjectPropertyDescr(name, desc, throw) {
if idx, ok := strPropToInt(name); ok {
return a._setIdx(idx, desc.Value, throw)
}
a.val.runtime.typeErrorResult(throw, "Cannot define property %q on a dynamic array", name.String())
}
return false
}
func (a *dynamicArray) defineOwnPropertyIdx(name valueInt, desc PropertyDescriptor, throw bool) bool {
if a.checkDynamicObjectPropertyDescr(name, desc, throw) {
return a._setIdx(toIntStrict(int64(name)), desc.Value, throw)
}
return false
}
func (a *dynamicArray) _delete(idx int, throw bool) bool {
if !a._has(idx) {
return true
}
a.val.runtime.typeErrorResult(throw, "Cannot delete index property %d from a dynamic array", idx)
return false
}
func (a *dynamicArray) deleteStr(name unistring.String, throw bool) bool {
if idx, ok := strPropToInt(name); ok {
return a._delete(idx, throw)
}
if a.hasOwnPropertyStr(name) {
a.val.runtime.typeErrorResult(throw, "Cannot delete property %q on a dynamic array", name.String())
return false
}
return true
}
func (a *dynamicArray) deleteIdx(idx valueInt, throw bool) bool {
return a._delete(toIntStrict(int64(idx)), throw)
}
type dynArrayPropIter struct {
a DynamicArray
idx, limit int
}
func (i *dynArrayPropIter) next() (propIterItem, iterNextFunc) {
if i.idx < i.limit && i.idx < i.a.Len() {
name := strconv.Itoa(i.idx)
i.idx++
return propIterItem{name: unistring.String(name), enumerable: _ENUM_TRUE}, i.next
}
return propIterItem{}, nil
}
func (a *dynamicArray) enumerateOwnKeys() iterNextFunc {
return (&dynArrayPropIter{
a: a.a,
limit: a.a.Len(),
}).next
}
func (a *dynamicArray) export(ctx *objectExportCtx) interface{} {
return a.a
}
func (a *dynamicArray) exportType() reflect.Type {
return reflect.TypeOf(a.a)
}
func (a *dynamicArray) equal(impl objectImpl) bool {
if other, ok := impl.(*dynamicArray); ok {
return a == other
}
return false
}
func (a *dynamicArray) ownKeys(all bool, accum []Value) []Value {
al := a.a.Len()
l := len(accum) + al
if all {
l++
}
if l > cap(accum) {
oldAccum := accum
accum = make([]Value, len(oldAccum), l)
copy(accum, oldAccum)
}
for i := 0; i < al; i++ {
accum = append(accum, asciiString(strconv.Itoa(i)))
}
if all {
accum = append(accum, asciiString("length"))
}
return accum
}
func (a *dynamicArray) ownPropertyKeys(all bool, accum []Value) []Value {
return a.ownKeys(all, accum)
} | vendor/github.com/dop251/goja/object_dynamic.go | 0.782829 | 0.411347 | object_dynamic.go | starcoder |
package bn256
import "math/bits"
// GT target group of the pairing
type GT = e12
type lineEvaluation struct {
r0 e2
r1 e2
r2 e2
}
// FinalExponentiation computes the final expo x**(p**6-1)(p**2+1)(p**4 - p**2 +1)/r
func FinalExponentiation(z *GT, _z ...*GT) GT {
var result GT
result.Set(z)
for _, e := range _z {
result.Mul(&result, e)
}
result.FinalExponentiation(&result)
return result
}
// FinalExponentiation sets z to the final expo x**((p**12 - 1)/r), returns z
func (z *GT) FinalExponentiation(x *GT) *GT {
// https://eprint.iacr.org/2008/490.pdf
var mt [4]GT // mt[i] is m^(t^i)
// easy part
mt[0].Set(x)
var temp GT
temp.Conjugate(&mt[0])
mt[0].Inverse(&mt[0])
temp.Mul(&temp, &mt[0])
mt[0].FrobeniusSquare(&temp).
Mul(&mt[0], &temp)
// hard part
mt[1].expt(&mt[0])
mt[2].expt(&mt[1])
mt[3].expt(&mt[2])
var y [7]GT
y[1].InverseUnitary(&mt[0])
y[4].Set(&mt[1])
y[5].InverseUnitary(&mt[2])
y[6].Set(&mt[3])
mt[0].Frobenius(&mt[0])
mt[1].Frobenius(&mt[1])
mt[2].Frobenius(&mt[2])
mt[3].Frobenius(&mt[3])
y[0].Set(&mt[0])
y[3].InverseUnitary(&mt[1])
y[4].Mul(&y[4], &mt[2]).InverseUnitary(&y[4])
y[6].Mul(&y[6], &mt[3]).InverseUnitary(&y[6])
mt[0].Frobenius(&mt[0])
mt[2].Frobenius(&mt[2])
y[0].Mul(&y[0], &mt[0])
y[2].Set(&mt[2])
mt[0].Frobenius(&mt[0])
y[0].Mul(&y[0], &mt[0])
// compute addition chain
var t [2]GT
t[0].CyclotomicSquare(&y[6])
t[0].Mul(&t[0], &y[4])
t[0].Mul(&t[0], &y[5])
t[1].Mul(&y[3], &y[5])
t[1].Mul(&t[1], &t[0])
t[0].Mul(&t[0], &y[2])
t[1].CyclotomicSquare(&t[1])
t[1].Mul(&t[1], &t[0])
t[1].CyclotomicSquare(&t[1])
t[0].Mul(&t[1], &y[1])
t[1].Mul(&t[1], &y[0])
t[0].CyclotomicSquare(&t[0])
z.Mul(&t[0], &t[1])
return z
}
// MillerLoop Miller loop
func MillerLoop(P G1Affine, Q G2Affine) *GT {
var result GT
result.SetOne()
if P.IsInfinity() || Q.IsInfinity() {
return &result
}
ch := make(chan struct{}, 30)
var evaluations [86]lineEvaluation
var Qjac G2Jac
Qjac.FromAffine(&Q)
go preCompute(&evaluations, &Qjac, &P, ch)
j := 0
for i := len(loopCounter) - 2; i >= 0; i-- {
result.Square(&result)
<-ch
result.mulAssign(&evaluations[j])
j++
if loopCounter[i] != 0 {
<-ch
result.mulAssign(&evaluations[j])
j++
}
}
// cf https://eprint.iacr.org/2010/354.pdf for instance for optimal Ate Pairing
var Q1, Q2 G2Jac
//Q1 = Frob(Q)
Q1.X.Conjugate(&Q.X).MulByNonResidue1Power2(&Q1.X)
Q1.Y.Conjugate(&Q.Y).MulByNonResidue1Power3(&Q1.Y)
Q1.Z.SetOne()
// Q2 = -Frob2(Q)
Q2.X.MulByNonResidue2Power2(&Q.X)
Q2.Y.MulByNonResidue2Power3(&Q.Y).Neg(&Q2.Y)
Q2.Z.SetOne()
var lEval lineEvaluation
lineEval(&Qjac, &Q1, &P, &lEval)
result.mulAssign(&lEval)
Qjac.AddAssign(&Q1)
lineEval(&Qjac, &Q2, &P, &lEval)
result.mulAssign(&lEval)
return &result
}
// lineEval computes the evaluation of the line through Q, R (on the twist) at P
// Q, R are in jacobian coordinates
func lineEval(Q, R *G2Jac, P *G1Affine, result *lineEvaluation) {
// converts _Q and _R to projective coords
var _Q, _R g2Proj
_Q.FromJacobian(Q)
_R.FromJacobian(R)
result.r1.Mul(&_Q.y, &_R.z)
result.r0.Mul(&_Q.z, &_R.x)
result.r2.Mul(&_Q.x, &_R.y)
_Q.z.Mul(&_Q.z, &_R.y)
_Q.x.Mul(&_Q.x, &_R.z)
_Q.y.Mul(&_Q.y, &_R.x)
result.r1.Sub(&result.r1, &_Q.z)
result.r0.Sub(&result.r0, &_Q.x)
result.r2.Sub(&result.r2, &_Q.y)
result.r1.MulByElement(&result.r1, &P.X)
result.r0.MulByElement(&result.r0, &P.Y)
}
func (z *GT) mulAssign(l *lineEvaluation) *GT {
var a, b, c GT
a.mulByVW(z, &l.r1)
b.mulByV(z, &l.r0)
c.mulByV2W(z, &l.r2)
z.Add(&a, &b).Add(z, &c)
return z
}
// precomputes the line evaluations used during the Miller loop.
func preCompute(evaluations *[86]lineEvaluation, Q *G2Jac, P *G1Affine, ch chan struct{}) {
var Q1, Qbuf, Qneg G2Jac
Q1.Set(Q)
Qbuf.Set(Q)
Qneg.Neg(Q)
j := 0
for i := len(loopCounter) - 2; i >= 0; i-- {
Q1.Set(Q)
Q.Double(&Q1).Neg(Q)
lineEval(&Q1, Q, P, &evaluations[j]) // f(P), div(f) = 2(Q1)+(-2Q)-3(O)
Q.Neg(Q)
ch <- struct{}{}
j++
if loopCounter[i] == 1 {
lineEval(Q, &Qbuf, P, &evaluations[j]) // f(P), div(f) = (Q)+(Qbuf)+(-Q-Qbuf)-3(O)
Q.AddAssign(&Qbuf)
ch <- struct{}{}
j++
} else if loopCounter[i] == -1 {
lineEval(Q, &Qneg, P, &evaluations[j]) // f(P), div(f) = (Q)+(-Qbuf)+(-Q+Qbuf)-3(O)
Q.AddAssign(&Qneg)
ch <- struct{}{}
j++
}
}
close(ch)
}
// mulByVW set z to x*(y*v*w) and return z
// here y*v*w means the GT element with C1.B1=y and all other components 0
func (z *GT) mulByVW(x *GT, y *e2) *GT {
var result GT
var yNR e2
yNR.MulByNonResidue(y)
result.C0.B0.Mul(&x.C1.B1, &yNR)
result.C0.B1.Mul(&x.C1.B2, &yNR)
result.C0.B2.Mul(&x.C1.B0, y)
result.C1.B0.Mul(&x.C0.B2, &yNR)
result.C1.B1.Mul(&x.C0.B0, y)
result.C1.B2.Mul(&x.C0.B1, y)
z.Set(&result)
return z
}
// mulByV set z to x*(y*v) and return z
// here y*v means the GT element with C0.B1=y and all other components 0
func (z *GT) mulByV(x *GT, y *e2) *GT {
var result GT
var yNR e2
yNR.MulByNonResidue(y)
result.C0.B0.Mul(&x.C0.B2, &yNR)
result.C0.B1.Mul(&x.C0.B0, y)
result.C0.B2.Mul(&x.C0.B1, y)
result.C1.B0.Mul(&x.C1.B2, &yNR)
result.C1.B1.Mul(&x.C1.B0, y)
result.C1.B2.Mul(&x.C1.B1, y)
z.Set(&result)
return z
}
// mulByV2W set z to x*(y*v^2*w) and return z
// here y*v^2*w means the GT element with C1.B2=y and all other components 0
func (z *GT) mulByV2W(x *GT, y *e2) *GT {
var result GT
var yNR e2
yNR.MulByNonResidue(y)
result.C0.B0.Mul(&x.C1.B0, &yNR)
result.C0.B1.Mul(&x.C1.B1, &yNR)
result.C0.B2.Mul(&x.C1.B2, &yNR)
result.C1.B0.Mul(&x.C0.B1, &yNR)
result.C1.B1.Mul(&x.C0.B2, &yNR)
result.C1.B2.Mul(&x.C0.B0, y)
z.Set(&result)
return z
}
// expt set z to x^t in GT and return z (t is the generator of the BN curve)
func (z *GT) expt(x *GT) *GT {
const tAbsVal uint64 = 4965661367192848881
var result GT
result.Set(x)
l := bits.Len64(tAbsVal) - 2
for i := l; i >= 0; i-- {
result.CyclotomicSquare(&result)
if tAbsVal&(1<<uint(i)) != 0 {
result.Mul(&result, x)
}
}
z.Set(&result)
return z
} | bn256/pairing.go | 0.620737 | 0.474936 | pairing.go | starcoder |
package types
//go:generate msgp
const (
// ReceiptStatusFailed is the status code of a transaction if execution failed.
ReceiptStatusFailed = uint64(0)
// ReceiptStatusSuccessful is the status code of a transaction if execution succeeded.
ReceiptStatusSuccessful = uint64(1)
)
type InternalTxCall struct {
/** The kind of the call. For zero-depth calls ::EVMC_CALL SHOULD be used. */
Kind int `msgp:"kind"`
/**
* Additional flags modifying the call execution behavior.
* In the current version the only valid values are ::EVMC_STATIC or 0.
*/
Flags uint32 `msgp:"flags"`
/** The call depth. */
Depth int32 `msgp:"depth"`
/** The amount of gas for message execution. */
Gas int64
/** The callee of the transaction. */
Destination [20]byte `msgp:"destination"`
/** The caller of the transaction. */
Sender [20]byte `msgp:"sender"`
/** the input data. */
Input []byte `msgp:"input"`
/**
* The amount of BCH transferred with the message.
*/
Value [32]byte `msgp:"value"`
}
type InternalTxReturn struct {
/** The execution status code. */
StatusCode int `msgp:"statusCode"`
/**
* The amount of gas left after the execution.
* If StatusCode is neither ::EVMC_SUCCESS nor ::EVMC_REVERT
* the value MUST be 0.
*/
GasLeft int64 `msgp:"gasLeft"`
/** the output data. */
Output []byte `msgp:"output"`
/**
* The address of the contract created by create instructions.
*
* This field has valid value only if:
* - it is a result of the Host method evmc_host_interface::call
* - and the result describes successful contract creation
* (StatusCode is ::EVMC_SUCCESS).
* In all other cases the address MUST be null bytes.
*/
CreateAddress [20]byte `msgp:"createAddress"`
}
type Log struct {
// Consensus fields:
// address of the contract that generated the event
Address [20]byte `msgp:"address"`
// list of topics provided by the contract.
Topics [][32]byte `msgp:"topics"`
// supplied by the contract, usually ABI-encoded
Data []byte `msgp:"data"`
// Derived fields. These fields are filled in by the node
// but not secured by consensus.
// block in which the transaction was included
BlockNumber uint64 `msgp:"blockNumber"`
// hash of the transaction
TxHash [32]byte `msgp:"transactionHash"`
// index of the transaction in the block
TxIndex uint `msgp:"transactionIndex"`
// hash of the block in which the transaction was included
BlockHash [32]byte `msgp:"blockHash"`
// index of the log in the block
Index uint `msgp:"logIndex"`
// The Removed field is true if this log was reverted due to a chain reorganisation.
// You must pay attention to this field if you receive logs through a filter query.
Removed bool `msgp:"removed"`
}
//logs are objects with following params (Using types.Log is OK):
// removed: true when the log was removed, due to a chain reorganization. false if it's a valid log.
// logIndex: integer of the log index position in the block. null when its pending log.
// transactionIndex: integer of the transactions index position log was created from. null when its pending log.
// transactionHash: 32 Bytes - hash of the transactions this log was created from. null when its pending log.
// blockHash: 32 Bytes - hash of the block where this log was in. null when its pending. null when its pending log.
// blockNumber: the block number where this log was in. null when its pending. null when its pending log.
// address: 20 Bytes - address from which this log originated.
// data: contains one or more 32 Bytes non-indexed arguments of the log.
// topics: Array of 0 to 4 32 Bytes of indexed log arguments. (In solidity: The first topic is the hash of the signature of the event (e.g. Deposit(address,bytes32,uint256)), except you declared the event with the anonymous specifier.)
//TRANSACTION - A transaction object, or null when no transaction was found
type Transaction struct {
Hash [32]byte `msg:"hash"` //32 Bytes - hash of the transaction.
TransactionIndex int64 `msg:"index"` //integer of the transactions index position in the block. null when its pending.
Nonce uint64 `msg:"nonce"` //the number of transactions made by the sender prior to this one.
BlockHash [32]byte `msg:"block"` //32 Bytes - hash of the block where this transaction was in. null when its pending.
BlockNumber int64 `msg:"height"` //block number where this transaction was in. null when its pending.
From [20]byte `msg:"from"` //20 Bytes - address of the sender.
To [20]byte `msg:"to"` //20 Bytes - address of the receiver. null when its a contract creation transaction.
Value [32]byte `msg:"value"` //value transferred in Wei.
GasPrice [32]byte `msg:"gasprice"` //gas price provided by the sender in Wei.
Gas uint64 `msg:"gas"` //gas provided by the sender.
Input []byte `msg:"input"` //the data send along with the transaction.
CumulativeGasUsed uint64 `msg:"cgasused"` // the total amount of gas used when this transaction was executed in the block.
GasUsed uint64 `msg:"gasused"` //the amount of gas used by this specific transaction alone.
ContractAddress [20]byte `msg:"contractaddr"` //20 Bytes - the contract address created, if the transaction was a contract creation, otherwise - null.
Logs []Log `msg:"logs"` //Array - Array of log objects, which this transaction generated.
LogsBloom [256]byte `msg:"bloom"` //256 Bytes - Bloom filter for light clients to quickly retrieve related logs.
Status uint64 `msg:"status"` //tx execute result: ReceiptStatusFailed or ReceiptStatusSuccessful
StatusStr string `msg:"statusstr"` //tx execute result explained
OutData []byte `msg:"outdata"` //the output data from the transaction
//PostState []byte //look at Receipt.PostState
InternalTxCalls []InternalTxCall `msg:"internalTxCalls"`
InternalTxReturns []InternalTxReturn `msg:"internalTxReturns"`
}
//TRANSACTION RECEIPT - A transaction receipt object, or null when no receipt was found:
// transactionHash: 32 Bytes - hash of the transaction.
// transactionIndex: integer of the transactions index position in the block.
// blockHash: 32 Bytes - hash of the block where this transaction was in.
// blockNumber: block number where this transaction was in.
// from: 20 Bytes - address of the sender.
// to: 20 Bytes - address of the receiver. Null when the transaction is a contract creation transaction.
// *cumulativeGasUsed: the total amount of gas used when this transaction was executed in the block.
// *gasUsed: the amount of gas used by this specific transaction alone.
// *contractAddress: 20 Bytes - the contract address created, if the transaction was a contract creation, otherwise - null.
// *logs: Array - Array of log objects, which this transaction generated.
// *logsBloom: 256 Bytes - Bloom filter for light clients to quickly retrieve related logs. | types/tx.go | 0.666931 | 0.408631 | tx.go | starcoder |
package build
import "fmt"
// InsertInto returns a new INSERT statement.
func InsertInto(table string, columns ...string) *InsertStmt {
stmt := &InsertStmt{table: Ident(table)}
if len(columns) > 0 {
stmt.columns = make([]Expression, len(columns))
for i := range columns {
stmt.columns[i] = Ident(columns[i])
}
}
return stmt
}
// DefaultValues adds the DEFAULT VALUES keyword.
func (stmt *InsertStmt) DefaultValues() *InsertStmt {
stmt.values = defaultvalues{}
return stmt
}
// Values adds VALUES.
func (stmt *InsertStmt) Values(values ...Expression) *InsertStmt {
stmt.values = valuesexpr{values: values}
return stmt
}
// Query adds a query.
func (stmt *InsertStmt) Query(query Expression) *InsertStmt {
stmt.values = queryexpr{query: query}
return stmt
}
type defaultvalues struct{}
func (defaultvalues) build(b *builder) {
b.write("DEFAULT VALUES")
}
type valuesexpr struct {
values []Expression
}
func (e valuesexpr) build(b *builder) {
b.write("VALUES (")
for i := range e.values {
if i > 0 {
b.write(", ")
}
e.values[i].build(b)
}
b.write(")")
}
type queryexpr struct {
query Expression
}
func (e queryexpr) build(b *builder) {
e.query.build(b)
}
// OnConflict adds a ON CONFLICT clause.
func (stmt *InsertStmt) OnConflict(action ConflictAction) *InsertStmt {
stmt.onconflict = &onconflictexpr{action: action}
return stmt
}
// OnConflictTarget adds a ON CONFLICT clause with a conflict target.
func (stmt *InsertStmt) OnConflictTarget(target Expression, action ConflictAction) *InsertStmt {
stmt.onconflict = &onconflictexpr{target: target, action: action}
return stmt
}
// ConflictTarget returns a new ConflictTargetExpr.
func ConflictTarget(columns ...string) ConflictTargetExpr {
exprs := make([]Expression, 0, len(columns))
for i := range columns {
exprs = append(exprs, Ident(columns[i]))
}
return ConflictTargetExpr{exprs: exprs}
}
// A ConflictTargetExpr is a conflict target expression.
type ConflictTargetExpr struct {
exprs []Expression
}
func (e ConflictTargetExpr) build(b *builder) {
for i := range e.exprs {
if i != 0 {
b.write(", ")
}
e.exprs[i].build(b)
}
}
type onconflictexpr struct {
target Expression
action ConflictAction
}
func (e onconflictexpr) build(b *builder) {
b.write("ON CONFLICT ")
if e.target != nil {
b.write("(")
e.target.build(b)
b.write(") ")
}
e.action.build(b)
}
// A ConflictAction is a conflict action.
type ConflictAction struct {
do conflictactiondo
values []Assignment
}
func (a ConflictAction) build(b *builder) {
switch do := a.do; do {
case donothing:
b.write("DO NOTHING")
case doupdateset:
b.write("DO UPDATE SET ")
for i := range a.values {
if i > 0 {
b.write(", ")
}
a.values[i].columnname.build(b)
b.write(" = ")
a.values[i].expr.build(b)
}
default:
panic(fmt.Sprintf("unknown conflict action %d", do))
}
}
// DoNothing is the DO NOTHING conflict_action.
var DoNothing = ConflictAction{do: donothing}
// DoUpdateSet is the DO UPDATE SET conflict_action.
func DoUpdateSet(values ...Assignment) ConflictAction {
return ConflictAction{
do: doupdateset,
values: values,
}
}
type conflictactiondo int
const (
donothing conflictactiondo = iota
doupdateset
)
// Returning adds a RETURNING clause.
func (stmt *InsertStmt) Returning(exprs ...Expression) *InsertStmt {
stmt.returning = exprs
return stmt
}
// Build builds stmt and its parameters.
func (stmt *InsertStmt) Build() (string, []interface{}) {
b := new(builder)
stmt.build(b)
return b.buf.String(), b.params
}
func (stmt *InsertStmt) build(b *builder) {
b.write("INSERT INTO ")
stmt.table.build(b)
b.write(" ")
if stmt.columns != nil {
b.write("(")
for i := range stmt.columns {
if i > 0 {
b.write(", ")
}
stmt.columns[i].build(b)
}
b.write(") ")
}
stmt.values.build(b)
if stmt.onconflict != nil {
b.write(" ")
stmt.onconflict.build(b)
}
if stmt.returning != nil {
b.write(" RETURNING ")
stmt.returning.build(b)
}
}
// A InsertStmt is a INSERT statement.
type InsertStmt struct {
table Expression
columns []Expression
values Expression
onconflict *onconflictexpr
returning selectexprs
}
// Assign returns a new assignment.
func Assign(columnname string, expr Expression) Assignment {
return Assignment{
columnname: Ident(columnname),
expr: expr,
}
}
// An Assignment is an assignment.
type Assignment struct {
columnname Expression
expr Expression
} | build/insert.go | 0.572842 | 0.473475 | insert.go | starcoder |
package duplo
import (
"image"
"image/color"
"math"
"math/rand"
"sort"
"github.com/nfnt/resize"
"github.com/rivo/duplo/haar"
)
// Hash represents the visual hash of an image.
type Hash struct {
haar.Matrix
// Thresholds contains the coefficient threholds. If you discard all
// coefficients with abs(coef) < threshold, you end up with TopCoefs
// coefficients.
Thresholds haar.Coef
// Ratio is image width / image height or 0 if height is 0.
Ratio float64
// DHash is a 128 bit vector where each bit value depends on the monotonicity
// of two adjacent pixels. The first 64 bits are based on a 8x8 version of
// the Y colour channel. The other two 32 bits are each based on a 8x4 version
// of the Cb, and Cr colour channel, respectively.
DHash [2]uint64
// Histogram is histogram quantized into 64 bits (32 for Y and 16 each for
// Cb and Cr). A bit is set to 1 if the intensity's occurence count is large
// than the median (for that colour channel) and set to 0 otherwise.
Histogram uint64
// HistoMax is the maximum value of the histogram (for each channel Y, Cb,
// and Cr).
HistoMax [3]float32
}
// CreateHash calculates and returns the visual hash of the provided image as
// well as a resized version of it (ImageScale x ImageScale) which may be
// ignored if not needed anymore.
func CreateHash(img image.Image) (Hash, image.Image) {
// Determine image ratio.
bounds := img.Bounds()
width := bounds.Max.X - bounds.Min.X
height := bounds.Max.Y - bounds.Min.Y
var ratio float64
if height > 0 {
ratio = float64(width) / float64(height)
}
// Resize the image for the Wavelet transform.
scaled := resize.Resize(ImageScale, ImageScale, img, resize.Bicubic)
// Then perform a 2D Haar Wavelet transform.
matrix := haar.Transform(scaled)
// Find the kth largest coefficients for each colour channel.
thresholds := coefThresholds(matrix.Coefs, TopCoefs)
// Create the dHash bit vector.
d := dHash(img)
// Create histogram bit vector.
h, hm := histogram(img)
return Hash{haar.Matrix{
Coefs: matrix.Coefs,
Width: ImageScale,
Height: ImageScale,
}, thresholds, ratio, d, h, hm}, scaled
}
// coefThreshold returns, for the given coefficients, the kth largest absolute
// value. Only the nth element in each Coef is considered. If you discard all
// values v with abs(v) < threshold, you will end up with k values.
func coefThreshold(coefs []haar.Coef, k int, n int) float64 {
// It's the QuickSelect algorithm.
randomIndex := rand.Intn(len(coefs))
pivot := math.Abs(coefs[randomIndex][n])
leftCoefs := make([]haar.Coef, 0, len(coefs))
rightCoefs := make([]haar.Coef, 0, len(coefs))
for _, coef := range coefs {
if math.Abs(coef[n]) > pivot {
leftCoefs = append(leftCoefs, coef)
} else if math.Abs(coef[n]) < pivot {
rightCoefs = append(rightCoefs, coef)
}
}
if k <= len(leftCoefs) {
return coefThreshold(leftCoefs, k, n)
} else if k > len(coefs)-len(rightCoefs) {
return coefThreshold(rightCoefs, k-(len(coefs)-len(rightCoefs)), n)
} else {
return pivot
}
}
// coefThreshold returns, for the given coefficients, the kth largest absolute
// values per colour channel. If you discard all values v with
// abs(v) < threshold, you will end up with k values.
func coefThresholds(coefs []haar.Coef, k int) haar.Coef {
// No data, no thresholds.
if len(coefs) == 0 {
return haar.Coef{}
}
// Select thresholds.
var thresholds haar.Coef
for index := range thresholds {
thresholds[index] = coefThreshold(coefs, k, index)
}
return thresholds
}
// ycbcr returns the YCbCr values for the given colour, converting to them if
// necessary.
func ycbcr(colour color.Color) (y, cb, cr uint8) {
switch spec := colour.(type) {
case color.YCbCr:
return spec.Y, spec.Cb, spec.Cr
default:
r, g, b, _ := colour.RGBA()
return color.RGBToYCbCr(uint8(r), uint8(g), uint8(b))
}
}
// dHash computes a 128 bit vector by comparing adjacent pixels of a downsized
// version of img. The first 64 bits correspond to a 8x8 version of the Y colour
// channel. A bit is set to 1 if a pixel value is higher than that of its left
// neighbour (the first bit is 1 if its colour value is > 0.5). The other two 32
// bits correspond to the Cb and Cr colour channels, based on a 8x4 version
// each.
func dHash(img image.Image) (bits [2]uint64) {
// Resize the image to 9x8.
scaled := resize.Resize(8, 8, img, resize.Bicubic)
// Scan it.
yPos := uint(0)
cbPos := uint(0)
crPos := uint(32)
for y := 0; y < 8; y++ {
for x := 0; x < 8; x++ {
yTR, cbTR, crTR := ycbcr(scaled.At(x, y))
if x == 0 {
// The first bit is a rough approximation of the colour value.
if yTR&0x80 > 0 {
bits[0] |= 1 << yPos
yPos++
}
if y&1 == 0 {
_, cbBR, crBR := ycbcr(scaled.At(x, y+1))
if (cbBR+cbTR)>>1&0x80 > 0 {
bits[1] |= 1 << cbPos
cbPos++
}
if (crBR+crTR)>>1&0x80 > 0 {
bits[1] |= 1 << crPos
crPos++
}
}
} else {
// Use a rough first derivative for the other bits.
yTL, cbTL, crTL := ycbcr(scaled.At(x-1, y))
if yTR > yTL {
bits[0] |= 1 << yPos
yPos++
}
if y&1 == 0 {
_, cbBR, crBR := ycbcr(scaled.At(x, y+1))
_, cbBL, crBL := ycbcr(scaled.At(x-1, y+1))
if (cbBR+cbTR)>>1 > (cbBL+cbTL)>>1 {
bits[1] |= 1 << cbPos
cbPos++
}
if (crBR+crTR)>>1 > (crBL+crTL)>>1 {
bits[1] |= 1 << crPos
crPos++
}
}
}
}
}
return
}
// histogram calculates a histogram based on the YCbCr values of img and returns
// a rough approximation of it in 64 bits. For each colour channel, a bit is
// set if a histogram value is greater than the median. The Y channel gets 32
// bits, the Cb and Cr values each get 16 bits.
func histogram(img image.Image) (bits uint64, histoMax [3]float32) {
h := new([64]int)
// Create histogram.
bounds := img.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
y, cb, cr := ycbcr(img.At(x, y))
h[y>>3]++
h[32+cb>>4]++
h[48+cr>>4]++
}
}
// Calculate medians and maximums.
median := func(v []int) (int, float32) {
sorted := make([]int, len(v))
copy(sorted, v)
sort.Ints(sorted)
return sorted[len(v)/2], float32(sorted[len(v)-1]) /
float32((bounds.Max.X-bounds.Min.X)*(bounds.Max.Y-bounds.Min.Y))
}
my, yMax := median(h[:32])
mcb, cbMax := median(h[32:48])
mcr, crMax := median(h[48:])
histoMax[0] = yMax
histoMax[1] = cbMax
histoMax[2] = crMax
// Quantize histogram.
for index, value := range h {
if index < 32 {
if value > my {
bits |= 1 << uint(index)
}
} else if index < 48 {
if value > mcb {
bits |= 1 << uint(index-32)
}
} else {
if value > mcr {
bits |= 1 << uint(index-32)
}
}
}
return
} | hash.go | 0.770551 | 0.569853 | hash.go | starcoder |
package video
import (
"runtime"
. "github.com/gooid/gocv/opencv3/internal/native"
)
type DualTVL1OpticalFlow struct {
*DenseOpticalFlow
}
func NewDualTVL1OpticalFlow(addr int64) (rcvr *DualTVL1OpticalFlow) {
rcvr = &DualTVL1OpticalFlow{}
rcvr.DenseOpticalFlow = NewDenseOpticalFlow(addr)
runtime.SetFinalizer(rcvr, func(interface{}) { rcvr.finalize() })
return
}
func DualTVL1OpticalFlowCreate(tau float64, lambda float64, theta float64, nscales int, warps int, epsilon float64, innnerIterations int, outerIterations int, scaleStep float64, gamma float64, medianFiltering int, useInitialFlow bool) *DualTVL1OpticalFlow {
retVal := NewDualTVL1OpticalFlow(DualTVL1OpticalFlowNative_create_0(tau, lambda, theta, nscales, warps, epsilon, innnerIterations, outerIterations, scaleStep, gamma, medianFiltering, useInitialFlow))
return retVal
}
func DualTVL1OpticalFlowCreate2() *DualTVL1OpticalFlow {
retVal := NewDualTVL1OpticalFlow(DualTVL1OpticalFlowNative_create_1())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) finalize() {
DualTVL1OpticalFlowNative_delete(rcvr.GetNativeObjAddr())
}
func (rcvr *DualTVL1OpticalFlow) GetEpsilon() float64 {
retVal := DualTVL1OpticalFlowNative_getEpsilon_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetGamma() float64 {
retVal := DualTVL1OpticalFlowNative_getGamma_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetInnerIterations() int {
retVal := DualTVL1OpticalFlowNative_getInnerIterations_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetLambda() float64 {
retVal := DualTVL1OpticalFlowNative_getLambda_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetMedianFiltering() int {
retVal := DualTVL1OpticalFlowNative_getMedianFiltering_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetOuterIterations() int {
retVal := DualTVL1OpticalFlowNative_getOuterIterations_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetScaleStep() float64 {
retVal := DualTVL1OpticalFlowNative_getScaleStep_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetScalesNumber() int {
retVal := DualTVL1OpticalFlowNative_getScalesNumber_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetTau() float64 {
retVal := DualTVL1OpticalFlowNative_getTau_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetTheta() float64 {
retVal := DualTVL1OpticalFlowNative_getTheta_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetUseInitialFlow() bool {
retVal := DualTVL1OpticalFlowNative_getUseInitialFlow_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) GetWarpingsNumber() int {
retVal := DualTVL1OpticalFlowNative_getWarpingsNumber_0(rcvr.GetNativeObjAddr())
return retVal
}
func (rcvr *DualTVL1OpticalFlow) SetEpsilon(val float64) {
DualTVL1OpticalFlowNative_setEpsilon_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetGamma(val float64) {
DualTVL1OpticalFlowNative_setGamma_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetInnerIterations(val int) {
DualTVL1OpticalFlowNative_setInnerIterations_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetLambda(val float64) {
DualTVL1OpticalFlowNative_setLambda_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetMedianFiltering(val int) {
DualTVL1OpticalFlowNative_setMedianFiltering_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetOuterIterations(val int) {
DualTVL1OpticalFlowNative_setOuterIterations_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetScaleStep(val float64) {
DualTVL1OpticalFlowNative_setScaleStep_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetScalesNumber(val int) {
DualTVL1OpticalFlowNative_setScalesNumber_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetTau(val float64) {
DualTVL1OpticalFlowNative_setTau_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetTheta(val float64) {
DualTVL1OpticalFlowNative_setTheta_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetUseInitialFlow(val bool) {
DualTVL1OpticalFlowNative_setUseInitialFlow_0(rcvr.GetNativeObjAddr(), val)
return
}
func (rcvr *DualTVL1OpticalFlow) SetWarpingsNumber(val int) {
DualTVL1OpticalFlowNative_setWarpingsNumber_0(rcvr.GetNativeObjAddr(), val)
return
} | opencv3/video/DualTVL1OpticalFlow.java.go | 0.660172 | 0.405861 | DualTVL1OpticalFlow.java.go | starcoder |
package require
import (
"reflect"
"testing"
)
func NoError(t *testing.T, err error, msgs ...string) {
if err != nil {
t.Errorf("Expected no error, but got: %s", err)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func NotNil(t *testing.T, object interface{}, msgs ...string) {
if isNil(object) {
t.Errorf("Expected nil, but got an object")
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func Nil(t *testing.T, object interface{}, msgs ...string) {
if !isNil(object) {
t.Errorf("Expected an object, but got nil")
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func isNil(object interface{}) bool {
if object == nil {
return true
}
value := reflect.ValueOf(object)
kind := value.Kind()
if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() {
return true
}
return false
}
func EqualError(t *testing.T, theError error, errString string, msgs ...string) {
if theError == nil {
t.Errorf("Expected an error but got nil")
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
return
}
if theError.Error() != errString {
t.Errorf("Expected an error with message:\n%qbut got \n%q", errString, theError)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func EqualFloat64(t *testing.T, expected, actual float64, msgs ...string) {
if expected != actual {
t.Errorf("Expected %f but got %f", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func EqualStringPtr(t *testing.T, expected, actual *string, msgs ...string) {
if expected == nil && actual == nil {
return
}
if expected != nil && actual != nil {
EqualString(t, *expected, *actual, msgs...)
return
}
t.Errorf("Expected %v but got %v", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
func EqualString(t *testing.T, expected, actual string, msgs ...string) {
if expected != actual {
t.Errorf("Expected %s but got %s", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func EqualUInt32(t *testing.T, expected, actual uint32, msgs ...string) {
if expected != actual {
t.Errorf("Expected %d but got %d", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func EqualUInt64Ptr(t *testing.T, expected, actual *uint64, msgs ...string) {
if expected == nil && actual == nil {
return
}
if expected != nil && actual != nil {
EqualUInt64(t, *expected, *actual, msgs...)
return
}
t.Errorf("Expected %v but got %v", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
func EqualUInt64(t *testing.T, expected, actual uint64, msgs ...string) {
if expected != actual {
t.Errorf("Expected %d but got %d", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func EqualIntPtr(t *testing.T, expected, actual *int, msgs ...string) {
if expected == nil && actual == nil {
return
}
if expected != nil && actual != nil {
EqualInt(t, *expected, *actual, msgs...)
return
}
t.Errorf("Expected %v but got %v", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
func EqualInt(t *testing.T, expected, actual int, msgs ...string) {
if expected != actual {
t.Errorf("Expected %d but got %d", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func EqualErr(t *testing.T, expected, actual error, msgs ...string) {
if expected != actual {
t.Errorf("Expected %s but got %s", expected, actual)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
}
func Implements(t *testing.T, interfaceObject interface{}, object interface{}, msgs ...string) {
interfaceType := reflect.TypeOf(interfaceObject).Elem()
if !reflect.TypeOf(object).Implements(interfaceType) {
t.Errorf("Expected %T but got %v", object, interfaceType)
for _, msg := range msgs {
t.Errorf("\n" + msg)
}
t.FailNow()
}
} | helpers/require/require.go | 0.579876 | 0.503845 | require.go | starcoder |
package tsdb
import (
"strconv"
"time"
"github.com/timberio/go-datemath"
)
func NewTimeRange(from, to string) *TimeRange {
return &TimeRange{
From: from,
To: to,
now: time.Now(),
}
}
func NewFakeTimeRange(from, to string, now time.Time) *TimeRange {
return &TimeRange{
From: from,
To: to,
now: now,
}
}
type TimeRange struct {
From string
To string
now time.Time
}
func (tr *TimeRange) GetFromAsMsEpoch() int64 {
return tr.MustGetFrom().UnixNano() / int64(time.Millisecond)
}
func (tr *TimeRange) GetFromAsSecondsEpoch() int64 {
return tr.GetFromAsMsEpoch() / 1000
}
func (tr *TimeRange) GetFromAsTimeUTC() time.Time {
return tr.MustGetFrom().UTC()
}
func (tr *TimeRange) GetToAsMsEpoch() int64 {
return tr.MustGetTo().UnixNano() / int64(time.Millisecond)
}
func (tr *TimeRange) GetToAsSecondsEpoch() int64 {
return tr.GetToAsMsEpoch() / 1000
}
func (tr *TimeRange) GetToAsTimeUTC() time.Time {
return tr.MustGetTo().UTC()
}
func (tr *TimeRange) MustGetFrom() time.Time {
res, err := tr.ParseFrom()
if err != nil {
return time.Unix(0, 0)
}
return res
}
func (tr *TimeRange) MustGetTo() time.Time {
res, err := tr.ParseTo()
if err != nil {
return time.Unix(0, 0)
}
return res
}
func tryParseUnixMsEpoch(val string) (time.Time, bool) {
if val, err := strconv.ParseInt(val, 10, 64); err == nil {
seconds := val / 1000
nano := (val - seconds*1000) * 1000000
return time.Unix(seconds, nano), true
}
return time.Time{}, false
}
func (tr *TimeRange) ParseFrom() (time.Time, error) {
return parse(tr.From, tr.now, false, nil, -1)
}
func (tr *TimeRange) ParseTo() (time.Time, error) {
return parse(tr.To, tr.now, true, nil, -1)
}
func (tr *TimeRange) ParseFromWithLocation(location *time.Location) (time.Time, error) {
return parse(tr.From, tr.now, false, location, -1)
}
func (tr *TimeRange) ParseToWithLocation(location *time.Location) (time.Time, error) {
return parse(tr.To, tr.now, true, location, -1)
}
func (tr *TimeRange) ParseFromWithWeekStart(location *time.Location, weekstart time.Weekday) (time.Time, error) {
return parse(tr.From, tr.now, false, location, weekstart)
}
func (tr *TimeRange) ParseToWithWeekStart(location *time.Location, weekstart time.Weekday) (time.Time, error) {
return parse(tr.To, tr.now, true, location, weekstart)
}
func parse(s string, now time.Time, withRoundUp bool, location *time.Location, weekstart time.Weekday) (time.Time, error) {
if res, ok := tryParseUnixMsEpoch(s); ok {
return res, nil
}
diff, err := time.ParseDuration("-" + s)
if err != nil {
options := []func(*datemath.Options){
datemath.WithNow(now),
datemath.WithRoundUp(withRoundUp),
}
if location != nil {
options = append(options, datemath.WithLocation(location))
}
if weekstart != -1 {
if weekstart > now.Weekday() {
weekstart = weekstart - 7
}
options = append(options, datemath.WithStartOfWeek(weekstart))
}
return datemath.ParseAndEvaluate(s, options...)
}
return now.Add(diff), nil
} | pkg/tsdb/time_range.go | 0.64969 | 0.40204 | time_range.go | starcoder |
package docs
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"text/template"
"github.com/Jeffail/benthos/v3/lib/util/config"
"github.com/Jeffail/gabs/v2"
"gopkg.in/yaml.v3"
)
// AnnotatedExample is an isolated example for a component.
type AnnotatedExample struct {
// A title for the example.
Title string
// Summary of the example.
Summary string
// A config snippet to show.
Config string
}
// Status of a component.
type Status string
// Component statuses.
var (
StatusStable Status = "stable"
StatusBeta Status = "beta"
StatusExperimental Status = "experimental"
StatusDeprecated Status = "deprecated"
StatusPlugin Status = "plugin"
)
// Type of a component.
type Type string
// Component types.
var (
TypeBuffer Type = "buffer"
TypeCache Type = "cache"
TypeInput Type = "input"
TypeMetrics Type = "metrics"
TypeOutput Type = "output"
TypeProcessor Type = "processor"
TypeRateLimit Type = "rate_limit"
TypeTracer Type = "tracer"
)
// Types returns a slice containing all component types.
func Types() []Type {
return []Type{
TypeBuffer,
TypeCache,
TypeInput,
TypeMetrics,
TypeOutput,
TypeProcessor,
TypeRateLimit,
TypeTracer,
}
}
// ComponentSpec describes a Benthos component.
type ComponentSpec struct {
// Name of the component
Name string
// Type of the component (input, output, etc)
Type Type
// The status of the component.
Status Status
// Summary of the component (in markdown, must be short).
Summary string
// Description of the component (in markdown).
Description string
// Categories that describe the purpose of the component.
Categories []string
// Footnotes of the component (in markdown).
Footnotes string
// Examples demonstrating use cases for the component.
Examples []AnnotatedExample
// A summary of each field in the component configuration.
Config FieldSpec
// Version is the Benthos version this component was introduced.
Version string
}
type fieldContext struct {
Name string
Type string
Description string
Default string
Advanced bool
Deprecated bool
Interpolated bool
Examples []string
AnnotatedOptions [][2]string
Options []string
Version string
}
type componentContext struct {
Name string
Type string
FrontMatterSummary string
Summary string
Description string
Categories string
Examples []AnnotatedExample
Fields []fieldContext
Footnotes string
CommonConfig string
AdvancedConfig string
Status string
Version string
}
var componentTemplate = `{{define "field_docs" -}}
## Fields
{{range $i, $field := .Fields -}}
### ` + "`{{$field.Name}}`" + `
{{$field.Description}}
{{if $field.Interpolated -}}
This field supports [interpolation functions](/docs/configuration/interpolation#bloblang-queries).
{{end}}
Type: ` + "`{{$field.Type}}`" + `
{{if gt (len $field.Default) 0}}Default: ` + "`{{$field.Default}}`" + `
{{end -}}
{{if gt (len $field.Version) 0}}Requires version {{$field.Version}} or newer
{{end -}}
{{if gt (len $field.AnnotatedOptions) 0}}
| Option | Summary |
|---|---|
{{range $j, $option := $field.AnnotatedOptions -}}` + "| `" + `{{index $option 0}}` + "` |" + ` {{index $option 1}} |
{{end}}
{{else if gt (len $field.Options) 0}}Options: {{range $j, $option := $field.Options -}}
{{if ne $j 0}}, {{end}}` + "`" + `{{$option}}` + "`" + `{{end}}.
{{end}}
{{if gt (len $field.Examples) 0 -}}
` + "```yaml" + `
# Examples
{{range $j, $example := $field.Examples -}}
{{if ne $j 0}}
{{end}}{{$example}}{{end -}}
` + "```" + `
{{end -}}
{{end -}}
{{end -}}
---
title: {{.Name}}
type: {{.Type}}
status: {{.Status}}
{{if gt (len .FrontMatterSummary) 0 -}}
description: "{{.FrontMatterSummary}}"
{{end -}}
{{if gt (len .Categories) 0 -}}
categories: {{.Categories}}
{{end -}}
---
<!--
THIS FILE IS AUTOGENERATED!
To make changes please edit the contents of:
lib/{{.Type}}/{{.Name}}.go
-->
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
{{if eq .Status "beta" -}}
BETA: This component is mostly stable but breaking changes could still be made outside of major version releases if a fundamental problem with the component is found.
{{end -}}
{{if eq .Status "experimental" -}}
EXPERIMENTAL: This component is experimental and therefore subject to change or removal outside of major version releases.
{{end -}}
{{if eq .Status "deprecated" -}}
:::warning DEPRECATED
This component is deprecated and will be removed in the next major version release. Please consider moving onto [alternative components](#alternatives).
:::
{{end -}}
{{if gt (len .Summary) 0 -}}
{{.Summary}}
{{end -}}{{if gt (len .Version) 0}}
Introduced in version {{.Version}}.
{{end}}
{{if eq .CommonConfig .AdvancedConfig -}}
` + "```yaml" + `
# Config fields, showing default values
{{.CommonConfig -}}
` + "```" + `
{{else}}
<Tabs defaultValue="common" values={{"{"}}[
{ label: 'Common', value: 'common', },
{ label: 'Advanced', value: 'advanced', },
]{{"}"}}>
<TabItem value="common">
` + "```yaml" + `
# Common config fields, showing default values
{{.CommonConfig -}}
` + "```" + `
</TabItem>
<TabItem value="advanced">
` + "```yaml" + `
# All config fields, showing default values
{{.AdvancedConfig -}}
` + "```" + `
</TabItem>
</Tabs>
{{end -}}
{{if gt (len .Description) 0}}
{{.Description}}
{{end}}
{{if and (le (len .Fields) 4) (gt (len .Fields) 0) -}}
{{template "field_docs" . -}}
{{end -}}
{{if gt (len .Examples) 0 -}}
## Examples
<Tabs defaultValue="{{ (index .Examples 0).Title }}" values={{"{"}}[
{{range $i, $example := .Examples -}}
{ label: '{{$example.Title}}', value: '{{$example.Title}}', },
{{end -}}
]{{"}"}}>
{{range $i, $example := .Examples -}}
<TabItem value="{{$example.Title}}">
{{if gt (len $example.Summary) 0 -}}
{{$example.Summary}}
{{end}}
{{if gt (len $example.Config) 0 -}}
` + "```yaml" + `{{$example.Config}}` + "```" + `
{{end}}
</TabItem>
{{end -}}
</Tabs>
{{end -}}
{{if gt (len .Fields) 4 -}}
{{template "field_docs" . -}}
{{end -}}
{{if gt (len .Footnotes) 0 -}}
{{.Footnotes}}
{{end}}
`
func createOrderedConfig(t Type, rawExample interface{}, filter FieldFilter) (*yaml.Node, error) {
var newNode yaml.Node
if err := newNode.Encode(rawExample); err != nil {
return nil, err
}
if err := SanitiseNode(t, &newNode, SanitiseConfig{
RemoveTypeField: true,
Filter: filter,
}); err != nil {
return nil, err
}
return &newNode, nil
}
func genExampleConfigs(t Type, nest bool, fullConfigExample interface{}) (string, string, error) {
var advConfig, commonConfig interface{}
var err error
if advConfig, err = createOrderedConfig(t, fullConfigExample, func(f FieldSpec) bool {
return !f.Deprecated
}); err != nil {
panic(err)
}
if commonConfig, err = createOrderedConfig(t, fullConfigExample, func(f FieldSpec) bool {
return !f.Advanced && !f.Deprecated
}); err != nil {
panic(err)
}
if nest {
advConfig = map[string]interface{}{string(t): advConfig}
commonConfig = map[string]interface{}{string(t): commonConfig}
}
advancedConfigBytes, err := config.MarshalYAML(advConfig)
if err != nil {
panic(err)
}
commonConfigBytes, err := config.MarshalYAML(commonConfig)
if err != nil {
panic(err)
}
return string(commonConfigBytes), string(advancedConfigBytes), nil
}
// AsMarkdown renders the spec of a component, along with a full configuration
// example, into a markdown document.
func (c *ComponentSpec) AsMarkdown(nest bool, fullConfigExample interface{}) ([]byte, error) {
if strings.Contains(c.Summary, "\n\n") {
return nil, fmt.Errorf("%v component '%v' has a summary containing empty lines", c.Type, c.Name)
}
ctx := componentContext{
Name: c.Name,
Type: string(c.Type),
Summary: c.Summary,
Description: c.Description,
Examples: c.Examples,
Footnotes: c.Footnotes,
Status: string(c.Status),
Version: c.Version,
}
if len(ctx.Status) == 0 {
ctx.Status = string(StatusStable)
}
if len(c.Categories) > 0 {
cats, _ := json.Marshal(c.Categories)
ctx.Categories = string(cats)
}
var err error
if ctx.CommonConfig, ctx.AdvancedConfig, err = genExampleConfigs(c.Type, nest, fullConfigExample); err != nil {
return nil, err
}
if len(c.Description) > 0 && c.Description[0] == '\n' {
ctx.Description = c.Description[1:]
}
if len(c.Footnotes) > 0 && c.Footnotes[0] == '\n' {
ctx.Footnotes = c.Footnotes[1:]
}
flattenedFields := FieldSpecs{}
var walkFields func(path string, f FieldSpecs)
walkFields = func(path string, f FieldSpecs) {
for _, v := range f {
if v.Deprecated {
continue
}
newV := v
if len(path) > 0 {
newV.Name = path + newV.Name
}
flattenedFields = append(flattenedFields, newV)
if len(v.Children) > 0 {
newPath := path + v.Name
if newV.IsArray {
newPath = newPath + "[]"
} else if newV.IsMap {
newPath = newPath + ".<name>"
}
walkFields(newPath+".", v.Children)
}
}
}
rootPath := ""
if c.Config.IsArray {
rootPath = "[]."
} else if c.Config.IsMap {
rootPath = "<name>."
}
walkFields(rootPath, c.Config.Children)
gConf := gabs.Wrap(fullConfigExample).S(c.Name)
for _, v := range flattenedFields {
defaultValue := v.Default
if defaultValue == nil {
defaultValue = gConf.Path(v.Name).Data()
}
if defaultValue == nil {
return nil, fmt.Errorf("field '%v' not found in config example and no default value was provided in the spec", v.Name)
}
defaultValueStr := gabs.Wrap(defaultValue).String()
if len(v.Children) > 0 {
defaultValueStr = ""
}
fieldType := v.Type
isArray := v.IsArray
if len(fieldType) == 0 {
if len(v.Examples) > 0 {
fieldType, isArray = getFieldTypeFromInterface(v.Examples[0])
} else {
fieldType, isArray = getFieldTypeFromInterface(defaultValue)
}
}
fieldTypeStr := string(fieldType)
if isArray {
fieldTypeStr = "array"
}
if v.IsMap {
fieldTypeStr = "object"
}
var examples []string
if len(v.Examples) > 0 {
nameSplit := strings.Split(v.Name, ".")
exampleName := nameSplit[len(nameSplit)-1]
for _, example := range v.Examples {
exampleBytes, err := config.MarshalYAML(map[string]interface{}{
exampleName: example,
})
if err != nil {
return nil, err
}
examples = append(examples, string(exampleBytes))
}
}
fieldCtx := fieldContext{
Name: v.Name,
Type: fieldTypeStr,
Description: v.Description,
Default: defaultValueStr,
Advanced: v.Advanced,
Examples: examples,
AnnotatedOptions: v.AnnotatedOptions,
Options: v.Options,
Interpolated: v.Interpolated,
Version: v.Version,
}
if len(fieldCtx.Description) == 0 {
fieldCtx.Description = "Sorry! This field is missing documentation."
}
if fieldCtx.Description[0] == '\n' {
fieldCtx.Description = fieldCtx.Description[1:]
}
ctx.Fields = append(ctx.Fields, fieldCtx)
}
var buf bytes.Buffer
err = template.Must(template.New("component").Parse(componentTemplate)).Execute(&buf, ctx)
return buf.Bytes(), err
} | internal/docs/component.go | 0.694199 | 0.641984 | component.go | starcoder |
package fax
import (
"errors"
"image"
"io"
)
const (
white = 0xFF
black = 0x00
)
var negativeWidth = errors.New("fax: negative width specified")
// DecodeG4 parses a Group 4 fax image from reader.
// The width will be applied as specified and the
// (estimated) height helps memory allocation.
func DecodeG4(reader io.ByteReader, width, height int) (image.Image, error) {
if width < 0 {
return nil, negativeWidth
}
if width == 0 {
return new(image.Gray), nil
}
if height <= 0 {
height = width
}
// include imaginary first line
height++
pixels := make([]byte, width, width*height)
for i := width - 1; i >= 0; i-- {
pixels[i] = white
}
d := &decoder{
reader: reader,
pixels: pixels,
width: width,
atNewLine: true,
color: white,
}
// initiate d.head
if err := d.pop(0); err != nil {
return nil, err
}
return d.parse()
}
func DecodeG4Pixels(reader io.ByteReader, width, height int) ([]byte, error) {
if width < 0 {
return nil, negativeWidth
}
if width == 0 {
return nil, nil
}
if height <= 0 {
height = width
}
// include imaginary first line
height++
pixels := make([]byte, width, width*height)
for i := width - 1; i >= 0; i-- {
pixels[i] = white
}
d := &decoder{
reader: reader,
pixels: pixels,
width: width,
atNewLine: true,
color: white,
}
// initiate d.head
if err := d.pop(0); err != nil {
return nil, err
}
return d.parsePixels()
}
type decoder struct {
// reader is the data source
reader io.ByteReader
// head contains the current data in the stream.
// The first upcoming bit is packed in the 32nd bit, the
// second upcoming bit in the 31st, etc.
head uint
// bitCount is the number of bits loaded in head.
bitCount uint
// pixels are black and white values.
pixels []byte
// width is the line length in pixels.
width int
// atNewLine is whether a0 is before the beginning of a line.
atNewLine bool
// color represents the state of a0.
color byte
}
// pop advances n bits in the stream.
// The 24-bit end-of-facsimile block exceeds all
// Huffman codes in length.
func (d *decoder) pop(n uint) error {
head := d.head
count := d.bitCount
head <<= n
count -= n
for count < 24 {
next, err := d.reader.ReadByte()
if err != nil {
return err
}
head |= uint(next) << (24 - count)
count += 8
}
d.head = head
d.bitCount = count
return nil
}
// paint adds n d.pixels in the specified color.
func (d *decoder) paint(n int, color byte) {
a := d.pixels
for ; n != 0; n-- {
a = append(a, color)
}
d.pixels = a
}
func (d *decoder) parse() (result image.Image, err error) {
// parse until end-of-facsimile block: 0x001001
for d.head&0xFE000000 != 0 && err == nil {
i := (d.head >> 28) & 0xF
err = modeTable[i](d)
}
width := d.width
pixels := d.pixels[width:] // strip imaginary line
bounds := image.Rect(0, 0, width, len(pixels)/width)
result = &image.Gray{pixels, width, bounds}
return
}
func (d *decoder) parsePixels() (data []byte, err error) {
// parse until end-of-facsimile block: 0x001001
for d.head&0xFE000000 != 0 && err == nil {
i := (d.head >> 28) & 0xF
err = modeTable[i](d)
}
data = d.pixels[d.width:] // strip imaginary line
return
}
var modeTable = [16]func(d *decoder) error{
func(d *decoder) error {
i := (d.head >> 25) & 7
return modeTable2[i](d)
},
pass,
horizontal,
horizontal,
verticalLeft1,
verticalLeft1,
verticalRight1,
verticalRight1,
vertical0, vertical0, vertical0, vertical0,
vertical0, vertical0, vertical0, vertical0,
}
var modeTable2 = [8]func(d *decoder) error{
nil,
extension,
verticalLeft3,
verticalRight3,
verticalLeft2,
verticalLeft2,
verticalRight2,
verticalRight2,
}
func pass(d *decoder) error {
if e := d.pop(4); e != nil {
return e
}
color := d.color
width := d.width
pixels := d.pixels
a := len(pixels)
lineStart := (a / width) * width
b := a - width // reference element
if !d.atNewLine {
for b != lineStart && pixels[b] != color {
b++
}
}
for b != lineStart && pixels[b] == color {
b++
}
// found b1
for b != lineStart && pixels[b] != color {
b++
}
// found b2
if b == lineStart {
d.atNewLine = true
d.color = white
} else {
d.atNewLine = false
}
d.paint(b-a+width, color)
return nil
}
func vertical0(d *decoder) error {
d.vertical(0)
return d.pop(1)
}
func verticalLeft1(d *decoder) error {
d.vertical(-1)
return d.pop(3)
}
func verticalLeft2(d *decoder) error {
d.vertical(-2)
return d.pop(6)
}
func verticalLeft3(d *decoder) error {
d.vertical(-3)
return d.pop(7)
}
func verticalRight1(d *decoder) error {
d.vertical(1)
return d.pop(3)
}
func verticalRight2(d *decoder) error {
d.vertical(2)
return d.pop(6)
}
func verticalRight3(d *decoder) error {
d.vertical(3)
return d.pop(7)
}
func (d *decoder) vertical(offset int) {
color := d.color
width := d.width
pixels := d.pixels
a := len(pixels)
lineStart := (a / width) * width
b := a - width // reference element
if !d.atNewLine {
for b != lineStart && pixels[b] != color {
b++
}
}
for b != lineStart && pixels[b] == color {
b++
}
// found b1
b += offset
if b >= lineStart {
b = lineStart
d.atNewLine = true
d.color = white
} else {
d.atNewLine = false
d.color = color ^ 0xFF
}
if count := b - a + width; count >= 0 {
d.paint(count, color)
}
}
func horizontal(d *decoder) (err error) {
if err = d.pop(3); err != nil {
return
}
color := d.color
flip := color ^ 0xFF
var rl1, rl2 int
if rl1, err = d.runLength(color); err == nil {
rl2, err = d.runLength(flip)
}
// pixels left in the line:
remaining := d.width - (len(d.pixels) % d.width)
if rl1 > remaining {
rl1 = remaining
}
d.paint(rl1, color)
remaining -= rl1
if rl2 >= remaining {
rl2 = remaining
d.atNewLine = true
d.color = white
} else {
d.atNewLine = false
}
d.paint(rl2, flip)
return
}
// runLength reads the amount of pixels for a color.
func (d *decoder) runLength(color byte) (count int, err error) {
match := uint16(0xFFFF) // lookup entry
for match&0xFC0 != 0 && err == nil {
if color == black {
if d.head&0xF0000000 != 0 {
match = blackShortLookup[(d.head>>26)&0x3F]
} else if d.head&0xFE000000 != 0 {
match = blackLookup[(d.head>>19)&0x1FF]
} else {
match = sharedLookup[(d.head>>20)&0x1F]
}
} else {
if d.head&0xFE000000 != 0 {
match = whiteLookup[(d.head>>23)&0x1FF]
} else {
match = sharedLookup[(d.head>>20)&0x1F]
}
}
err = d.pop(uint(match) >> 12)
count += int(match) & 0x0FFF
}
return
}
// Lookup tables are used by runLength to find Huffman codes. Their index
// size is large enough to fit the longest code in the group. Shorter codes
// have duplicate entries with all possible tailing bits.
// Entries consist of two parts. The 4 most significant bits contain the
// Huffman code length in bits and the 12 least significant bits contain
// the pixel count.
var blackShortLookup = [64]uint16{
0x0, 0x0, 0x0, 0x0, 0x6009, 0x6008, 0x5007, 0x5007,
0x4006, 0x4006, 0x4006, 0x4006, 0x4005, 0x4005, 0x4005, 0x4005,
0x3001, 0x3001, 0x3001, 0x3001, 0x3001, 0x3001, 0x3001, 0x3001,
0x3004, 0x3004, 0x3004, 0x3004, 0x3004, 0x3004, 0x3004, 0x3004,
0x2003, 0x2003, 0x2003, 0x2003, 0x2003, 0x2003, 0x2003, 0x2003,
0x2003, 0x2003, 0x2003, 0x2003, 0x2003, 0x2003, 0x2003, 0x2003,
0x2002, 0x2002, 0x2002, 0x2002, 0x2002, 0x2002, 0x2002, 0x2002,
0x2002, 0x2002, 0x2002, 0x2002, 0x2002, 0x2002, 0x2002, 0x2002,
}
var blackLookup = [512]uint16{
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xa012, 0xa012, 0xa012, 0xa012, 0xa012, 0xa012, 0xa012, 0xa012,
0xc034, 0xc034, 0xd280, 0xd2c0, 0xd300, 0xd340, 0xc037, 0xc037,
0xc038, 0xc038, 0xd500, 0xd540, 0xd580, 0xd5c0, 0xc03b, 0xc03b,
0xc03c, 0xc03c, 0xd600, 0xd640, 0xb018, 0xb018, 0xb018, 0xb018,
0xb019, 0xb019, 0xb019, 0xb019, 0xd680, 0xd6c0, 0xc140, 0xc140,
0xc180, 0xc180, 0xc1c0, 0xc1c0, 0xd200, 0xd240, 0xc035, 0xc035,
0xc036, 0xc036, 0xd380, 0xd3c0, 0xd400, 0xd440, 0xd480, 0xd4c0,
0xa040, 0xa040, 0xa040, 0xa040, 0xa040, 0xa040, 0xa040, 0xa040,
0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d,
0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d,
0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d,
0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d, 0x800d,
0xb017, 0xb017, 0xb017, 0xb017, 0xc032, 0xc032, 0xc033, 0xc033,
0xc02c, 0xc02c, 0xc02d, 0xc02d, 0xc02e, 0xc02e, 0xc02f, 0xc02f,
0xc039, 0xc039, 0xc03a, 0xc03a, 0xc03d, 0xc03d, 0xc100, 0xc100,
0xa010, 0xa010, 0xa010, 0xa010, 0xa010, 0xa010, 0xa010, 0xa010,
0xa011, 0xa011, 0xa011, 0xa011, 0xa011, 0xa011, 0xa011, 0xa011,
0xc030, 0xc030, 0xc031, 0xc031, 0xc03e, 0xc03e, 0xc03f, 0xc03f,
0xc01e, 0xc01e, 0xc01f, 0xc01f, 0xc020, 0xc020, 0xc021, 0xc021,
0xc028, 0xc028, 0xc029, 0xc029, 0xb016, 0xb016, 0xb016, 0xb016,
0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e,
0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e,
0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e,
0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e, 0x800e,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a, 0x700a,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b, 0x700b,
0x900f, 0x900f, 0x900f, 0x900f, 0x900f, 0x900f, 0x900f, 0x900f,
0x900f, 0x900f, 0x900f, 0x900f, 0x900f, 0x900f, 0x900f, 0x900f,
0xc080, 0xc080, 0xc0c0, 0xc0c0, 0xc01a, 0xc01a, 0xc01b, 0xc01b,
0xc01c, 0xc01c, 0xc01d, 0xc01d, 0xb013, 0xb013, 0xb013, 0xb013,
0xb014, 0xb014, 0xb014, 0xb014, 0xc022, 0xc022, 0xc023, 0xc023,
0xc024, 0xc024, 0xc025, 0xc025, 0xc026, 0xc026, 0xc027, 0xc027,
0xb015, 0xb015, 0xb015, 0xb015, 0xc02a, 0xc02a, 0xc02b, 0xc02b,
0xa000, 0xa000, 0xa000, 0xa000, 0xa000, 0xa000, 0xa000, 0xa000,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c, 0x700c,
}
var whiteLookup = [512]uint16{
0x0, 0x0, 0x0, 0x0, 0x801d, 0x801d, 0x801e, 0x801e,
0x802d, 0x802d, 0x802e, 0x802e, 0x7016, 0x7016, 0x7016, 0x7016,
0x7017, 0x7017, 0x7017, 0x7017, 0x802f, 0x802f, 0x8030, 0x8030,
0x600d, 0x600d, 0x600d, 0x600d, 0x600d, 0x600d, 0x600d, 0x600d,
0x7014, 0x7014, 0x7014, 0x7014, 0x8021, 0x8021, 0x8022, 0x8022,
0x8023, 0x8023, 0x8024, 0x8024, 0x8025, 0x8025, 0x8026, 0x8026,
0x7013, 0x7013, 0x7013, 0x7013, 0x801f, 0x801f, 0x8020, 0x8020,
0x6001, 0x6001, 0x6001, 0x6001, 0x6001, 0x6001, 0x6001, 0x6001,
0x600c, 0x600c, 0x600c, 0x600c, 0x600c, 0x600c, 0x600c, 0x600c,
0x8035, 0x8035, 0x8036, 0x8036, 0x701a, 0x701a, 0x701a, 0x701a,
0x8027, 0x8027, 0x8028, 0x8028, 0x8029, 0x8029, 0x802a, 0x802a,
0x802b, 0x802b, 0x802c, 0x802c, 0x7015, 0x7015, 0x7015, 0x7015,
0x701c, 0x701c, 0x701c, 0x701c, 0x803d, 0x803d, 0x803e, 0x803e,
0x803f, 0x803f, 0x8000, 0x8000, 0x8140, 0x8140, 0x8180, 0x8180,
0x500a, 0x500a, 0x500a, 0x500a, 0x500a, 0x500a, 0x500a, 0x500a,
0x500a, 0x500a, 0x500a, 0x500a, 0x500a, 0x500a, 0x500a, 0x500a,
0x500b, 0x500b, 0x500b, 0x500b, 0x500b, 0x500b, 0x500b, 0x500b,
0x500b, 0x500b, 0x500b, 0x500b, 0x500b, 0x500b, 0x500b, 0x500b,
0x701b, 0x701b, 0x701b, 0x701b, 0x803b, 0x803b, 0x803c, 0x803c,
0x95c0, 0x9600, 0x9640, 0x96c0, 0x7012, 0x7012, 0x7012, 0x7012,
0x7018, 0x7018, 0x7018, 0x7018, 0x8031, 0x8031, 0x8032, 0x8032,
0x8033, 0x8033, 0x8034, 0x8034, 0x7019, 0x7019, 0x7019, 0x7019,
0x8037, 0x8037, 0x8038, 0x8038, 0x8039, 0x8039, 0x803a, 0x803a,
0x60c0, 0x60c0, 0x60c0, 0x60c0, 0x60c0, 0x60c0, 0x60c0, 0x60c0,
0x6680, 0x6680, 0x6680, 0x6680, 0x6680, 0x6680, 0x6680, 0x6680,
0x81c0, 0x81c0, 0x8200, 0x8200, 0x92c0, 0x9300, 0x8280, 0x8280,
0x8240, 0x8240, 0x9340, 0x9380, 0x93c0, 0x9400, 0x9440, 0x9480,
0x94c0, 0x9500, 0x9540, 0x9580, 0x7100, 0x7100, 0x7100, 0x7100,
0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002,
0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002,
0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002,
0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002, 0x4002,
0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003,
0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003,
0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003,
0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003, 0x4003,
0x5080, 0x5080, 0x5080, 0x5080, 0x5080, 0x5080, 0x5080, 0x5080,
0x5080, 0x5080, 0x5080, 0x5080, 0x5080, 0x5080, 0x5080, 0x5080,
0x5008, 0x5008, 0x5008, 0x5008, 0x5008, 0x5008, 0x5008, 0x5008,
0x5008, 0x5008, 0x5008, 0x5008, 0x5008, 0x5008, 0x5008, 0x5008,
0x5009, 0x5009, 0x5009, 0x5009, 0x5009, 0x5009, 0x5009, 0x5009,
0x5009, 0x5009, 0x5009, 0x5009, 0x5009, 0x5009, 0x5009, 0x5009,
0x6010, 0x6010, 0x6010, 0x6010, 0x6010, 0x6010, 0x6010, 0x6010,
0x6011, 0x6011, 0x6011, 0x6011, 0x6011, 0x6011, 0x6011, 0x6011,
0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004,
0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004,
0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004,
0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004, 0x4004,
0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005,
0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005,
0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005,
0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005, 0x4005,
0x600e, 0x600e, 0x600e, 0x600e, 0x600e, 0x600e, 0x600e, 0x600e,
0x600f, 0x600f, 0x600f, 0x600f, 0x600f, 0x600f, 0x600f, 0x600f,
0x5040, 0x5040, 0x5040, 0x5040, 0x5040, 0x5040, 0x5040, 0x5040,
0x5040, 0x5040, 0x5040, 0x5040, 0x5040, 0x5040, 0x5040, 0x5040,
0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006,
0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006,
0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006,
0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006, 0x4006,
0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007,
0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007,
0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007,
0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007, 0x4007,
}
var sharedLookup = [32]uint16{
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0xb700, 0xb700, 0xc7c0, 0xc800, 0xc840, 0xc880, 0xc8c0, 0xc900,
0xb740, 0xb740, 0xb780, 0xb780, 0xc940, 0xc980, 0xc9c0, 0xca00,
} | internal/fax/read.go | 0.692018 | 0.483831 | read.go | starcoder |
package data_type
//ICollection ISequence IAssociative IIndexed IStack
type TypVector struct {
buffers []interface{}
count int
}
func (t *TypVector) Count() int {
return t.count
}
func (t *TypVector) Conj(val ...interface{}) {
if t.buffers == nil || t.count == cap(t.buffers) {
t.allocateMore()
}
t.buffers[t.count] = val[0]
t.count++
}
func (t *TypVector) allocateMore() {
if t.buffers == nil {
t.buffers = make([]interface{}, 2)
} else {
bflen := len(t.buffers)
if bflen >= 2 {
newbuffer := make([]interface{}, bflen<<1)
copy(newbuffer, t.buffers)
t.buffers = newbuffer
}
}
}
func (t *TypVector) Empty() ICollection {
return &TypVector{}
}
func (t *TypVector) Get(idx interface{}) interface{} {
return t.buffers[idx.(int)]
}
func (t *TypVector) Assoc(k interface{}, v interface{}) {
if k.(int) == t.Count() {
t.Conj(v)
} else {
t.buffers[k.(int)] = v
}
}
func (t *TypVector) Dissoc(k interface{}) {
t.RemoveAt(k.(int))
}
func (t *TypVector) ContainsKey(k interface{}) bool {
if k.(int) >= 0 && k.(int) < t.count {
return true
}
return false
}
func (t *TypVector) Nth(k int) interface{} {
return t.buffers[k]
}
func (t *TypVector) RemoveAt(index int) {
if t.buffers != nil && index < len(t.buffers) {
for i := index; i < t.count; i++ {
t.buffers[i] = t.buffers[i+1]
t.buffers[t.count] = nil
}
t.count = t.count - 1
}
}
func (t *TypVector) Peek() interface{} {
return t.buffers[t.count]
}
func (t *TypVector) Pop() interface{} {
retVal := t.buffers[t.count]
t.RemoveAt(t.count)
return retVal
}
func Vector(args ...interface{}) *TypVector {
RetVec := &TypVector{}
for _, v := range args {
RetVec.Conj(v)
}
return RetVec
}
//=============================================================
func (t *TypVector) GetIterator() IIterator {
return &VectorIterator{0, t, true}
}
type VectorIterator struct {
curIndex int
iterVec *TypVector
isFirst bool
}
func (v *VectorIterator) MoveNext() bool {
if v.isFirst == true {
v.isFirst = false
if v.iterVec.Count() == 0 {
return false
}
return true
}
v.curIndex++
if v.curIndex >= v.iterVec.Count() {
return false
}
return true
}
func (v *VectorIterator) Current() interface{} {
return v.iterVec.buffers[v.curIndex]
} | src/lib/lisp_core/data_type/Vector.go | 0.504639 | 0.425605 | Vector.go | starcoder |
package models
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// OrganizationalBrandingProperties provides operations to manage the organizationalBranding singleton.
type OrganizationalBrandingProperties struct {
Entity
// Color that appears in place of the background image in low-bandwidth connections. We recommend that you use the primary color of your banner logo or your organization color. Specify this in hexadecimal format, for example, white is #FFFFFF.
backgroundColor *string
// Image that appears as the background of the sign-in page. The allowed types are PNG or JPEG not smaller than 300 KB and not larger than 1920 × 1080 pixels. A smaller image will reduce bandwidth requirements and make the page load faster.
backgroundImage []byte
// A relative URL for the backgroundImage property that is combined with a CDN base URL from the cdnList to provide the version served by a CDN. Read-only.
backgroundImageRelativeUrl *string
// A banner version of your company logo that appears on the sign-in page. The allowed types are PNG or JPEG not larger than 36 × 245 pixels. We recommend using a transparent image with no padding around the logo.
bannerLogo []byte
// A relative URL for the bannerLogo property that is combined with a CDN base URL from the cdnList to provide the read-only version served by a CDN. Read-only.
bannerLogoRelativeUrl *string
// A list of base URLs for all available CDN providers that are serving the assets of the current resource. Several CDN providers are used at the same time for high availability of read requests. Read-only.
cdnList []string
// Text that appears at the bottom of the sign-in box. Use this to communicate additional information, such as the phone number to your help desk or a legal statement. This text must be in Unicode format and not exceed 1024 characters.
signInPageText *string
// A square version of your company logo that appears in Windows 10 out-of-box experiences (OOBE) and when Windows Autopilot is enabled for deployment. Allowed types are PNG or JPEG not larger than 240 x 240 pixels and not more than 10 KB in size. We recommend using a transparent image with no padding around the logo.
squareLogo []byte
// A relative URL for the squareLogo property that is combined with a CDN base URL from the cdnList to provide the version served by a CDN. Read-only.
squareLogoRelativeUrl *string
// A string that shows as the hint in the username textbox on the sign-in screen. This text must be a Unicode, without links or code, and can't exceed 64 characters.
usernameHintText *string
}
// NewOrganizationalBrandingProperties instantiates a new organizationalBrandingProperties and sets the default values.
func NewOrganizationalBrandingProperties()(*OrganizationalBrandingProperties) {
m := &OrganizationalBrandingProperties{
Entity: *NewEntity(),
}
return m
}
// CreateOrganizationalBrandingPropertiesFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateOrganizationalBrandingPropertiesFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewOrganizationalBrandingProperties(), nil
}
// GetBackgroundColor gets the backgroundColor property value. Color that appears in place of the background image in low-bandwidth connections. We recommend that you use the primary color of your banner logo or your organization color. Specify this in hexadecimal format, for example, white is #FFFFFF.
func (m *OrganizationalBrandingProperties) GetBackgroundColor()(*string) {
if m == nil {
return nil
} else {
return m.backgroundColor
}
}
// GetBackgroundImage gets the backgroundImage property value. Image that appears as the background of the sign-in page. The allowed types are PNG or JPEG not smaller than 300 KB and not larger than 1920 × 1080 pixels. A smaller image will reduce bandwidth requirements and make the page load faster.
func (m *OrganizationalBrandingProperties) GetBackgroundImage()([]byte) {
if m == nil {
return nil
} else {
return m.backgroundImage
}
}
// GetBackgroundImageRelativeUrl gets the backgroundImageRelativeUrl property value. A relative URL for the backgroundImage property that is combined with a CDN base URL from the cdnList to provide the version served by a CDN. Read-only.
func (m *OrganizationalBrandingProperties) GetBackgroundImageRelativeUrl()(*string) {
if m == nil {
return nil
} else {
return m.backgroundImageRelativeUrl
}
}
// GetBannerLogo gets the bannerLogo property value. A banner version of your company logo that appears on the sign-in page. The allowed types are PNG or JPEG not larger than 36 × 245 pixels. We recommend using a transparent image with no padding around the logo.
func (m *OrganizationalBrandingProperties) GetBannerLogo()([]byte) {
if m == nil {
return nil
} else {
return m.bannerLogo
}
}
// GetBannerLogoRelativeUrl gets the bannerLogoRelativeUrl property value. A relative URL for the bannerLogo property that is combined with a CDN base URL from the cdnList to provide the read-only version served by a CDN. Read-only.
func (m *OrganizationalBrandingProperties) GetBannerLogoRelativeUrl()(*string) {
if m == nil {
return nil
} else {
return m.bannerLogoRelativeUrl
}
}
// GetCdnList gets the cdnList property value. A list of base URLs for all available CDN providers that are serving the assets of the current resource. Several CDN providers are used at the same time for high availability of read requests. Read-only.
func (m *OrganizationalBrandingProperties) GetCdnList()([]string) {
if m == nil {
return nil
} else {
return m.cdnList
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *OrganizationalBrandingProperties) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["backgroundColor"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetBackgroundColor(val)
}
return nil
}
res["backgroundImage"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetByteArrayValue()
if err != nil {
return err
}
if val != nil {
m.SetBackgroundImage(val)
}
return nil
}
res["backgroundImageRelativeUrl"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetBackgroundImageRelativeUrl(val)
}
return nil
}
res["bannerLogo"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetByteArrayValue()
if err != nil {
return err
}
if val != nil {
m.SetBannerLogo(val)
}
return nil
}
res["bannerLogoRelativeUrl"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetBannerLogoRelativeUrl(val)
}
return nil
}
res["cdnList"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfPrimitiveValues("string")
if err != nil {
return err
}
if val != nil {
res := make([]string, len(val))
for i, v := range val {
res[i] = *(v.(*string))
}
m.SetCdnList(res)
}
return nil
}
res["signInPageText"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetSignInPageText(val)
}
return nil
}
res["squareLogo"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetByteArrayValue()
if err != nil {
return err
}
if val != nil {
m.SetSquareLogo(val)
}
return nil
}
res["squareLogoRelativeUrl"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetSquareLogoRelativeUrl(val)
}
return nil
}
res["usernameHintText"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUsernameHintText(val)
}
return nil
}
return res
}
// GetSignInPageText gets the signInPageText property value. Text that appears at the bottom of the sign-in box. Use this to communicate additional information, such as the phone number to your help desk or a legal statement. This text must be in Unicode format and not exceed 1024 characters.
func (m *OrganizationalBrandingProperties) GetSignInPageText()(*string) {
if m == nil {
return nil
} else {
return m.signInPageText
}
}
// GetSquareLogo gets the squareLogo property value. A square version of your company logo that appears in Windows 10 out-of-box experiences (OOBE) and when Windows Autopilot is enabled for deployment. Allowed types are PNG or JPEG not larger than 240 x 240 pixels and not more than 10 KB in size. We recommend using a transparent image with no padding around the logo.
func (m *OrganizationalBrandingProperties) GetSquareLogo()([]byte) {
if m == nil {
return nil
} else {
return m.squareLogo
}
}
// GetSquareLogoRelativeUrl gets the squareLogoRelativeUrl property value. A relative URL for the squareLogo property that is combined with a CDN base URL from the cdnList to provide the version served by a CDN. Read-only.
func (m *OrganizationalBrandingProperties) GetSquareLogoRelativeUrl()(*string) {
if m == nil {
return nil
} else {
return m.squareLogoRelativeUrl
}
}
// GetUsernameHintText gets the usernameHintText property value. A string that shows as the hint in the username textbox on the sign-in screen. This text must be a Unicode, without links or code, and can't exceed 64 characters.
func (m *OrganizationalBrandingProperties) GetUsernameHintText()(*string) {
if m == nil {
return nil
} else {
return m.usernameHintText
}
}
// Serialize serializes information the current object
func (m *OrganizationalBrandingProperties) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteStringValue("backgroundColor", m.GetBackgroundColor())
if err != nil {
return err
}
}
{
err = writer.WriteByteArrayValue("backgroundImage", m.GetBackgroundImage())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("backgroundImageRelativeUrl", m.GetBackgroundImageRelativeUrl())
if err != nil {
return err
}
}
{
err = writer.WriteByteArrayValue("bannerLogo", m.GetBannerLogo())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("bannerLogoRelativeUrl", m.GetBannerLogoRelativeUrl())
if err != nil {
return err
}
}
if m.GetCdnList() != nil {
err = writer.WriteCollectionOfStringValues("cdnList", m.GetCdnList())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("signInPageText", m.GetSignInPageText())
if err != nil {
return err
}
}
{
err = writer.WriteByteArrayValue("squareLogo", m.GetSquareLogo())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("squareLogoRelativeUrl", m.GetSquareLogoRelativeUrl())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("usernameHintText", m.GetUsernameHintText())
if err != nil {
return err
}
}
return nil
}
// SetBackgroundColor sets the backgroundColor property value. Color that appears in place of the background image in low-bandwidth connections. We recommend that you use the primary color of your banner logo or your organization color. Specify this in hexadecimal format, for example, white is #FFFFFF.
func (m *OrganizationalBrandingProperties) SetBackgroundColor(value *string)() {
if m != nil {
m.backgroundColor = value
}
}
// SetBackgroundImage sets the backgroundImage property value. Image that appears as the background of the sign-in page. The allowed types are PNG or JPEG not smaller than 300 KB and not larger than 1920 × 1080 pixels. A smaller image will reduce bandwidth requirements and make the page load faster.
func (m *OrganizationalBrandingProperties) SetBackgroundImage(value []byte)() {
if m != nil {
m.backgroundImage = value
}
}
// SetBackgroundImageRelativeUrl sets the backgroundImageRelativeUrl property value. A relative URL for the backgroundImage property that is combined with a CDN base URL from the cdnList to provide the version served by a CDN. Read-only.
func (m *OrganizationalBrandingProperties) SetBackgroundImageRelativeUrl(value *string)() {
if m != nil {
m.backgroundImageRelativeUrl = value
}
}
// SetBannerLogo sets the bannerLogo property value. A banner version of your company logo that appears on the sign-in page. The allowed types are PNG or JPEG not larger than 36 × 245 pixels. We recommend using a transparent image with no padding around the logo.
func (m *OrganizationalBrandingProperties) SetBannerLogo(value []byte)() {
if m != nil {
m.bannerLogo = value
}
}
// SetBannerLogoRelativeUrl sets the bannerLogoRelativeUrl property value. A relative URL for the bannerLogo property that is combined with a CDN base URL from the cdnList to provide the read-only version served by a CDN. Read-only.
func (m *OrganizationalBrandingProperties) SetBannerLogoRelativeUrl(value *string)() {
if m != nil {
m.bannerLogoRelativeUrl = value
}
}
// SetCdnList sets the cdnList property value. A list of base URLs for all available CDN providers that are serving the assets of the current resource. Several CDN providers are used at the same time for high availability of read requests. Read-only.
func (m *OrganizationalBrandingProperties) SetCdnList(value []string)() {
if m != nil {
m.cdnList = value
}
}
// SetSignInPageText sets the signInPageText property value. Text that appears at the bottom of the sign-in box. Use this to communicate additional information, such as the phone number to your help desk or a legal statement. This text must be in Unicode format and not exceed 1024 characters.
func (m *OrganizationalBrandingProperties) SetSignInPageText(value *string)() {
if m != nil {
m.signInPageText = value
}
}
// SetSquareLogo sets the squareLogo property value. A square version of your company logo that appears in Windows 10 out-of-box experiences (OOBE) and when Windows Autopilot is enabled for deployment. Allowed types are PNG or JPEG not larger than 240 x 240 pixels and not more than 10 KB in size. We recommend using a transparent image with no padding around the logo.
func (m *OrganizationalBrandingProperties) SetSquareLogo(value []byte)() {
if m != nil {
m.squareLogo = value
}
}
// SetSquareLogoRelativeUrl sets the squareLogoRelativeUrl property value. A relative URL for the squareLogo property that is combined with a CDN base URL from the cdnList to provide the version served by a CDN. Read-only.
func (m *OrganizationalBrandingProperties) SetSquareLogoRelativeUrl(value *string)() {
if m != nil {
m.squareLogoRelativeUrl = value
}
}
// SetUsernameHintText sets the usernameHintText property value. A string that shows as the hint in the username textbox on the sign-in screen. This text must be a Unicode, without links or code, and can't exceed 64 characters.
func (m *OrganizationalBrandingProperties) SetUsernameHintText(value *string)() {
if m != nil {
m.usernameHintText = value
}
} | models/organizational_branding_properties.go | 0.732113 | 0.509764 | organizational_branding_properties.go | starcoder |
package internal
import (
"errors"
"fmt"
"math"
"reflect"
"github.com/lyraproj/dgo/dgo"
)
type (
// structType describes each mapEntry of a map
structType struct {
additional bool
keys array
values array
required []bool
}
structEntry struct {
mapEntry
required bool
}
)
// StructMapTypeUnresolved returns an unresolved new StructMapType type built from the given StructMapEntries. The
// fact that it is unresolved vouches for that it may have keys that are not yet exact types but might become exact
// once they are resolved.
func StructMapTypeUnresolved(additional bool, entries []dgo.StructMapEntry) dgo.StructMapType {
l := len(entries)
exact := !additional
keys := make([]dgo.Value, l)
values := make([]dgo.Value, l)
required := make([]bool, l)
for i := 0; i < l; i++ {
e := entries[i]
kt := e.Key().(dgo.Type)
vt := e.Value().(dgo.Type)
if exact && !(e.Required() && dgo.IsExact(kt) && dgo.IsExact(vt)) {
exact = false
}
keys[i] = kt
values[i] = vt
required[i] = e.Required()
}
if exact {
return createExactMap(keys, values)
}
return &structType{
additional: additional,
keys: array{slice: keys, frozen: true},
values: array{slice: values, frozen: true},
required: required}
}
func createExactMap(keys, values []dgo.Value) dgo.StructMapType {
l := len(keys)
m := MapWithCapacity(l)
for i := 0; i < l; i++ {
m.Put(keys[i].(dgo.ExactType).ExactValue(), values[i].(dgo.ExactType).ExactValue())
}
return m.Type().(dgo.StructMapType)
}
// StructMapType returns a new StructMapType type built from the given StructMapEntries.
func StructMapType(additional bool, entries []dgo.StructMapEntry) dgo.StructMapType {
t := StructMapTypeUnresolved(additional, entries)
if st, ok := t.(*structType); ok {
st.checkExactKeys()
}
return t
}
var sfmType dgo.MapType
// StructFromMapType returns the map type used when validating the map sent to
// StructMapTypeFromMap
func StructFromMapType() dgo.MapType {
if sfmType == nil {
sfmType = Parse(`map[string](dgo|type|{type:dgo|type,required?:bool,...})`).(dgo.MapType)
}
return sfmType
}
// StructMapTypeFromMap returns a new type built from a map[string](dgo|type|{type:dgo|type,required?:bool,...})
func StructMapTypeFromMap(additional bool, entries dgo.Map) dgo.StructMapType {
if !StructFromMapType().Instance(entries) {
panic(IllegalAssignment(sfmType, entries))
}
l := entries.Len()
keys := make([]dgo.Value, l)
values := make([]dgo.Value, l)
required := make([]bool, l)
i := 0
// turn dgo|type into type
asType := func(v dgo.Value) dgo.Type {
tp, ok := v.(dgo.Type)
if !ok {
var s dgo.String
if s, ok = v.(dgo.String); ok {
v = Parse(s.GoString())
tp, ok = v.(dgo.Type)
}
if !ok {
tp = v.Type()
}
}
return tp
}
exact := !additional
entries.EachEntry(func(e dgo.MapEntry) {
rq := true
kt := e.Key().Type()
var vt dgo.Type
if vm, ok := e.Value().(dgo.Map); ok {
vt = asType(vm.Get(`type`))
if rqv := vm.Get(`required`); rqv != nil {
rq = rqv.(dgo.Boolean).GoBool()
}
} else {
vt = asType(e.Value())
}
if exact && !(rq && dgo.IsExact(kt) && dgo.IsExact(vt)) {
exact = false
}
keys[i] = kt
values[i] = vt
required[i] = rq
i++
})
if exact {
return createExactMap(keys, values)
}
t := &structType{
additional: additional,
keys: array{slice: keys, frozen: true},
values: array{slice: values, frozen: true},
required: required}
t.checkExactKeys()
return t
}
func (t *structType) checkExactKeys() {
ks := t.keys.slice
for i := range ks {
if !dgo.IsExact(ks[i].(dgo.Type)) {
panic(`non exact key types is not yet supported`)
}
}
}
func (t *structType) Additional() bool {
return t.additional
}
func (t *structType) Assignable(other dgo.Type) bool {
return Assignable(nil, t, other)
}
func (t *structType) DeepAssignable(guard dgo.RecursionGuard, other dgo.Type) bool {
switch ot := other.(type) {
case *structType:
mrs := t.required
mks := t.keys.slice
mvs := t.values.slice
ors := ot.required
oks := ot.keys.slice
ovs := ot.values.slice
oc := 0
nextKey:
for mi := range mks {
rq := mrs[mi]
mk := mks[mi]
for oi := range oks {
ok := oks[oi]
if mk.Equals(ok) {
if rq && !ors[oi] {
return false
}
if !Assignable(guard, mvs[mi].(dgo.Type), ovs[oi].(dgo.Type)) {
return false
}
oc++
continue nextKey
}
}
if rq || ot.additional { // additional included since key is allowed with unconstrained value
return false
}
}
return t.additional || oc == len(oks)
case *exactMapType:
ov := ot.value
return Instance(guard, t, ov)
}
return CheckAssignableTo(guard, other, t)
}
func (t *structType) Each(actor func(dgo.StructMapEntry)) {
ks := t.keys.slice
vs := t.values.slice
rs := t.required
for i := range ks {
actor(&structEntry{mapEntry: mapEntry{key: ks[i], value: vs[i]}, required: rs[i]})
}
}
func (t *structType) Equals(other interface{}) bool {
return equals(nil, t, other)
}
func (t *structType) deepEqual(seen []dgo.Value, other deepEqual) bool {
if ot, ok := other.(*structType); ok {
return t.additional == ot.additional &&
boolsEqual(t.required, ot.required) &&
equals(seen, &t.keys, &ot.keys) &&
equals(seen, &t.values, &ot.values)
}
return false
}
func (t *structType) Generic() dgo.Type {
return newMapType(Generic(t.KeyType()), Generic(t.ValueType()), 0, math.MaxInt64)
}
func (t *structType) HashCode() int {
return deepHashCode(nil, t)
}
func (t *structType) deepHashCode(seen []dgo.Value) int {
h := boolsHash(t.required)*31 + deepHashCode(seen, &t.keys)*31 + deepHashCode(seen, &t.values)
if t.additional {
h *= 3
}
return h
}
func (t *structType) Instance(value interface{}) bool {
return Instance(nil, t, value)
}
func (t *structType) DeepInstance(guard dgo.RecursionGuard, value interface{}) bool {
if om, ok := value.(dgo.Map); ok {
ks := t.keys.slice
vs := t.values.slice
rs := t.required
oc := 0
for i := range ks {
k := ks[i].(dgo.ExactType)
if ov := om.Get(k.ExactValue()); ov != nil {
oc++
if !Instance(guard, vs[i].(dgo.Type), ov) {
return false
}
} else if rs[i] {
return false
}
}
return t.additional || oc == om.Len()
}
return false
}
func (t *structType) Get(key interface{}) dgo.StructMapEntry {
kv := Value(key)
if _, ok := kv.(dgo.Type); !ok {
kv = kv.Type()
}
i := t.keys.IndexOf(kv)
if i >= 0 {
return StructMapEntry(kv, t.values.slice[i], t.required[i])
}
return nil
}
func (t *structType) KeyType() dgo.Type {
switch t.keys.Len() {
case 0:
return DefaultAnyType
case 1:
return t.keys.Get(0).(dgo.Type)
default:
return (*allOfType)(&t.keys)
}
}
func (t *structType) Len() int {
return len(t.required)
}
func (t *structType) Max() int {
m := len(t.required)
if m == 0 || t.additional {
return math.MaxInt64
}
return m
}
func (t *structType) Min() int {
min := 0
rs := t.required
for i := range rs {
if rs[i] {
min++
}
}
return min
}
func (t *structType) New(arg dgo.Value) dgo.Value {
return newMap(t, arg)
}
func (t *structType) ReflectType() reflect.Type {
return reflect.MapOf(t.KeyType().ReflectType(), t.ValueType().ReflectType())
}
func (t *structType) Resolve(ap dgo.AliasAdder) {
ks := t.keys.slice
vs := t.values.slice
t.keys.slice = []dgo.Value{}
t.values.slice = []dgo.Value{}
for i := range ks {
ks[i] = ap.Replace(ks[i].(dgo.Type))
vs[i] = ap.Replace(vs[i].(dgo.Type))
}
t.keys.slice = ks
t.values.slice = vs
t.checkExactKeys()
}
func (t *structType) String() string {
return TypeString(t)
}
func (t *structType) Type() dgo.Type {
return &metaType{t}
}
func (t *structType) TypeIdentifier() dgo.TypeIdentifier {
return dgo.TiStruct
}
func (t *structType) Unbounded() bool {
return t.additional && t.Min() == 0
}
func parameterLabel(key dgo.Value) string {
return fmt.Sprintf(`parameter '%s'`, key)
}
func (t *structType) Validate(keyLabel func(key dgo.Value) string, value interface{}) []error {
return validate(t, keyLabel, value)
}
func (t *structType) ValidateVerbose(value interface{}, out dgo.Indenter) bool {
return validateVerbose(t, value, out)
}
func validate(t dgo.StructMapType, keyLabel func(key dgo.Value) string, value interface{}) []error {
var errs []error
pm, ok := Value(value).(dgo.Map)
if !ok {
return []error{errors.New(`value is not a Map`)}
}
if keyLabel == nil {
keyLabel = parameterLabel
}
t.Each(func(e dgo.StructMapEntry) {
ek := e.Key().(dgo.ExactType).ExactValue()
if v := pm.Get(ek); v != nil {
ev := e.Value().(dgo.Type)
if !ev.Instance(v) {
errs = append(errs, fmt.Errorf(`%s is not an instance of type %s`, keyLabel(ek), ev))
}
} else if e.Required() {
errs = append(errs, fmt.Errorf(`missing required %s`, keyLabel(ek)))
}
})
pm.EachKey(func(k dgo.Value) {
if t.Get(k) == nil {
errs = append(errs, fmt.Errorf(`unknown %s`, keyLabel(k)))
}
})
return errs
}
func validateVerbose(t dgo.StructMapType, value interface{}, out dgo.Indenter) bool {
pm, ok := Value(value).(dgo.Map)
if !ok {
out.Append(`value is not a Map`)
return false
}
inner := out.Indent()
t.Each(func(e dgo.StructMapEntry) {
ek := e.Key().(dgo.ExactType).ExactValue()
ev := e.Value().(dgo.Type)
out.Printf(`Validating '%s' against definition %s`, ek, ev)
inner.NewLine()
inner.Printf(`'%s' `, ek)
if v := pm.Get(ek); v != nil {
if ev.Instance(v) {
inner.Append(`OK!`)
} else {
ok = false
inner.Append(`FAILED!`)
inner.NewLine()
inner.Printf(`Reason: expected a value of type %s, got %s`, ev, v.Type())
}
} else if e.Required() {
ok = false
inner.Append(`FAILED!`)
inner.NewLine()
inner.Append(`Reason: required key not found in input`)
}
out.NewLine()
})
pm.EachKey(func(k dgo.Value) {
if t.Get(k) == nil {
ok = false
out.Printf(`Validating '%s'`, k)
inner.NewLine()
inner.Printf(`'%s' FAILED!`, k)
inner.NewLine()
inner.Append(`Reason: key is not found in definition`)
out.NewLine()
}
})
return ok
}
func (t *structType) ValueType() dgo.Type {
switch t.values.Len() {
case 0:
return DefaultAnyType
case 1:
return t.values.Get(0).(dgo.Type)
default:
return (*allOfType)(&t.values)
}
}
// StructMapEntry returns a new StructMapEntry initiated with the given parameters
func StructMapEntry(key interface{}, value interface{}, required bool) dgo.StructMapEntry {
kv := Value(key)
if _, ok := kv.(dgo.Type); !ok {
kv = kv.Type()
}
vv := Value(value)
if _, ok := vv.(dgo.Type); !ok {
vv = vv.Type()
}
return &structEntry{mapEntry: mapEntry{key: kv, value: vv}, required: required}
}
func (t *structEntry) Equals(other interface{}) bool {
return equals(nil, t, other)
}
func (t *structEntry) deepEqual(seen []dgo.Value, other deepEqual) bool {
if ot, ok := other.(dgo.StructMapEntry); ok {
return t.required == ot.Required() &&
equals(seen, t.mapEntry.key, ot.Key()) &&
equals(seen, t.mapEntry.value, ot.Value())
}
return false
}
func (t *structEntry) Required() bool {
return t.required
}
func boolsHash(s []bool) int {
h := 1
for i := range s {
m := 2
if s[i] {
m = 3
}
h *= m
}
return h
}
func boolsEqual(a, b []bool) bool {
l := len(a)
if l != len(b) {
return false
}
for l--; l >= 0; l-- {
if a[l] != b[l] {
return false
}
}
return true
} | internal/mapstruct.go | 0.62395 | 0.461563 | mapstruct.go | starcoder |
package asm_amd64
import (
"github.com/tetratelabs/wazero/internal/asm"
)
// Assembler is the interface used by amd64 JIT compiler.
type Assembler interface {
asm.AssemblerBase
// CompileRegisterToRegisterWithMode adds an instruction where source and destination
// are `from` and `to` registers and the instruction's "Mode" is specified by `Mode`.
CompileRegisterToRegisterWithMode(instruction asm.Instruction, from, to asm.Register, mode Mode)
// CompileMemoryWithIndexToRegister adds an instruction where source operand is the memory address
// specified as `srcBaseReg + srcOffsetConst + srcIndex*srcScale` and destination is the register `DstReg`.
// Note: sourceScale must be one of 1, 2, 4, 8.
CompileMemoryWithIndexToRegister(instruction asm.Instruction, srcBaseReg asm.Register, srcOffsetConst int64, srcIndex asm.Register, srcScale int16, dstReg asm.Register)
// CompileRegisterToMemoryWithIndex adds an instruction where source operand is the register `SrcReg`,
// and the destination is the memory address specified as `dstBaseReg + dstOffsetConst + dstIndex*dstScale`
// Note: dstScale must be one of 1, 2, 4, 8.
CompileRegisterToMemoryWithIndex(instruction asm.Instruction, srcReg asm.Register, dstBaseReg asm.Register, dstOffsetConst int64, dstIndex asm.Register, dstScale int16)
// CompileRegisterToConst adds an instruction where source operand is the register `srcRegister`,
// and the destination is the const `value`.
CompileRegisterToConst(instruction asm.Instruction, srcRegister asm.Register, value int64) asm.Node
// CompileRegisterToNone adds an instruction where source operand is the register `register`,
// and there's no destination operand.
CompileRegisterToNone(instruction asm.Instruction, register asm.Register)
// CompileNoneToRegister adds an instruction where destination operand is the register `register`,
// and there's no source operand.
CompileNoneToRegister(instruction asm.Instruction, register asm.Register)
// CompileNoneToMemory adds an instruction where destination operand is the memory address specified
// as `baseReg+offset`. and there's no source operand.
CompileNoneToMemory(instruction asm.Instruction, baseReg asm.Register, offset int64)
// CompileConstToMemory adds an instruction where source operand is the constant `value` and
// the destination is the memory address sppecified as `dstbaseReg+dstOffset`.
CompileConstToMemory(instruction asm.Instruction, value int64, dstbaseReg asm.Register, dstOffset int64) asm.Node
// CompileMemoryToConst adds an instruction where source operand is the memory address, and
// the destination is the constant `value`.
CompileMemoryToConst(instruction asm.Instruction, srcBaseReg asm.Register, srcOffset int64, value int64) asm.Node
}
// Mode represents a Mode for specific instruction.
// For example, ROUND** instructions' behavior can be modified "Mode" constant.
// See https://www.felixcloutier.com/x86/roundss for ROUNDSS as an example.
type Mode = byte | vendor/github.com/tetratelabs/wazero/internal/asm/amd64/assembler.go | 0.799207 | 0.455017 | assembler.go | starcoder |
package fp
func(l BoolArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l StringArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l IntArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Int64Array) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l ByteArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l RuneArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Float32Array) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Float64Array) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l AnyArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Tuple2Array) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l BoolArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l StringArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l IntArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Int64ArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l ByteArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l RuneArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Float32ArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Float64ArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l AnyArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped }
func(l Tuple2ArrayArray) ZipWithIndex() Tuple2Array {
zipped := make([]Tuple2, len(l))
for i, e := range l {
zipped[i] = Tuple2 { e, i }
}
return zipped } | fp/bootstrap_array_zipwithindex.go | 0.636466 | 0.641703 | bootstrap_array_zipwithindex.go | starcoder |
package matrixexp
import (
"github.com/gonum/blas/blas64"
"strconv"
)
// NewFuture constructs a Future MatrixLiteral from a Matrix Expression and
// then begins evaluating it.
func NewFuture(M MatrixExp) *Future {
ch := make(chan struct{})
r, c := M.Dims()
F := &Future{
r: r,
c: c,
ch: ch,
m: nil,
}
go func(M MatrixExp, F *Future, ch chan<- struct{}) {
F.m = M.Eval()
close(ch)
}(M, F, ch)
return F
}
// Future is a matrix literal that is asynchronously evaluating.
type Future struct {
r, c int
ch <-chan struct{}
m MatrixLiteral
}
// String implements the Stringer interface.
func (m1 *Future) String() string {
return "Future{" + strconv.Itoa(m1.r) + ", " + strconv.Itoa(m1.c) + "}"
}
// Dims returns the matrix dimensions.
func (m1 *Future) Dims() (r, c int) {
r = m1.r
c = m1.c
return
}
// At returns the value at a given row, column index.
func (m1 *Future) At(r, c int) float64 {
<-m1.ch
return m1.m.At(r, c)
}
// Set changes the value at a given row, column index.
func (m1 *Future) Set(r, c int, v float64) {
<-m1.ch
m1.m.Set(r, c, v)
}
// Eval returns a matrix literal.
func (m1 *Future) Eval() MatrixLiteral {
return m1
}
// Copy creates a (deep) copy of the Matrix Expression.
func (m1 *Future) Copy() MatrixExp {
//TODO(jonlawlor): handle the case where we want to copy a running job,
// maybe with pub/sub?
<-m1.ch
return &Future{
r: m1.r,
c: m1.c,
ch: m1.ch,
m: m1.m.Copy().Eval(),
}
}
// Err returns the first error encountered while constructing the matrix expression.
func (m1 *Future) Err() error {
// This is not ideal. We can't tell if the matrix is invalid until we have
// already calculated it, and by that time it is likely that it will have
// panicked. On the other hand, you should only get a future by Async, so
// compiling the matrix expression that generates this future should yield
// an error before here.
<-m1.ch
return m1.m.Err()
}
// T transposes a matrix.
func (m1 *Future) T() MatrixExp {
return &T{m1}
}
// Add two matrices together.
func (m1 *Future) Add(m2 MatrixExp) MatrixExp {
return &Add{
Left: m1,
Right: m2,
}
}
// Sub subtracts the right matrix from the left matrix.
func (m1 *Future) Sub(m2 MatrixExp) MatrixExp {
return &Sub{
Left: m1,
Right: m2,
}
}
// Scale performs scalar multiplication.
func (m1 *Future) Scale(c float64) MatrixExp {
return &Scale{
C: c,
M: m1,
}
}
// Mul performs matrix multiplication.
func (m1 *Future) Mul(m2 MatrixExp) MatrixExp {
return &Mul{
Left: m1,
Right: m2,
}
}
// MulElem performs element-wise multiplication.
func (m1 *Future) MulElem(m2 MatrixExp) MatrixExp {
return &MulElem{
Left: m1,
Right: m2,
}
}
// DivElem performs element-wise division.
func (m1 *Future) DivElem(m2 MatrixExp) MatrixExp {
return &DivElem{
Left: m1,
Right: m2,
}
}
// AsVector returns a copy of the values in the matrix as a []float64, in row order.
func (m1 *Future) AsVector() []float64 {
<-m1.ch
return m1.m.AsVector()
}
// AsGeneral returns the matrix as a blas64.General (not a copy!)
func (m1 *Future) AsGeneral() blas64.General {
<-m1.ch
return m1.m.AsGeneral()
} | future.go | 0.776369 | 0.455501 | future.go | starcoder |
package pt
import (
"math"
)
type Matrix struct {
x00, x01, x02, x03 float64
x10, x11, x12, x13 float64
x20, x21, x22, x23 float64
x30, x31, x32, x33 float64
}
func Identity() Matrix {
return Matrix{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1}
}
func Translate(v Vector) Matrix {
return Matrix{
1, 0, 0, v.X,
0, 1, 0, v.Y,
0, 0, 1, v.Z,
0, 0, 0, 1}
}
func Scale(v Vector) Matrix {
return Matrix{
v.X, 0, 0, 0,
0, v.Y, 0, 0,
0, 0, v.Z, 0,
0, 0, 0, 1}
}
func Rotate(v Vector, a float64) Matrix {
v = v.Normalize()
s := math.Sin(a)
c := math.Cos(a)
m := 1 - c
return Matrix{
m*v.X*v.X + c, m*v.X*v.Y + v.Z*s, m*v.Z*v.X - v.Y*s, 0,
m*v.X*v.Y - v.Z*s, m*v.Y*v.Y + c, m*v.Y*v.Z + v.X*s, 0,
m*v.Z*v.X + v.Y*s, m*v.Y*v.Z - v.X*s, m*v.Z*v.Z + c, 0,
0, 0, 0, 1}
}
func Frustum(l, r, b, t, n, f float64) Matrix {
t1 := 2 * n
t2 := r - l
t3 := t - b
t4 := f - n
return Matrix{
t1 / t2, 0, (r + l) / t2, 0,
0, t1 / t3, (t + b) / t3, 0,
0, 0, (-f - n) / t4, (-t1 * f) / t4,
0, 0, -1, 0}
}
func Orthographic(l, r, b, t, n, f float64) Matrix {
return Matrix{
2 / (r - l), 0, 0, -(r + l) / (r - l),
0, 2 / (t - b), 0, -(t + b) / (t - b),
0, 0, -2 / (f - n), -(f + n) / (f - n),
0, 0, 0, 1}
}
func Perspective(fovy, aspect, near, far float64) Matrix {
ymax := near * math.Tan(fovy*math.Pi/360)
xmax := ymax * aspect
return Frustum(-xmax, xmax, -ymax, ymax, near, far)
}
func LookAtMatrix(eye, center, up Vector) Matrix {
up = up.Normalize()
f := center.Sub(eye).Normalize()
s := f.Cross(up).Normalize()
u := s.Cross(f)
m := Matrix{
s.X, u.X, f.X, 0,
s.Y, u.Y, f.Y, 0,
s.Z, u.Z, f.Z, 0,
0, 0, 0, 1,
}
return m.Transpose().Inverse().Translate(eye)
}
func (m Matrix) Translate(v Vector) Matrix {
return Translate(v).Mul(m)
}
func (m Matrix) Scale(v Vector) Matrix {
return Scale(v).Mul(m)
}
func (m Matrix) Rotate(v Vector, a float64) Matrix {
return Rotate(v, a).Mul(m)
}
func (m Matrix) Frustum(l, r, b, t, n, f float64) Matrix {
return Frustum(l, r, b, t, n, f).Mul(m)
}
func (m Matrix) Orthographic(l, r, b, t, n, f float64) Matrix {
return Orthographic(l, r, b, t, n, f).Mul(m)
}
func (m Matrix) Perspective(fovy, aspect, near, far float64) Matrix {
return Perspective(fovy, aspect, near, far).Mul(m)
}
func (a Matrix) Mul(b Matrix) Matrix {
m := Matrix{}
m.x00 = a.x00*b.x00 + a.x01*b.x10 + a.x02*b.x20 + a.x03*b.x30
m.x10 = a.x10*b.x00 + a.x11*b.x10 + a.x12*b.x20 + a.x13*b.x30
m.x20 = a.x20*b.x00 + a.x21*b.x10 + a.x22*b.x20 + a.x23*b.x30
m.x30 = a.x30*b.x00 + a.x31*b.x10 + a.x32*b.x20 + a.x33*b.x30
m.x01 = a.x00*b.x01 + a.x01*b.x11 + a.x02*b.x21 + a.x03*b.x31
m.x11 = a.x10*b.x01 + a.x11*b.x11 + a.x12*b.x21 + a.x13*b.x31
m.x21 = a.x20*b.x01 + a.x21*b.x11 + a.x22*b.x21 + a.x23*b.x31
m.x31 = a.x30*b.x01 + a.x31*b.x11 + a.x32*b.x21 + a.x33*b.x31
m.x02 = a.x00*b.x02 + a.x01*b.x12 + a.x02*b.x22 + a.x03*b.x32
m.x12 = a.x10*b.x02 + a.x11*b.x12 + a.x12*b.x22 + a.x13*b.x32
m.x22 = a.x20*b.x02 + a.x21*b.x12 + a.x22*b.x22 + a.x23*b.x32
m.x32 = a.x30*b.x02 + a.x31*b.x12 + a.x32*b.x22 + a.x33*b.x32
m.x03 = a.x00*b.x03 + a.x01*b.x13 + a.x02*b.x23 + a.x03*b.x33
m.x13 = a.x10*b.x03 + a.x11*b.x13 + a.x12*b.x23 + a.x13*b.x33
m.x23 = a.x20*b.x03 + a.x21*b.x13 + a.x22*b.x23 + a.x23*b.x33
m.x33 = a.x30*b.x03 + a.x31*b.x13 + a.x32*b.x23 + a.x33*b.x33
return m
}
func (a Matrix) MulPosition(b Vector) Vector {
x := a.x00*b.X + a.x01*b.Y + a.x02*b.Z + a.x03
y := a.x10*b.X + a.x11*b.Y + a.x12*b.Z + a.x13
z := a.x20*b.X + a.x21*b.Y + a.x22*b.Z + a.x23
return Vector{x, y, z}
}
func (a Matrix) MulDirection(b Vector) Vector {
x := a.x00*b.X + a.x01*b.Y + a.x02*b.Z
y := a.x10*b.X + a.x11*b.Y + a.x12*b.Z
z := a.x20*b.X + a.x21*b.Y + a.x22*b.Z
return Vector{x, y, z}.Normalize()
}
func (a Matrix) MulRay(b Ray) Ray {
return Ray{a.MulPosition(b.Origin), a.MulDirection(b.Direction)}
}
func (a Matrix) MulBox(box Box) Box {
// http://dev.theomader.com/transform-bounding-boxes/
r := Vector{a.x00, a.x10, a.x20}
u := Vector{a.x01, a.x11, a.x21}
b := Vector{a.x02, a.x12, a.x22}
t := Vector{a.x03, a.x13, a.x23}
xa := r.MulScalar(box.Min.X)
xb := r.MulScalar(box.Max.X)
ya := u.MulScalar(box.Min.Y)
yb := u.MulScalar(box.Max.Y)
za := b.MulScalar(box.Min.Z)
zb := b.MulScalar(box.Max.Z)
xa, xb = xa.Min(xb), xa.Max(xb)
ya, yb = ya.Min(yb), ya.Max(yb)
za, zb = za.Min(zb), za.Max(zb)
min := xa.Add(ya).Add(za).Add(t)
max := xb.Add(yb).Add(zb).Add(t)
return Box{min, max}
}
func (a Matrix) Transpose() Matrix {
return Matrix{
a.x00, a.x10, a.x20, a.x30,
a.x01, a.x11, a.x21, a.x31,
a.x02, a.x12, a.x22, a.x32,
a.x03, a.x13, a.x23, a.x33}
}
func (a Matrix) Determinant() float64 {
return (a.x00*a.x11*a.x22*a.x33 - a.x00*a.x11*a.x23*a.x32 +
a.x00*a.x12*a.x23*a.x31 - a.x00*a.x12*a.x21*a.x33 +
a.x00*a.x13*a.x21*a.x32 - a.x00*a.x13*a.x22*a.x31 -
a.x01*a.x12*a.x23*a.x30 + a.x01*a.x12*a.x20*a.x33 -
a.x01*a.x13*a.x20*a.x32 + a.x01*a.x13*a.x22*a.x30 -
a.x01*a.x10*a.x22*a.x33 + a.x01*a.x10*a.x23*a.x32 +
a.x02*a.x13*a.x20*a.x31 - a.x02*a.x13*a.x21*a.x30 +
a.x02*a.x10*a.x21*a.x33 - a.x02*a.x10*a.x23*a.x31 +
a.x02*a.x11*a.x23*a.x30 - a.x02*a.x11*a.x20*a.x33 -
a.x03*a.x10*a.x21*a.x32 + a.x03*a.x10*a.x22*a.x31 -
a.x03*a.x11*a.x22*a.x30 + a.x03*a.x11*a.x20*a.x32 -
a.x03*a.x12*a.x20*a.x31 + a.x03*a.x12*a.x21*a.x30)
}
func (a Matrix) Inverse() Matrix {
m := Matrix{}
d := a.Determinant()
m.x00 = (a.x12*a.x23*a.x31 - a.x13*a.x22*a.x31 + a.x13*a.x21*a.x32 - a.x11*a.x23*a.x32 - a.x12*a.x21*a.x33 + a.x11*a.x22*a.x33) / d
m.x01 = (a.x03*a.x22*a.x31 - a.x02*a.x23*a.x31 - a.x03*a.x21*a.x32 + a.x01*a.x23*a.x32 + a.x02*a.x21*a.x33 - a.x01*a.x22*a.x33) / d
m.x02 = (a.x02*a.x13*a.x31 - a.x03*a.x12*a.x31 + a.x03*a.x11*a.x32 - a.x01*a.x13*a.x32 - a.x02*a.x11*a.x33 + a.x01*a.x12*a.x33) / d
m.x03 = (a.x03*a.x12*a.x21 - a.x02*a.x13*a.x21 - a.x03*a.x11*a.x22 + a.x01*a.x13*a.x22 + a.x02*a.x11*a.x23 - a.x01*a.x12*a.x23) / d
m.x10 = (a.x13*a.x22*a.x30 - a.x12*a.x23*a.x30 - a.x13*a.x20*a.x32 + a.x10*a.x23*a.x32 + a.x12*a.x20*a.x33 - a.x10*a.x22*a.x33) / d
m.x11 = (a.x02*a.x23*a.x30 - a.x03*a.x22*a.x30 + a.x03*a.x20*a.x32 - a.x00*a.x23*a.x32 - a.x02*a.x20*a.x33 + a.x00*a.x22*a.x33) / d
m.x12 = (a.x03*a.x12*a.x30 - a.x02*a.x13*a.x30 - a.x03*a.x10*a.x32 + a.x00*a.x13*a.x32 + a.x02*a.x10*a.x33 - a.x00*a.x12*a.x33) / d
m.x13 = (a.x02*a.x13*a.x20 - a.x03*a.x12*a.x20 + a.x03*a.x10*a.x22 - a.x00*a.x13*a.x22 - a.x02*a.x10*a.x23 + a.x00*a.x12*a.x23) / d
m.x20 = (a.x11*a.x23*a.x30 - a.x13*a.x21*a.x30 + a.x13*a.x20*a.x31 - a.x10*a.x23*a.x31 - a.x11*a.x20*a.x33 + a.x10*a.x21*a.x33) / d
m.x21 = (a.x03*a.x21*a.x30 - a.x01*a.x23*a.x30 - a.x03*a.x20*a.x31 + a.x00*a.x23*a.x31 + a.x01*a.x20*a.x33 - a.x00*a.x21*a.x33) / d
m.x22 = (a.x01*a.x13*a.x30 - a.x03*a.x11*a.x30 + a.x03*a.x10*a.x31 - a.x00*a.x13*a.x31 - a.x01*a.x10*a.x33 + a.x00*a.x11*a.x33) / d
m.x23 = (a.x03*a.x11*a.x20 - a.x01*a.x13*a.x20 - a.x03*a.x10*a.x21 + a.x00*a.x13*a.x21 + a.x01*a.x10*a.x23 - a.x00*a.x11*a.x23) / d
m.x30 = (a.x12*a.x21*a.x30 - a.x11*a.x22*a.x30 - a.x12*a.x20*a.x31 + a.x10*a.x22*a.x31 + a.x11*a.x20*a.x32 - a.x10*a.x21*a.x32) / d
m.x31 = (a.x01*a.x22*a.x30 - a.x02*a.x21*a.x30 + a.x02*a.x20*a.x31 - a.x00*a.x22*a.x31 - a.x01*a.x20*a.x32 + a.x00*a.x21*a.x32) / d
m.x32 = (a.x02*a.x11*a.x30 - a.x01*a.x12*a.x30 - a.x02*a.x10*a.x31 + a.x00*a.x12*a.x31 + a.x01*a.x10*a.x32 - a.x00*a.x11*a.x32) / d
m.x33 = (a.x01*a.x12*a.x20 - a.x02*a.x11*a.x20 + a.x02*a.x10*a.x21 - a.x00*a.x12*a.x21 - a.x01*a.x10*a.x22 + a.x00*a.x11*a.x22) / d
return m
} | pt/matrix.go | 0.822011 | 0.668082 | matrix.go | starcoder |
package simple
import (
"strings"
)
/* twoSum: https://leetcode.com/problems/two-sum/
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
solution:
take advantage of existing data structure: map have O(1) access time:
1. loop for one round to keep position of every value
2. also check for the diff part is existing in map or not,
a. if exists, then we get one answer, just return the index of diff + current
*/
func TwoSum(nums []int, target int) []int {
var nmap map[int]int = map[int]int{}
result := make([]int, 2)
for index, num := range nums {
diff := target - num
if _, ok := nmap[diff]; ok {
result[0] = nmap[diff]
result[1] = index
return result
}
nmap[num] = index
}
return result
}
/*WordPattern
give pattern: abba, words: "dog cat cat dog" is one match
solution:
1. split string s, make sure it have same length as pattern,
2. define 2 maps, for keep: pattern to value , and value to pattern
2. loop rune (char) in pattern
if rune in map, the value should also in map
if they both in map, then the value of each mapped item should also as expected
map[rune] == value && map[value] == rune
if they both not in map, just add them to map
* make sure diff partten match diff word (so we use 2 maps here)
*/
func WordPattern(pattern string, s string) bool {
results := strings.Split(s, " ")
if len(results) != len(pattern) {
return false
}
var maps map[rune]string = map[rune]string{}
var mapsr map[string]rune = map[string]rune{}
for i, char := range pattern {
target := results[i]
vs, oks := maps[char]
pr, okr := mapsr[target]
if oks != okr {
return false
}
if oks {
if vs != target || char != pr {
return false
}
continue
} else {
maps[char] = target
mapsr[target] = char
}
}
return true
} | Algorithm-go/simple/map.go | 0.826187 | 0.533154 | map.go | starcoder |
package goparquet
import (
"io"
"github.com/pkg/errors"
)
// The two following decoder are identical, since there is no generic, I had two option, one use the interfaces
// which was my first choice but its branchy and full of if and else. so I decided to go for second solution and
// almost copy/paste this two types
type deltaBitPackDecoder32 struct {
r io.Reader
blockSize int32
miniBlockCount int32
valuesCount int32
miniBlockValueCount int32
previousValue int32
minDelta int32
miniBlockBitWidth []uint8
currentMiniBlock int32
currentMiniBlockBitWidth uint8
miniBlockPosition int32 // position inside the current mini block
position int32 // position in the value. since delta may have padding we need to track this
currentUnpacker unpack8int32Func
miniBlockInt32 [8]int32
}
func (d *deltaBitPackDecoder32) initSize(r io.Reader) error {
return d.init(r)
}
func (d *deltaBitPackDecoder32) init(r io.Reader) error {
d.r = r
if err := d.readBlockHeader(); err != nil {
return err
}
if err := d.readMiniBlockHeader(); err != nil {
return err
}
return nil
}
func (d *deltaBitPackDecoder32) readBlockHeader() error {
var err error
if d.blockSize, err = readUVariant32(d.r); err != nil {
return errors.Wrap(err, "failed to read block size")
}
if d.blockSize <= 0 && d.blockSize%128 != 0 {
return errors.New("invalid block size")
}
if d.miniBlockCount, err = readUVariant32(d.r); err != nil {
return errors.Wrap(err, "failed to read number of mini blocks")
}
if d.miniBlockCount <= 0 || d.blockSize%d.miniBlockCount != 0 {
return errors.New("int/delta: invalid number of mini blocks")
}
d.miniBlockValueCount = d.blockSize / d.miniBlockCount
if d.miniBlockValueCount == 0 {
return errors.Errorf("invalid mini block value count, it can't be zero")
}
if d.valuesCount, err = readUVariant32(d.r); err != nil {
return errors.Wrapf(err, "failed to read total value count")
}
if d.valuesCount < 0 {
return errors.New("invalid total value count")
}
if d.previousValue, err = readVariant32(d.r); err != nil {
return errors.Wrap(err, "failed to read first value")
}
return nil
}
func (d *deltaBitPackDecoder32) readMiniBlockHeader() error {
var err error
if d.minDelta, err = readVariant32(d.r); err != nil {
return errors.Wrap(err, "failed to read min delta")
}
// the mini block bitwidth is always there, even if the value is zero
d.miniBlockBitWidth = make([]uint8, d.miniBlockCount)
if _, err = io.ReadFull(d.r, d.miniBlockBitWidth); err != nil {
return errors.Wrap(err, "not enough data to read all miniblock bit widths")
}
for i := range d.miniBlockBitWidth {
if d.miniBlockBitWidth[i] > 32 {
return errors.Errorf("invalid miniblock bit width : %d", d.miniBlockBitWidth[i])
}
}
// start from the first min block in a big block
d.currentMiniBlock = 0
return nil
}
func (d *deltaBitPackDecoder32) next() (int32, error) {
if d.position >= d.valuesCount {
// No value left in the buffer
return 0, io.EOF
}
// need new byte?
if d.position%8 == 0 {
// do we need to advance a mini block?
if d.position%d.miniBlockValueCount == 0 {
// do we need to advance a big block?
if d.currentMiniBlock >= d.miniBlockCount {
if err := d.readMiniBlockHeader(); err != nil {
return 0, err
}
}
d.currentMiniBlockBitWidth = d.miniBlockBitWidth[d.currentMiniBlock]
d.currentUnpacker = unpack8Int32FuncByWidth[int(d.currentMiniBlockBitWidth)]
d.miniBlockPosition = 0
d.currentMiniBlock++
}
// read next 8 values
w := int32(d.currentMiniBlockBitWidth)
buf := make([]byte, w)
if _, err := io.ReadFull(d.r, buf); err != nil {
return 0, err
}
d.miniBlockInt32 = d.currentUnpacker(buf)
d.miniBlockPosition += w
// there is padding here, read them all from the reader, first deal with the remaining of the current block,
// then the next blocks. if the blocks bit width is zero then simply ignore them, but the docs said reader
// should accept any arbitrary bit width here.
if d.position+8 >= d.valuesCount {
// current block
l := (d.miniBlockValueCount/8)*w - d.miniBlockPosition
if l < 0 {
return 0, errors.New("invalid stream")
}
remaining := make([]byte, l)
_, _ = io.ReadFull(d.r, remaining)
for i := d.currentMiniBlock; i < d.miniBlockCount; i++ {
w := int32(d.miniBlockBitWidth[d.currentMiniBlock])
if w != 0 {
remaining := make([]byte, (d.miniBlockValueCount/8)*w)
_, _ = io.ReadFull(d.r, remaining)
}
}
}
}
// value is the previous value + delta stored in the reader and the min delta for the block, also we always read one
// value ahead
ret := d.previousValue
d.previousValue += d.miniBlockInt32[d.position%8] + d.minDelta
d.position++
return ret, nil
}
type deltaBitPackDecoder64 struct {
r io.Reader
blockSize int32
miniBlockCount int32
valuesCount int32
miniBlockValueCount int32
previousValue int64
minDelta int64
miniBlockBitWidth []uint8
currentMiniBlock int32
currentMiniBlockBitWidth uint8
miniBlockPosition int32 // position inside the current mini block
position int32 // position in the value. since delta may have padding we need to track this
currentUnpacker unpack8int64Func
miniBlockInt64 [8]int64
}
func (d *deltaBitPackDecoder64) init(r io.Reader) error {
d.r = r
if err := d.readBlockHeader(); err != nil {
return err
}
if err := d.readMiniBlockHeader(); err != nil {
return err
}
return nil
}
func (d *deltaBitPackDecoder64) readBlockHeader() error {
var err error
if d.blockSize, err = readUVariant32(d.r); err != nil {
return errors.Wrap(err, "failed to read block size")
}
if d.blockSize <= 0 && d.blockSize%128 != 0 {
return errors.New("invalid block size")
}
if d.miniBlockCount, err = readUVariant32(d.r); err != nil {
return errors.Wrap(err, "failed to read number of mini blocks")
}
if d.miniBlockCount <= 0 || d.blockSize%d.miniBlockCount != 0 {
return errors.New("int/delta: invalid number of mini blocks")
}
d.miniBlockValueCount = d.blockSize / d.miniBlockCount
if d.valuesCount, err = readUVariant32(d.r); err != nil {
return errors.Wrapf(err, "failed to read total value count")
}
if d.valuesCount < 0 {
return errors.New("invalid total value count")
}
if d.previousValue, err = readVariant64(d.r); err != nil {
return errors.Wrap(err, "failed to read first value")
}
return nil
}
func (d *deltaBitPackDecoder64) readMiniBlockHeader() error {
var err error
if d.minDelta, err = readVariant64(d.r); err != nil {
return errors.Wrap(err, "failed to read min delta")
}
// the mini block bitwidth is always there, even if the value is zero
d.miniBlockBitWidth = make([]uint8, d.miniBlockCount)
if _, err = io.ReadFull(d.r, d.miniBlockBitWidth); err != nil {
return errors.Wrap(err, "not enough data to read all miniblock bit widths")
}
for i := range d.miniBlockBitWidth {
if d.miniBlockBitWidth[i] > 64 {
return errors.Errorf("invalid miniblock bit width : %d", d.miniBlockBitWidth[i])
}
}
// start from the first min block in a big block
d.currentMiniBlock = 0
return nil
}
func (d *deltaBitPackDecoder64) next() (int64, error) {
if d.position >= d.valuesCount {
// No value left in the buffer
return 0, io.EOF
}
// need new byte?
if d.position%8 == 0 {
// do we need to advance a mini block?
if d.position%d.miniBlockValueCount == 0 {
// do we need to advance a big block?
if d.currentMiniBlock >= d.miniBlockCount {
if err := d.readMiniBlockHeader(); err != nil {
return 0, err
}
}
d.currentMiniBlockBitWidth = d.miniBlockBitWidth[d.currentMiniBlock]
d.currentUnpacker = unpack8Int64FuncByWidth[int(d.currentMiniBlockBitWidth)]
d.miniBlockPosition = 0
d.currentMiniBlock++
}
// read next 8 values
w := int32(d.currentMiniBlockBitWidth)
buf := make([]byte, w)
if _, err := io.ReadFull(d.r, buf); err != nil {
return 0, err
}
d.miniBlockInt64 = d.currentUnpacker(buf)
d.miniBlockPosition += w
// there is padding here, read them all from the reader, first deal with the remaining of the current block,
// then the next blocks. if the blocks bit width is zero then simply ignore them, but the docs said reader
// should accept any arbitrary bit width here.
if d.position+8 >= d.valuesCount {
// current block
remaining := make([]byte, (d.miniBlockValueCount/8)*w-d.miniBlockPosition)
_, _ = io.ReadFull(d.r, remaining)
for i := d.currentMiniBlock; i < d.miniBlockCount; i++ {
w := int32(d.miniBlockBitWidth[d.currentMiniBlock])
if w != 0 {
remaining := make([]byte, (d.miniBlockValueCount/8)*w)
_, _ = io.ReadFull(d.r, remaining)
}
}
}
}
// value is the previous value + delta stored in the reader and the min delta for the block, also we always read one
// value ahead
ret := d.previousValue
d.previousValue += d.miniBlockInt64[d.position%8] + d.minDelta
d.position++
return ret, nil
} | deltabp_decoder.go | 0.59843 | 0.428771 | deltabp_decoder.go | starcoder |
package fr
import "github.com/MaxSlyugrov/cldr"
var calendar = cldr.Calendar{
Formats: cldr.CalendarFormats{
Date: cldr.CalendarDateFormat{Full: "EEEE d MMMM y", Long: "d MMMM y", Medium: "d MMM y", Short: "dd/MM/y"},
Time: cldr.CalendarDateFormat{Full: "HH:mm:ss zzzz", Long: "HH:mm:ss z", Medium: "HH:mm:ss", Short: "HH:mm"},
DateTime: cldr.CalendarDateFormat{Full: "{1} {0}", Long: "{1} {0}", Medium: "{1} {0}", Short: "{1} {0}"},
},
FormatNames: cldr.CalendarFormatNames{
Months: cldr.CalendarMonthFormatNames{
Abbreviated: cldr.CalendarMonthFormatNameValue{Jan: "Janv.", Feb: "Févr.", Mar: "Mars", Apr: "Avr.", May: "Mai", Jun: "Juin", Jul: "Juil.", Aug: "Août", Sep: "Sept.", Oct: "Oct.", Nov: "Nov.", Dec: "Déc."},
Narrow: cldr.CalendarMonthFormatNameValue{Jan: "J", Feb: "F", Mar: "M", Apr: "A", May: "M", Jun: "J", Jul: "J", Aug: "A", Sep: "S", Oct: "O", Nov: "N", Dec: "D"},
Short: cldr.CalendarMonthFormatNameValue{},
Wide: cldr.CalendarMonthFormatNameValue{Jan: "Janvier", Feb: "Février", Mar: "Mars", Apr: "Avril", May: "Mai", Jun: "Juin", Jul: "Juillet", Aug: "Août", Sep: "Septembre", Oct: "Octobre", Nov: "Novembre", Dec: "Décembre"},
},
Days: cldr.CalendarDayFormatNames{
Abbreviated: cldr.CalendarDayFormatNameValue{Sun: "Dim.", Mon: "Lun.", Tue: "Mar.", Wed: "Mer.", Thu: "Jeu.", Fri: "Ven.", Sat: "Sam."},
Narrow: cldr.CalendarDayFormatNameValue{Sun: "D", Mon: "L", Tue: "M", Wed: "M", Thu: "J", Fri: "V", Sat: "S"},
Short: cldr.CalendarDayFormatNameValue{Sun: "Di", Mon: "Lu", Tue: "Ma", Wed: "Me", Thu: "Je", Fri: "Ve", Sat: "Sa"},
Wide: cldr.CalendarDayFormatNameValue{Sun: "Dimanche", Mon: "Lundi", Tue: "Mardi", Wed: "Mercredi", Thu: "Jeudi", Fri: "Vendredi", Sat: "Samedi"},
},
Periods: cldr.CalendarPeriodFormatNames{
Abbreviated: cldr.CalendarPeriodFormatNameValue{AM: "av.m.", PM: "ap.m."},
Narrow: cldr.CalendarPeriodFormatNameValue{AM: "a", PM: "p"},
Short: cldr.CalendarPeriodFormatNameValue{},
Wide: cldr.CalendarPeriodFormatNameValue{AM: "avant-midi", PM: "après-midi"},
},
},
} | resources/locales/fr/calendar.go | 0.505859 | 0.464962 | calendar.go | starcoder |
package metrics
import (
"time"
"github.com/uber-go/tally/v4"
"go.temporal.io/server/common/log"
)
type (
excludeTags map[string]map[string]struct{}
tallyMetricsHandler struct {
tags []Tag
scope tally.Scope
perUnitBuckets map[MetricUnit]tally.Buckets
excludeTags excludeTags
}
)
var _ MetricsHandler = (*tallyMetricsHandler)(nil)
func NewTallyMetricsHandler(cfg ClientConfig, scope tally.Scope) *tallyMetricsHandler {
perUnitBuckets := make(map[MetricUnit]tally.Buckets)
if cfg.PerUnitHistogramBoundaries == nil {
setDefaultPerUnitHistogramBoundaries(&cfg)
}
for unit, boundariesList := range cfg.PerUnitHistogramBoundaries {
perUnitBuckets[MetricUnit(unit)] = tally.ValueBuckets(boundariesList)
}
return &tallyMetricsHandler{
scope: scope,
perUnitBuckets: perUnitBuckets,
excludeTags: configExcludeTags(cfg),
}
}
// WithTags creates a new MetricProvder with provided []Tag
// Tags are merged with registered Tags from the source MetricsHandler
func (tmp *tallyMetricsHandler) WithTags(tags ...Tag) MetricsHandler {
return &tallyMetricsHandler{
scope: tmp.scope,
perUnitBuckets: tmp.perUnitBuckets,
tags: append(tmp.tags, tags...),
}
}
// Counter obtains a counter for the given name and MetricOptions.
func (tmp *tallyMetricsHandler) Counter(counter string) CounterMetric {
return CounterMetricFunc(func(i int64, t ...Tag) {
tmp.scope.Tagged(tagsToMap(tmp.tags, t, tmp.excludeTags)).Counter(counter).Inc(i)
})
}
// Gauge obtains a gauge for the given name and MetricOptions.
func (tmp *tallyMetricsHandler) Gauge(gauge string) GaugeMetric {
return GaugeMetricFunc(func(f float64, t ...Tag) {
tmp.scope.Tagged(tagsToMap(tmp.tags, t, tmp.excludeTags)).Gauge(gauge).Update(f)
})
}
// Timer obtains a timer for the given name and MetricOptions.
func (tmp *tallyMetricsHandler) Timer(timer string) TimerMetric {
return TimerMetricFunc(func(d time.Duration, tag ...Tag) {
tmp.scope.Tagged(tagsToMap(tmp.tags, tag, tmp.excludeTags)).Timer(timer).Record(d)
})
}
// Histogram obtains a histogram for the given name and MetricOptions.
func (tmp *tallyMetricsHandler) Histogram(histogram string, unit MetricUnit) HistogramMetric {
return HistogramMetricFunc(func(i int64, t ...Tag) {
tmp.scope.Tagged(tagsToMap(tmp.tags, t, tmp.excludeTags)).Histogram(histogram, tmp.perUnitBuckets[unit]).RecordValue(float64(i))
})
}
func (*tallyMetricsHandler) Stop(log.Logger) {}
func tagsToMap(t1 []Tag, t2 []Tag, e excludeTags) map[string]string {
m := make(map[string]string, len(t1)+len(t2))
convert := func(tag Tag) {
if vals, ok := e[tag.Key()]; ok {
if _, ok := vals[tag.Value()]; !ok {
m[tag.Key()] = tagExcludedValue
return
}
}
m[tag.Key()] = tag.Value()
}
for i := range t1 {
convert(t1[i])
}
for i := range t2 {
convert(t2[i])
}
return m
} | common/metrics/tally_metric_provider.go | 0.620737 | 0.405272 | tally_metric_provider.go | starcoder |
// Package vec2d offers a two-dimensional vector implementation for Go.
package vec2d
import "math"
// Vector type defines vector using exported float64 values: X and Y
type Vector struct {
X, Y float64
}
// New returns a new vector
func New(x, y float64) *Vector {
return &Vector{X: x, Y: y}
}
// IsEqual compares а Vector with another and returns true if they're equal
func (v *Vector) IsEqual(other *Vector) bool {
return v.X == other.X && v.Y == other.Y
}
// Angle returns the Vector's angle in float64
func (v *Vector) Angle() float64 {
return math.Atan2(v.Y, v.X) / (math.Pi / 180)
}
// SetAngle changes Vector's angle using vector rotation
func (v *Vector) SetAngle(angle_degrees float64) {
v.X = v.Length()
v.Y = 0.0
v.Rotate(angle_degrees)
}
// Length returns... well the Vector's length
func (v *Vector) Length() float64 {
return math.Sqrt(math.Pow(v.X, 2) + math.Pow(v.Y, 2))
}
// SetLength changes Vector's length, which obviously changes
// the values of Vector.X and Vector.Y
func (v *Vector) SetLength(value float64) {
length := v.Length()
v.X *= value / length
v.Y *= value / length
}
// Rotate Vector by given angle degrees in float64
func (v *Vector) Rotate(angle_degrees float64) {
radians := (math.Pi / 180) * angle_degrees
sin := math.Sin(radians)
cos := math.Cos(radians)
x := v.X*cos - v.Y*sin
y := v.X*sin + v.Y*cos
v.X = x
v.Y = y
}
// Collect changes Vector's X and Y by collecting them with other's
func (v *Vector) Collect(other *Vector) {
v.X += other.X
v.Y += other.Y
}
// CollectToFloat64 changes Vector's X and Y by collecting them with value
func (v *Vector) CollectToFloat64(value float64) {
v.X += value
v.Y += value
}
// Sub changes Vector's X and Y by substracting them with other's
func (v *Vector) Sub(other *Vector) {
v.X -= other.X
v.Y -= other.Y
}
// SubToFloat64 changes Vector's X and Y by substracting them with value
func (v *Vector) SubToFloat64(value float64) {
v.X -= value
v.Y -= value
}
// Mul changes Vector's X and Y by multiplying them with other's
func (v *Vector) Mul(other *Vector) {
v.X *= other.X
v.Y *= other.Y
}
// MulToFloat64 changes Vector's X and Y by multiplying them with value
func (v *Vector) MulToFloat64(value float64) {
v.X *= value
v.Y *= value
}
// Div changes Vector's X and Y by dividing them with other's
func (v *Vector) Div(other *Vector) {
v.X /= other.X
v.Y /= other.Y
}
// DivToFloat64 changes Vector's X and Y by dividing them with value
func (v *Vector) DivToFloat64(value float64) {
v.X /= value
v.Y /= value
} | vector.go | 0.919489 | 0.786295 | vector.go | starcoder |
package goa
import "context"
// Location is the enum defining where the value of key based security schemes should be read:
// either a HTTP request header or a URL querystring value
type Location string
// LocHeader indicates the secret value should be loaded from the request headers.
const LocHeader Location = "header"
// LocQuery indicates the secret value should be loaded from the request URL querystring.
const LocQuery Location = "query"
// ContextRequiredScopes extracts the security scopes from the given context.
// This should be used in auth handlers to validate that the required scopes are present in the
// JWT or OAuth2 token.
func ContextRequiredScopes(ctx context.Context) []string {
if s := ctx.Value(securityScopesKey); s != nil {
return s.([]string)
}
return nil
}
// WithRequiredScopes builds a context containing the given required scopes.
func WithRequiredScopes(ctx context.Context, scopes []string) context.Context {
return context.WithValue(ctx, securityScopesKey, scopes)
}
// OAuth2Security represents the `oauth2` security scheme. It is instantiated by the generated code
// accordingly to the use of the different `*Security()` DSL functions and `Security()` in the
// design.
type OAuth2Security struct {
// Description of the security scheme
Description string
// Flow defines the OAuth2 flow type. See http://swagger.io/specification/#securitySchemeObject
Flow string
// TokenURL defines the OAuth2 tokenUrl. See http://swagger.io/specification/#securitySchemeObject
TokenURL string
// AuthorizationURL defines the OAuth2 authorizationUrl. See http://swagger.io/specification/#securitySchemeObject
AuthorizationURL string
// Scopes defines a list of scopes for the security scheme, along with their description.
Scopes map[string]string
}
// BasicAuthSecurity represents the `Basic` security scheme, which consists of a simple login/pass,
// accessible through Request.BasicAuth().
type BasicAuthSecurity struct {
// Description of the security scheme
Description string
}
// APIKeySecurity represents the `apiKey` security scheme. It handles a key that can be in the
// headers or in the query parameters, and does authentication based on that. The Name field
// represents the key of either the query string parameter or the header, depending on the In field.
type APIKeySecurity struct {
// Description of the security scheme
Description string
// In represents where to check for some data, `query` or `header`
In Location
// Name is the name of the `header` or `query` parameter to check for data.
Name string
}
// JWTSecurity represents an api key based scheme, with support for scopes and a token URL.
type JWTSecurity struct {
// Description of the security scheme
Description string
// In represents where to check for the JWT, `query` or `header`
In Location
// Name is the name of the `header` or `query` parameter to check for data.
Name string
// TokenURL defines the URL where you'd get the JWT tokens.
TokenURL string
// Scopes defines a list of scopes for the security scheme, along with their description.
Scopes map[string]string
} | security.go | 0.867892 | 0.419648 | security.go | starcoder |
package jdwp
import (
"fmt"
"io"
)
// Reader provides methods for decoding values.
type Reader interface {
io.Reader
// Data reads the data bytes in their entirety.
Data([]byte)
// Bool decodes and returns a boolean value from the Reader.
Bool() bool
// Int8 decodes and returns a signed, 8 bit integer value from the Reader.
Int8() int8
// Uint8 decodes and returns an unsigned, 8 bit integer value from the Reader.
Uint8() uint8
// Int16 decodes and returns a signed, 16 bit integer value from the Reader.
Int16() int16
// Uint16 decodes and returns an unsigned, 16 bit integer value from the Reader.
Uint16() uint16
// Int32 decodes and returns a signed, 32 bit integer value from the Reader.
Int32() int32
// Uint32 decodes and returns an unsigned, 32 bit integer value from the Reader.
Uint32() uint32
// Float16 decodes and returns a 16 bit floating-point value from the Reader.
Float16() Number
// Float32 decodes and returns a 32 bit floating-point value from the Reader.
Float32() float32
// Int64 decodes and returns a signed, 64 bit integer value from the Reader.
Int64() int64
// Uint64 decodes and returns an unsigned, 64 bit integer value from the Reader.
Uint64() uint64
// Float64 decodes and returns a 64 bit floating-point value from the Reader.
Float64() float64
// String decodes and returns a string from the Reader.
String() string
// Decode a collection count from the stream.
Count() uint32
// If there is an error reading any input, all further reading returns the
// zero value of the type read. Error() returns the error which stopped
// reading from the stream. If reading has not stopped it returns nil.
Error() error
// Set the error state and stop reading from the stream.
SetError(error)
}
// ReadUint reads an unsigned integer of either 8, 16, 32 or 64 bits from r,
// returning the result as a uint64.
func ReadUint(r Reader, bits int32) uint64 {
switch bits {
case 8:
return uint64(r.Uint8())
case 16:
return uint64(r.Uint16())
case 32:
return uint64(r.Uint32())
case 64:
return r.Uint64()
default:
r.SetError(fmt.Errorf("Unsupported integer bit count %v", bits))
return 0
}
}
// ReadInt reads a signed integer of either 8, 16, 32 or 64 bits from r,
// returning the result as a int64.
func ReadInt(r Reader, bits int32) int64 {
switch bits {
case 8:
return int64(r.Int8())
case 16:
return int64(r.Int16())
case 32:
return int64(r.Int32())
case 64:
return r.Int64()
default:
r.SetError(fmt.Errorf("Unsupported integer bit count %v", bits))
return 0
}
}
// ConsumeBytes reads and throws away a number of bytes from r, returning the
// number of bytes it consumed.
func ConsumeBytes(r Reader, bytes uint64) uint64 {
for i := uint64(0); i < bytes; i++ {
r.Uint8()
}
return bytes
} | jdwp/reader.go | 0.669853 | 0.427875 | reader.go | starcoder |
package eth
import (
"encoding/hex"
"encoding/json"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/sha3"
"github.com/INFURA/go-ethlibs/rlp"
)
type Data string
type Data8 Data
type Data20 Data
type Data32 Data
type Data256 Data
// Aliases
type Hash = Data32
type Topic = Data32
func NewData(value string) (*Data, error) {
parsed, err := validateHex(value, -1, "data")
if err != nil {
return nil, err
}
d := Data(parsed)
return &d, nil
}
func NewData8(value string) (*Data8, error) {
parsed, err := validateHex(value, 8, "data")
if err != nil {
return nil, err
}
d := Data8(parsed)
return &d, nil
}
func NewData20(value string) (*Data20, error) {
parsed, err := validateHex(value, 20, "data")
if err != nil {
return nil, err
}
d := Data20(parsed)
return &d, nil
}
func NewData32(value string) (*Data32, error) {
parsed, err := validateHex(value, 32, "data")
if err != nil {
return nil, err
}
d := Data32(parsed)
return &d, nil
}
func NewHash(value string) (*Hash, error) {
return NewData32(value)
}
func NewTopic(value string) (*Hash, error) {
return NewData32(value)
}
func NewData256(value string) (*Data256, error) {
parsed, err := validateHex(value, 256, "data")
if err != nil {
return nil, err
}
d := Data256(parsed)
return &d, nil
}
func MustData(value string) *Data {
d, err := NewData(value)
if err != nil {
panic(err)
}
return d
}
func MustData8(value string) *Data8 {
d, err := NewData8(value)
if err != nil {
panic(err)
}
return d
}
func MustData20(value string) *Data20 {
d, err := NewData20(value)
if err != nil {
panic(err)
}
return d
}
func MustData32(value string) *Data32 {
d, err := NewData32(value)
if err != nil {
panic(err)
}
return d
}
func MustHash(value string) *Hash {
return MustData32(value)
}
func MustTopic(value string) *Hash {
return MustData32(value)
}
func MustData256(value string) *Data256 {
d, err := NewData256(value)
if err != nil {
panic(err)
}
return d
}
func (d Data) String() string {
return string(d)
}
func (d Data8) String() string {
return string(d)
}
func (d Data20) String() string {
return string(d)
}
func (d Data32) String() string {
return string(d)
}
func (d Data256) String() string {
return string(d)
}
func (d Data) Bytes() []byte {
b, err := hex.DecodeString(d.String()[2:])
if err != nil {
panic(err)
}
return b
}
func (d Data8) Bytes() []byte {
b, err := hex.DecodeString(d.String()[2:])
if err != nil {
panic(err)
}
return b
}
func (d Data20) Bytes() []byte {
b, err := hex.DecodeString(d.String()[2:])
if err != nil {
panic(err)
}
return b
}
func (d Data32) Bytes() []byte {
b, err := hex.DecodeString(d.String()[2:])
if err != nil {
panic(err)
}
return b
}
func (d Data256) Bytes() []byte {
b, err := hex.DecodeString(d.String()[2:])
if err != nil {
panic(err)
}
return b
}
// Hash returns the keccak256 hash of the Data.
func (d Data) Hash() Hash {
return hash(d)
}
// Hash returns the keccak256 hash of the Data8.
func (d Data8) Hash() Hash {
return hash(d)
}
// Hash returns the keccak256 hash of the Data20.
func (d Data20) Hash() Hash {
return hash(d)
}
// Hash returns the keccak256 hash of the Data32.
func (d Data32) Hash() Hash {
return hash(d)
}
// Hash returns the keccak256 hash of the Data256.
func (d Data256) Hash() Hash {
return hash(d)
}
func (d *Data) UnmarshalJSON(data []byte) error {
str, err := unmarshalHex(data, -1, "data")
if err != nil {
return err
}
*d = Data(str)
return nil
}
func (d *Data8) UnmarshalJSON(data []byte) error {
str, err := unmarshalHex(data, 8, "data")
if err != nil {
return err
}
*d = Data8(str)
return nil
}
func (d *Data20) UnmarshalJSON(data []byte) error {
str, err := unmarshalHex(data, 20, "data")
if err != nil {
return err
}
*d = Data20(str)
return nil
}
func (d *Data32) UnmarshalJSON(data []byte) error {
str, err := unmarshalHex(data, 32, "data")
if err != nil {
return err
}
*d = Data32(str)
return nil
}
func (d *Data256) UnmarshalJSON(data []byte) error {
str, err := unmarshalHex(data, 256, "data")
if err != nil {
return err
}
*d = Data256(str)
return nil
}
func (d *Data) MarshalJSON() ([]byte, error) {
s := string(*d)
return json.Marshal(&s)
}
func unmarshalHex(data []byte, size int, typ string) (string, error) {
var str string
err := json.Unmarshal(data, &str)
if err != nil {
return "", err
}
return validateHex(str, size, typ)
}
func validateHex(value string, size int, typ string) (string, error) {
if !strings.HasPrefix(value, "0x") {
return "", errors.Errorf("%s types must start with 0x", typ)
}
if size != -1 {
dataSize := (len(value) - 2) / 2
if size != dataSize {
return "", errors.Errorf("%s type size mismatch, expected %d got %d", typ, size, dataSize)
}
}
// validate that the input characters after 0x are only 0-9, a-f, A-F
for i, c := range value[2:] {
switch {
case '0' <= c && c <= '9':
continue
case 'a' <= c && c <= 'f':
continue
case 'A' <= c && c <= 'F':
continue
}
return "", errors.Errorf("invalid hex string, invalid character '%c' at index %d", c, i+2)
}
return value, nil
}
// RLP returns the Data as an RLP-encoded string.
func (d *Data) RLP() rlp.Value {
return rlp.Value{
String: d.String(),
}
}
// RLP returns the Data32 as an RLP-encoded string.
func (d *Data32) RLP() rlp.Value {
return rlp.Value{
String: d.String(),
}
}
type hasBytes interface {
Bytes() []byte
}
func hash(from hasBytes) Hash {
b := from.Bytes()
// And feed the bytes into our hash
hash := sha3.NewLegacyKeccak256()
hash.Write(b)
sum := hash.Sum(nil)
// and finally return the hash as a 0x prefixed string
digest := hex.EncodeToString(sum)
return Hash("0x" + digest)
} | eth/data.go | 0.691081 | 0.44083 | data.go | starcoder |
package shapes
import (
"math"
"github.com/factorion/graytracer/pkg/primitives"
)
// Cube Basic cube representation
type Cube struct {
ShapeBase
}
// CheckAxis Checks two sides of a cube on an axis from a ray's path on that axis
func CheckAxis(origin, direction, minimum, maximum float64) (float64, float64) {
// We can do just this because go handles division by zero
tmin := (minimum - origin) / direction
tmax := (maximum - origin) / direction
if tmin > tmax {
tmin, tmax = tmax, tmin
}
return tmin, tmax
}
// MakeCube Make a regular cube with an identity matrix for transform
func MakeCube() *Cube {
return &Cube{MakeShapeBase()}
}
// GetBounds Return an axis aligned bounding box for the sphere
func (c *Cube) GetBounds() *Bounds {
bounds := Bounds{Min:primitives.MakePoint(-1, -1, -1), Max:primitives.MakePoint(1, 1, 1)}
return bounds.Transform(c.transform)
}
// Intersect Check for intersection along one of the six sides of the cube
func (c *Cube) Intersect(r primitives.Ray) Intersections {
// convert ray to object space
oray := r.Transform(c.Inverse())
xtmin, xtmax := CheckAxis(oray.Origin.X, oray.Direction.X, -1, 1)
ytmin, ytmax := CheckAxis(oray.Origin.Y, oray.Direction.Y, -1, 1)
ztmin, ztmax := CheckAxis(oray.Origin.Z, oray.Direction.Z, -1, 1)
tmin := math.Max(math.Max(xtmin, ytmin), ztmin)
tmax := math.Min(math.Min(xtmax, ytmax), ztmax)
if tmin > tmax {
return Intersections{}
}
return Intersections{Intersection{Distance:tmin, Obj:c}, Intersection{Distance:tmax, Obj:c}}
}
// Normal Calculate the normal at a given point on the cube
func (c *Cube) Normal(worldPoint primitives.PV) primitives.PV {
objectPoint := c.WorldToObjectPV(worldPoint)
absx := math.Abs(objectPoint.X)
absy := math.Abs(objectPoint.Y)
absz := math.Abs(objectPoint.Z)
max := math.Max(absx, math.Max(absy, absz))
var objectNormal primitives.PV
if max == absx {
objectNormal = primitives.MakeVector(objectPoint.X, 0, 0)
} else if max == absy {
objectNormal = primitives.MakeVector(0, objectPoint.Y, 0)
} else {
objectNormal = primitives.MakeVector(0, 0, objectPoint.Z)
}
worldNormal := c.ObjectToWorldPV(objectNormal)
worldNormal.W = 0.0
return worldNormal.Normalize()
}
// UVMapping Return the 2D coordinates of an intersection point
func (c *Cube) UVMapping(point primitives.PV) primitives.PV {
return primitives.MakePoint(point.X, point.Y, 0)
} | pkg/shapes/cube.go | 0.930324 | 0.499939 | cube.go | starcoder |
package onshape
import (
"encoding/json"
)
// BTSplineDescription2118AllOf struct for BTSplineDescription2118AllOf
type BTSplineDescription2118AllOf struct {
BtType *string `json:"btType,omitempty"`
ControlPoints *[]float64 `json:"controlPoints,omitempty"`
Degree *int32 `json:"degree,omitempty"`
IsPeriodic *bool `json:"isPeriodic,omitempty"`
IsRational *bool `json:"isRational,omitempty"`
Knots *[]float64 `json:"knots,omitempty"`
}
// NewBTSplineDescription2118AllOf instantiates a new BTSplineDescription2118AllOf 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 NewBTSplineDescription2118AllOf() *BTSplineDescription2118AllOf {
this := BTSplineDescription2118AllOf{}
return &this
}
// NewBTSplineDescription2118AllOfWithDefaults instantiates a new BTSplineDescription2118AllOf 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 NewBTSplineDescription2118AllOfWithDefaults() *BTSplineDescription2118AllOf {
this := BTSplineDescription2118AllOf{}
return &this
}
// GetBtType returns the BtType field value if set, zero value otherwise.
func (o *BTSplineDescription2118AllOf) 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 *BTSplineDescription2118AllOf) 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 *BTSplineDescription2118AllOf) 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 *BTSplineDescription2118AllOf) SetBtType(v string) {
o.BtType = &v
}
// GetControlPoints returns the ControlPoints field value if set, zero value otherwise.
func (o *BTSplineDescription2118AllOf) GetControlPoints() []float64 {
if o == nil || o.ControlPoints == nil {
var ret []float64
return ret
}
return *o.ControlPoints
}
// GetControlPointsOk returns a tuple with the ControlPoints field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTSplineDescription2118AllOf) GetControlPointsOk() (*[]float64, bool) {
if o == nil || o.ControlPoints == nil {
return nil, false
}
return o.ControlPoints, true
}
// HasControlPoints returns a boolean if a field has been set.
func (o *BTSplineDescription2118AllOf) HasControlPoints() bool {
if o != nil && o.ControlPoints != nil {
return true
}
return false
}
// SetControlPoints gets a reference to the given []float64 and assigns it to the ControlPoints field.
func (o *BTSplineDescription2118AllOf) SetControlPoints(v []float64) {
o.ControlPoints = &v
}
// GetDegree returns the Degree field value if set, zero value otherwise.
func (o *BTSplineDescription2118AllOf) GetDegree() int32 {
if o == nil || o.Degree == nil {
var ret int32
return ret
}
return *o.Degree
}
// GetDegreeOk returns a tuple with the Degree field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTSplineDescription2118AllOf) GetDegreeOk() (*int32, bool) {
if o == nil || o.Degree == nil {
return nil, false
}
return o.Degree, true
}
// HasDegree returns a boolean if a field has been set.
func (o *BTSplineDescription2118AllOf) HasDegree() bool {
if o != nil && o.Degree != nil {
return true
}
return false
}
// SetDegree gets a reference to the given int32 and assigns it to the Degree field.
func (o *BTSplineDescription2118AllOf) SetDegree(v int32) {
o.Degree = &v
}
// GetIsPeriodic returns the IsPeriodic field value if set, zero value otherwise.
func (o *BTSplineDescription2118AllOf) GetIsPeriodic() bool {
if o == nil || o.IsPeriodic == nil {
var ret bool
return ret
}
return *o.IsPeriodic
}
// GetIsPeriodicOk returns a tuple with the IsPeriodic field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTSplineDescription2118AllOf) GetIsPeriodicOk() (*bool, bool) {
if o == nil || o.IsPeriodic == nil {
return nil, false
}
return o.IsPeriodic, true
}
// HasIsPeriodic returns a boolean if a field has been set.
func (o *BTSplineDescription2118AllOf) HasIsPeriodic() bool {
if o != nil && o.IsPeriodic != nil {
return true
}
return false
}
// SetIsPeriodic gets a reference to the given bool and assigns it to the IsPeriodic field.
func (o *BTSplineDescription2118AllOf) SetIsPeriodic(v bool) {
o.IsPeriodic = &v
}
// GetIsRational returns the IsRational field value if set, zero value otherwise.
func (o *BTSplineDescription2118AllOf) GetIsRational() bool {
if o == nil || o.IsRational == nil {
var ret bool
return ret
}
return *o.IsRational
}
// GetIsRationalOk returns a tuple with the IsRational field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTSplineDescription2118AllOf) GetIsRationalOk() (*bool, bool) {
if o == nil || o.IsRational == nil {
return nil, false
}
return o.IsRational, true
}
// HasIsRational returns a boolean if a field has been set.
func (o *BTSplineDescription2118AllOf) HasIsRational() bool {
if o != nil && o.IsRational != nil {
return true
}
return false
}
// SetIsRational gets a reference to the given bool and assigns it to the IsRational field.
func (o *BTSplineDescription2118AllOf) SetIsRational(v bool) {
o.IsRational = &v
}
// GetKnots returns the Knots field value if set, zero value otherwise.
func (o *BTSplineDescription2118AllOf) GetKnots() []float64 {
if o == nil || o.Knots == nil {
var ret []float64
return ret
}
return *o.Knots
}
// GetKnotsOk returns a tuple with the Knots field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTSplineDescription2118AllOf) GetKnotsOk() (*[]float64, bool) {
if o == nil || o.Knots == nil {
return nil, false
}
return o.Knots, true
}
// HasKnots returns a boolean if a field has been set.
func (o *BTSplineDescription2118AllOf) HasKnots() bool {
if o != nil && o.Knots != nil {
return true
}
return false
}
// SetKnots gets a reference to the given []float64 and assigns it to the Knots field.
func (o *BTSplineDescription2118AllOf) SetKnots(v []float64) {
o.Knots = &v
}
func (o BTSplineDescription2118AllOf) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.BtType != nil {
toSerialize["btType"] = o.BtType
}
if o.ControlPoints != nil {
toSerialize["controlPoints"] = o.ControlPoints
}
if o.Degree != nil {
toSerialize["degree"] = o.Degree
}
if o.IsPeriodic != nil {
toSerialize["isPeriodic"] = o.IsPeriodic
}
if o.IsRational != nil {
toSerialize["isRational"] = o.IsRational
}
if o.Knots != nil {
toSerialize["knots"] = o.Knots
}
return json.Marshal(toSerialize)
}
type NullableBTSplineDescription2118AllOf struct {
value *BTSplineDescription2118AllOf
isSet bool
}
func (v NullableBTSplineDescription2118AllOf) Get() *BTSplineDescription2118AllOf {
return v.value
}
func (v *NullableBTSplineDescription2118AllOf) Set(val *BTSplineDescription2118AllOf) {
v.value = val
v.isSet = true
}
func (v NullableBTSplineDescription2118AllOf) IsSet() bool {
return v.isSet
}
func (v *NullableBTSplineDescription2118AllOf) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableBTSplineDescription2118AllOf(val *BTSplineDescription2118AllOf) *NullableBTSplineDescription2118AllOf {
return &NullableBTSplineDescription2118AllOf{value: val, isSet: true}
}
func (v NullableBTSplineDescription2118AllOf) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableBTSplineDescription2118AllOf) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | onshape/model_bt_spline_description_2118_all_of.go | 0.758689 | 0.441131 | model_bt_spline_description_2118_all_of.go | starcoder |
package api
func init() {
Swagger.Add("compliance_reporting_stats_stats", `{
"swagger": "2.0",
"info": {
"title": "components/automate-gateway/api/compliance/reporting/stats/stats.proto",
"version": "version not set"
},
"schemes": [
"http",
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/compliance/reporting/stats/failures": {
"post": {
"operationId": "ReadFailures",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/v1Failures"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1Query"
}
}
],
"tags": [
"StatsService"
]
}
},
"/compliance/reporting/stats/profiles": {
"post": {
"summary": "should cover /profiles, profiles/:profile-id/summary, profiles/:profile-id/controls",
"operationId": "ReadProfiles",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/v1Profile"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1Query"
}
}
],
"tags": [
"StatsService"
]
}
},
"/compliance/reporting/stats/summary": {
"post": {
"summary": "should cover /summary, /summary/nodes, /summary/controls",
"operationId": "ReadSummary",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/v1Summary"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1Query"
}
}
],
"tags": [
"StatsService"
]
}
},
"/compliance/reporting/stats/trend": {
"post": {
"summary": "should cover /trend/nodes, /trend/controls",
"operationId": "ReadTrend",
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/v1Trends"
}
}
},
"parameters": [
{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1Query"
}
}
],
"tags": [
"StatsService"
]
}
}
},
"definitions": {
"QueryOrderType": {
"type": "string",
"enum": [
"ASC",
"DESC"
],
"default": "ASC"
},
"v1ControlStats": {
"type": "object",
"properties": {
"control": {
"type": "string"
},
"title": {
"type": "string"
},
"passed": {
"type": "integer",
"format": "int32"
},
"failed": {
"type": "integer",
"format": "int32"
},
"skipped": {
"type": "integer",
"format": "int32"
},
"impact": {
"type": "number",
"format": "float"
}
}
},
"v1ControlsSummary": {
"type": "object",
"properties": {
"failures": {
"type": "integer",
"format": "int32"
},
"majors": {
"type": "integer",
"format": "int32"
},
"minors": {
"type": "integer",
"format": "int32"
},
"criticals": {
"type": "integer",
"format": "int32"
},
"passed": {
"type": "integer",
"format": "int32"
},
"skipped": {
"type": "integer",
"format": "int32"
}
}
},
"v1FailureSummary": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"failures": {
"type": "integer",
"format": "int32"
},
"id": {
"type": "string"
},
"profile": {
"type": "string"
}
}
},
"v1Failures": {
"type": "object",
"properties": {
"profiles": {
"type": "array",
"items": {
"$ref": "#/definitions/v1FailureSummary"
}
},
"platforms": {
"type": "array",
"items": {
"$ref": "#/definitions/v1FailureSummary"
}
},
"controls": {
"type": "array",
"items": {
"$ref": "#/definitions/v1FailureSummary"
}
},
"environments": {
"type": "array",
"items": {
"$ref": "#/definitions/v1FailureSummary"
}
}
}
},
"v1ListFilter": {
"type": "object",
"properties": {
"values": {
"type": "array",
"items": {
"type": "string"
}
},
"type": {
"type": "string"
}
}
},
"v1NodeSummary": {
"type": "object",
"properties": {
"compliant": {
"type": "integer",
"format": "int32"
},
"skipped": {
"type": "integer",
"format": "int32"
},
"noncompliant": {
"type": "integer",
"format": "int32"
},
"high_risk": {
"type": "integer",
"format": "int32"
},
"medium_risk": {
"type": "integer",
"format": "int32"
},
"low_risk": {
"type": "integer",
"format": "int32"
}
}
},
"v1Profile": {
"type": "object",
"properties": {
"profile_list": {
"type": "array",
"items": {
"$ref": "#/definitions/v1ProfileList"
}
},
"profile_summary": {
"$ref": "#/definitions/v1ProfileSummary"
},
"control_stats": {
"type": "array",
"items": {
"$ref": "#/definitions/v1ControlStats"
}
}
}
},
"v1ProfileList": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"id": {
"type": "string"
},
"failures": {
"type": "integer",
"format": "int32"
},
"majors": {
"type": "integer",
"format": "int32"
},
"minors": {
"type": "integer",
"format": "int32"
},
"criticals": {
"type": "integer",
"format": "int32"
},
"passed": {
"type": "integer",
"format": "int32"
},
"skipped": {
"type": "integer",
"format": "int32"
}
}
},
"v1ProfileSummary": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"title": {
"type": "string"
},
"version": {
"type": "string"
},
"license": {
"type": "string"
},
"maintainer": {
"type": "string"
},
"copyright": {
"type": "string"
},
"copyright_email": {
"type": "string"
},
"summary": {
"type": "string"
},
"supports": {
"type": "array",
"items": {
"$ref": "#/definitions/v1Support"
}
},
"stats": {
"$ref": "#/definitions/v1ProfileSummaryStats"
}
}
},
"v1ProfileSummaryStats": {
"type": "object",
"properties": {
"failed": {
"type": "integer",
"format": "int32"
},
"passed": {
"type": "integer",
"format": "int32"
},
"skipped": {
"type": "integer",
"format": "int32"
},
"failed_nodes": {
"type": "integer",
"format": "int32"
},
"total_nodes": {
"type": "integer",
"format": "int32"
}
}
},
"v1Query": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"type": {
"type": "string"
},
"size": {
"type": "integer",
"format": "int32"
},
"interval": {
"type": "integer",
"format": "int32"
},
"filters": {
"type": "array",
"items": {
"$ref": "#/definitions/v1ListFilter"
}
},
"order": {
"$ref": "#/definitions/QueryOrderType"
},
"sort": {
"type": "string"
},
"page": {
"type": "integer",
"format": "int32"
},
"per_page": {
"type": "integer",
"format": "int32"
}
}
},
"v1ReportSummary": {
"type": "object",
"properties": {
"stats": {
"$ref": "#/definitions/v1Stats"
},
"status": {
"type": "string"
},
"duration": {
"type": "number",
"format": "double"
},
"start_date": {
"type": "string"
}
}
},
"v1Stats": {
"type": "object",
"properties": {
"nodes": {
"type": "string",
"format": "int64"
},
"platforms": {
"type": "integer",
"format": "int32"
},
"environments": {
"type": "integer",
"format": "int32"
},
"profiles": {
"type": "integer",
"format": "int32"
}
}
},
"v1Summary": {
"type": "object",
"properties": {
"controls_summary": {
"$ref": "#/definitions/v1ControlsSummary"
},
"node_summary": {
"$ref": "#/definitions/v1NodeSummary"
},
"report_summary": {
"$ref": "#/definitions/v1ReportSummary"
}
}
},
"v1Support": {
"type": "object",
"properties": {
"os_name": {
"type": "string"
},
"os_family": {
"type": "string"
},
"release": {
"type": "string"
},
"inspec_version": {
"type": "string"
},
"platform_name": {
"type": "string"
},
"platform_family": {
"type": "string"
},
"platform": {
"type": "string"
}
}
},
"v1Trend": {
"type": "object",
"properties": {
"report_time": {
"type": "string"
},
"passed": {
"type": "integer",
"format": "int32"
},
"failed": {
"type": "integer",
"format": "int32"
},
"skipped": {
"type": "integer",
"format": "int32"
}
}
},
"v1Trends": {
"type": "object",
"properties": {
"trends": {
"type": "array",
"items": {
"$ref": "#/definitions/v1Trend"
}
}
}
}
}
}
`)
} | components/automate-gateway/api/compliance_reporting_stats_stats.pb.swagger.go | 0.614857 | 0.415077 | compliance_reporting_stats_stats.pb.swagger.go | starcoder |
package flagday
import (
"sync"
"time"
)
var (
jstLocation *time.Location
jstOnce sync.Once
)
// HolidayKind is kind of holiday.
type HolidayKind int
const (
// PublicHoliday means that holiday is public holiday.
PublicHoliday HolidayKind = iota
// NationalHoliday means that holiday is national holiday.
NationalHoliday
// SubstituteHoliday means that holiday is substitute holiday.
SubstituteHoliday
// ImperialRelated means that holiday is Imperial related holiday.
ImperialRelated
)
// Holiday holds public holiday information.
type Holiday interface {
// Def returns definition of holiday.
Def() *Definition
// Year of holiday.
Year() int
// Month of holiday.
Month() int
// Day of holiday.
Day() int
// Name of holiday.
Name() string
// Kind of holiday.
Kind() HolidayKind
// Time is time.Time instance of holiday (JST)
Time() time.Time
// Original is original holiday.
// This field is only set when holiday is substitute holiday.
Original() Holiday
// IsSubstituted returns that this holiday is substituted by substitute holiday.
IsSubstituted() bool
}
type substitutedSetter interface {
SetSubstituted(b bool)
}
type holiday struct {
def *Definition
year int
month int
day int
name string
kind HolidayKind
time time.Time
original Holiday
substituted bool
}
func (d *holiday) Def() *Definition {
return d.def
}
func (d *holiday) Year() int {
return d.year
}
func (d *holiday) Month() int {
return d.month
}
func (d *holiday) Day() int {
return d.day
}
func (d *holiday) Name() string {
return d.name
}
func (d *holiday) Kind() HolidayKind {
return d.kind
}
func (d *holiday) Time() time.Time {
return d.time
}
func (d *holiday) Original() Holiday {
return d.original
}
func (d *holiday) IsSubstituted() bool {
return d.substituted
}
func (d *holiday) SetSubstituted(b bool) {
d.substituted = b
}
// NewHoliday returns new date with time.
func NewHoliday(def *Definition, year, month, day int, name string, kind HolidayKind, original Holiday) Holiday {
return &holiday{
def: def,
year: year,
month: month,
day: day,
name: name,
kind: kind,
time: timeFrom(year, month, day),
original: original,
}
}
func newPublicHoliday(def Definition, year, day int) Holiday {
return NewHoliday(&def, year, def.Month(), day, def.Name(), PublicHoliday, nil)
}
func newNationalHoliday(year, month, day int) Holiday {
return NewHoliday(nil, year, month, day, "国民の休日", NationalHoliday, nil)
}
func newSubstituteHoliday(year, month, day int, original Holiday) Holiday {
return NewHoliday(nil, year, month, day, "振替休日", SubstituteHoliday, original)
}
func newImperialRelatedHoliday(def Definition, year, day int) Holiday {
return NewHoliday(&def, year, def.Month(), day, def.Name(), ImperialRelated, nil)
}
func jst() *time.Location {
jstOnce.Do(func() {
loc, err := time.LoadLocation("Asia/Tokyo")
if err != nil {
loc = time.FixedZone("Asia/Tokyo", 9*60*60)
}
jstLocation = loc
})
return jstLocation
}
func timeFrom(year, month, day int) time.Time {
return time.Date(year, time.Month(month), day, 0, 0, 0, 0, jst())
} | holiday.go | 0.571767 | 0.504944 | holiday.go | starcoder |
package main
import (
"fmt"
"strings"
)
func basics() {
/*
A slice is a
... dynamically-sized, flexible view
... into the elements of an array.
A slice does not store any data, it just describes a section of an underlying array.
*/
// 0 1 2 3 4 5
primes := [6]int{2, 3, 5, 7, 11, 13}
// The type []T is a slice with elements of type T.
// A slice is formed by specifying two indices, a low and high bound, separated by a colon:
// a[low : high] includes the low-st element but exclude the high-st element
var slice1 []int = primes[1:4] // [3 5 7] !!!!!!!!!!!!!!
fmt.Println(slice1)
slice2 := primes[2:6]
slice1[2] = 17
fmt.Println(primes) // [2 3 5 17 11 13]
fmt.Println(slice2) // [5 17 11 13]
colorSlice := []string{"red", "blue", "green"} // this creates an array and then builds a slice that reference it
fmt.Println(colorSlice) // [red blue green]
}
func lengthAndCapacity() {
primes := [6]int{2, 3, 5, 17, 11, 13}
// The default is zero for the low bound and the length of the slice for the high bound.
slice3 := primes[:]
fmt.Println(slice3) // [2 3 5 17 11 13]
slice4 := primes[3:]
fmt.Println(slice4) // [17 11 13]
slice5 := primes[:len(primes)/2]
fmt.Println(slice5) // [2 3 5]
/*
A slice has a length
... the length of a slice is the number of elements it contains.
A slice has a capacity.
... the capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).
*/
fmt.Printf("len(primes)=%d cap(primes)=%d\n", len(primes), cap(primes)) // len(primes)=6 cap(primes)=6
fmt.Printf("len(slice4)=%d cap(slice4)=%d\n", len(slice4), cap(slice4)) // len(slice4)=3 cap(slice4)=3
fmt.Printf("len(slice5)=%d cap(slice5)=%d\n", len(slice5), cap(slice5)) // len(slice5)=3 cap(slice5)=6
// You can extend a slice's length by re-slicing it, ...
slice5 = slice5[:cap(slice5)]
fmt.Printf("len(slice5)=%d cap(slice5)=%d slice5=%v\n", len(slice5), cap(slice5), slice5) // len(slice5)=6 cap(slice5)=6 slice5=[2 3 5 17 11 13]
// ... provided it has sufficient capacity.
// slice5 = slice5[:cap(slice5)+1]
// fmt.Printf("len(slice5)=%d cap(slice5)=%d slice5=%v\n", len(slice5), cap(slice5), slice5) // panic: runtime error: slice bounds out of range [:7] with capacity 6
}
func nilSlices() {
/*
The zero value of a slice is nil.
A nil slice has a length and capacity of 0 and has no underlying array.
*/
var slice []int
fmt.Println(slice, len(slice), cap(slice), slice == nil) // [] 0 0 true
}
func createSliceWithMake() {
/*
Slices can be created with the built-in make function; this is how you create dynamically-sized arrays.
*/
slice := make([]int, 5) // allocates a zeroed array and returns a slice with length and capacity 5
fmt.Println(slice, len(slice), cap(slice)) // [0 0 0 0 0] 5 5
slice = make([]int, 5, 8) // allocates a zeroed array and returns a slice with length 5 and capacity 8
fmt.Println(slice, len(slice), cap(slice)) // [0 0 0 0 0] 5 8
slice = slice[:cap(slice)]
slice[7] = 99
fmt.Println(slice, len(slice), cap(slice)) // [0 0 0 0 0 0 0 99] 8 8
}
func slicesOfslices() {
board := [][]string{
[]string{"__", "__", "__"},
[]string{"__", "__", "__"},
[]string{"__", "__", "__"},
}
board[0][0] = "1A"
board[2][2] = "2A"
board[1][2] = "1B"
board[1][0] = "2B"
board[0][2] = "1C"
for i := 0; i < len(board); i++ {
fmt.Printf("%s\n", strings.Join(board[i], " "))
}
}
func appendingToSlices() {
var s []int // nil slice
printSlice(s)
// Go provides a built-in append to append new elements to a slice
s = append(s, 0)
printSlice(s)
// The slice grows as needed
s = append(s, 1)
printSlice(s)
// We can append a variable number of elements
s = append(s, 2, 3, 4)
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
func main() {
basics()
lengthAndCapacity()
nilSlices()
createSliceWithMake()
slicesOfslices()
appendingToSlices()
} | tour13slices/slices.go | 0.547222 | 0.578895 | slices.go | starcoder |
package kata
import (
"strings"
"unicode"
)
// ----------------------- STORAGE ----------------------------------
// A digit in the problem.
// The digit is a letter in the problem.
// During the calculation the value of the digit will be found.
// value < 0 if the value of the digit is unknown.
type aDigit struct {
name rune
zeroAllowed bool
value int
}
func (digit aDigit) String() string {
switch {
case digit.value >= 0:
return string(digit.name) + "=" + string(digit.value)
case digit.zeroAllowed:
return string(digit.name) + "=?"
default:
return string(digit.name) + ">0"
}
}
// A number in the problem.
// A number is a sequence of digits.
// Weight of digit i is 10^i.
type aNumber []*aDigit
func (num aNumber) String() string {
runes := make([]rune, len(num))
o := len(runes) - 1
for i, d := range num {
if d.value >= 0 {
runes[o-i] = rune('0' + d.value)
} else {
runes[o-i] = d.name
}
}
return string(runes)
}
// The problem has summands and a sum.
// Each digit used in any number is stored only once in the digits.
type aProblem struct {
digits []*aDigit
summands []aNumber
sum aNumber
}
func (prob aProblem) String() string {
var result strings.Builder
for i, s := range prob.summands {
result.WriteString(s.String())
if i < len(prob.summands)-1 {
result.WriteString(" + ")
}
}
result.WriteString(" = ")
result.WriteString(prob.sum.String())
return result.String()
}
// ----------------------- PARSER -----------------------------------
type aToken int8
const (
tokenOperator aToken = iota
tokenSummand
tokenSum
tokenEnd
)
func isLetter(s string) bool {
for _, r := range s {
if !unicode.IsLetter(r) {
return false
}
}
return true
}
func parse(task string) aProblem {
problem := aProblem{
digits: make([]*aDigit, 0, 10),
summands: make([]aNumber, 0, 7),
sum: aNumber{}}
rune2digit := make(map[rune]*aDigit)
nextToken := tokenSummand
for _, w := range strings.Fields(task) {
switch {
case w == "+" && nextToken == tokenOperator:
nextToken = tokenSummand
case w == "=" && nextToken == tokenOperator:
nextToken = tokenSum
case isLetter(w) && (nextToken == tokenSum || nextToken == tokenSummand):
num := make(aNumber, len(w))
for i, r := range w {
d := rune2digit[r]
if d == nil {
d = &aDigit{
name: r,
zeroAllowed: true,
value: -1}
problem.digits = append(problem.digits, d)
rune2digit[r] = d
}
if i == 0 {
d.zeroAllowed = false
}
num[len(w)-1-i] = d
}
if nextToken == tokenSummand {
problem.summands = append(problem.summands, num)
nextToken = tokenOperator
} else {
problem.sum = num
nextToken = tokenEnd
}
default:
panic("invalid problem string")
}
}
if len(problem.digits) > 10 {
panic("more than 10 digits to find")
}
return problem
}
// ----------------------- SOLVER -----------------------------------
type aStepOperation int8
const (
stepTrial aStepOperation = iota
stepCalculate
stepCheck
)
type aStep struct {
operation aStepOperation
operator *aDigit
}
func (step aStep) String() string {
switch step.operation {
case stepTrial:
return "try:" + string(step.operator.name)
case stepCalculate:
return "calc:" + string(step.operator.name)
case stepCheck:
return "check:" + string(step.operator.name)
default:
panic("invalid step operation")
}
}
func plan(prob aProblem) []aStep {
result := make([]aStep, 0, 10)
toFind := make(map[*aDigit]bool, len(prob.digits))
for _, d := range prob.digits {
toFind[d] = true
}
for col := 0; col < len(prob.sum); col++ {
for _, s := range prob.summands {
if len(s) > col {
d := s[col]
if toFind[d] {
toFind[d] = false
result = append(result, aStep{
operation: stepTrial,
operator: d})
}
}
}
d := prob.sum[col]
result = append(result, aStep{operator: d})
if toFind[d] {
result[len(result)-1].operation = stepCalculate
toFind[d] = false
} else {
result[len(result)-1].operation = stepCheck
}
}
if len(prob.digits) > len(result) {
panic("invalid length of plan")
}
return result
}
func solve(prob aProblem, app []aStep) aProblem {
// Array of avaiable digits 0,1,..,9
digits := [10]bool{true, true, true, true, true, true, true, true, true, true}
setValue := func(stepIndex int, v int) {
digits[v] = false
app[stepIndex].operator.value = v
}
backtrack := func(stepIndex int) int {
for goon := true; goon; {
if app[stepIndex].operation != stepCheck {
v := app[stepIndex].operator.value
if v >= 0 {
digits[v] = true
}
app[stepIndex].operator.value = -1
}
stepIndex--
goon = stepIndex > 0 && app[stepIndex].operation != stepTrial
}
return stepIndex
}
calculate := func(digit *aDigit) int {
result := -1
hasValue := true
accu := 0
for col := 0; col < len(prob.sum) && hasValue; col++ {
for _, s := range prob.summands {
if col < len(s) {
accu += s[col].value
hasValue = hasValue && s[col].value >= 0
}
}
if hasValue {
if digit == prob.sum[col] {
result = accu % 10
}
if prob.sum[col].value >= 0 {
hasValue = accu%10 == prob.sum[col].value
}
if !hasValue {
result = -1
}
}
accu /= 10
}
return result
}
// Current step in the plan.
for currentStep := 0; currentStep < len(app); {
switch app[currentStep].operation {
case stepTrial:
// Try next available value or backtrack to the last trial step.
v := app[currentStep].operator.value
if v >= 0 {
digits[v] = true
}
v++
if v == 0 && !app[currentStep].operator.zeroAllowed {
v++
}
for v < len(digits) && !digits[v] {
v++
}
if v < len(digits) {
setValue(currentStep, v)
currentStep++
} else {
currentStep = backtrack(currentStep)
}
case stepCalculate:
// Calculate the value of the digit or backtrack.
v := calculate(app[currentStep].operator)
if v >= 0 && digits[v] && (v > 0 || app[currentStep].operator.zeroAllowed) {
setValue(currentStep, v)
currentStep++
} else {
currentStep = backtrack(currentStep)
}
case stepCheck:
// Check the value of the digit or backtrack.
v := calculate(app[currentStep].operator)
if v >= 0 {
currentStep++
} else {
currentStep = backtrack(currentStep)
}
default:
panic("invalid operation code in plan")
}
}
return prob
}
// ----------------------- MAIN -------------------------------------
func Alphametics(task string) string {
// Parse the problem.
problem := parse(task)
// Plan the approach.
approach := plan(problem)
// Solve the problem.
problem = solve(problem, approach)
// Return the solution.
return problem.String()
} | 3_kyu/Alphametics_Solver.go | 0.531453 | 0.52275 | Alphametics_Solver.go | starcoder |
// Package geomfn contains functions that are used for geometry-based builtins.
package geomfn
import "github.com/twpayne/go-geom"
// applyCoordFunc applies a function on src to copy onto dst.
// Both slices represent a single Coord within the FlatCoord array.
type applyCoordFunc func(l geom.Layout, dst []float64, src []float64) error
// applyOnCoords applies the applyCoordFunc on each coordinate, returning
// a new array for the coordinates.
func applyOnCoords(flatCoords []float64, l geom.Layout, f applyCoordFunc) ([]float64, error) {
newCoords := make([]float64, len(flatCoords))
for i := 0; i < len(flatCoords); i += l.Stride() {
if err := f(l, newCoords[i:i+l.Stride()], flatCoords[i:i+l.Stride()]); err != nil {
return nil, err
}
}
return newCoords, nil
}
// applyOnCoordsForGeomT applies the applyCoordFunc on each coordinate in the geom.T,
// returning a copied over geom.T.
func applyOnCoordsForGeomT(g geom.T, f applyCoordFunc) (geom.T, error) {
if geomCollection, ok := g.(*geom.GeometryCollection); ok {
return applyOnCoordsForGeometryCollection(geomCollection, f)
}
newCoords, err := applyOnCoords(g.FlatCoords(), g.Layout(), f)
if err != nil {
return nil, err
}
switch t := g.(type) {
case *geom.Point:
g = geom.NewPointFlat(t.Layout(), newCoords).SetSRID(g.SRID())
case *geom.LineString:
g = geom.NewLineStringFlat(t.Layout(), newCoords).SetSRID(g.SRID())
case *geom.Polygon:
g = geom.NewPolygonFlat(t.Layout(), newCoords, t.Ends()).SetSRID(g.SRID())
case *geom.MultiPoint:
g = geom.NewMultiPointFlat(t.Layout(), newCoords, geom.NewMultiPointFlatOptionWithEnds(t.Ends())).SetSRID(g.SRID())
case *geom.MultiLineString:
g = geom.NewMultiLineStringFlat(t.Layout(), newCoords, t.Ends()).SetSRID(g.SRID())
case *geom.MultiPolygon:
g = geom.NewMultiPolygonFlat(t.Layout(), newCoords, t.Endss()).SetSRID(g.SRID())
default:
return nil, geom.ErrUnsupportedType{Value: g}
}
return g, nil
}
// applyOnCoordsForGeometryCollection applies the applyCoordFunc on each coordinate
// inside a geometry collection, returning a copied over geom.T.
func applyOnCoordsForGeometryCollection(
geomCollection *geom.GeometryCollection, f applyCoordFunc,
) (*geom.GeometryCollection, error) {
res := geom.NewGeometryCollection()
for _, subG := range geomCollection.Geoms() {
subGeom, err := applyOnCoordsForGeomT(subG, f)
if err != nil {
return nil, err
}
if err := res.Push(subGeom); err != nil {
return nil, err
}
}
return res, nil
}
// removeConsecutivePointsFromGeomT removes duplicate consecutive points from a given geom.T.
// If the resultant geometry is invalid, it will be EMPTY.
func removeConsecutivePointsFromGeomT(t geom.T) (geom.T, error) {
if t.Empty() {
return t, nil
}
switch t := t.(type) {
case *geom.Point, *geom.MultiPoint:
return t, nil
case *geom.LineString:
newCoords := make([]float64, 0, len(t.FlatCoords()))
newCoords = append(newCoords, t.Coord(0)...)
for i := 1; i < t.NumCoords(); i++ {
if !t.Coord(i).Equal(t.Layout(), t.Coord(i-1)) {
newCoords = append(newCoords, t.Coord(i)...)
}
}
if len(newCoords) < t.Stride()*2 {
newCoords = newCoords[:0]
}
return geom.NewLineStringFlat(t.Layout(), newCoords).SetSRID(t.SRID()), nil
case *geom.Polygon:
ret := geom.NewPolygon(t.Layout()).SetSRID(t.SRID())
for ringIdx := 0; ringIdx < t.NumLinearRings(); ringIdx++ {
ring := t.LinearRing(ringIdx)
newCoords := make([]float64, 0, len(ring.FlatCoords()))
newCoords = append(newCoords, ring.Coord(0)...)
for i := 1; i < ring.NumCoords(); i++ {
if !ring.Coord(i).Equal(ring.Layout(), ring.Coord(i-1)) {
newCoords = append(newCoords, ring.Coord(i)...)
}
}
if len(newCoords) < t.Stride()*4 {
// If the outer ring is invalid, the polygon should be entirely empty.
if ringIdx == 0 {
return ret, nil
}
// Ignore any holes.
continue
}
if err := ret.Push(geom.NewLinearRingFlat(t.Layout(), newCoords)); err != nil {
return nil, err
}
}
return ret, nil
case *geom.MultiLineString:
ret := geom.NewMultiLineString(t.Layout()).SetSRID(t.SRID())
for i := 0; i < t.NumLineStrings(); i++ {
ls, err := removeConsecutivePointsFromGeomT(t.LineString(i))
if err != nil {
return nil, err
}
if ls.Empty() {
continue
}
if err := ret.Push(ls.(*geom.LineString)); err != nil {
return nil, err
}
}
return ret, nil
case *geom.MultiPolygon:
ret := geom.NewMultiPolygon(t.Layout()).SetSRID(t.SRID())
for i := 0; i < t.NumPolygons(); i++ {
p, err := removeConsecutivePointsFromGeomT(t.Polygon(i))
if err != nil {
return nil, err
}
if p.Empty() {
continue
}
if err := ret.Push(p.(*geom.Polygon)); err != nil {
return nil, err
}
}
return ret, nil
case *geom.GeometryCollection:
ret := geom.NewGeometryCollection().SetSRID(t.SRID())
for i := 0; i < t.NumGeoms(); i++ {
g, err := removeConsecutivePointsFromGeomT(t.Geom(i))
if err != nil {
return nil, err
}
if g.Empty() {
continue
}
if err := ret.Push(g); err != nil {
return nil, err
}
}
return ret, nil
}
return nil, geom.ErrUnsupportedType{Value: t}
} | pkg/geo/geomfn/geomfn.go | 0.762247 | 0.516413 | geomfn.go | starcoder |
package stats
import (
"math"
"github.com/jgbaldwinbrown/go-moremath/mathx"
)
// HypergeometicDist is a hypergeometric distribution.
type HypergeometicDist struct {
// N is the size of the population. N >= 0.
N int
// K is the number of successes in the population. 0 <= K <= N.
K int
// Draws is the number of draws from the population. This is
// usually written "n", but is called Draws here because of
// limitations on Go identifier naming. 0 <= Draws <= N.
Draws int
}
// PMF is the probability of getting exactly int(k) successes in
// d.Draws draws with replacement from a population of size d.N that
// contains exactly d.K successes.
func (d HypergeometicDist) PMF(k float64) float64 {
ki := int(math.Floor(k))
l, h := d.bounds()
if ki < l || ki > h {
return 0
}
return d.pmf(ki)
}
func (d HypergeometicDist) pmf(k int) float64 {
return math.Exp(mathx.Lchoose(d.K, k) + mathx.Lchoose(d.N-d.K, d.Draws-k) - mathx.Lchoose(d.N, d.Draws))
}
// CDF is the probability of getting int(k) or fewer successes in
// d.Draws draws with replacement from a population of size d.N that
// contains exactly d.K successes.
func (d HypergeometicDist) CDF(k float64) float64 {
// Based on Klotz, A Computational Approach to Statistics.
ki := int(math.Floor(k))
l, h := d.bounds()
if ki < l {
return 0
} else if ki >= h {
return 1
}
// Use symmetry to compute the smaller sum.
flip := false
if ki > (d.Draws+1)/(d.N+1)*(d.K+1) {
flip = true
ki = d.K - ki - 1
d.Draws = d.N - d.Draws
}
p := d.pmf(ki) * d.sum(ki)
if flip {
p = 1 - p
}
return p
}
func (d HypergeometicDist) sum(k int) float64 {
const epsilon = 1e-14
sum, ak := 1.0, 1.0
L := maxint(0, d.Draws+d.K-d.N)
for dk := 1; dk <= k-L && ak/sum > epsilon; dk++ {
ak *= float64(1+k-dk) / float64(d.Draws-k+dk)
ak *= float64(d.N-d.K-d.Draws+k+1-dk) / float64(d.K-k+dk)
sum += ak
}
return sum
}
func (d HypergeometicDist) bounds() (int, int) {
return maxint(0, d.Draws+d.K-d.N), minint(d.Draws, d.K)
}
func (d HypergeometicDist) Bounds() (float64, float64) {
l, h := d.bounds()
return float64(l), float64(h)
}
func (d HypergeometicDist) Step() float64 {
return 1
}
func (d HypergeometicDist) Mean() float64 {
return float64(d.Draws*d.K) / float64(d.N)
}
func (d HypergeometicDist) Variance() float64 {
return float64(d.Draws*d.K*(d.N-d.K)*(d.N-d.Draws)) /
float64(d.N*d.N*(d.N-1))
} | stats/hypergdist.go | 0.821331 | 0.619097 | hypergdist.go | starcoder |
package ast
import (
"fmt"
"strings"
)
func NewStringArrayNode(values []string) *StringArrayNode {
result := &StringArrayNode{}
for _, val := range values {
result.values = append(result.values, &StringConstNode{value: val})
}
return result
}
// StringArrayNode encapsulates a string array
type StringArrayNode struct {
values []StringNode
}
func (node *StringArrayNode) String() string {
builder := &strings.Builder{}
builder.WriteString("[")
if len(node.values) > 0 {
builder.WriteString(node.values[0].String())
for _, child := range node.values[1:] {
builder.WriteString(", ")
builder.WriteString(child.String())
}
}
builder.WriteString("]")
return builder.String()
}
func (*StringArrayNode) GetType() NodeType {
return NodeTypeOther
}
func (node *StringArrayNode) Accept(visitor Visitor) {
visitor.VisitStringArrayNodeStart(node)
for _, child := range node.values {
child.Accept(visitor)
}
visitor.VisitStringArrayNodeEnd(node)
}
func (node *StringArrayNode) AsStringArray() *StringArrayNode {
return node
}
func (node *StringArrayNode) IsConst() bool {
return true
}
// Float64ArrayNode encapsulates a float64 array
type Float64ArrayNode struct {
values []Float64Node
}
func (node *Float64ArrayNode) String() string {
builder := &strings.Builder{}
builder.WriteString("[")
if len(node.values) > 0 {
builder.WriteString(node.values[0].String())
for _, child := range node.values[1:] {
builder.WriteString(", ")
builder.WriteString(child.String())
}
}
builder.WriteString("]")
return builder.String()
}
func (node *Float64ArrayNode) GetType() NodeType {
return NodeTypeOther
}
func (node *Float64ArrayNode) Accept(visitor Visitor) {
visitor.VisitFloat64ArrayNodeStart(node)
for _, child := range node.values {
child.Accept(visitor)
}
visitor.VisitFloat64ArrayNodeEnd(node)
}
func (node *Float64ArrayNode) AsStringArray() *StringArrayNode {
result := &StringArrayNode{}
for _, child := range node.values {
result.values = append(result.values, child)
}
return result
}
func (node *Float64ArrayNode) IsConst() bool {
return true
}
// Int64ArrayNode encapsulates an int64 array
type Int64ArrayNode struct {
values []Int64Node
}
func (node *Int64ArrayNode) String() string {
builder := &strings.Builder{}
builder.WriteString("[")
if len(node.values) > 0 {
builder.WriteString(node.values[0].String())
for _, child := range node.values[1:] {
builder.WriteString(", ")
builder.WriteString(child.String())
}
}
builder.WriteString("]")
return builder.String()
}
func (node *Int64ArrayNode) GetType() NodeType {
return NodeTypeOther
}
func (node *Int64ArrayNode) ToFloat64ArrayNode() *Float64ArrayNode {
result := &Float64ArrayNode{}
for _, intNode := range node.values {
result.values = append(result.values, intNode.ToFloat64())
}
return result
}
func (node *Int64ArrayNode) Accept(visitor Visitor) {
visitor.VisitInt64ArrayNodeStart(node)
for _, child := range node.values {
child.Accept(visitor)
}
visitor.VisitInt64ArrayNodeEnd(node)
}
func (node *Int64ArrayNode) AsStringArray() *StringArrayNode {
result := &StringArrayNode{}
for _, child := range node.values {
result.values = append(result.values, child)
}
return result
}
func (node *Int64ArrayNode) IsConst() bool {
return true
}
// DatetimeArrayNode encapsulates a datetime array
type DatetimeArrayNode struct {
values []DatetimeNode
}
func (node *DatetimeArrayNode) String() string {
builder := &strings.Builder{}
builder.WriteString("[")
if len(node.values) > 0 {
builder.WriteString(node.values[0].String())
for _, child := range node.values[1:] {
builder.WriteString(", ")
builder.WriteString(child.String())
}
}
builder.WriteString("]")
return builder.String()
}
func (node *DatetimeArrayNode) GetType() NodeType {
return NodeTypeOther
}
func (node *DatetimeArrayNode) Accept(visitor Visitor) {
visitor.VisitDatetimeArrayNodeStart(node)
for _, child := range node.values {
child.Accept(visitor)
}
visitor.VisitDatetimeArrayNodeEnd(node)
}
func (node *DatetimeArrayNode) IsConst() bool {
return true
}
type InStringArrayExprNode struct {
left StringNode
right *StringArrayNode
}
func (node *InStringArrayExprNode) String() string {
return fmt.Sprintf("%v in %v", node.left, node.right)
}
func (*InStringArrayExprNode) GetType() NodeType {
return NodeTypeBool
}
func (node *InStringArrayExprNode) EvalBool(s Symbols) bool {
left := node.left.EvalString(s)
for _, rightNode := range node.right.values {
right := rightNode.EvalString(s)
if left != nil && right != nil {
if *left == *right {
return true
}
}
}
return false
}
func (node *InStringArrayExprNode) Accept(visitor Visitor) {
visitor.VisitInStringArrayExprNodeStart(node)
node.left.Accept(visitor)
node.right.Accept(visitor)
visitor.VisitInStringArrayExprNodeEnd(node)
}
func (node *InStringArrayExprNode) IsConst() bool {
return false
}
type InInt64ArrayExprNode struct {
left Int64Node
right *Int64ArrayNode
}
func (node *InInt64ArrayExprNode) String() string {
return fmt.Sprintf("%v in %v", node.left, node.right)
}
func (node *InInt64ArrayExprNode) GetType() NodeType {
return NodeTypeBool
}
func (node *InInt64ArrayExprNode) EvalBool(s Symbols) bool {
left := node.left.EvalInt64(s)
for _, rightNode := range node.right.values {
right := rightNode.EvalInt64(s)
if left != nil && right != nil {
if *left == *right {
return true
}
}
}
return false
}
func (node *InInt64ArrayExprNode) Accept(visitor Visitor) {
visitor.VisitInInt64ArrayExprNodeStart(node)
node.left.Accept(visitor)
node.right.Accept(visitor)
visitor.VisitInInt64ArrayExprNodeEnd(node)
}
func (node *InInt64ArrayExprNode) IsConst() bool {
return false
}
type InFloat64ArrayExprNode struct {
left Float64Node
right *Float64ArrayNode
}
func (node *InFloat64ArrayExprNode) String() string {
return fmt.Sprintf("%v in %v", node.left, node.right)
}
func (node *InFloat64ArrayExprNode) GetType() NodeType {
return NodeTypeBool
}
func (node *InFloat64ArrayExprNode) EvalBool(s Symbols) bool {
left := node.left.EvalFloat64(s)
for _, rightNode := range node.right.values {
right := rightNode.EvalFloat64(s)
if left != nil && right != nil {
if *left == *right {
return true
}
}
}
return false
}
func (node *InFloat64ArrayExprNode) Accept(visitor Visitor) {
visitor.VisitInFloat64ArrayExprNodeStart(node)
node.left.Accept(visitor)
node.right.Accept(visitor)
visitor.VisitInFloat64ArrayExprNodeEnd(node)
}
func (node *InFloat64ArrayExprNode) IsConst() bool {
return false
}
type InDatetimeArrayExprNode struct {
left DatetimeNode
right *DatetimeArrayNode
}
func (node *InDatetimeArrayExprNode) String() string {
return fmt.Sprintf("%v in %v", node.left, node.right)
}
func (*InDatetimeArrayExprNode) GetType() NodeType {
return NodeTypeBool
}
func (node *InDatetimeArrayExprNode) EvalBool(s Symbols) bool {
left := node.left.EvalDatetime(s)
for _, rightNode := range node.right.values {
right := rightNode.EvalDatetime(s)
if left != nil && right != nil {
if left.Equal(*right) {
return true
}
}
}
return false
}
func (node *InDatetimeArrayExprNode) Accept(visitor Visitor) {
visitor.VisitInDatetimeArrayExprNodeStart(node)
node.left.Accept(visitor)
node.right.Accept(visitor)
visitor.VisitInDatetimeArrayExprNodeEnd(node)
}
func (node *InDatetimeArrayExprNode) IsConst() bool {
return false
} | storage/ast/node_arrays.go | 0.740456 | 0.443661 | node_arrays.go | starcoder |
package drawille
import (
"fmt"
"math"
)
// Braille chars start at 0x2800
var brailleStartOrdinal = 0x2800
func internalPosition(n, base int) int {
if n >= 0 {
return n % base
}
result := n % base
if result == 0 {
return -base
}
return result
}
func getDot(y, x int, inverse bool) int {
y = internalPosition(y, 4)
x = internalPosition(x, 2)
/* x>=0 && y>=0 && !inverse */
if y == 0 && x == 0 && !inverse {
return 0x1
}
if y == 1 && x == 0 && !inverse {
return 0x2
}
if y == 2 && x == 0 && !inverse {
return 0x4
}
if y == 3 && x == 0 && !inverse {
return 0x40
}
if y == 0 && x == 1 && !inverse {
return 0x8
}
if y == 1 && x == 1 && !inverse {
return 0x10
}
if y == 2 && x == 1 && !inverse {
return 0x20
}
if y == 3 && x == 1 && !inverse {
return 0x80
}
/* x>=0 && y>=0 && inverse */
if y == 0 && x == 0 && inverse {
return 0x40
}
if y == 1 && x == 0 && inverse {
return 0x4
}
if y == 2 && x == 0 && inverse {
return 0x2
}
if y == 3 && x == 0 && inverse {
return 0x1
}
if y == 0 && x == 1 && inverse {
return 0x80
}
if y == 1 && x == 1 && inverse {
return 0x20
}
if y == 2 && x == 1 && inverse {
return 0x10
}
if y == 3 && x == 1 && inverse {
return 0x8
}
/* x<0 && y<0 && !inverse */
if y == -1 && x == -1 && !inverse {
return 0x80
}
if y == -2 && x == -1 && !inverse {
return 0x20
}
if y == -3 && x == -1 && !inverse {
return 0x10
}
if y == -4 && x == -1 && !inverse {
return 0x8
}
if y == -1 && x == -2 && !inverse {
return 0x40
}
if y == -2 && x == -2 && !inverse {
return 0x4
}
if y == -3 && x == -2 && !inverse {
return 0x2
}
if y == -4 && x == -2 && !inverse {
return 0x1
}
/* x<0 && y<0 && inverse */
if y == -1 && x == -1 && inverse {
return 0x8
}
if y == -2 && x == -1 && inverse {
return 0x10
}
if y == -3 && x == -1 && inverse {
return 0x20
}
if y == -4 && x == -1 && inverse {
return 0x80
}
if y == -1 && x == -2 && inverse {
return 0x1
}
if y == -2 && x == -2 && inverse {
return 0x2
}
if y == -3 && x == -2 && inverse {
return 0x4
}
if y == -4 && x == -2 && inverse {
return 0x40
}
/* x>=0 && y<0 && !inverse */
if y == -1 && x == 0 && !inverse {
return 0x40
}
if y == -2 && x == 0 && !inverse {
return 0x4
}
if y == -3 && x == 0 && !inverse {
return 0x2
}
if y == -4 && x == 0 && !inverse {
return 0x1
}
if y == -1 && x == 1 && !inverse {
return 0x80
}
if y == -2 && x == 1 && !inverse {
return 0x20
}
if y == -3 && x == 1 && !inverse {
return 0x10
}
if y == -4 && x == 1 && !inverse {
return 0x8
}
/* x>=0 && y<0 && inverse */
if y == -1 && x == 0 && inverse {
return 0x1
}
if y == -2 && x == 0 && inverse {
return 0x2
}
if y == -3 && x == 0 && inverse {
return 0x4
}
if y == -4 && x == 0 && inverse {
return 0x40
}
if y == -1 && x == 1 && inverse {
return 0x8
}
if y == -2 && x == 1 && inverse {
return 0x10
}
if y == -3 && x == 1 && inverse {
return 0x20
}
if y == -4 && x == 1 && inverse {
return 0x80
}
/* x<0 && y>=0 && !inverse */
if y == 0 && x == -1 && !inverse {
return 0x8
}
if y == 1 && x == -1 && !inverse {
return 0x10
}
if y == 2 && x == -1 && !inverse {
return 0x20
}
if y == 3 && x == -1 && !inverse {
return 0x80
}
if y == 0 && x == -2 && !inverse {
return 0x1
}
if y == 1 && x == -2 && !inverse {
return 0x2
}
if y == 2 && x == -2 && !inverse {
return 0x4
}
if y == 3 && x == -2 && !inverse {
return 0x40
}
/* x<0 && y>=0 && inverse */
if y == 0 && x == -1 && inverse {
return 0x80
}
if y == 1 && x == -1 && inverse {
return 0x20
}
if y == 2 && x == -1 && inverse {
return 0x10
}
if y == 3 && x == -1 && inverse {
return 0x8
}
if y == 0 && x == -2 && inverse {
return 0x40
}
if y == 1 && x == -2 && inverse {
return 0x4
}
if y == 2 && x == -2 && inverse {
return 0x2
}
if y == 3 && x == -2 && inverse {
return 0x1
}
panic(fmt.Sprintf("Unknown values: y=%d x=%d inverse=%t", y, x, inverse))
}
func externalPosition(n, base int) int {
return int(math.Floor(float64(n) / float64(base)))
}
// Convert x,y to cols, rows
func getPos(x, y int) (int, int) {
c := externalPosition(x, 2)
r := externalPosition(y, 4)
return c, r
}
type Canvas struct {
LineEnding string
Inverse bool
chars map[int]map[int]int
}
// Make a new canvas
func NewCanvas() Canvas {
c := Canvas{LineEnding: "\n", Inverse: false}
c.Clear()
return c
}
func (c Canvas) MaxY() int {
max := 0
for k, _ := range c.chars {
if k > max {
max = k
}
}
return max * 4
}
func (c Canvas) MinY() int {
min := 0
for k, _ := range c.chars {
if k < min {
min = k
}
}
return min * 4
}
func (c Canvas) MaxX() int {
max := 0
for _, v := range c.chars {
for k, _ := range v {
if k > max {
max = k
}
}
}
return max * 2
}
func (c Canvas) MinX() int {
min := 0
for _, v := range c.chars {
for k, _ := range v {
if k < min {
min = k
}
}
}
return min * 2
}
// Clear all pixels
func (c *Canvas) Clear() {
c.chars = make(map[int]map[int]int)
}
// Set a pixel of c
func (c *Canvas) Set(x, y int) {
col, row := getPos(x, y)
if m := c.chars[row]; m == nil {
c.chars[row] = make(map[int]int)
}
val := c.chars[row][col]
mapv := getDot(y, x, c.Inverse)
c.chars[row][col] = val | mapv
}
// Unset a pixel of c
func (c *Canvas) UnSet(x, y int) {
col, row := getPos(x, y)
if m := c.chars[row]; m == nil {
c.chars[row] = make(map[int]int)
}
c.chars[row][col] &^= getDot(y, x, c.Inverse)
}
// Toggle a point
func (c *Canvas) Toggle(x, y int) {
col, row := getPos(x, y)
if m := c.chars[row]; m == nil {
c.chars[row] = make(map[int]int)
}
c.chars[row][col] ^= getDot(y, x, c.Inverse)
}
// Set text to the given coordinates
func (c *Canvas) SetText(x, y int, text string) {
col, row := getPos(x, y)
if m := c.chars[row]; m == nil {
c.chars[row] = make(map[int]int)
}
for i, char := range text {
c.chars[row][col+i] = int(char) - brailleStartOrdinal
}
}
// Get pixel at the given coordinates
func (c Canvas) Get(x, y int) bool {
dot := getDot(y, x, c.Inverse)
col, row := getPos(x, y)
char := c.chars[row][col]
return (char & dot) != 0
}
// Get character at the given screen coordinates
func (c Canvas) GetScreenCharacter(x, y int) rune {
return rune(c.chars[y][x] + brailleStartOrdinal)
}
// Get character for the given pixel
func (c Canvas) GetCharacter(x, y int) rune {
return c.GetScreenCharacter(x/4, y/4)
}
// Retrieve the rows from a given view
func (c Canvas) Rows(minX, minY, maxX, maxY int) []string {
minRow, maxRow := minY/4, maxY/4
minCol, maxCol := minX/2, maxX/2
txts := make([]string, 0)
if c.Inverse {
for row := maxRow; row >= minRow; row-- {
txts = append(txts, c.line(row, minCol, maxCol))
}
} else {
for row := minRow; row <= maxRow; row++ {
txts = append(txts, c.line(row, minCol, maxCol))
}
}
return txts
}
func (c Canvas) line(row, minCol, maxCol int) string {
txt := []rune{}
for col := minCol; col <= maxCol; col++ {
char := c.chars[row][col]
txt = append(txt, rune(char+brailleStartOrdinal))
}
return string(txt)
}
// Retrieve a string representation of the frame at the given parameters
func (c Canvas) Frame(minX, minY, maxX, maxY int) string {
var txt string
for _, row := range c.Rows(minX, minY, maxX, maxY) {
txt += row
txt += c.LineEnding
}
return txt
}
func (c Canvas) String() string {
return c.Frame(c.MinX(), c.MinY(), c.MaxX(), c.MaxY())
}
func (c *Canvas) DrawLine(x1, y1, x2, y2 float64) {
xdiff := math.Abs(x1 - x2)
ydiff := math.Abs(y2 - y1)
var xdir, ydir float64
if x1 <= x2 {
xdir = 1
} else {
xdir = -1
}
if y1 <= y2 {
ydir = 1
} else {
ydir = -1
}
r := math.Max(xdiff, ydiff)
for i := 0; i < round(r)+1; i = i + 1 {
x, y := x1, y1
if ydiff != 0 {
y += (float64(i) * ydiff) / (r * ydir)
}
if xdiff != 0 {
x += (float64(i) * xdiff) / (r * xdir)
}
c.Toggle(round(x), round(y))
}
}
func (c *Canvas) DrawPolygon(center_x, center_y, sides, radius float64) {
degree := 360 / sides
for n := 0; n < int(sides); n = n + 1 {
a := float64(n) * degree
b := float64(n+1) * degree
x1 := (center_x + (math.Cos(radians(a)) * (radius/2 + 1)))
y1 := (center_y + (math.Sin(radians(a)) * (radius/2 + 1)))
x2 := (center_x + (math.Cos(radians(b)) * (radius/2 + 1)))
y2 := (center_y + (math.Sin(radians(b)) * (radius/2 + 1)))
c.DrawLine(x1, y1, x2, y2)
}
}
func radians(d float64) float64 {
return d * (math.Pi / 180)
}
func round(x float64) int {
return int(x + 0.5)
} | vendor/github.com/Kerrigan29a/drawille-go/drawille.go | 0.536799 | 0.564999 | drawille.go | starcoder |
package keys
// All returns a new key range matching all keys
func All() Range {
return Range{}
}
// Range represents all keys such that
// k >= Min and k < Max
// If Min = nil that indicates the start of all keys
// If Max = nil that indicatese the end of all keys
// If multiple modifiers are called on a range the end
// result is effectively the same as ANDing all the
// restrictions.
type Range struct {
Min []byte
Max []byte
ns []byte
}
// Eq confines the range to just key k
func (r Range) Eq(k []byte) Range {
if k == nil {
return r
}
return r.Gte(k).Lte(k)
}
// Gt confines the range to keys that are
// greater than k
func (r Range) Gt(k []byte) Range {
if k == nil {
return r
}
return r.refineMin(Next(k))
}
// Gte confines the range to keys that are
// greater than or equal to k
func (r Range) Gte(k []byte) Range {
if k == nil {
return r
}
return r.refineMin(k)
}
// Lt confines the range to keys that are
// less than k
func (r Range) Lt(k []byte) Range {
if k == nil {
return r
}
return r.refineMax(k)
}
// Lte confines the range to keys that are
// less than or equal to k
func (r Range) Lte(k []byte) Range {
if k == nil {
return r
}
return r.refineMax(Next(k))
}
// Prefix confines the range to keys that
// have the prefix k, excluding k itself
func (r Range) Prefix(k []byte) Range {
if k == nil {
return r
}
return r.Gt(k).Lt(Inc(k))
}
// Namespace namespaces keys in the range with
// to keys with the prefix ns. Subsequent modifier
// methods will keep keys within this namespace.
func (r Range) Namespace(ns []byte) Range {
if ns == nil {
return r
}
r.Min = prefix(r.Min, ns)
if r.Max == nil {
r.Max = Inc(ns)
} else {
r.Max = prefix(r.Max, ns)
}
r.ns = append(r.ns, ns...)
return r
}
// Contains returns true if the range contains
// key
func (r Range) Contains(key Key) bool {
if r.Min != nil && Compare(key, r.Min) < 0 {
return false
}
if r.Max != nil && Compare(key, r.Max) >= 0 {
return false
}
return true
}
func (r Range) refineMin(min []byte) Range {
if len(r.ns) > 0 {
min = prefix(min, r.ns)
}
if Compare(min, r.Min) <= 0 {
return r
}
r.Min = min
return r
}
func (r Range) refineMax(max []byte) Range {
if len(r.ns) > 0 {
if max == nil {
max = Inc(r.ns)
} else {
max = prefix(max, r.ns)
}
}
if r.Max != nil && Compare(max, r.Max) >= 0 {
return r
}
r.Max = max
return r
}
// prefix appends k to p
func prefix(k []byte, p []byte) []byte {
if len(k) == 0 && len(p) == 0 {
return k
}
prefixedK := make([]byte, 0, len(p)+len(k))
prefixedK = append(prefixedK, p...)
prefixedK = append(prefixedK, k...)
return prefixedK
} | storage/kv/keys/range.go | 0.840324 | 0.479016 | range.go | starcoder |
package x86_64
/*
Instructions
The below instructions implement a simple Instruction interface that allows
them to be combined, optimised and encoded into machine code.
x86_64 is a bit interesting in that instructions with different sets of
operands might require subtly different machine code opcodes, even though
they do the same thing functionally speaking, so the below instructions
make use of a thing called OpcodeMaps that will match the given arguments
to an appropriate opcode. For more on OpcodeMaps see asm/opcodes/
*/
import (
"github.com/bspaans/jit-compiler/asm/x86_64/encoding"
"github.com/bspaans/jit-compiler/asm/x86_64/opcodes"
"github.com/bspaans/jit-compiler/lib"
)
func ADD(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("add", opcodes.ADD, 2, dest, src)
}
func AND(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("and", opcodes.AND, 2, dest, src)
}
func CALL(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("call", opcodes.CALL, 1, dest)
}
func CMP(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("cmp", opcodes.CMP, 2, dest, src)
}
func CMP_immediate(v uint64, dest lib.Operand) lib.Instruction {
if reg, ok := dest.(*encoding.Register); ok && reg.Width() == lib.BYTE {
return CMP(encoding.Uint8(v), dest)
}
return opcodes.OpcodesToInstruction("cmp", opcodes.CMP, 2, dest, encoding.Uint32(v))
}
// Convert signed integer to scalar double-precision floating point (float64)
func CVTSI2SD(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("cvtsi2sd", opcodes.CVTSI2SD, 2, dest, src)
}
// Convert double precision float to signed integer
func CVTTSD2SI(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("cvttsd2si", opcodes.CVTTSD2SI, 2, dest, src)
}
// Convert Byte to Word; al:ah = sign extend(ah)
func CBW() lib.Instruction {
return opcodes.OpcodesToInstruction("cbw", []*encoding.Opcode{opcodes.CBW}, 0)
}
// Convert Word to Doubleword; dx:ax = sign extend(ax)
func CWD() lib.Instruction {
return opcodes.OpcodesToInstruction("cwd", []*encoding.Opcode{opcodes.CWD}, 0)
}
// Convert Double word to Quadword; edx:eax = sign extend(eax)
func CDQ() lib.Instruction {
return opcodes.OpcodesToInstruction("cdq", []*encoding.Opcode{opcodes.CDQ}, 0)
}
// Convert Quad word to double quad word; rdx:rax = sign extend(rax)
func CQO() lib.Instruction {
return opcodes.OpcodesToInstruction("cqo", []*encoding.Opcode{opcodes.CQO}, 0)
}
func DEC(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("dec", opcodes.DEC, 1, dest)
}
func DIV(src lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("div", opcodes.DIV, 1, src)
}
func IDIV1(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("div", opcodes.IDIV1, 1, dest)
}
func IDIV2(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("div", opcodes.IDIV2, 2, dest, src)
}
func INC(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("inc", opcodes.INC, 1, dest)
}
func JA(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("ja", opcodes.JA, 1, dest)
}
func JAE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jae", opcodes.JAE, 1, dest)
}
func JB(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jb", opcodes.JB, 1, dest)
}
func JBE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jbe", opcodes.JBE, 1, dest)
}
func JE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("je", opcodes.JE, 1, dest)
}
func JG(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jg", opcodes.JG, 1, dest)
}
func JGE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jge", opcodes.JGE, 1, dest)
}
func JL(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jl", opcodes.JL, 1, dest)
}
func JLE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jle", opcodes.JLE, 1, dest)
}
func JNA(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jna", opcodes.JNA, 1, dest)
}
func JNAE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jnae", opcodes.JNAE, 1, dest)
}
func JNB(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jnb", opcodes.JNB, 1, dest)
}
func JNBE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jnbe", opcodes.JNBE, 1, dest)
}
func JNE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jne", opcodes.JNE, 1, dest)
}
func JNG(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jng", opcodes.JNG, 1, dest)
}
func JNGE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jnge", opcodes.JNGE, 1, dest)
}
func JNL(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jnl", opcodes.JNL, 1, dest)
}
func JNLE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jnle", opcodes.JNLE, 1, dest)
}
func JMP(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("jmp", opcodes.JMP, 1, dest)
}
func LEA(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("lea", opcodes.LEA, 2, dest, src)
}
func MOV(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("mov", opcodes.MOV, 2, dest, src)
}
func MOV_immediate(v uint64, dest lib.Operand) lib.Instruction {
if reg, ok := dest.(*encoding.Register); ok && reg.Width() == lib.BYTE {
return MOV(encoding.Uint8(v), dest)
}
if reg, ok := dest.(*encoding.Register); ok && reg.Width() == lib.WORD {
return MOV(encoding.Uint16(v), dest)
}
if v < (1 << 32) {
return MOV(encoding.Uint32(v), dest)
}
return MOV(encoding.Uint64(v), dest)
}
// Move with sign-extend
func MOVSX(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("movsx", opcodes.MOVSX, 2, dest, src)
}
// Move with zero-extend
func MOVZX(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("movzx", opcodes.MOVZX, 2, dest, src)
}
func IMUL1(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("imul", opcodes.IMUL1, 1, dest)
}
func IMUL2(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("imul", opcodes.IMUL2, 2, dest, src)
}
func MUL(src lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("mul", opcodes.MUL, 1, src)
}
func OR(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("or", opcodes.OR, 2, dest, src)
}
func POP(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("pop", opcodes.POP, 1, dest)
}
func PUSH(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("push", opcodes.PUSH, 1, dest)
}
func PUSHFQ() lib.Instruction {
return opcodes.OpcodeToInstruction("pushfq", opcodes.PUSHFQ, 0)
}
func RETURN() lib.Instruction {
return opcodes.OpcodeToInstruction("return", opcodes.RETURN, 0)
}
func SETA(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("seta", opcodes.SETA, 1, dest)
}
func SETAE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setae", opcodes.SETAE, 1, dest)
}
func SETB(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setb", opcodes.SETB, 1, dest)
}
func SETBE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setbe", opcodes.SETBE, 1, dest)
}
func SETC(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setc", opcodes.SETC, 1, dest)
}
func SETE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("sete", opcodes.SETE, 1, dest)
}
func SETL(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setl", opcodes.SETL, 1, dest)
}
func SETLE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setle", opcodes.SETLE, 1, dest)
}
func SETG(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setg", opcodes.SETG, 1, dest)
}
func SETGE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setge", opcodes.SETGE, 1, dest)
}
func SETNE(dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("setne", opcodes.SETNE, 1, dest)
}
func SUB(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("sub", opcodes.SUB, 2, dest, src)
}
func SHL(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("shl", opcodes.SHL, 2, dest, src)
}
func SHR(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("shr", opcodes.SHR, 2, dest, src)
}
func SYSCALL() lib.Instruction {
return opcodes.OpcodeToInstruction("syscall", opcodes.SYSCALL, 0)
}
// Add packed byte integers from op1 (register), and op2 (register or address)
// and store in dest.
func VPADDB(op1, op2, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("vpaddb", opcodes.VPADDB, 3, dest, op2, op1)
}
// Add packed word integers from op1 (register), and op2 (register or address)
// and store in dest.
func VPADDW(op1, op2, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("vpaddw", opcodes.VPADDW, 3, dest, op2, op1)
}
// Add packed double integers from op1 (register), and op2 (register or address)
// and store in dest.
func VPADDD(op1, op2, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("vpaddd", opcodes.VPADDD, 3, dest, op2, op1)
}
// Add packed quadword integers from op1 (register), and op2 (register or address)
// and store in dest.
func VPADDQ(op1, op2, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("vpaddq", opcodes.VPADDD, 3, dest, op2, op1)
}
// Bitwise AND of op1 and op2, store result in dest.
func VPAND(op1, op2, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("vpand", opcodes.VPAND, 3, dest, op2, op1)
}
// Bitwise OR of op1 and op2, store result in dest.
func VPOR(op1, op2, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("vpor", opcodes.VPOR, 3, dest, op2, op1)
}
func XOR(src, dest lib.Operand) lib.Instruction {
return opcodes.OpcodesToInstruction("xor", opcodes.XOR, 2, dest, src)
} | asm/x86_64/assembler.go | 0.669313 | 0.57678 | assembler.go | starcoder |
package ahrs
import (
"log"
"math"
"github.com/skelterjohn/go.matrix"
)
const (
minDT = 1e-6 // Below this time interval, don't recalculate
maxDT = 10.0 // Above this time interval, re-initialize--too stale
minGS = 5.0 // Below this GS, don't use any GPS data
fastSmoothConstDefault = 0.7 // Sensible default for fast smoothing of AHRS values
slowSmoothConstDefault = 0.1 // Sensible default for slow smoothing of AHRS values
verySlowSmoothConstDefault = 0.02 // Five-second smoothing mainly for groundspeed, to decide static mode
gpsWeightDefault = 0.04 // Sensible default for weight of GPS-derived values in solution
)
var (
fastSmoothConst = fastSmoothConstDefault // Decay constant for smoothing values reported to the user
slowSmoothConst = slowSmoothConstDefault // Decay constant for smoothing values reported to the user
verySlowSmoothConst = verySlowSmoothConstDefault // Decay constant for smoothing values reported to the user
gpsWeight = gpsWeightDefault // Weight given to GPS quaternion over gyro quaternion
)
type SimpleState struct {
State
tW float64 // Time of last GPS reading
eGPS0, eGPS1, eGPS2, eGPS3 float64 // GPS-derived orientation quaternion
eGyr0, eGyr1, eGyr2, eGyr3 float64 // GPS-derived orientation quaternion
rollGPS, pitchGPS, headingGPS float64 // GPS/accel-based attitude, Rad
rollGyr, pitchGyr, headingGyr float64 // Gyro-based attitude, Rad
w1, w2, w3, gs float64 // Groundspeed & ROC, Kts
smoothW1, smoothW2, smoothGS float64 // Smoothed groundspeed used to determine if stationary
staticMode bool // For low groundspeed or invalid GPS
headingValid bool // Whether to slew quickly to correct heading
}
//NewSimpleAHRS returns a new Simple AHRS object.
// It is initialized with a beginning sensor orientation quaternion f0.
func NewSimpleAHRS() (s *SimpleState) {
s = new(SimpleState)
s.needsInitialization = true
s.aNorm = 1
s.F0 = 1 // Initial guess is that it's oriented pointing forward and level
s.M = matrix.Zeros(32, 32)
s.N = matrix.Zeros(32, 32)
s.logMap = make(map[string]interface{})
s.updateLogMap(NewMeasurement(), s.logMap)
return
}
func (s *SimpleState) init(m *Measurement) {
s.State.init(m)
s.headingValid = false
s.tW = m.TW
if m.WValid {
s.gs = math.Hypot(m.W1, m.W2)
s.smoothW1 = s.smoothW1 + verySlowSmoothConst*(m.W1-s.smoothW1)
s.smoothW2 = s.smoothW2 + verySlowSmoothConst*(m.W2-s.smoothW2)
s.smoothGS = math.Hypot(s.smoothW1, s.smoothW2)
s.w1 = m.W1
s.w2 = m.W2
s.w3 = m.W3
} else {
s.gs = 0
s.smoothW1 = 0
s.smoothW2 = 0
s.smoothGS = 0
s.w1 = 0
s.w2 = 0
s.w3 = 0
}
if s.smoothGS > minGS {
s.heading = math.Atan2(m.W1, m.W2)
for s.heading < 0 {
s.heading += 2 * Pi
}
for s.heading >= 2*Pi {
s.heading -= 2 * Pi
}
}
s.eGPS0, s.eGPS1, s.eGPS2, s.eGPS3 = ToQuaternion(s.roll, s.pitch, s.heading)
s.eGyr0, s.eGyr1, s.eGyr2, s.eGyr3 = ToQuaternion(s.roll, s.pitch, s.heading)
s.E0, s.E1, s.E2, s.E3 = s.eGPS0, s.eGPS1, s.eGPS2, s.eGPS3
s.updateLogMap(m, s.logMap)
}
// Compute performs the AHRSSimple AHRS computations.
func (s *SimpleState) Compute(m *Measurement) {
if s.needsInitialization {
s.init(m)
return
}
dt := m.T - s.T
dtw := m.TW - s.tW
if dt > maxDT || dtw > maxDT {
log.Printf("AHRS Info: Reinitializing at %f\n", m.T)
s.init(m)
return
}
// Rotate measurements from sensor frame to aircraft frame
a1, a2, a3 := s.rotateByF(-m.A1, -m.A2, -m.A3, false)
b1, b2, b3 := s.rotateByF(m.B1-s.D1, m.B2-s.D2, m.B3-s.D3, false)
m1, m2, m3 := s.rotateByF(m.M1, m.M2, m.M3, false)
// Update estimates of current gyro and accel rates
s.Z1 += fastSmoothConst * (a1/s.aNorm - s.Z1)
s.Z2 += fastSmoothConst * (a2/s.aNorm - s.Z2)
s.Z3 += fastSmoothConst * (a3/s.aNorm - s.Z3)
s.H1 += fastSmoothConst * (b1 - s.H1)
s.H2 += fastSmoothConst * (b2 - s.H2)
s.H3 += fastSmoothConst * (b3 - s.H3)
if m.WValid && dtw > minDT {
s.gs = math.Hypot(m.W1, m.W2)
s.smoothW1 = s.smoothW1 + verySlowSmoothConst*(m.W1-s.smoothW1)
s.smoothW2 = s.smoothW2 + verySlowSmoothConst*(m.W2-s.smoothW2)
s.smoothGS = math.Hypot(s.smoothW1, s.smoothW2)
}
ae := [3]float64{0, 0, -1} // Acceleration due to gravity in earth frame
ve := [3]float64{0, 1, 0} // Groundspeed in earth frame (default for desktop mode)
s.staticMode = !(m.WValid && (s.smoothGS > minGS))
if !s.staticMode {
if !s.headingValid {
s.init(m)
s.headingValid = true
return
}
if dtw < minDT {
log.Printf("No GPS update at %f\n", m.T)
return
}
ve = [3]float64{m.W1, m.W2, m.W3} // Instantaneous groundspeed in earth frame
// Instantaneous acceleration in earth frame based on change in GPS groundspeed
ae[0] -= (m.W1 - s.w1) / dtw / G
ae[1] -= (m.W2 - s.w2) / dtw / G
ae[2] -= (m.W3 - s.w3) / dtw / G
}
ha, err := MakeUnitVector([3]float64{s.Z1, s.Z2, s.Z3})
if err != nil {
log.Println("AHRS Error: IMU-measured acceleration was zero")
return
}
he, _ := MakeUnitVector(ae)
se, _ := MakeUnitVector(ve)
// Left-multiplying a vector in the aircraft frame by rotmat will put it into the earth frame.
// rotmat maps the current IMU acceleration to the GPS-acceleration and the x-axis to the GPS-velocity.
rotmat, err := MakeHardSoftRotationMatrix(*ha, [3]float64{1, 0, 0}, *he, *se)
if err != nil {
log.Printf("AHRS Error: %s\n", err)
return
}
// This orientation quaternion EGPS rotates from aircraft frame to earth frame at the current time,
// as estimated using GPS and accelerometer.
e0, e1, e2, e3 := RotationMatrixToQuaternion(*rotmat)
e0, e1, e2, e3 = QuaternionSign(e0, e1, e2, e3, s.eGPS0, s.eGPS1, s.eGPS2, s.eGPS3)
s.eGPS0, s.eGPS1, s.eGPS2, s.eGPS3 = QuaternionNormalize(
s.eGPS0+fastSmoothConst*(e0-s.eGPS0),
s.eGPS1+fastSmoothConst*(e1-s.eGPS1),
s.eGPS2+fastSmoothConst*(e2-s.eGPS2),
s.eGPS3+fastSmoothConst*(e3-s.eGPS3),
)
// By rotating the orientation quaternion at the last time step, s.E, by the measured gyro rates,
// we get another estimate of the current orientation quaternion using the gyro.
s.eGyr0, s.eGyr1, s.eGyr2, s.eGyr3 = QuaternionRotate(s.E0, s.E1, s.E2, s.E3, s.H1*dt*Deg, s.H2*dt*Deg, s.H3*dt*Deg)
// Now fuse the GPS/Accelerometer and Gyro estimates, smooth the result and normalize.
s.eGPS0, s.eGPS1, s.eGPS2, s.eGPS3 = QuaternionSign(s.eGPS0, s.eGPS1, s.eGPS2, s.eGPS3,
s.eGyr0, s.eGyr1, s.eGyr2, s.eGyr3)
de0 := s.eGPS0 - s.eGyr0
de1 := s.eGPS1 - s.eGyr1
de2 := s.eGPS2 - s.eGyr2
de3 := s.eGPS3 - s.eGyr3
s.E0, s.E1, s.E2, s.E3 = QuaternionNormalize(
s.eGyr0+gpsWeight*de0*(0.5+de0*de0),
s.eGyr1+gpsWeight*de1*(0.5+de1*de1),
s.eGyr2+gpsWeight*de2*(0.5+de2*de2),
s.eGyr3+gpsWeight*de3*(0.5+de3*de3),
)
s.roll, s.pitch, s.heading = FromQuaternion(s.E0, s.E1, s.E2, s.E3)
s.rollGPS, s.pitchGPS, s.headingGPS = FromQuaternion(s.eGPS0, s.eGPS1, s.eGPS2, s.eGPS3)
s.rollGyr, s.pitchGyr, s.headingGyr = FromQuaternion(s.eGyr0, s.eGyr1, s.eGyr2, s.eGyr3)
// Update Magnetic Heading
dhM := AngleDiff(math.Atan2(m1, -m2), s.headingMag) + 0*m3
s.headingMag += slowSmoothConst * dhM
for s.headingMag < 0 {
s.headingMag += 2 * Pi
}
for s.headingMag >= 2*Pi {
s.headingMag -= 2 * Pi
}
// Update Slip/Skid
s.slipSkid += slowSmoothConst * (math.Atan2(a2, -a3) - s.slipSkid)
// Update Rate of Turn
if s.gs > 0 && dtw > 0 {
s.turnRate += slowSmoothConst * ((m.W2*(m.W1-s.w1)-m.W1*(m.W2-s.w2))/(s.gs*s.gs)/dtw - s.turnRate)
}
// Update GLoad
s.gLoad += slowSmoothConst * (-a3/s.aNorm - s.gLoad)
s.updateLogMap(m, s.logMap)
s.T = m.T
s.tW = m.TW
s.w1 = m.W1
s.w2 = m.W2
s.w3 = m.W3
}
// RollPitchHeading returns the current attitude values as estimated by the Kalman algorithm.
func (s *SimpleState) RollPitchHeading() (roll float64, pitch float64, heading float64) {
roll, pitch, heading = s.State.RollPitchHeading()
if s.staticMode {
heading = Invalid
}
return
}
// RateOfTurn returns the turn rate in degrees per second.
func (s *SimpleState) RateOfTurn() (turnRate float64) {
if s.staticMode {
return Invalid
}
return s.State.RateOfTurn()
}
// SetConfig lets the user alter some of the configuration settings.
func (s *SimpleState) SetConfig(configMap map[string]float64) {
if v, ok := configMap["fastSmoothConst"]; ok {
fastSmoothConst = v
}
if v, ok := configMap["slowSmoothConst"]; ok {
slowSmoothConst = v
}
if v, ok := configMap["verySlowSmoothConst"]; ok {
verySlowSmoothConst = v
}
if v, ok := configMap["gpsWeight"]; ok {
gpsWeight = v
}
if fastSmoothConst == 0 || slowSmoothConst == 0 || verySlowSmoothConst == 0 {
// This doesn't make sense, means user hasn't set correctly.
// Set sensible defaults.
fastSmoothConst = fastSmoothConstDefault
slowSmoothConst = slowSmoothConstDefault
verySlowSmoothConst = verySlowSmoothConstDefault
gpsWeight = gpsWeightDefault
}
}
func (s *SimpleState) updateLogMap(m *Measurement, p map[string]interface{}) {
s.State.updateLogMap(m, s.logMap)
var simpleLogMap = map[string]func(s *SimpleState, m *Measurement) float64{
"RollGPS": func(s *SimpleState, m *Measurement) float64 { return s.rollGPS / Deg },
"PitchGPS": func(s *SimpleState, m *Measurement) float64 { return s.pitchGPS / Deg },
"HeadingGPS": func(s *SimpleState, m *Measurement) float64 { return s.headingGPS / Deg },
"RollGyr": func(s *SimpleState, m *Measurement) float64 { return s.rollGyr / Deg },
"PitchGyr": func(s *SimpleState, m *Measurement) float64 { return s.pitchGyr / Deg },
"HeadingGyr": func(s *SimpleState, m *Measurement) float64 { return s.headingGyr / Deg },
"GroundSpeed": func(s *SimpleState, m *Measurement) float64 { return s.gs },
"SmoothW1": func(s *SimpleState, m *Measurement) float64 { return s.smoothW1 },
"SmoothW2": func(s *SimpleState, m *Measurement) float64 { return s.smoothW2 },
"SmoothGroundSpeed": func(s *SimpleState, m *Measurement) float64 { return s.smoothGS },
"TWa": func(s *SimpleState, m *Measurement) float64 { return s.tW },
"W1a": func(s *SimpleState, m *Measurement) float64 { return s.w1 },
"W2a": func(s *SimpleState, m *Measurement) float64 { return s.w2 },
"W3a": func(s *SimpleState, m *Measurement) float64 { return s.w3 },
"EGPS0": func(s *SimpleState, m *Measurement) float64 { return s.eGPS0 },
"EGPS1": func(s *SimpleState, m *Measurement) float64 { return s.eGPS1 },
"EGPS2": func(s *SimpleState, m *Measurement) float64 { return s.eGPS2 },
"EGPS3": func(s *SimpleState, m *Measurement) float64 { return s.eGPS3 },
"EGyr0": func(s *SimpleState, m *Measurement) float64 { return s.eGyr0 },
"EGyr1": func(s *SimpleState, m *Measurement) float64 { return s.eGyr1 },
"EGyr2": func(s *SimpleState, m *Measurement) float64 { return s.eGyr2 },
"EGyr3": func(s *SimpleState, m *Measurement) float64 { return s.eGyr3 },
"staticMode": func(s *SimpleState, m *Measurement) float64 {
if s.staticMode {
return 1
}
return 0
},
"headingValid": func(s *SimpleState, m *Measurement) float64 {
if s.headingValid {
return 1
}
return 0
},
}
for k := range simpleLogMap {
p[k] = simpleLogMap[k](s, m)
}
}
var SimpleJSONConfig = `{
"State": [
["Roll", "RollGPS", "RollGyr", "RollActual", 0],
["Pitch", "PitchGPS", "PitchGyr", "PitchActual", 0],
["Heading", "HeadingGPS", "HeadingGyr", "HeadingActual", null],
["turnRate", null, null, "turnRateActual", 0],
["gLoad", null, null, "gLoadActual", 1],
["slipSkid", null, null, "slipSkidActual", 0],
["GroundSpeed", null, null, null, 0],
["T", null, null, null, null],
["E0", "EGPS0", "EGyr0", "E0Actual", null],
["E1", "EGPS1", "EGyr1", "E1Actual", null],
["E2", "EGPS2", "EGyr2", "E2Actual", null],
["E3", "EGPS3", "EGyr3", "E3Actual", null],
["Z1", null, null, "Z1Actual", 0],
["Z2", null, null, "Z2Actual", 0],
["Z3", null, null, "Z3Actual", -1]
["C1", null, null, "C1Actual", 0],
["C2", null, null, "C2Actual", 0],
["C3", null, null, "C3Actual", 0]
["H1", null, null, "H1Actual", 0],
["H2", null, null, "H2Actual", 0],
["H3", null, null, "H3Actual", 0]
["D1", null, null, "D1Actual", 0],
["D2", null, null, "D2Actual", 0],
["D3", null, null, "D3Actual", 0]
],
"Measurement": [
["W1", "W1a", 0],
["W2", "W2a", 0],
["W3", "W3a", 0],
["A1", null, 0],
["A2", null, 0],
["A3", null, 0],
["B1", null, 0],
["B2", null, 0],
["B3", null, 0]
["M1", null, 0],
["M2", null, 0],
["M3", null, 0]
]
}` | ahrs/ahrs.go | 0.669529 | 0.433802 | ahrs.go | starcoder |
package filter
import "github.com/spiegel-im-spiegel/cov19data/values"
//Filters is a filter class for entity classes
type Filters struct {
periods []values.Period
prefJpCodes []values.PrefJpCode
countryCodes []values.CountryCode
regionCodes []values.RegionCode
}
//FiltersOptFunc type is self-referential function type for New functions. (functional options pattern)
type FiltersOptFunc func(*Filters)
//New function returns a new Filters instance with options.
func New(opts ...FiltersOptFunc) *Filters {
f := &Filters{
periods: []values.Period{},
prefJpCodes: []values.PrefJpCode{},
countryCodes: []values.CountryCode{},
regionCodes: []values.RegionCode{},
}
for _, opt := range opts {
opt(f)
}
return f
}
//WithPeriod function returns FiltersOptFunc function value.
//This function is used in New functions that represents Marketplace data.
func WithPeriod(period values.Period) FiltersOptFunc {
return func(f *Filters) {
if f != nil {
existFlag := false
for _, p := range f.periods {
if p.Equal(period) {
existFlag = true
break
}
}
if !existFlag {
f.periods = append(f.periods, period)
}
}
}
}
//WithPrefJpCode function returns FiltersOptFunc function value.
//This function is used in New functions that represents Marketplace data.
func WithPrefJpCode(code values.PrefJpCode) FiltersOptFunc {
return func(f *Filters) {
if f != nil {
existFlag := false
for _, c := range f.prefJpCodes {
if c == code {
existFlag = true
break
}
}
if !existFlag {
f.prefJpCodes = append(f.prefJpCodes, code)
}
}
}
}
//WithCountryCode function returns FiltersOptFunc function value.
//This function is used in New functions that represents Marketplace data.
func WithCountryCode(code values.CountryCode) FiltersOptFunc {
return func(f *Filters) {
if f != nil {
existFlag := false
for _, c := range f.countryCodes {
if c == code {
existFlag = true
break
}
}
if !existFlag {
f.countryCodes = append(f.countryCodes, code)
}
}
}
}
//WithRegionCode function returns FiltersOptFunc function value.
//This function is used in New functions that represents Marketplace data.
func WithRegionCode(code values.RegionCode) FiltersOptFunc {
return func(f *Filters) {
if f != nil {
existFlag := false
for _, c := range f.regionCodes {
if c == code {
existFlag = true
break
}
}
if !existFlag {
f.regionCodes = append(f.regionCodes, code)
}
}
}
}
//Period method returns true if Periods filter contains date of parameter.
func (f *Filters) Period(dt values.Date) bool {
if f == nil {
return true
}
if len(f.periods) == 0 {
return true
}
for _, p := range f.periods {
if p.Contains(dt) {
return true
}
}
return false
}
//PrefJpCode method returns true if PrefJpCode filter contains Pref Code of parameter.
func (f *Filters) PrefJpCode(code values.PrefJpCode) bool {
if f == nil {
return true
}
if !f.CountryCode(values.CC_JP) {
return false
}
if len(f.prefJpCodes) == 0 {
return true
}
for _, c := range f.prefJpCodes {
if c == code {
return true
}
}
return false
}
//CountryCode method returns true if CountryCodes filter contains Country Codes of parameter.
func (f *Filters) CountryCode(code values.CountryCode) bool {
if f == nil {
return true
}
if len(f.countryCodes) == 0 {
return true
}
for _, c := range f.countryCodes {
if c == code {
return true
}
}
return false
}
//CountryCode method returns true if CountryCodes filter contains Region Code of parameter.
func (f *Filters) RegionCode(code values.RegionCode) bool {
if f == nil {
return true
}
if len(f.regionCodes) == 0 {
return true
}
for _, c := range f.regionCodes {
if c == code {
return true
}
}
return false
}
/* Copyright 2020-2021 Spiegel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | filter/filter.go | 0.717012 | 0.455804 | filter.go | starcoder |
package number
import schema "github.com/frolFomich/document-schema"
func WithMaximum(m float64) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
sch.Put(schema.MaximumSchemaKeyword, m)
}
}
}
func WithMinimum(m float64) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
sch.Put(schema.MinimumSchemaKeyword, m)
}
}
}
func WithExclusiveMaximum(m bool) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
sch.Put(schema.ExclusiveMaximumSchemaKeyword, m)
}
}
}
func WithExclusiveMinimum(m bool) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
sch.Put(schema.ExclusiveMinimumSchemaKeyword, m)
}
}
}
func WithMultipleOf(m float64) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
sch.Put(schema.MultipleOfSchemaKeyword, m)
}
}
}
func WithFormat(m schema.FormatType) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
// TODO check m for int* and float* formats
sch.Put(schema.ExclusiveMaximumSchemaKeyword, m)
}
}
}
func WithDefaultInt(m int64) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
sch.Put(schema.DefaultSchemaKeyword, m)
}
}
}
func WithDefaultFloat(m float64) schema.SchemaOption {
return func(sch *schema.SchemaBase) {
if sch != nil && (schema.NumberSchemaType == sch.Type() || schema.IntegerSchemaType == sch.Type()) {
sch.Put(schema.DefaultSchemaKeyword, m)
}
}
} | number/options.go | 0.593845 | 0.472866 | options.go | starcoder |
package tty
import (
"gopheros/device"
"gopheros/device/video/console"
"gopheros/kernel"
"io"
)
// VT implements a terminal supporting scrollback. The terminal interprets the
// following special characters:
// - \r (carriage-return)
// - \n (line-feed)
// - \b (backspace)
// - \t (tab; expanded to tabWidth spaces)
type VT struct {
cons console.Device
// Terminal dimensions
termWidth uint32
termHeight uint32
viewportWidth uint32
viewportHeight uint32
// The number of additional lines of output that are buffered by the
// terminal to support scrolling up.
scrollback uint32
// The terminal contents. Each character occupies 3 bytes and uses the
// format: (ASCII char, fg, bg)
data []uint8
// Terminal state.
tabWidth uint8
defaultFg, curFg uint8
defaultBg, curBg uint8
cursorX uint32
cursorY uint32
viewportY uint32
dataOffset uint
state State
}
// NewVT creates a new virtual terminal device. The tabWidth parameter controls
// tab expansion whereas the scrollback parameter defines the line count that
// gets buffered by the terminal to provide scrolling beyond the console
// height.
func NewVT(tabWidth uint8, scrollback uint32) *VT {
return &VT{
tabWidth: tabWidth,
scrollback: scrollback,
cursorX: 1,
cursorY: 1,
}
}
// AttachTo connects a TTY to a console instance.
func (t *VT) AttachTo(cons console.Device) {
if cons == nil {
return
}
t.cons = cons
t.viewportWidth, t.viewportHeight = cons.Dimensions(console.Characters)
t.viewportY = 0
t.defaultFg, t.defaultBg = cons.DefaultColors()
t.curFg, t.curBg = t.defaultFg, t.defaultBg
t.termWidth, t.termHeight = t.viewportWidth, t.viewportHeight+t.scrollback
t.cursorX, t.cursorY = 1, 1
// Allocate space for the contents and fill it with empty characters
// using the default fg/bg colors for the attached console.
t.data = make([]uint8, t.termWidth*t.termHeight*3)
for i := 0; i < len(t.data); i += 3 {
t.data[i] = ' '
t.data[i+1] = t.defaultFg
t.data[i+2] = t.defaultBg
}
}
// State returns the TTY's state.
func (t *VT) State() State {
return t.state
}
// SetState updates the TTY's state.
func (t *VT) SetState(newState State) {
if t.state == newState {
return
}
t.state = newState
// If the terminal became active, update the console with its contents
if t.state == StateActive && t.cons != nil {
for y := uint32(1); y <= t.viewportHeight; y++ {
offset := (y - 1 + t.viewportY) * (t.viewportWidth * 3)
for x := uint32(1); x <= t.viewportWidth; x, offset = x+1, offset+3 {
t.cons.Write(t.data[offset], t.data[offset+1], t.data[offset+2], x, y)
}
}
}
}
// CursorPosition returns the current cursor position.
func (t *VT) CursorPosition() (uint32, uint32) {
return t.cursorX, t.cursorY
}
// SetCursorPosition sets the current cursor position to (x,y).
func (t *VT) SetCursorPosition(x, y uint32) {
if t.cons == nil {
return
}
if x < 1 {
x = 1
} else if x > t.viewportWidth {
x = t.viewportWidth
}
if y < 1 {
y = 1
} else if y > t.viewportHeight {
y = t.viewportHeight
}
t.cursorX, t.cursorY = x, y
t.updateDataOffset()
}
// Write implements io.Writer.
func (t *VT) Write(data []byte) (int, error) {
for count, b := range data {
err := t.WriteByte(b)
if err != nil {
return count, err
}
}
return len(data), nil
}
// WriteByte implements io.ByteWriter.
func (t *VT) WriteByte(b byte) error {
if t.cons == nil {
return io.ErrClosedPipe
}
switch b {
case '\r':
t.cr()
case '\n':
t.lf(true)
case '\b':
if t.cursorX > 1 {
t.SetCursorPosition(t.cursorX-1, t.cursorY)
t.doWrite(' ', false)
}
case '\t':
for i := uint8(0); i < t.tabWidth; i++ {
t.doWrite(' ', true)
}
default:
t.doWrite(b, true)
}
return nil
}
// doWrite writes the specified character together with the current fg/bg
// attributes at the current data offset advancing the cursor position if
// advanceCursor is true. If the terminal is active, then doWrite also writes
// the character to the attached console.
func (t *VT) doWrite(b byte, advanceCursor bool) {
if t.state == StateActive {
t.cons.Write(b, t.curFg, t.curBg, t.cursorX, t.cursorY)
}
t.data[t.dataOffset] = b
t.data[t.dataOffset+1] = t.curFg
t.data[t.dataOffset+2] = t.curBg
if advanceCursor {
// Advance x position and handle wrapping when the cursor reaches the
// end of the current line
t.dataOffset += 3
t.cursorX++
if t.cursorX > t.viewportWidth {
t.lf(true)
}
}
}
// cr resets the x coordinate of the terminal cursor to 0.
func (t *VT) cr() {
t.cursorX = 1
t.updateDataOffset()
}
// lf advances the y coordinate of the terminal cursor by one line scrolling
// the terminal contents if the end of the last terminal line is reached.
func (t *VT) lf(withCR bool) {
if withCR {
t.cursorX = 1
}
switch {
// Cursor has not reached the end of the viewport
case t.cursorY+1 <= t.viewportHeight:
t.cursorY++
default:
// Check if the viewport can be scrolled down
if t.viewportY+t.viewportHeight < t.termHeight {
t.viewportY++
} else {
// We have reached the bottom of the terminal buffer.
// We need to scroll its contents up and clear the last line
var stride = int(t.viewportWidth * 3)
var startOffset = int(t.viewportY) * stride
var endOffset = int(t.viewportY+t.viewportHeight-1) * stride
for offset := startOffset; offset < endOffset; offset++ {
t.data[offset] = t.data[offset+stride]
}
for offset := endOffset; offset < endOffset+stride; offset += 3 {
t.data[offset+0] = ' '
t.data[offset+1] = t.defaultFg
t.data[offset+2] = t.defaultBg
}
}
// Sync console
if t.state == StateActive {
t.cons.Scroll(console.ScrollDirUp, 1)
t.cons.Fill(1, t.cursorY, t.termWidth, 1, t.defaultFg, t.defaultBg)
}
}
t.updateDataOffset()
}
// updateDataOffset calculates the offset in the data buffer taking into account
// the cursor position and the viewportY value.
func (t *VT) updateDataOffset() {
t.dataOffset = uint((t.viewportY+(t.cursorY-1))*(t.viewportWidth*3) + ((t.cursorX - 1) * 3))
}
// DriverName returns the name of this driver.
func (t *VT) DriverName() string {
return "vt"
}
// DriverVersion returns the version of this driver.
func (t *VT) DriverVersion() (uint16, uint16, uint16) {
return 0, 0, 1
}
// DriverInit initializes this driver.
func (t *VT) DriverInit(_ io.Writer) *kernel.Error { return nil }
func probeForVT() device.Driver {
return NewVT(DefaultTabWidth, DefaultScrollback)
}
func init() {
device.RegisterDriver(&device.DriverInfo{
Order: device.DetectOrderEarly,
Probe: probeForVT,
})
} | src/gopheros/device/tty/vt.go | 0.564579 | 0.413596 | vt.go | starcoder |
package carrot
/*
This file describes the construction and types of messages sent during the Picnic Protocol handshake
between the server and primary and secondary devices.
Example initial message to devices. Since the session_token and uuid are the same,
this is a primary device message. The two fields would be different for secondary devices.
{
session_token: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F";
endpoint: "carrot_beacon";
payload: {
params: {
identifier = "com.Carrot.PrimaryBeacon";
uuid = "E621E1F8-C36C-495A-93FC-0C247A3E6E5F";
};
};
}
*/
// createInitialDeviceInfo creates initial message to be sent to a newly connected device.
// It establishes a device's primary or secondary role in order to send and recieve further information.
func createInitialDeviceInfo(uuid string, token string) ([]byte, error) {
params := ResponseParams{"identifier": "com.Carrot.Beacon", "uuid": uuid}
payload, err := newPayloadNoTransform(nil, params)
res, err := NewResponse(token, "carrot_beacon", payload)
info, err := res.Build()
return info, err
}
/*
Example request to obtain T_P from the primary device.
Since params (and offsets) are unnecessary for this case, the payload is empty.
{
session_token: "E621E1F8-C36C-495A-93FC-0C247A3E6E5F";
endpoint: "carrot_transform";
payload: {
};
}
*/
// getT_PFromPrimaryDeviceRes requests information to determine a secondary device's
// position relative to the primary device.
func getT_PFromPrimaryDeviceRes(token string) ([]byte, error) {
payload, err := newPayloadNoTransform(nil, nil)
res, err := NewResponse(token, "carrot_transform", payload)
ask, err := res.Build()
return ask, err
}
/*
Example response from a primary device sending its T_P or a secondary device sending its T_L.
These messages look identical so the context in transform.go determines where and what the offset is stored as.
{
"session_token": "E62<PASSWORD>-C36C-<PASSWORD>-9<PASSWORD>-<PASSWORD>",
"endpoint": "carrot_transform",
"payload": {
"offset": {
"x": 1,
"y": 1,
"z": 1
}
}
}
*/ | beacon.go | 0.630685 | 0.455441 | beacon.go | starcoder |
package pinapi
import (
"encoding/json"
)
// Currency struct for Currency
type Currency struct {
// Currency code.
Code *string `json:"code,omitempty"`
// Currency name.
Name *string `json:"name,omitempty"`
// Exchange rate to USD.
Rate *float64 `json:"rate,omitempty"`
}
// NewCurrency instantiates a new Currency 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 NewCurrency() *Currency {
this := Currency{}
return &this
}
// NewCurrencyWithDefaults instantiates a new Currency 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 NewCurrencyWithDefaults() *Currency {
this := Currency{}
return &this
}
// GetCode returns the Code field value if set, zero value otherwise.
func (o *Currency) GetCode() string {
if o == nil || o.Code == nil {
var ret string
return ret
}
return *o.Code
}
// GetCodeOk returns a tuple with the Code field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *Currency) GetCodeOk() (*string, bool) {
if o == nil || o.Code == nil {
return nil, false
}
return o.Code, true
}
// HasCode returns a boolean if a field has been set.
func (o *Currency) HasCode() bool {
if o != nil && o.Code != nil {
return true
}
return false
}
// SetCode gets a reference to the given string and assigns it to the Code field.
func (o *Currency) SetCode(v string) {
o.Code = &v
}
// GetName returns the Name field value if set, zero value otherwise.
func (o *Currency) GetName() string {
if o == nil || o.Name == nil {
var ret string
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 *Currency) GetNameOk() (*string, 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 *Currency) HasName() bool {
if o != nil && o.Name != nil {
return true
}
return false
}
// SetName gets a reference to the given string and assigns it to the Name field.
func (o *Currency) SetName(v string) {
o.Name = &v
}
// GetRate returns the Rate field value if set, zero value otherwise.
func (o *Currency) GetRate() float64 {
if o == nil || o.Rate == nil {
var ret float64
return ret
}
return *o.Rate
}
// GetRateOk returns a tuple with the Rate field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *Currency) GetRateOk() (*float64, bool) {
if o == nil || o.Rate == nil {
return nil, false
}
return o.Rate, true
}
// HasRate returns a boolean if a field has been set.
func (o *Currency) HasRate() bool {
if o != nil && o.Rate != nil {
return true
}
return false
}
// SetRate gets a reference to the given float64 and assigns it to the Rate field.
func (o *Currency) SetRate(v float64) {
o.Rate = &v
}
func (o Currency) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.Code != nil {
toSerialize["code"] = o.Code
}
if o.Name != nil {
toSerialize["name"] = o.Name
}
if o.Rate != nil {
toSerialize["rate"] = o.Rate
}
return json.Marshal(toSerialize)
}
type NullableCurrency struct {
value *Currency
isSet bool
}
func (v NullableCurrency) Get() *Currency {
return v.value
}
func (v *NullableCurrency) Set(val *Currency) {
v.value = val
v.isSet = true
}
func (v NullableCurrency) IsSet() bool {
return v.isSet
}
func (v *NullableCurrency) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableCurrency(val *Currency) *NullableCurrency {
return &NullableCurrency{value: val, isSet: true}
}
func (v NullableCurrency) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableCurrency) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | pinapi/model_currency.go | 0.821295 | 0.423458 | model_currency.go | starcoder |
package order
import (
"github.com/MaximilianMeister/asset/broker"
"github.com/shopspring/decimal"
)
// Order contains data to calculate order figures
type Order struct {
brokerAlias string
volume int64
target, actual, stop decimal.Decimal
}
// RiskRewardRatio returns a risk reward ratio value for an order
func (o *Order) RiskRewardRatio() (rrr decimal.Decimal) {
chance := o.target.Sub(o.actual)
risk := o.actual.Sub(o.stop)
rrr = chance.Div(risk).Round(1)
return
}
// TotalCommission returns the total broker commission fee for an order
func (o *Order) TotalCommission(brokerAlias string) (commission decimal.Decimal, err error) {
commission = decimal.NewFromFloat(0.0)
broker, err := broker.FindBroker(brokerAlias)
if err != nil {
return commission, err
}
volumeRateBuy := decimal.New(o.Amount(), 0).Mul(o.actual).Mul(broker.CommissionRate)
volumeRateSell := decimal.New(o.Amount(), 0).Mul(o.target).Mul(broker.CommissionRate)
buySell := []decimal.Decimal{
volumeRateBuy,
volumeRateSell,
}
for _, bs := range buySell {
if (bs.Add(broker.BasicPrice)).Cmp(broker.MinRate) == 1 {
if (bs.Add(broker.BasicPrice)).Cmp(broker.MaxRate) == 1 {
commission = commission.Add(broker.MaxRate)
} else {
commission = commission.Add(broker.BasicPrice.Add(bs))
}
} else {
commission = commission.Add(broker.MinRate)
}
}
commission = commission.Round(2)
return
}
// Amount returns the actual amount of stocks that can be bought for an order
func (o *Order) Amount() (amount int64) {
amount = decimal.New(o.volume, 0).Div(o.actual).Round(0).IntPart()
return
}
// Gain returns the highest possible gain for an order
func (o *Order) Gain(broker string) (gain decimal.Decimal, err error) {
amount := decimal.New(o.Amount(), 0)
volume := decimal.New(o.volume, 0)
commission, err := o.TotalCommission(broker)
if err != nil {
return decimal.NewFromFloat(0.0), err
}
gain = amount.Mul(o.target)
gain = gain.Sub(volume).Sub(commission)
gain = gain.Round(2)
return gain, nil
}
// Loss returns the highest possible loss for an order
func (o *Order) Loss(broker string) (loss decimal.Decimal, err error) {
amount := decimal.New(o.Amount(), 0)
volume := decimal.New(o.volume, 0)
commission, err := o.TotalCommission(broker)
if err != nil {
return decimal.NewFromFloat(0.0), err
}
loss = volume.Sub(amount.Mul(o.stop)).Add(commission)
loss = loss.Round(2)
return loss, nil
}
// Even returns the exact break even point for an order
func (o *Order) Even(broker string) (even decimal.Decimal, err error) {
amount := decimal.New(o.Amount(), 0)
volume := decimal.New(o.volume, 0)
commission, err := o.TotalCommission(broker)
if err != nil {
return decimal.NewFromFloat(0.0), err
}
even = volume.Add(commission)
even = even.Div(amount)
even = even.Round(2)
return even, nil
}
// StopLoss returns nil when it is valid.
func StopLoss(actual, stop float64) error {
if stop >= actual {
return &HigherLowerError{stop, actual}
}
return nil
} | order/order.go | 0.853852 | 0.452959 | order.go | starcoder |
package sql
// PrivilegedOperation represents an operation that requires privileges to execute.
type PrivilegedOperation struct {
Database string
Table string
Column string
Privileges []PrivilegeType
}
// NewPrivilegedOperation returns a new PrivilegedOperation with the given parameters.
func NewPrivilegedOperation(dbName string, tblName string, colName string, privs ...PrivilegeType) PrivilegedOperation {
return PrivilegedOperation{
Database: dbName,
Table: tblName,
Column: colName,
Privileges: privs,
}
}
// PrivilegedOperationChecker contains the necessary data to check whether the operation should succeed based on the
// privileges contained by the user. The user is retrieved from the context, along with their active roles.
type PrivilegedOperationChecker interface {
// UserHasPrivileges fetches the User, and returns whether they have the desired privileges necessary to perform the
// privileged operation(s). This takes into account the active roles, which are set in the context, therefore both
// the user and the active roles are pulled from the context.
UserHasPrivileges(ctx *Context, operations ...PrivilegedOperation) bool
}
// PrivilegeType represents a privilege.
type PrivilegeType int
const (
PrivilegeType_Select PrivilegeType = iota
PrivilegeType_Insert
PrivilegeType_Update
PrivilegeType_Delete
PrivilegeType_Create
PrivilegeType_Drop
PrivilegeType_Reload
PrivilegeType_Shutdown
PrivilegeType_Process
PrivilegeType_File
PrivilegeType_Grant
PrivilegeType_References
PrivilegeType_Index
PrivilegeType_Alter
PrivilegeType_ShowDB
PrivilegeType_Super
PrivilegeType_CreateTempTable
PrivilegeType_LockTables
PrivilegeType_Execute
PrivilegeType_ReplicationSlave
PrivilegeType_ReplicationClient
PrivilegeType_CreateView
PrivilegeType_ShowView
PrivilegeType_CreateRoutine
PrivilegeType_AlterRoutine
PrivilegeType_CreateUser
PrivilegeType_Event
PrivilegeType_Trigger
PrivilegeType_CreateTablespace
PrivilegeType_CreateRole
PrivilegeType_DropRole
)
// privilegeTypeStrings are in the same order as the enumerations above, so that it's a simple index access.
var privilegeTypeStrings = []string{
"SELECT",
"INSERT",
"UPDATE",
"DELETE",
"CREATE",
"DROP",
"RELOAD",
"SHUTDOWN",
"PROCESS",
"FILE",
"GRANT",
"REFERENCES",
"INDEX",
"ALTER",
"SHOW DATABASES",
"SUPER",
"CREATE TEMPORARY TABLES",
"LOCK TABLES",
"EXECUTE",
"REPLICATION SLAVE",
"REPLICATION CLIENT",
"CREATE VIEW",
"SHOW VIEW",
"CREATE ROUTINE",
"ALTER ROUTINE",
"CREATE USER",
"EVENT",
"TRIGGER",
"CREATE TABLESPACE",
"CREATE ROLE",
"DROP ROLE",
}
// String returns the sql.PrivilegeType as a string, for display in places such as "SHOW GRANTS".
func (pt PrivilegeType) String() string {
return privilegeTypeStrings[pt]
}
// privilegeTypeStringMap map each string (same ones in privilegeTypeStrings) to their appropriate PrivilegeType.
var privilegeTypeStringMap = map[string]PrivilegeType{
"SELECT": PrivilegeType_Select,
"INSERT": PrivilegeType_Insert,
"UPDATE": PrivilegeType_Update,
"DELETE": PrivilegeType_Delete,
"CREATE": PrivilegeType_Create,
"DROP": PrivilegeType_Drop,
"RELOAD": PrivilegeType_Reload,
"SHUTDOWN": PrivilegeType_Shutdown,
"PROCESS": PrivilegeType_Process,
"FILE": PrivilegeType_File,
"GRANT": PrivilegeType_Grant,
"REFERENCES": PrivilegeType_References,
"INDEX": PrivilegeType_Index,
"ALTER": PrivilegeType_Alter,
"SHOW DATABASES": PrivilegeType_ShowDB,
"SUPER": PrivilegeType_Super,
"CREATE TEMPORARY TABLES": PrivilegeType_CreateTempTable,
"LOCK TABLES": PrivilegeType_LockTables,
"EXECUTE": PrivilegeType_Execute,
"REPLICATION SLAVE": PrivilegeType_ReplicationSlave,
"REPLICATION CLIENT": PrivilegeType_ReplicationClient,
"CREATE VIEW": PrivilegeType_CreateView,
"SHOW VIEW": PrivilegeType_ShowView,
"CREATE ROUTINE": PrivilegeType_CreateRoutine,
"ALTER ROUTINE": PrivilegeType_AlterRoutine,
"CREATE USER": PrivilegeType_CreateUser,
"EVENT": PrivilegeType_Event,
"TRIGGER": PrivilegeType_Trigger,
"CREATE TABLESPACE": PrivilegeType_CreateTablespace,
"CREATE ROLE": PrivilegeType_CreateRole,
"DROP ROLE": PrivilegeType_DropRole,
}
// PrivilegeTypeFromString returns the matching PrivilegeType for the given string. If there is no match, returns false.
func PrivilegeTypeFromString(privilegeType string) (PrivilegeType, bool) {
match, ok := privilegeTypeStringMap[privilegeType]
return match, ok
} | sql/privileges.go | 0.657318 | 0.509947 | privileges.go | starcoder |
package util
import (
"bufio"
"bytes"
"math"
"sort"
"strconv"
"strings"
"github.com/sajari/regression"
)
func ConvertToBoundingBox(x, y float64) BeamBoundingBox {
hypotenuse := math.Sqrt(
math.Pow(x, 2) + math.Pow(y, 2),
)
angle := math.Acos(x/hypotenuse) * 180 / math.Pi
bbb, x, y := BoundingBox(hypotenuse, angle)
return bbb
}
func BoundingBox(hypotenuse, angle float64) (thisBeam BeamBoundingBox, x, y float64) {
bounding_side := 2 * math.Pi * hypotenuse / 360
if angle < 0 {
x = math.Cos((180-math.Abs(angle))*math.Pi/180) * hypotenuse * -1
y = math.Sin((180-math.Abs(angle))*math.Pi/180) * hypotenuse * -1
bbx := math.Cos((90-math.Abs(angle))*math.Pi/180) * bounding_side / 2
bby := math.Sin((90-math.Abs(angle))*math.Pi/180) * bounding_side / 2
bbx2 := math.Cos(angle*math.Pi/180) * bounding_side
bby2 := math.Sin(angle*math.Pi/180) * bounding_side
if angle < -90 {
thisBeam = BeamBoundingBox{
UpperRight: BeamPoint{}.New(x+bbx, y-bby),
LowerRight: BeamPoint{}.New(x+bbx-bbx2, y-bby-bby2),
UpperLeft: BeamPoint{}.New(x-bbx, y+bby),
LowerLeft: BeamPoint{}.New(x-bbx-bbx2, y+bby-bby2),
}
} else {
thisBeam = BeamBoundingBox{
UpperRight: BeamPoint{}.New(x+bbx, y+bby),
LowerRight: BeamPoint{}.New(x+bbx+bbx2, y+bby-bby2),
UpperLeft: BeamPoint{}.New(x-bbx, y-bby),
LowerLeft: BeamPoint{}.New(x-bbx+bbx2, y-bby-bby2),
}
}
} else {
x = math.Cos(angle*math.Pi/180) * hypotenuse
y = math.Sin(angle*math.Pi/180) * hypotenuse
bbx := math.Cos((90-math.Abs(angle))*math.Pi/180) * bounding_side / 2
bby := math.Sin((90-math.Abs(angle))*math.Pi/180) * bounding_side / 2
bbx2 := math.Cos(angle*math.Pi/180) * bounding_side
bby2 := math.Sin(angle*math.Pi/180) * bounding_side
if angle < 90 {
thisBeam = BeamBoundingBox{
LowerRight: BeamPoint{}.New(x+bbx, y-bby),
UpperRight: BeamPoint{}.New(x+bbx+bbx2, y-bby+bby2),
LowerLeft: BeamPoint{}.New(x-bbx, y+bby),
UpperLeft: BeamPoint{}.New(x-bbx+bbx2, y+bby+bby2),
}
} else {
thisBeam = BeamBoundingBox{
LowerRight: BeamPoint{}.New(x+bbx, y+bby),
UpperRight: BeamPoint{}.New(x+bbx-bbx2, y+bby+bby2),
LowerLeft: BeamPoint{}.New(x-bbx, y-bby),
UpperLeft: BeamPoint{}.New(x-bbx-bbx2, y-bby+bby2),
}
}
}
return thisBeam, x, y
}
// Regression takes in a CSV data, which should have
// "link" suffixes added. The regression will iterate over
// the given data and replace linked parts with linear models,
// which should be connected with a point.
func Regression(data []byte) (map[int][]float64, error) {
var connectedBuffer bytes.Buffer
cScanner := bufio.NewScanner(bytes.NewReader(
bytes.TrimSpace(data),
))
lc := 0
angleMap := make(map[int][]float64)
for cScanner.Scan() {
if lc == 360 {
lc = 0
}
if strings.HasSuffix(cScanner.Text(), "link") {
connectedBuffer.WriteString(cScanner.Text() + "\n")
lc++
continue
}
if connectedBuffer.Len() > 0 {
r := new(regression.Regression)
r.SetVar(0, "x")
eScanner := bufio.NewScanner(bytes.NewReader(
bytes.TrimSpace(connectedBuffer.Bytes()),
))
var ymin float64 = math.MaxFloat64
var ymax float64 = math.MinInt64
for eScanner.Scan() {
values := strings.Split(eScanner.Text(), ",")
var boundingbox string
for _, s := range values[3] {
switch s {
case '}', '{':
continue
default:
boundingbox = boundingbox + string(s)
}
}
var edges [][]float64
var point []float64
for _, edge := range strings.Split(boundingbox, " ") {
e, _ := strconv.ParseFloat(edge, 64)
point = append(point, e)
if len(point) == 2 {
edges = append(edges, point)
point = []float64{}
}
}
y, _ := strconv.ParseFloat(values[5], 64)
if y < ymin {
ymin = y
}
if y > ymax {
ymax = y
}
r.Train(regression.MakeDataPoints(edges, 0)...)
}
if err := eScanner.Err(); err != nil {
return angleMap, err
}
err := r.Run()
if err != nil {
return angleMap, err
}
var formulaBuffer bytes.Buffer
for _, r := range strings.TrimLeft(r.Formula, "Predicted = ") {
switch r {
case ' ', '+', 'x':
continue
case '*':
formulaBuffer.WriteString(",")
default:
formulaBuffer.WriteString(string(r))
}
}
formula := strings.Split(formulaBuffer.String(), ",")
a, _ := strconv.ParseFloat(formula[0], 64)
b, _ := strconv.ParseFloat(formula[1], 64)
lineStart := a + ymin*b
lineEnd := a + ymax*b
if val, ok := angleMap[lc]; ok {
s := []float64{
(val[0] / lineStart),
(val[1] / ymin),
(val[2] / lineEnd),
(val[3] / ymax),
}
sort.Float64s(s)
if s[0] > 0.95 && s[3] < 1.05 {
lineStart = math.Min(val[0], lineStart)
ymin = math.Min(val[1], ymin)
lineEnd = math.Max(val[2], lineEnd)
ymax = math.Max(val[3], ymax)
}
}
angleMap[lc] = []float64{lineStart, ymin, lineEnd, ymax}
}
lc++
connectedBuffer.Reset()
}
return angleMap, cScanner.Err()
} | castle/util/linear.go | 0.719482 | 0.521532 | linear.go | starcoder |
package datatype
import (
"fmt"
"github.com/i-sevostyanov/NanoDB/internal/sql"
)
type Boolean struct {
value bool
}
func NewBoolean(v bool) Boolean {
return Boolean{value: v}
}
func (b Boolean) Raw() interface{} {
return b.value
}
func (b Boolean) DataType() sql.DataType {
return sql.Boolean
}
func (b Boolean) Compare(v sql.Value) (sql.CompareType, error) {
switch value := v.Raw().(type) {
case bool:
x := b.toInt(b.value)
y := b.toInt(value)
switch {
case x < y:
return sql.Less, nil
case x > y:
return sql.Greater, nil
default:
return sql.Equal, nil
}
case nil:
return sql.Greater, nil
default:
return sql.Equal, fmt.Errorf("unexptected arg type: %T", value)
}
}
func (b Boolean) UnaryPlus() (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) UnaryMinus() (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) Add(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) Sub(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) Mul(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) Div(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) Pow(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) Mod(_ sql.Value) (sql.Value, error) {
return nil, fmt.Errorf("unsupported operation")
}
func (b Boolean) Equal(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
return Boolean{value: b.value == value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("equal: unexptected arg type: %T", value)
}
}
func (b Boolean) NotEqual(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
return Boolean{value: b.value != value}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("not-equal: unexptected arg type: %T", value)
}
}
func (b Boolean) GreaterThan(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
x := b.toInt(b.value)
y := b.toInt(value)
return Boolean{value: x > y}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("greater-than: unexptected arg type: %T", value)
}
}
func (b Boolean) LessThan(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
x := b.toInt(b.value)
y := b.toInt(value)
return Boolean{value: x < y}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("less-than: unexptected arg type: %T", value)
}
}
func (b Boolean) GreaterOrEqual(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
x := b.toInt(b.value)
y := b.toInt(value)
return Boolean{value: x >= y}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("greater-or-equal: unexptected arg type: %T", value)
}
}
func (b Boolean) LessOrEqual(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
x := b.toInt(b.value)
y := b.toInt(value)
return Boolean{value: x <= y}, nil
case nil:
return Null{}, nil
default:
return nil, fmt.Errorf("less-or-equal: unexptected arg type: %T", value)
}
}
func (b Boolean) And(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
return Boolean{value: b.value && value}, nil
case nil:
if b.value {
return Null{}, nil
}
return Boolean{}, nil
default:
return nil, fmt.Errorf("and: unexptected arg type: %T", value)
}
}
func (b Boolean) Or(v sql.Value) (sql.Value, error) {
switch value := v.Raw().(type) {
case bool:
return Boolean{value: b.value || value}, nil
case nil:
if b.value {
return Boolean{value: true}, nil
}
return Null{}, nil
default:
return nil, fmt.Errorf("or: unexptected arg type: %T", value)
}
}
func (b Boolean) toInt(value bool) uint {
if value {
return 1
}
return 0
} | internal/sql/datatype/boolean.go | 0.720958 | 0.460228 | boolean.go | starcoder |
package model
import (
"errors"
)
/*
The Api type exposes the exernal API to the model package. In most cases, the
api methods are simple wrappers to sister methods in the model type which take
care of validating the input parameters like email names and skill Uids. This
frees all the other modules from checking method parameters, and thus keeps
them simpler.
*/
type Api struct {
model *model
}
func NewApi() *Api {
return &Api{
model: newModel(),
}
}
//----------------------------------------------------------------------------
// Add methods
//----------------------------------------------------------------------------
/*
The AddPerson method adds a person to the model. A person is defined throughout
the model by the name part of their email address. Errors: PersonExists.
*/
func (api *Api) AddPerson(emailName string) (err error) {
if api.model.personExists(emailName) {
err = errors.New(PersonExists)
return
}
api.model.addPerson(emailName)
return
}
/*
The AddSkillNode method adds a skill to the model, as a child of the given
parent skill. The method returns a unique ID for the skill (Uid) by which it
may be referred to subsequently. If the model is empty, the new node is adopted
as the root for the tree, and the parent parameter is ignored. The role of
skill nodes in the tree as branches or leaves remains open until a person
registers as having a skill. At that point, the skill becomes fixed as a leaf,
and children may not be added to it subsequently. Errors: UnknownSkill
(parent), IllegalForLeaf.
*/
func (api *Api) AddSkillNode(title string, description string,
parent int) (skillId int, err error) {
if api.model.treeIsEmpty() {
skillId = api.model.addRootSkillNode(title, description)
return
}
if api.model.skillExists(parent) == false {
err = errors.New(UnknownSkill)
return
}
parentNode := api.model.skillNode(parent)
if api.model.someoneHasThisSkill(parentNode) {
err = errors.New(IllegalForHeldSkill)
return
}
skillId = api.model.addChildSkillNode(title, description, parent)
return
}
/*
The GivePersonSkill method registers the given person as having the given
skill. You cannot assign skills in the tree that have children to people.
Errors: UnknownSkill, UnknownPerson, DisallowedForAParent.
*/
func (api *Api) GivePersonSkill(emailName string, skillId int) (err error) {
if api.model.personExists(emailName) == false {
err = errors.New(UnknownPerson)
return
}
if api.model.skillExists(skillId) == false {
err = errors.New(UnknownSkill)
return
}
skill := api.model.skillNode(skillId)
api.model.givePersonSkill(skill, emailName)
return
}
//----------------------------------------------------------------------------
// UiState editing (in model space)
//----------------------------------------------------------------------------
/*
The ToggleSkillCollapsed method marks the given skill in the tree as being
collapsed for the given person. (or vice versa depending on the current state).
It is illegal to call it on a node with no children. Errors: UnknownSkill,
UnknownPerson, IllegalWhenNoChildren
*/
func (api *Api) ToggleSkillCollapsed(
emailName string, skillId int) (err error) {
if api.model.personExists(emailName) == false {
err = errors.New(UnknownPerson)
return
}
if api.model.skillExists(skillId) == false {
err = errors.New(UnknownSkill)
return
}
skill := api.model.skillNode(skillId)
if skill.hasChildren() == false {
err = errors.New(IllegalWhenNoChildren)
return
}
api.model.toggleSkillCollapsed(emailName, skill)
return
}
//----------------------------------------------------------------------------
// Queries
//----------------------------------------------------------------------------
func (api *Api) PersonExists(emailName string) bool {
return api.model.personExists(emailName)
}
func (api *Api) SkillExists(skillId int) bool {
return api.model.skillExists(skillId)
}
func (api *Api) TitleOfSkill(skillId int) (title string, err error) {
if api.model.skillExists(skillId) == false {
err = errors.New(UnknownSkill)
return
}
title = api.model.titleOfSkill(skillId)
return
}
func (api *Api) PersonHasSkill(skillId int, email string) (
hasSkill bool, err error) {
if api.model.skillExists(skillId) == false {
err = errors.New(UnknownSkill)
return
}
if api.model.personExists(email) == false {
err = errors.New(UnknownPerson)
return
}
hasSkill = api.model.personHasSkill(skillId, email)
return
}
func (api *Api) IsCollapsed(email string, skillId int) (
collapsed bool, err error) {
if api.model.personExists(email) == false {
err = errors.New(UnknownPerson)
return
}
collapsed = api.model.isCollapsed(email, skillId)
return
}
/*
The EnumerateTree method provides a linear sequence of the skill Uids which
can be used essentiall as an iteratorto used to render the skill tree. It is
personalised to a particular person in the sense that it will exclude skill
nodes that that person has collapsed in the (abstract) gui. Separate query
methods are available to get the extra data that might be needed for each
row - like for example its depth in the tree.
*/
func (api *Api) EnumerateTree(email string) (skillSeq []int) {
skillSeq = api.model.enumerateTree(email)
return
} | model/api.go | 0.591133 | 0.44342 | api.go | starcoder |
package xrand
import (
"encoding/binary"
"fmt"
"math"
"math/bits"
"time"
)
// https://prng.di.unimi.it/xoshiro512plus.c
type Xoshiro512p struct {
s [8]uint64
}
func NewXoshiro512p(seed int64) *Xoshiro512p {
x := Xoshiro512p{}
x.Seed(seed)
return &x
}
func (x Xoshiro512p) State() []byte {
s := make([]byte, 64)
binary.BigEndian.PutUint64(s[:8], x.s[0])
binary.BigEndian.PutUint64(s[8:16], x.s[1])
binary.BigEndian.PutUint64(s[16:24], x.s[2])
binary.BigEndian.PutUint64(s[24:32], x.s[3])
binary.BigEndian.PutUint64(s[32:40], x.s[4])
binary.BigEndian.PutUint64(s[40:48], x.s[5])
binary.BigEndian.PutUint64(s[48:56], x.s[6])
binary.BigEndian.PutUint64(s[56:64], x.s[7])
return s
}
func (x *Xoshiro512p) SetState(state []byte) {
mix := NewSplitMix64(time.Now().UTC().UnixNano())
x.s[0] = bytesToState64(state, 0, &mix)
x.s[1] = bytesToState64(state, 1, &mix)
x.s[2] = bytesToState64(state, 2, &mix)
x.s[3] = bytesToState64(state, 3, &mix)
x.s[4] = bytesToState64(state, 4, &mix)
x.s[5] = bytesToState64(state, 5, &mix)
x.s[6] = bytesToState64(state, 6, &mix)
x.s[7] = bytesToState64(state, 7, &mix)
}
func (x *Xoshiro512p) Seed(seed int64) {
s := NewSplitMix64(seed)
x.s[0] = s.Uint64()
x.s[1] = s.Uint64()
x.s[2] = s.Uint64()
x.s[3] = s.Uint64()
x.s[4] = s.Uint64()
x.s[5] = s.Uint64()
x.s[6] = s.Uint64()
x.s[7] = s.Uint64()
}
func (x *Xoshiro512p) Uint64() uint64 {
result := x.s[0] + x.s[2]
t := x.s[1] << 11
x.s[2] ^= x.s[0]
x.s[5] ^= x.s[1]
x.s[1] ^= x.s[2]
x.s[7] ^= x.s[3]
x.s[3] ^= x.s[4]
x.s[4] ^= x.s[5]
x.s[0] ^= x.s[6]
x.s[6] ^= x.s[7]
x.s[6] ^= t
x.s[7] = bits.RotateLeft64(x.s[7], 21)
return result
}
func (x *Xoshiro512p) Int64() int64 {
return unsafeUint64ToInt64(x.Uint64())
}
func (x *Xoshiro512p) Int63() int64 {
return int64(x.Uint64() & (1<<63 - 1))
}
func (x *Xoshiro512p) Float64() float64 {
return math.Float64frombits(0x3ff<<52|x.Uint64()>>12) - 1.0
}
// Call Uint64() * 2^256
func (x *Xoshiro512p) Jump() {
var (
jump = [...]uint64{
0x33ed89b6e7a353f9, 0x760083d7955323be, 0x2837f2fbb5f22fae, 0x4b8c5674d309511c,
0xb11ac47a7ba28c25, 0xf1be7667092bcc1c, 0x53851efdb6df0aaf, 0x1ebbc8b23eaf25db,
}
)
s := [...]uint64{0, 0, 0, 0, 0, 0, 0, 0}
for i := range jump {
for b := 0; b < 64; b++ {
if (jump[i] & 1 << b) != 0 {
s[0] ^= x.s[0]
s[1] ^= x.s[1]
s[2] ^= x.s[2]
s[3] ^= x.s[3]
s[4] ^= x.s[4]
s[5] ^= x.s[5]
s[6] ^= x.s[6]
s[7] ^= x.s[7]
}
}
x.Uint64()
}
x.s[0] = s[0]
x.s[1] = s[1]
x.s[2] = s[2]
x.s[3] = s[3]
x.s[4] = s[4]
x.s[5] = s[5]
x.s[6] = s[6]
x.s[7] = s[7]
}
// Call Uint64() * 2^192
func (x *Xoshiro512p) LongJump() {
var (
jump = [...]uint64{
0x11467fef8f921d28, 0xa2a819f2e79c8ea8, 0xa8299fc284b3959a, 0xb4d347340ca63ee1,
0x1cb0940bedbff6ce, 0xd956c5c4fa1f8e17, 0x915e38fd4eda93bc, 0x5b3ccdfa5d7daca5,
}
)
s := [...]uint64{0, 0, 0, 0, 0, 0, 0, 0}
for i := range jump {
for b := 0; b < 64; b++ {
if (jump[i] & 1 << b) != 0 {
s[0] ^= x.s[0]
s[1] ^= x.s[1]
s[2] ^= x.s[2]
s[3] ^= x.s[3]
s[4] ^= x.s[4]
s[5] ^= x.s[5]
s[6] ^= x.s[6]
s[7] ^= x.s[7]
}
}
x.Uint64()
}
x.s[0] = s[0]
x.s[1] = s[1]
x.s[2] = s[2]
x.s[3] = s[3]
x.s[4] = s[4]
x.s[5] = s[5]
x.s[6] = s[6]
x.s[7] = s[7]
}
func (x Xoshiro512p) String() string {
return fmt.Sprintf("%0128x", x.State())
}
func (x Xoshiro512p) GoString() string {
return "xrand.Xoshiro512p{state:\"" + x.String() + "\"}"
} | xoshiro512p.go | 0.513425 | 0.461259 | xoshiro512p.go | starcoder |
package gopark
import (
"encoding/gob"
"fmt"
"math"
"math/rand"
"strings"
"time"
)
type Vector []float64
type IndexedVector map[interface{}]float64
func init() {
gob.Register(new(Vector))
gob.Register(new(IndexedVector))
}
// Vector methods
func NewZeroVector(size int) Vector {
v := make(Vector, size)
return v
}
func NewSameValueVector(size int, value float64) Vector {
v := make(Vector, size)
for i := range v {
v[i] = value
}
return v
}
func NewRandomVector(size int) Vector {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
v := make(Vector, size)
for i := range v {
v[i] = r.Float64()
}
return v
}
func NewRandomNormVector(size int, dev, mean float64) Vector {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
v := make(Vector, size)
for i := range v {
v[i] = r.NormFloat64()*dev + mean
}
return v
}
func NewRandomLimitedVector(size int, minValue, maxValue float64) Vector {
if maxValue <= minValue {
panic("NewRandomLimitedVector cannot use maxValue <= minValue")
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
v := make(Vector, size)
for i := range v {
v[i] = r.Float64()*(maxValue-minValue) + minValue
}
return v
}
func (v Vector) String() string {
fields := make([]string, len(v))
for i := range v {
fields[i] = fmt.Sprintf("%v", v[i])
}
return strings.Join(fields, "\t")
}
func (v Vector) Plus(o Vector) Vector {
return biVectorsOp(v, o, func(x, y float64) float64 {
return x + y
})
}
func (v Vector) Minus(o Vector) Vector {
return biVectorsOp(v, o, func(x, y float64) float64 {
return x - y
})
}
func (v Vector) Multiply(m float64) Vector {
result := make(Vector, len(v))
for i := range v {
result[i] = v[i] * m
}
return result
}
func (v Vector) Divide(d float64) Vector {
if d == 0 {
panic(fmt.Errorf("Vector divided by zero."))
}
result := make(Vector, len(v))
for i := range v {
result[i] = v[i] / d
}
return result
}
func (v Vector) Sum() float64 {
sum := 0.0
for i := range v {
sum += v[i]
}
return sum
}
func (v Vector) Dot(o Vector) float64 {
if len(v) != len(o) {
panic(fmt.Errorf("Two vectors of different length"))
}
sum := 0.0
for i := range v {
sum += v[i] * o[i]
}
return sum
}
func (v Vector) NormL2() float64 {
return v.Dot(v)
}
func (v Vector) Magnitude() float64 {
return math.Sqrt(v.Dot(v))
}
func (v Vector) Cosine(o Vector) float64 {
return v.Dot(o) / v.Magnitude() / o.Magnitude()
}
func (v Vector) EulaDistance(o Vector) float64 {
if len(v) != len(o) {
panic(fmt.Errorf("Two vectors of different length"))
}
dist := 0.0
for i := range v {
dist += (v[i] - o[i]) * (v[i] - o[i])
}
return math.Sqrt(dist)
}
type operand func(x, y float64) float64
func biVectorsOp(v1, v2 Vector, fn operand) Vector {
if len(v1) != len(v2) {
panic(fmt.Errorf("Two vectors of different length"))
}
result := make(Vector, len(v1))
for i := range v1 {
result[i] = fn(v1[i], v2[i])
}
return result
}
// IndexedVector methods
func NewIndexedVector() IndexedVector {
return make(IndexedVector)
}
func (v IndexedVector) String() string {
fields := make([]string, len(v))
i := 0
for key, value := range v {
fields[i] = fmt.Sprintf("%v:%v", key, value)
i++
}
return strings.Join(fields, "\t")
}
func (v IndexedVector) RandomFeature(feature interface{}) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
v[feature] = r.Float64()
}
func (v IndexedVector) RandomLimitedFeature(feature interface{}, minValue, maxValue float64) {
if maxValue <= minValue {
panic("RandomLimitedFeature cannot use maxValue <= minValue")
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
v[feature] = r.Float64()*(maxValue-minValue) + minValue
}
func (v IndexedVector) RandomNormFeature(feature interface{}, dev, mean float64) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
v[feature] = r.NormFloat64()*dev + mean
}
func (v IndexedVector) Copy() IndexedVector {
result := make(IndexedVector)
for key, value := range v {
result[key] = value
}
return result
}
func (v IndexedVector) Keys() []interface{} {
keys := make([]interface{}, len(v))
i := 0
for key := range v {
keys[i] = key
i++
}
return keys
}
func (v IndexedVector) Plus(o IndexedVector) IndexedVector {
result := v.Copy()
for key, value := range o {
result[key] += value
}
return result
}
func (v IndexedVector) Minus(o IndexedVector) IndexedVector {
result := v.Copy()
for key, value := range o {
result[key] -= value
}
return result
}
func (v IndexedVector) Multiply(m float64) IndexedVector {
result := v.Copy()
for key := range result {
result[key] *= m
}
return result
}
func (v IndexedVector) Divide(d float64) IndexedVector {
if d == 0 {
panic("IndexedVector divide by zero")
}
result := v.Copy()
for key := range result {
result[key] /= d
}
return result
}
func (v IndexedVector) Sum() float64 {
var sum float64 = 0
for _, value := range v {
sum += value
}
return sum
}
func (v IndexedVector) Dot(o IndexedVector) float64 {
var sum float64 = 0
vx, vy := v, o
if len(v) > len(o) {
vx, vy = o, v
}
for key, value := range vx {
sum += value * vy[key]
}
return sum
}
func (v IndexedVector) NormL2() float64 {
var sum float64 = 0
for _, value := range v {
sum += value * value
}
return sum
}
func (v IndexedVector) Magnitude() float64 {
return math.Sqrt(v.NormL2())
}
func (v IndexedVector) Cosine(o IndexedVector) float64 {
return v.Dot(o) / v.Magnitude() / o.Magnitude()
}
func (v IndexedVector) EulaDistance(o IndexedVector) float64 {
var dist float64 = 0
for key, value := range v {
dist += (value - o[key]) * (value - o[key])
}
for key, value := range o {
if _, ok := v[key]; !ok {
dist += value * value
}
}
return dist
} | vector.go | 0.77569 | 0.658424 | vector.go | starcoder |
package routex
import "strconv"
type value string
type values map[string]value
// ErrEmptyValue is a error returned from number conversion functions when the
// string value is empty and does not represent a number.
const ErrEmptyValue = errStr("value is empty")
func (v value) String() string {
return string(v)
}
func (v value) Bool() (bool, error) {
if len(v) == 0 {
return false, ErrEmptyValue
}
return strconv.ParseBool(string(v))
}
func (v value) Int() (int64, error) {
if len(v) == 0 {
return 0, ErrEmptyValue
}
return strconv.ParseInt(string(v), 10, 64)
}
func (v value) Uint() (uint64, error) {
if len(v) == 0 {
return 0, ErrEmptyValue
}
return strconv.ParseUint(string(v), 10, 64)
}
func (v value) Float() (float64, error) {
if len(v) == 0 {
return 0, ErrEmptyValue
}
return strconv.ParseFloat(string(v), 64)
}
func (v values) Bool(s string) (bool, error) {
o, ok := v[s]
if !ok {
return false, &errValue{s: s, e: ErrNotExists}
}
return o.Bool()
}
func (v values) Int(s string) (int64, error) {
o, ok := v[s]
if !ok {
return 0, &errValue{s: s, e: ErrNotExists}
}
return o.Int()
}
func (v values) Uint(s string) (uint64, error) {
o, ok := v[s]
if !ok {
return 0, &errValue{s: s, e: ErrNotExists}
}
return o.Uint()
}
func (v values) String(s string) (string, error) {
o, ok := v[s]
if !ok {
return "", &errValue{s: s, e: ErrNotExists}
}
return o.String(), nil
}
func (v values) Float(s string) (float64, error) {
o, ok := v[s]
if !ok {
return 0, &errValue{s: s, e: ErrNotExists}
}
return o.Float()
}
func (v values) StringDefault(s, d string) string {
o, ok := v[s]
if !ok {
return d
}
return o.String()
}
func (v values) BoolDefault(s string, d bool) bool {
o, ok := v[s]
if !ok {
return d
}
if r, err := o.Bool(); err == nil {
return r
}
return d
}
func (v values) IntDefault(s string, d int64) int64 {
o, ok := v[s]
if !ok {
return d
}
if r, err := o.Int(); err == nil {
return r
}
return d
}
func (v values) UintDefault(s string, d uint64) uint64 {
o, ok := v[s]
if !ok {
return d
}
if r, err := o.Uint(); err == nil {
return r
}
return d
}
func (v values) FloatDefault(s string, d float64) float64 {
o, ok := v[s]
if !ok {
return d
}
if r, err := o.Float(); err == nil {
return r
}
return d
} | values.go | 0.685739 | 0.467575 | values.go | starcoder |
package bytehist
import "sort"
// ByteHistogram is an structure that holds the information of a byte histogram.
type ByteHistogram struct {
Count [256]uint64
DataSize uint64
}
// NewByteHistogram creates a new ByteHistogram.
func NewByteHistogram() *ByteHistogram {
return &ByteHistogram{}
}
// Init initializes a ByteHistogram.
func (bh *ByteHistogram) Init() {
for i := 0; i < 256; i++ {
bh.Count[i] = 0
}
bh.DataSize = 0
}
// Update updates a ByteHistogram with an array of bytes.
func (bh *ByteHistogram) Update(bytes []byte) {
for _, b := range bytes {
bh.Count[b]++
}
bh.DataSize += uint64(len(bytes))
}
// ByteList returns two values: a slice of the bytes that have been counted
// once at least and a slice with the actual number of times that every byte
// appears on the processed data.
func (bh *ByteHistogram) ByteList() ([]byte, []uint64) {
bytelist := make([]byte, 256)
bytecount := make([]uint64, 256)
listlen := 0
for i, c := range bh.Count {
if c > 0 {
bytelist[listlen] = byte(i)
bytecount[listlen] = uint64(c)
listlen++
}
}
return bytelist[0:listlen], bytecount[0:listlen]
}
type byteCountPair struct {
b byte
c uint64
}
type byCountAsc []byteCountPair
func (a byCountAsc) Len() int { return len(a) }
func (a byCountAsc) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byCountAsc) Less(i, j int) bool {
return (a[i].c < a[j].c) || (a[i].c == a[j].c && a[i].b < a[j].b)
}
type byCountDesc []byteCountPair
func (a byCountDesc) Len() int { return len(a) }
func (a byCountDesc) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byCountDesc) Less(i, j int) bool {
return (a[i].c > a[j].c) || (a[i].c == a[j].c && a[i].b < a[j].b)
}
// SortedByteList returns two values as the ByteList function does, but the
// resulting slices are sorted by the number of bytes.
// The sorting order is specified by ascOrder, that will be ascending if
// the param is true or descending if it is false.
func (bh *ByteHistogram) SortedByteList(ascOrder bool) ([]byte, []uint64) {
pairs := make([]byteCountPair, 256)
for i, count := range bh.Count {
pairs[i] = byteCountPair{b: byte(i), c: count}
}
if ascOrder {
sort.Sort(byCountAsc(pairs))
} else {
sort.Sort(byCountDesc(pairs))
}
bytelist := make([]byte, 256)
bytecount := make([]uint64, 256)
listlen := 0
for _, pair := range pairs {
if pair.c > 0 {
bytelist[listlen] = pair.b
bytecount[listlen] = pair.c
listlen++
}
}
return bytelist[0:listlen], bytecount[0:listlen]
} | bytehist/bytehist.go | 0.777891 | 0.604953 | bytehist.go | starcoder |
package templating
import (
"fmt"
"strings"
)
// Template represents a pattern and tags to map a metric string to a influxdb Point
type Template struct {
separator string
parts []string
defaultTags map[string]string
greedyField bool
greedyMeasurement bool
}
// apply extracts the template fields from the given line and returns the measurement
// name, tags and field name
func (t *Template) Apply(line string, joiner string) (string, map[string]string, string, error) {
fields := strings.Split(line, t.separator)
var (
measurement []string
tags = make(map[string][]string)
field []string
)
// Set any default tags
for k, v := range t.defaultTags {
tags[k] = append(tags[k], v)
}
// See if an invalid combination has been specified in the template:
for _, tag := range t.parts {
if tag == "measurement*" {
t.greedyMeasurement = true
} else if tag == "field*" {
t.greedyField = true
}
}
if t.greedyField && t.greedyMeasurement {
return "", nil, "",
fmt.Errorf("either 'field*' or 'measurement*' can be used in each "+
"template (but not both together): %q",
strings.Join(t.parts, joiner))
}
for i, tag := range t.parts {
if i >= len(fields) {
continue
}
if tag == "" {
continue
}
switch tag {
case "measurement":
measurement = append(measurement, fields[i])
case "field":
field = append(field, fields[i])
case "field*":
field = append(field, fields[i:]...)
break
case "measurement*":
measurement = append(measurement, fields[i:]...)
break
default:
tags[tag] = append(tags[tag], fields[i])
}
}
// Convert to map of strings.
outtags := make(map[string]string)
for k, values := range tags {
outtags[k] = strings.Join(values, joiner)
}
return strings.Join(measurement, joiner), outtags, strings.Join(field, joiner), nil
}
func NewDefaultTemplateWithPattern(pattern string) (*Template, error) {
return NewTemplate(DefaultSeparator, pattern, nil)
}
// NewTemplate returns a new template ensuring it has a measurement
// specified.
func NewTemplate(separator string, pattern string, defaultTags map[string]string) (*Template, error) {
parts := strings.Split(pattern, separator)
hasMeasurement := false
template := &Template{
separator: separator,
parts: parts,
defaultTags: defaultTags,
}
for _, part := range parts {
if strings.HasPrefix(part, "measurement") {
hasMeasurement = true
}
if part == "measurement*" {
template.greedyMeasurement = true
} else if part == "field*" {
template.greedyField = true
}
}
if !hasMeasurement {
return nil, fmt.Errorf("no measurement specified for template. %q", pattern)
}
return template, nil
}
// templateSpec is a template string split in its constituent parts
type templateSpec struct {
separator string
filter string
template string
tagstring string
}
// templateSpecs is simply an array of template specs implementing the sorting interface
type templateSpecs []templateSpec
// Less reports whether the element with
// index j should sort before the element with index k.
func (e templateSpecs) Less(j, k int) bool {
jlen := len(e[j].filter)
klen := len(e[k].filter)
if jlen == 0 && klen != 0 {
return true
}
if klen == 0 && jlen != 0 {
return false
}
return strings.Count(e[j].template, e[j].separator) <
strings.Count(e[k].template, e[k].separator)
}
// Swap swaps the elements with indexes i and j.
func (e templateSpecs) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
// Len is the number of elements in the collection.
func (e templateSpecs) Len() int { return len(e) } | internal/templating/template.go | 0.767516 | 0.455078 | template.go | starcoder |
// +build !amd64
package poly1305
const (
msgBlock = uint32(1 << 24)
finalBlock = uint32(0)
)
// Sum generates an authenticator for msg using a one-time key and puts the
// 16-byte result into out. Authenticating two different messages with the same
// key allows an attacker to forge messages at will.
func Sum(out *[TagSize]byte, msg []byte, key *[32]byte) {
var (
h, r [5]uint32
pad [4]uint32
block [TagSize]byte
off int
)
initialize(&r, &pad, key)
n := len(msg) & (^(TagSize - 1))
if n > 0 {
core(msg[:n], msgBlock, &h, &r)
msg = msg[n:]
}
if len(msg) > 0 {
off += copy(block[:], msg)
block[off] = 1
core(block[:], finalBlock, &h, &r)
}
finalize(out, &h, &pad)
}
// New returns a hash.Hash computing the poly1305 sum.
// Notice that Poly1305 is inseure if one key is used twice.
func New(key *[32]byte) *Hash {
p := new(Hash)
initialize(&(p.r), &(p.pad), key)
return p
}
// Hash implements a Poly1305 writer interface.
// Poly1305 cannot be used like common hash.Hash implementations,
// beause of using a Poly1305 key twice breaks its security.
// So poly1305.Hash does not support some kind of reset.
type Hash struct {
h, r [5]uint32
pad [4]uint32
buf [TagSize]byte
off int
done bool
}
// Write adds more data to the running Poly1305 hash.
// This function returns an non-nil error, if a call
// to Write happens after the hash's Sum function was
// called. So it's not possible to compute the checksum
// and than add more data.
func (p *Hash) Write(msg []byte) (int, error) {
if p.done {
return 0, errWriteAfterSum
}
n := len(msg)
if p.off > 0 {
dif := TagSize - p.off
if n > dif {
p.off += copy(p.buf[p.off:], msg[:dif])
msg = msg[dif:]
core(p.buf[:], msgBlock, &(p.h), &(p.r))
p.off = 0
} else {
p.off += copy(p.buf[p.off:], msg)
return n, nil
}
}
if nn := len(msg) & (^(TagSize - 1)); nn > 0 {
core(msg[:nn], msgBlock, &(p.h), &(p.r))
msg = msg[nn:]
}
if len(msg) > 0 {
p.off += copy(p.buf[p.off:], msg)
}
return n, nil
}
// Sum computes the Poly1305 checksum of the prevouisly
// processed data and writes it to out. It is legal to
// call this function more than one time.
func (p *Hash) Sum(out *[TagSize]byte) {
h, r := p.h, p.r
pad := p.pad
if p.off > 0 {
var buf [TagSize]byte
copy(buf[:], p.buf[:p.off])
buf[p.off] = 1 // invariant: p.off < TagSize
core(buf[:], finalBlock, &h, &r)
}
finalize(out, &h, &pad)
p.done = true
}
func initialize(r *[5]uint32, pad *[4]uint32, key *[32]byte) {
r[0] = (uint32(key[0]) | uint32(key[1])<<8 | uint32(key[2])<<16 | uint32(key[3])<<24) & 0x3ffffff
r[1] = ((uint32(key[3]) | uint32(key[4])<<8 | uint32(key[5])<<16 | uint32(key[6])<<24) >> 2) & 0x3ffff03
r[2] = ((uint32(key[6]) | uint32(key[7])<<8 | uint32(key[8])<<16 | uint32(key[9])<<24) >> 4) & 0x3ffc0ff
r[3] = ((uint32(key[9]) | uint32(key[10])<<8 | uint32(key[11])<<16 | uint32(key[12])<<24) >> 6) & 0x3f03fff
r[4] = ((uint32(key[12]) | uint32(key[13])<<8 | uint32(key[14])<<16 | uint32(key[15])<<24) >> 8) & 0x00fffff
pad[0] = (uint32(key[16]) | uint32(key[17])<<8 | uint32(key[18])<<16 | uint32(key[19])<<24)
pad[1] = (uint32(key[20]) | uint32(key[21])<<8 | uint32(key[22])<<16 | uint32(key[23])<<24)
pad[2] = (uint32(key[24]) | uint32(key[25])<<8 | uint32(key[26])<<16 | uint32(key[27])<<24)
pad[3] = (uint32(key[28]) | uint32(key[29])<<8 | uint32(key[30])<<16 | uint32(key[31])<<24)
}
func core(msg []byte, flag uint32, h, r *[5]uint32) {
h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4]
r0, r1, r2, r3, r4 := uint64(r[0]), uint64(r[1]), uint64(r[2]), uint64(r[3]), uint64(r[4])
s1, s2, s3, s4 := r1*5, r2*5, r3*5, r4*5
var d0, d1, d2, d3, d4 uint64
length := len(msg) & (^(TagSize - 1))
for i := 0; i < length; i += TagSize {
// h += m
h0 += (uint32(msg[i+0]) | uint32(msg[i+1])<<8 | uint32(msg[i+2])<<16 | uint32(msg[i+3])<<24) & 0x3ffffff
h1 += ((uint32(msg[i+3]) | uint32(msg[i+4])<<8 | uint32(msg[i+5])<<16 | uint32(msg[i+6])<<24) >> 2) & 0x3ffffff
h2 += ((uint32(msg[i+6]) | uint32(msg[i+7])<<8 | uint32(msg[i+8])<<16 | uint32(msg[i+9])<<24) >> 4) & 0x3ffffff
h3 += ((uint32(msg[i+9]) | uint32(msg[i+10])<<8 | uint32(msg[i+11])<<16 | uint32(msg[i+12])<<24) >> 6) & 0x3ffffff
h4 += ((uint32(msg[i+12]) | uint32(msg[i+13])<<8 | uint32(msg[i+14])<<16 | uint32(msg[i+15])<<24) >> 8) | flag
// h *= r
d0 = (uint64(h0) * r0) + (uint64(h1) * s4) + (uint64(h2) * s3) + (uint64(h3) * s2) + (uint64(h4) * s1)
d1 = (d0 >> 26) + (uint64(h0) * r1) + (uint64(h1) * r0) + (uint64(h2) * s4) + (uint64(h3) * s3) + (uint64(h4) * s2)
d2 = (d1 >> 26) + (uint64(h0) * r2) + (uint64(h1) * r1) + (uint64(h2) * r0) + (uint64(h3) * s4) + (uint64(h4) * s3)
d3 = (d2 >> 26) + (uint64(h0) * r3) + (uint64(h1) * r2) + (uint64(h2) * r1) + (uint64(h3) * r0) + (uint64(h4) * s4)
d4 = (d3 >> 26) + (uint64(h0) * r4) + (uint64(h1) * r3) + (uint64(h2) * r2) + (uint64(h3) * r1) + (uint64(h4) * r0)
// h %= p
h0 = uint32(d0) & 0x3ffffff
h1 = uint32(d1) & 0x3ffffff
h2 = uint32(d2) & 0x3ffffff
h3 = uint32(d3) & 0x3ffffff
h4 = uint32(d4) & 0x3ffffff
h0 += uint32(d4>>26) * 5
h1 += h0 >> 26
h0 = h0 & 0x3ffffff
}
h[0], h[1], h[2], h[3], h[4] = h0, h1, h2, h3, h4
}
func finalize(tag *[TagSize]byte, h *[5]uint32, pad *[4]uint32) {
var g0, g1, g2, g3, g4 uint32
// fully carry h
h0, h1, h2, h3, h4 := h[0], h[1], h[2], h[3], h[4]
h2 += h1 >> 26
h1 &= 0x3ffffff
h3 += h2 >> 26
h2 &= 0x3ffffff
h4 += h3 >> 26
h3 &= 0x3ffffff
h0 += 5 * (h4 >> 26)
h4 &= 0x3ffffff
h1 += h0 >> 26
h0 &= 0x3ffffff
// h + -p
g0 = h0 + 5
g1 = h1 + (g0 >> 26)
g0 &= 0x3ffffff
g2 = h2 + (g1 >> 26)
g1 &= 0x3ffffff
g3 = h3 + (g2 >> 26)
g2 &= 0x3ffffff
g4 = h4 + (g3 >> 26) - (1 << 26)
g3 &= 0x3ffffff
// select h if h < p else h + -p
mask := (g4 >> (32 - 1)) - 1
g0 &= mask
g1 &= mask
g2 &= mask
g3 &= mask
g4 &= mask
mask = ^mask
h0 = (h0 & mask) | g0
h1 = (h1 & mask) | g1
h2 = (h2 & mask) | g2
h3 = (h3 & mask) | g3
h4 = (h4 & mask) | g4
// h %= 2^128
h0 |= h1 << 26
h1 = ((h1 >> 6) | (h2 << 20))
h2 = ((h2 >> 12) | (h3 << 14))
h3 = ((h3 >> 18) | (h4 << 8))
// tag = (h + pad) % (2^128)
f := uint64(h0) + uint64(pad[0])
h0 = uint32(f)
f = uint64(h1) + uint64(pad[1]) + (f >> 32)
h1 = uint32(f)
f = uint64(h2) + uint64(pad[2]) + (f >> 32)
h2 = uint32(f)
f = uint64(h3) + uint64(pad[3]) + (f >> 32)
h3 = uint32(f)
tag[0] = byte(h0)
tag[1] = byte(h0 >> 8)
tag[2] = byte(h0 >> 16)
tag[3] = byte(h0 >> 24)
tag[4] = byte(h1)
tag[5] = byte(h1 >> 8)
tag[6] = byte(h1 >> 16)
tag[7] = byte(h1 >> 24)
tag[8] = byte(h2)
tag[9] = byte(h2 >> 8)
tag[10] = byte(h2 >> 16)
tag[11] = byte(h2 >> 24)
tag[12] = byte(h3)
tag[13] = byte(h3 >> 8)
tag[14] = byte(h3 >> 16)
tag[15] = byte(h3 >> 24)
} | vendor/github.com/aead/poly1305/poly1305_ref.go | 0.578448 | 0.402451 | poly1305_ref.go | starcoder |
package main
import (
"regexp"
"strconv"
. "github.com/asuahsahua/advent2019/cmd/common"
)
func main() {
// --- Day 4: Secure Container ---
// You arrive at the Venus fuel depot only to discover it's protected by a
// password. The Elves had written the password on a sticky note, but
// someone threw it out.
// How many different passwords within the range given in your puzzle input
// meet these criteria?
input := parseInput1(`240920-789857`)
Part1("%d", GetPasswordCount(input, false))
// --- Part Two ---
// An Elf just remembered one more important detail: the two adjacent
// matching digits are not part of a larger group of matching digits.
// How many different passwords within the range given in your puzzle input
// meet all of the criteria?
Part2("%d", GetPasswordCount(input, true))
}
func parseInput1(input string) IntRange {
regexp := regexp.MustCompile(`^(\d+)-(\d+)$`)
match := regexp.FindStringSubmatch(input)
PanicIf(match == nil, "Could not find match")
first, err1 := strconv.Atoi(match[1])
PanicIfErr(err1)
second, err2 := strconv.Atoi(match[2])
PanicIfErr(err2)
return IntRange{first, second}
}
type IntRange struct{
start int
end int
}
func MeetsPasswordCriteria(password int, valueRange IntRange, checkLargerGroup bool) bool {
// It is a six-digit number.
if password < 100000 || password > <PASSWORD> {
return false
}
// The value is within the range given in your puzzle input.
if password < valueRange.start || password > valueRange.end {
return false
}
digits := DecimalDigits(password)
for i := 0; i < len(digits) - 1; i++ {
first, second := digits[i], digits[i+1]
// Going from left to right, the digits never decrease; they only ever
// increase or stay the same (like 111123 or 135679).
if first > second {
return false
}
}
adjacents := FindAdjacentGroups(digits)
if false == checkLargerGroup {
return len(adjacents) > 0
}
for _, group := range(adjacents) {
if group.count == 2 {
return true
}
}
// If the previous for{} loop didn't return true, this is an invalid password.
return false
}
func GetPasswordCount(valueRange IntRange, checkLargerGroup bool) int {
passwordCount := 0
for i := valueRange.start ; i <= valueRange.end; i++ {
if MeetsPasswordCriteria(i, valueRange, checkLargerGroup) {
passwordCount++
}
}
return passwordCount
}
type AdjacentDigits struct{
digit int // The digit that has adjacency
count int // How many digits are adjacent in this match
}
func FindAdjacentGroups(digits []int) []AdjacentDigits {
adjacent := make([]AdjacentDigits, 0)
current := -1 // A digit can't be -1, so this is our 'null' value
count := 1
for i := 0; i < len(digits); i++ {
if int(digits[i]) == current {
// If we have a match, increment the count and move on
count++
} else if count > 1 {
// If we didn't have a match and the count is more than 1, then we have adjacent values!
// Record those adjacent values and
adjacent = append(adjacent, AdjacentDigits{current, count})
count = 1
}
current = int(digits[i])
}
// Finally, clean up the tail end of lingering possibilities
if count > 1 {
adjacent = append(adjacent, AdjacentDigits{current, count})
}
return adjacent
} | cmd/day04/main.go | 0.572723 | 0.462716 | main.go | starcoder |
// Package math provides a mockable wrapper for math.
package math
import (
math "math"
)
var _ Interface = &Impl{}
var _ = math.Abs
type Interface interface {
Abs(x float64) float64
Acos(x float64) float64
Acosh(x float64) float64
Asin(x float64) float64
Asinh(x float64) float64
Atan(x float64) float64
Atan2(y float64, x float64) float64
Atanh(x float64) float64
Cbrt(x float64) float64
Ceil(x float64) float64
Copysign(x float64, y float64) float64
Cos(x float64) float64
Cosh(x float64) float64
Dim(x float64, y float64) float64
Erf(x float64) float64
Erfc(x float64) float64
Erfcinv(x float64) float64
Erfinv(x float64) float64
Exp(x float64) float64
Exp2(x float64) float64
Expm1(x float64) float64
FMA(x float64, y float64, z float64) float64
Float32bits(f float32) uint32
Float32frombits(b uint32) float32
Float64bits(f float64) uint64
Float64frombits(b uint64) float64
Floor(x float64) float64
Frexp(f float64) (frac float64, exp int)
Gamma(x float64) float64
Hypot(p float64, q float64) float64
Ilogb(x float64) int
Inf(sign int) float64
IsInf(f float64, sign int) bool
IsNaN(f float64) (is bool)
J0(x float64) float64
J1(x float64) float64
Jn(n int, x float64) float64
Ldexp(frac float64, exp int) float64
Lgamma(x float64) (lgamma float64, sign int)
Log(x float64) float64
Log10(x float64) float64
Log1p(x float64) float64
Log2(x float64) float64
Logb(x float64) float64
Max(x float64, y float64) float64
Min(x float64, y float64) float64
Mod(x float64, y float64) float64
Modf(f float64) (int float64, frac float64)
NaN() float64
Nextafter(x float64, y float64) (r float64)
Nextafter32(x float32, y float32) (r float32)
Pow(x float64, y float64) float64
Pow10(n int) float64
Remainder(x float64, y float64) float64
Round(x float64) float64
RoundToEven(x float64) float64
Signbit(x float64) bool
Sin(x float64) float64
Sincos(x float64) (sin float64, cos float64)
Sinh(x float64) float64
Sqrt(x float64) float64
Tan(x float64) float64
Tanh(x float64) float64
Trunc(x float64) float64
Y0(x float64) float64
Y1(x float64) float64
Yn(n int, x float64) float64
}
type Impl struct{}
func (*Impl) Abs(x float64) float64 {
return math.Abs(x)
}
func (*Impl) Acos(x float64) float64 {
return math.Acos(x)
}
func (*Impl) Acosh(x float64) float64 {
return math.Acosh(x)
}
func (*Impl) Asin(x float64) float64 {
return math.Asin(x)
}
func (*Impl) Asinh(x float64) float64 {
return math.Asinh(x)
}
func (*Impl) Atan(x float64) float64 {
return math.Atan(x)
}
func (*Impl) Atan2(y float64, x float64) float64 {
return math.Atan2(y, x)
}
func (*Impl) Atanh(x float64) float64 {
return math.Atanh(x)
}
func (*Impl) Cbrt(x float64) float64 {
return math.Cbrt(x)
}
func (*Impl) Ceil(x float64) float64 {
return math.Ceil(x)
}
func (*Impl) Copysign(x float64, y float64) float64 {
return math.Copysign(x, y)
}
func (*Impl) Cos(x float64) float64 {
return math.Cos(x)
}
func (*Impl) Cosh(x float64) float64 {
return math.Cosh(x)
}
func (*Impl) Dim(x float64, y float64) float64 {
return math.Dim(x, y)
}
func (*Impl) Erf(x float64) float64 {
return math.Erf(x)
}
func (*Impl) Erfc(x float64) float64 {
return math.Erfc(x)
}
func (*Impl) Erfcinv(x float64) float64 {
return math.Erfcinv(x)
}
func (*Impl) Erfinv(x float64) float64 {
return math.Erfinv(x)
}
func (*Impl) Exp(x float64) float64 {
return math.Exp(x)
}
func (*Impl) Exp2(x float64) float64 {
return math.Exp2(x)
}
func (*Impl) Expm1(x float64) float64 {
return math.Expm1(x)
}
func (*Impl) FMA(x float64, y float64, z float64) float64 {
return math.FMA(x, y, z)
}
func (*Impl) Float32bits(f float32) uint32 {
return math.Float32bits(f)
}
func (*Impl) Float32frombits(b uint32) float32 {
return math.Float32frombits(b)
}
func (*Impl) Float64bits(f float64) uint64 {
return math.Float64bits(f)
}
func (*Impl) Float64frombits(b uint64) float64 {
return math.Float64frombits(b)
}
func (*Impl) Floor(x float64) float64 {
return math.Floor(x)
}
func (*Impl) Frexp(f float64) (frac float64, exp int) {
return math.Frexp(f)
}
func (*Impl) Gamma(x float64) float64 {
return math.Gamma(x)
}
func (*Impl) Hypot(p float64, q float64) float64 {
return math.Hypot(p, q)
}
func (*Impl) Ilogb(x float64) int {
return math.Ilogb(x)
}
func (*Impl) Inf(sign int) float64 {
return math.Inf(sign)
}
func (*Impl) IsInf(f float64, sign int) bool {
return math.IsInf(f, sign)
}
func (*Impl) IsNaN(f float64) (is bool) {
return math.IsNaN(f)
}
func (*Impl) J0(x float64) float64 {
return math.J0(x)
}
func (*Impl) J1(x float64) float64 {
return math.J1(x)
}
func (*Impl) Jn(n int, x float64) float64 {
return math.Jn(n, x)
}
func (*Impl) Ldexp(frac float64, exp int) float64 {
return math.Ldexp(frac, exp)
}
func (*Impl) Lgamma(x float64) (lgamma float64, sign int) {
return math.Lgamma(x)
}
func (*Impl) Log(x float64) float64 {
return math.Log(x)
}
func (*Impl) Log10(x float64) float64 {
return math.Log10(x)
}
func (*Impl) Log1p(x float64) float64 {
return math.Log1p(x)
}
func (*Impl) Log2(x float64) float64 {
return math.Log2(x)
}
func (*Impl) Logb(x float64) float64 {
return math.Logb(x)
}
func (*Impl) Max(x float64, y float64) float64 {
return math.Max(x, y)
}
func (*Impl) Min(x float64, y float64) float64 {
return math.Min(x, y)
}
func (*Impl) Mod(x float64, y float64) float64 {
return math.Mod(x, y)
}
func (*Impl) Modf(f float64) (int float64, frac float64) {
return math.Modf(f)
}
func (*Impl) NaN() float64 {
return math.NaN()
}
func (*Impl) Nextafter(x float64, y float64) (r float64) {
return math.Nextafter(x, y)
}
func (*Impl) Nextafter32(x float32, y float32) (r float32) {
return math.Nextafter32(x, y)
}
func (*Impl) Pow(x float64, y float64) float64 {
return math.Pow(x, y)
}
func (*Impl) Pow10(n int) float64 {
return math.Pow10(n)
}
func (*Impl) Remainder(x float64, y float64) float64 {
return math.Remainder(x, y)
}
func (*Impl) Round(x float64) float64 {
return math.Round(x)
}
func (*Impl) RoundToEven(x float64) float64 {
return math.RoundToEven(x)
}
func (*Impl) Signbit(x float64) bool {
return math.Signbit(x)
}
func (*Impl) Sin(x float64) float64 {
return math.Sin(x)
}
func (*Impl) Sincos(x float64) (sin float64, cos float64) {
return math.Sincos(x)
}
func (*Impl) Sinh(x float64) float64 {
return math.Sinh(x)
}
func (*Impl) Sqrt(x float64) float64 {
return math.Sqrt(x)
}
func (*Impl) Tan(x float64) float64 {
return math.Tan(x)
}
func (*Impl) Tanh(x float64) float64 {
return math.Tanh(x)
}
func (*Impl) Trunc(x float64) float64 {
return math.Trunc(x)
}
func (*Impl) Y0(x float64) float64 {
return math.Y0(x)
}
func (*Impl) Y1(x float64) float64 {
return math.Y1(x)
}
func (*Impl) Yn(n int, x float64) float64 {
return math.Yn(n, x)
} | math/math.go | 0.879522 | 0.691595 | math.go | starcoder |
package square
// A [CatalogObject](#type-CatalogObject) instance of the `ITEM` type, also referred to as an item, in the catalog.
type CatalogItem struct {
// The item's name. This is a searchable attribute for use in applicable query filters, its value must not be empty, and the length is of Unicode code points.
Name string `json:"name,omitempty"`
// The item's description. This is a searchable attribute for use in applicable query filters, and its value length is of Unicode code points.
Description string `json:"description,omitempty"`
// The text of the item's display label in the Square Point of Sale app. Only up to the first five characters of the string are used. This attribute is searchable, and its value length is of Unicode code points.
Abbreviation string `json:"abbreviation,omitempty"`
// The color of the item's display label in the Square Point of Sale app. This must be a valid hex color code.
LabelColor string `json:"label_color,omitempty"`
// If `true`, the item can be added to shipping orders from the merchant's online store.
AvailableOnline bool `json:"available_online,omitempty"`
// If `true`, the item can be added to pickup orders from the merchant's online store.
AvailableForPickup bool `json:"available_for_pickup,omitempty"`
// If `true`, the item can be added to electronically fulfilled orders from the merchant's online store.
AvailableElectronically bool `json:"available_electronically,omitempty"`
// The ID of the item's category, if any.
CategoryId string `json:"category_id,omitempty"`
// A set of IDs indicating the taxes enabled for this item. When updating an item, any taxes listed here will be added to the item. Taxes may also be added to or deleted from an item using `UpdateItemTaxes`.
TaxIds []string `json:"tax_ids,omitempty"`
// A set of `CatalogItemModifierListInfo` objects representing the modifier lists that apply to this item, along with the overrides and min and max limits that are specific to this item. Modifier lists may also be added to or deleted from an item using `UpdateItemModifierLists`.
ModifierListInfo []CatalogItemModifierListInfo `json:"modifier_list_info,omitempty"`
// A list of CatalogObjects containing the `CatalogItemVariation`s for this item.
Variations []CatalogObject `json:"variations,omitempty"`
// The product type of the item. May not be changed once an item has been created. Only items of product type `REGULAR` or `APPOINTMENTS_SERVICE` may be created by this API; items with other product types are read-only. See [CatalogItemProductType](#type-catalogitemproducttype) for possible values
ProductType string `json:"product_type,omitempty"`
// If `false`, the Square Point of Sale app will present the `CatalogItem`'s details screen immediately, allowing the merchant to choose `CatalogModifier`s before adding the item to the cart. This is the default behavior. If `true`, the Square Point of Sale app will immediately add the item to the cart with the pre-selected modifiers, and merchants can edit modifiers by drilling down onto the item's details. Third-party clients are encouraged to implement similar behaviors.
SkipModifierScreen bool `json:"skip_modifier_screen,omitempty"`
// List of item options IDs for this item. Used to manage and group item variations in a specified order. Maximum: 6 item options.
ItemOptions []CatalogItemOptionForItem `json:"item_options,omitempty"`
} | square/model_catalog_item.go | 0.817392 | 0.401394 | model_catalog_item.go | starcoder |
package math
import nativeMath "math"
type Vector2 struct {
X float32
Y float32
}
func NewDefaultVector2() *Vector2 {
return NewVector2(0, 0)
}
func NewVector2(x float32, y float32) *Vector2 {
return &Vector2{
X: x,
Y: y,
}
}
func NewVector2Inf(sign int) *Vector2 {
return &Vector2{
X: float32(nativeMath.Inf(sign)),
Y: float32(nativeMath.Inf(sign)),
}
}
func NewVector2FromArray(arr []float32, offset int) *Vector2 {
return &Vector2{
X: arr[offset],
Y: arr[offset+1],
}
}
func (vec *Vector2) GetWidth() float32 {
return vec.X
}
func (vec *Vector2) SetWidth(width float32) {
vec.X = width
}
func (vec *Vector2) SetX(x float32) {
vec.X = x
}
func (vec *Vector2) GetHeight() float32 {
return vec.Y
}
func (vec *Vector2) SetHeight(height float32) {
vec.Y = height
}
func (vec *Vector2) SetY(y float32) {
vec.Y = y
}
func (vec *Vector2) Set(x float32, y float32) {
vec.X = x
vec.Y = y
}
func (vec *Vector2) SetScalar(num float32) {
vec.X = num
vec.Y = num
}
func (vec *Vector2) Copy(source *Vector2) {
vec.X = source.X
vec.Y = source.Y
}
func (vec *Vector2) Clone() *Vector2 {
return &Vector2{
X: vec.X,
Y: vec.Y,
}
}
func (vec *Vector2) Add(v *Vector2) {
vec.X += v.X
vec.Y += v.Y
}
func (vec *Vector2) AddScalar(num float32) {
vec.X += num
vec.Y += num
}
func (vec *Vector2) SetAddVectors(v1 *Vector2, v2 *Vector2) {
vec.X = v1.X + v2.X
vec.Y = v1.Y + v2.Y
}
func (vec *Vector2) AddScaledVector(v1 *Vector2, scale float32) {
vec.X += v1.X * scale
vec.Y += v1.Y * scale
}
func (vec *Vector2) Sub(v *Vector2) {
vec.X -= v.X
vec.Y -= v.Y
}
func (vec *Vector2) SubScalar(num float32) {
vec.X -= num
vec.Y -= num
}
func (vec *Vector2) SetSubVectors(v1 *Vector2, v2 *Vector2) {
vec.X = v1.X - v2.X
vec.Y = v1.Y - v2.Y
}
func (vec *Vector2) Multiply(v *Vector2) {
vec.X *= v.X
vec.Y *= v.Y
}
func (vec *Vector2) MultiplyScalar(num float32) {
vec.X *= num
vec.Y *= num
}
func (vec *Vector2) Divide(v *Vector2) {
vec.X /= v.X
vec.Y /= v.Y
}
func (vec *Vector2) DivideScalar(num float32) {
vec.X /= num
vec.Y /= num
}
func (vec *Vector2) ApplyMatrix3(m *Matrix3) {
x := vec.X
y := vec.Y
e := m.GetElements()
vec.X = e[0]*x + e[3]*y + e[6]
vec.Y = e[1]*x + e[4]*y + e[7]
}
func (vec *Vector2) Min(v *Vector2) {
vec.X = Min(vec.X, v.X)
vec.Y = Min(vec.Y, v.Y)
}
func (vec *Vector2) Max(v *Vector2) {
vec.X = Max(vec.X, v.X)
vec.Y = Max(vec.Y, v.Y)
}
/*
Clamps the value to be between min and max.
*/
func (vec *Vector2) Clamp(min *Vector2, max *Vector2) {
vec.X = Max(min.X, Min(max.X, vec.X))
vec.Y = Max(min.Y, Min(max.Y, vec.Y))
}
func (vec *Vector2) ClampScalar(min float32, max float32) {
minVec := NewVector2(min, min)
maxVec := NewVector2(max, max)
vec.Clamp(minVec, maxVec)
}
func (vec *Vector2) ClampLength(min float32, max float32) {
length := vec.GetLength()
div := length
if length == 0 {
div = 1
}
vec.DivideScalar(div)
vec.MultiplyScalar(Max(min, Min(max, length)))
}
func (vec *Vector2) Floor() {
vec.X = Floor(vec.X)
vec.Y = Floor(vec.Y)
}
func (vec *Vector2) Ceil() {
vec.X = Ceil(vec.X)
vec.Y = Ceil(vec.Y)
}
func (vec *Vector2) Round() {
vec.X = Round(vec.X)
vec.Y = Round(vec.Y)
}
func (vec *Vector2) RoundToZero() {
if vec.X < 0 {
vec.X = Ceil(vec.X)
} else {
vec.X = Floor(vec.X)
}
if vec.Y < 0 {
vec.Y = Ceil(vec.Y)
} else {
vec.Y = Floor(vec.Y)
}
}
func (vec *Vector2) Negate() {
vec.X = -vec.X
vec.Y = -vec.Y
}
func (vec *Vector2) Dot(v *Vector2) float32 {
return vec.X*v.X + vec.Y*v.Y
}
func (vec *Vector2) Cross(v *Vector2) float32 {
return vec.X*v.X - vec.Y + v.Y
}
func (vec *Vector2) GetLengthSq() float32 {
return vec.X*vec.X + vec.Y*vec.Y
}
func (vec *Vector2) GetLength() float32 {
return Sqrt(vec.X*vec.X + vec.Y*vec.Y)
}
func (vec *Vector2) SetLength(length float32) {
vec.Normalize()
vec.MultiplyScalar(length)
}
func (vec *Vector2) GetManhattanLength() float32 {
return Abs(vec.X) + Abs(vec.Y)
}
func (vec *Vector2) Normalize() {
div := vec.GetLength()
if div == 0 {
div = 1
}
vec.DivideScalar(div)
}
func (vec *Vector2) GetAngle() float32 {
angle := Atan2(vec.Y, vec.X)
if angle < 0 {
angle += 2 * Pi
}
return angle
}
func (vec *Vector2) GetDistanceTo(v *Vector2) float32 {
return Sqrt(vec.GetDistanceToSquared(v))
}
func (vec *Vector2) GetDistanceToSquared(v *Vector2) float32 {
dx := vec.X - v.X
dy := vec.Y - v.Y
return dx*dx + dy*dy
}
func (vec *Vector2) GetManhattanDistanceTo(v *Vector2) float32 {
return Abs(vec.X-v.X) + Abs(vec.Y-v.Y)
}
func (vec *Vector2) Lerp(v *Vector2, alpha float32) {
vec.X += (v.X - vec.X) * alpha
vec.Y += (v.Y - vec.Y) * alpha
}
func (vec *Vector2) LerpVectors(v1 *Vector2, v2 *Vector2, alpha float32) {
vec.SetSubVectors(v2, v1)
vec.MultiplyScalar(alpha)
vec.Add(v1)
}
func (vec *Vector2) Equals(v *Vector2) bool {
return vec.X == v.X && vec.Y == v.Y
}
func (vec *Vector2) RotateAround(center *Vector2, angle float32) {
c := Cos(angle)
s := Sin(angle)
x := vec.X - center.X
y := vec.Y - center.Y
vec.X = x*c - y*s + center.X
vec.Y = x*s + y*c + center.Y
}
func (vec *Vector2) ToArray() [2]float32 {
return [2]float32{vec.X, vec.Y}
}
func (vec *Vector2) CopyToArray(array []float32, offset int) {
va := vec.ToArray()
copy(array[offset:], va[0:])
} | vector2.go | 0.879393 | 0.862872 | vector2.go | starcoder |
package duration
import (
"fmt"
"regexp"
"strconv"
"strings"
)
var reg = regexp.MustCompile(`(\d+)([a-zA-Z]+)`)
// Duration represents a period of zero or more days, weeks, months, and/or years
type Duration struct {
Days int
Weeks int
Months int
Years int
}
// unit represents a time unit during parsing
type unit int
const (
invalid unit = iota
day
week
month
year
)
// unitMap maps the various versions of a string to the proper unit value
var unitMap = map[string]unit{
"d": day,
"day": day,
"days": day,
"w": week,
"week": week,
"weeks": week,
"m": month,
"month": month,
"months": month,
"y": year,
"year": year,
"years": year,
}
// Parse attempts to conver the given string into a Duration. An invalid
// format will result in an error.
func Parse(s string) (Duration, error) {
var d Duration
s = strings.ToLower(strings.Replace(s, " ", "", -1))
if s == "" {
return d, nil
}
if s == "0" {
return d, nil
}
var groups = reg.FindAllStringSubmatch(s, -1)
if len(groups) == 0 {
return d, fmt.Errorf("invalid time period")
}
for _, group := range groups {
var numStr, unit = group[1], group[2]
var num, _ = strconv.Atoi(numStr)
var u = unitMap[unit]
switch u {
case day:
if d.Days > 0 {
return d, fmt.Errorf("days specified more than once")
}
d.Days = num
case week:
if d.Weeks > 0 {
return d, fmt.Errorf("weeks specified more than once")
}
d.Weeks = num
case month:
if d.Months > 0 {
return d, fmt.Errorf("months specified more than once")
}
d.Months = num
case year:
if d.Years > 0 {
return d, fmt.Errorf("years specified more than once")
}
d.Years = num
default:
return d, fmt.Errorf("invalid unit name %q", unit)
}
}
return d, nil
}
func appendDuration(out []string, num int, unit string) []string {
if num < 1 {
return out
}
if num == 1 {
return append(out, "1 "+unit)
}
return append(out, strconv.Itoa(num)+" "+unit+"s")
}
func (d Duration) String() string {
var out []string
out = appendDuration(out, d.Years, "year")
out = appendDuration(out, d.Months, "month")
out = appendDuration(out, d.Weeks, "week")
out = appendDuration(out, d.Days, "day")
if len(out) == 0 {
return "0 days"
}
return strings.Join(out, " ")
}
// RFC3339 returns an unambiguous, machine-friendly string containing one or
// more groups of number + single-letter unit, uppercased
func (d Duration) RFC3339() string {
if d.Zero() {
return "P0D"
}
if d.Weeks > 0 && d.Years == 0 && d.Months == 0 && d.Days == 0 {
return "P" + strconv.Itoa(d.Weeks) + "W"
}
var s = "P"
var inf = []struct {
num int
unit string
}{
{d.Years, "Y"},
{d.Months, "M"},
{d.Days + d.Weeks*7, "D"},
}
for _, i := range inf {
if i.num > 0 {
s += strconv.Itoa(i.num) + i.unit
}
}
return s
}
// Zero returns true if the duration represents precisely zero
func (d Duration) Zero() bool {
return d.Years == 0 && d.Months == 0 && d.Weeks == 0 && d.Days == 0
} | src/duration/duration.go | 0.683208 | 0.471467 | duration.go | starcoder |
package msgraph
// OnPremisesPublishingType undocumented
type OnPremisesPublishingType int
const (
// OnPremisesPublishingTypeVAppProxy undocumented
OnPremisesPublishingTypeVAppProxy OnPremisesPublishingType = 0
// OnPremisesPublishingTypeVExchangeOnline undocumented
OnPremisesPublishingTypeVExchangeOnline OnPremisesPublishingType = 1
// OnPremisesPublishingTypeVAuthentication undocumented
OnPremisesPublishingTypeVAuthentication OnPremisesPublishingType = 2
// OnPremisesPublishingTypeVProvisioning undocumented
OnPremisesPublishingTypeVProvisioning OnPremisesPublishingType = 3
// OnPremisesPublishingTypeVIntunePfx undocumented
OnPremisesPublishingTypeVIntunePfx OnPremisesPublishingType = 4
// OnPremisesPublishingTypeVOflineDomainJoin undocumented
OnPremisesPublishingTypeVOflineDomainJoin OnPremisesPublishingType = 5
// OnPremisesPublishingTypeVUnknownFutureValue undocumented
OnPremisesPublishingTypeVUnknownFutureValue OnPremisesPublishingType = 6
)
// OnPremisesPublishingTypePAppProxy returns a pointer to OnPremisesPublishingTypeVAppProxy
func OnPremisesPublishingTypePAppProxy() *OnPremisesPublishingType {
v := OnPremisesPublishingTypeVAppProxy
return &v
}
// OnPremisesPublishingTypePExchangeOnline returns a pointer to OnPremisesPublishingTypeVExchangeOnline
func OnPremisesPublishingTypePExchangeOnline() *OnPremisesPublishingType {
v := OnPremisesPublishingTypeVExchangeOnline
return &v
}
// OnPremisesPublishingTypePAuthentication returns a pointer to OnPremisesPublishingTypeVAuthentication
func OnPremisesPublishingTypePAuthentication() *OnPremisesPublishingType {
v := OnPremisesPublishingTypeVAuthentication
return &v
}
// OnPremisesPublishingTypePProvisioning returns a pointer to OnPremisesPublishingTypeVProvisioning
func OnPremisesPublishingTypePProvisioning() *OnPremisesPublishingType {
v := OnPremisesPublishingTypeVProvisioning
return &v
}
// OnPremisesPublishingTypePIntunePfx returns a pointer to OnPremisesPublishingTypeVIntunePfx
func OnPremisesPublishingTypePIntunePfx() *OnPremisesPublishingType {
v := OnPremisesPublishingTypeVIntunePfx
return &v
}
// OnPremisesPublishingTypePOflineDomainJoin returns a pointer to OnPremisesPublishingTypeVOflineDomainJoin
func OnPremisesPublishingTypePOflineDomainJoin() *OnPremisesPublishingType {
v := OnPremisesPublishingTypeVOflineDomainJoin
return &v
}
// OnPremisesPublishingTypePUnknownFutureValue returns a pointer to OnPremisesPublishingTypeVUnknownFutureValue
func OnPremisesPublishingTypePUnknownFutureValue() *OnPremisesPublishingType {
v := OnPremisesPublishingTypeVUnknownFutureValue
return &v
} | beta/OnPremisesPublishingTypeEnum.go | 0.552298 | 0.524699 | OnPremisesPublishingTypeEnum.go | starcoder |
package main
//Multiple functions can read from the same channel until that channel is closed;
// this is called fan-out. This provides a way to distribute work amongst a group of workers to parallelize CPU use and I/O.
// A function can read from multiple inputs and proceed until all are closed by multiplexing the input channels
// onto a single channel that's closed when all the inputs are closed. This is called fan-in.
import (
"fmt"
"sync"
)
/*
There's no formal definition of a pipeline in Go; it's just one of many kinds of concurrent programs. Informally, a pipeline is a series of stages connected by channels, where each stage is a group of goroutines running the same function. In each stage, the goroutines
receive values from upstream via inbound channels
perform some function on that data, usually producing new values
send values downstream via outbound channels
Each stage has any number of inbound and outbound channels, except the first and last stages, which have only outbound or inbound channels, respectively. The first stage is sometimes called the source or producer; the last stage, the sink or consumer.
*/
func main() {
in := gen(2, 3)
// Distribute the sq work across two goroutines that both read from in.
c1 := sq(in)
c2 := sq(in)
// Consume the merged output from c1 and c2.
for n := range merge(c1, c2) {
fmt.Println(n) // 4 then 9, or 9 then 4
}
}
//The merge function converts a list of channels to a single channel by starting a goroutine for each inbound channel that copies
// the values to the sole outbound channel. Once all the output goroutines have been started,
// merge starts one more goroutine to close the outbound channel after all sends on that channel are done.
// Sends on a closed channel panic, so it's important to ensure all sends are done before calling close.
// The sync.WaitGroup type provides a simple way to arrange this synchronization:
func merge(cs ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan int)
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan int) {
for n := range c {
out <- n
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
// Start a goroutine to close out once all the output goroutines are
// done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}
//The first stage, gen, is a function that converts a list of integers to a channel that emits the integers in the list.
// The gen function starts a goroutine that sends the integers on the channel and closes the channel when all
// the values have been sent:
func gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
out <- n
}
}()
return out
}
//The second stage, sq, receives integers from a channel and returns a channel that emits the square of
// each received integer. After the inbound channel is closed and this stage has sent all the values downstream,
// it closes the outbound channel:
func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for n := range in {
out <- n * n
}
close(out)
}()
return out
} | messaging/fan_in_out/main.go | 0.702224 | 0.612426 | main.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.