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 templateutils import ( "fmt" "reflect" "strings" ) // Equal will check whether two value is equal. func Equal(a, b reflect.Value) bool { aType := reflect.TypeOf(a) if aType == nil { return false } bType := reflect.ValueOf(b) if bType.IsValid() && bType.Type().ConvertibleTo(aType) { // Attempt comparison after type conversion return reflect.DeepEqual(bType.Convert(aType).Interface(), a) } return false } // In will check whether value is in item func In(item reflect.Value, value reflect.Value) (bool, error) { // indirect item item = indirectInterface(item) if !item.IsValid() { return false, fmt.Errorf("value of untyped nil") } var isNil bool if item, isNil = indirect(item); isNil { return false, fmt.Errorf("value of nil pointer") } // indirect value value = indirectInterface(value) if !value.IsValid() { return false, fmt.Errorf("value of untyped nil") } if value, isNil = indirect(value); isNil { return false, fmt.Errorf("value of nil pointer") } itemType := item.Type() valueType := value.Type() switch itemType.Kind() { case reflect.Array, reflect.Slice: if itemType.Elem().Kind() != valueType.Kind() { return false, fmt.Errorf("not the same type, expected %s, got %s", itemType, valueType) } for i := 0; i < item.Len(); i++ { if reflect.DeepEqual(item.Index(i).Interface(), value.Interface()) { return true, nil } } return false, nil case reflect.String: if valueType.Kind() != reflect.String { return false, fmt.Errorf("type expect String, got %s", value) } return strings.Contains(item.String(), value.String()), nil case reflect.Map: if itemType.Key().Kind() != valueType.Kind() { return false, fmt.Errorf("not the same type, expected %s, got %s", itemType, valueType) } v := item.MapIndex(value) return v.IsValid(), nil case reflect.Invalid: // the loop holds invariant: item.IsValid() panic("unreachable") default: return false, fmt.Errorf("can't check item of type %s", item.Type()) } } // MakeSlice will create a new slice via input values. func MakeSlice(item ...interface{}) []interface{} { return item }
utils.go
0.677474
0.441312
utils.go
starcoder
package set type StringSet map[string]struct{} // NewStringSet creates a new string set with optional input values. func NewStringSet(values ...string) StringSet { s := make(map[string]struct{}, len(values)) for _, value := range values { s[value] = struct{}{} } return s } // NewStringSetFromMap creates a new string set from a map. func NewStringSetFromMap(values map[string]string) StringSet { s := make(map[string]struct{}, len(values)) for value := range values { s[value] = struct{}{} } return s } // List returns the string set as the original array. func (s StringSet) List() []string { result := make([]string, 0, len(s)) for value := range s { result = append(result, value) } return result } // Add adds one or more values to string set. func (s StringSet) Add(values ...string) { for _, value := range values { s[value] = struct{}{} } } // Remove removes items from a strng set. func (s StringSet) Remove(values ...string) { for _, value := range values { delete(s, value) } } // Contains returns true if item is present in the string set. func (s StringSet) Contains(value string) bool { _, c := s[value] return c } // SymmetricDifference returns string set that consists of items that are not in both sets. func (s StringSet) SymmetricDifference(other StringSet) StringSet { return s.Difference(other).Union(other.Difference(s)) } // SymmetricDifferenceList returns string set that consists of items that are not in set and list. func (s StringSet) SymmetricDifferenceList(values ...string) StringSet { return s.SymmetricDifference(NewStringSet(values...)) } // SymmetricDifferenceMap returns string set that consists of items that are not in set and map. func (s StringSet) SymmetricDifferenceMap(values map[string]string) StringSet { return s.SymmetricDifference(NewStringSetFromMap(values)) } // Difference returns string set that consists of items that are in set and and not in second set. func (s StringSet) Difference(other StringSet) StringSet { result := NewStringSet() for k := range s { if !other.Contains(k) { result.Add(k) } } return result } // DifferenceList returns string set that consists of items that are in set and and not in list. func (s StringSet) DifferenceList(values ...string) StringSet { return s.Difference(NewStringSet(values...)) } // DifferenceMap returns string set that consists of items that are in set and and not in map. func (s StringSet) DifferenceMap(values map[string]string) StringSet { return s.Difference(NewStringSetFromMap(values)) } // Intersection returns string set that consists of items that are in both sets. func (s StringSet) Intersection(other StringSet) StringSet { result := NewStringSet() for k := range s { if other.Contains(k) { result.Add(k) } } return result } // IntersectonList returns string set that consists of items that are in both set and list. func (s StringSet) IntersectionList(values ...string) StringSet { return s.Intersection(NewStringSet(values...)) } // IntersectonMap returns string set that consists of items that are in both set and map. func (s StringSet) IntersectionMap(values map[string]string) StringSet { return s.Intersection(NewStringSetFromMap(values)) } // Union returns string set that consists of items that are in either of the 2 sets. func (s StringSet) Union(other StringSet) StringSet { result := NewStringSet() for k := range s { result.Add(k) } for k := range other { result.Add(k) } return result } // UnionList returns string set that consists of items that are in either the set or the list. func (s StringSet) UnionList(values ...string) StringSet { result := NewStringSet() for k := range s { result.Add(k) } for _, k := range values { result.Add(k) } return result } // UnionMap returns string set that consists of items that are in either the set or the map. func (s StringSet) UnionMap(values map[string]string) StringSet { result := NewStringSet() for k := range s { result.Add(k) } for k := range values { result.Add(k) } return result }
pkg/set/stringset.go
0.885477
0.578746
stringset.go
starcoder
package infra import ( "sort" "github.com/rboyer/devconsul/util" ) type NetworkShape string const ( // NetworkShapeIslands describes an isolated island topology where only the // mesh gateways are on the WAN. NetworkShapeIslands = NetworkShape("islands") // NetworkShapeDual describes a private/public lan/wan split where the // servers/meshGateways can route to all other servers/meshGateways and the // clients are isolated. NetworkShapeDual = NetworkShape("dual") // NetworkShapeFlat describes a flat network where every agent has a single // ip address and they all are routable. NetworkShapeFlat = NetworkShape("flat") ) func (s NetworkShape) GetNetworkName(dc string) string { switch s { case NetworkShapeIslands, NetworkShapeDual: return dc case NetworkShapeFlat: return "lan" default: panic("unknown shape: " + s) } } type ClusterLinkMode string const ( ClusterLinkModePeer = ClusterLinkMode("peer") ClusterLinkModeFederate = ClusterLinkMode("federate") ) type Topology struct { NetworkShape NetworkShape LinkMode ClusterLinkMode networks map[string]*Network clusters []*Cluster nm map[string]*Node servers []string // node names clients []string // node names additionalPrimaryGateways []string } func (t *Topology) LinkWithFederation() bool { return t.LinkMode == ClusterLinkModeFederate } func (t *Topology) LinkWithPeering() bool { return t.LinkMode == ClusterLinkModePeer } func (t *Topology) LeaderIP(cluster string, wan bool) string { for _, name := range t.servers { n := t.Node(name) if n.Cluster == cluster { if wan { return n.PublicAddress() } else { return n.LocalAddress() } } } panic("no such dc") } func (t *Topology) Clusters() []Cluster { out := make([]Cluster, len(t.clusters)) for i, c := range t.clusters { out[i] = *c } return out } func (t *Topology) Networks() []*Network { out := make([]*Network, 0, len(t.networks)) for _, n := range t.networks { out = append(out, n) } sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) return out } func (t *Topology) Cluster(name string) *Cluster { for _, c := range t.clusters { if c.Name == name { return c } } panic("no such cluster") } func (t *Topology) ServerIPs(cluster string) []string { var out []string for _, name := range t.servers { n := t.Node(name) if n.Cluster == cluster { out = append(out, n.LocalAddress()) } } return out } func (t *Topology) GatewayAddrs(cluster string) []string { var out []string for _, name := range t.clients { n := t.Node(name) if n.Cluster == cluster && n.MeshGateway { out = append(out, n.PublicAddress()+":8443") } } out = append(out, t.additionalPrimaryGateways...) return out } func (t *Topology) all() []string { o := make([]string, 0, len(t.servers)+len(t.clients)) o = append(o, t.servers...) o = append(o, t.clients...) return o } func (t *Topology) Node(name string) *Node { if t.nm == nil { panic("node not found: " + name) } n, ok := t.nm[name] if !ok { panic("node not found: " + name) } return n } func (t *Topology) Nodes() []*Node { out := make([]*Node, 0, len(t.nm)) t.WalkSilent(func(n *Node) { out = append(out, n) }) return out } func (t *Topology) ClusterNodes(cluster string) []*Node { out := make([]*Node, 0, len(t.nm)) t.WalkSilent(func(n *Node) { if n.Cluster == cluster { out = append(out, n) } }) return out } func (t *Topology) Walk(f func(n *Node) error) error { for _, nodeName := range t.all() { node := t.Node(nodeName) if err := f(node); err != nil { return err } } return nil } func (t *Topology) WalkSilent(f func(n *Node)) { for _, nodeName := range t.all() { node := t.Node(nodeName) f(node) } } func (t *Topology) AddNetwork(n *Network) { if t.networks == nil { t.networks = make(map[string]*Network) } t.networks[n.Name] = n } func (t *Topology) AddNode(node *Node) { if t.nm == nil { t.nm = make(map[string]*Node) } t.nm[node.Name] = node if node.Server { t.servers = append(t.servers, node.Name) } else { t.clients = append(t.clients, node.Name) } } func (t *Topology) AddAdditionalPrimaryGateway(addr string) { t.additionalPrimaryGateways = append(t.additionalPrimaryGateways, addr) } type Cluster struct { Name string Primary bool Index int Servers int Clients int MeshGateways int BaseIP string WANBaseIP string } type Network struct { Name string CIDR string } func (n *Network) DockerName() string { return "devconsul-" + n.Name } type Node struct { Cluster string Name string Partition string // will be not empty Server bool Addresses []Address Service *Service MeshGateway bool UseBuiltinProxy bool Index int Canary bool // mesh-gateway only MeshGatewayUseDNSWANAddress bool } func (n *Node) AddLabels(m map[string]string) { m["devconsul.cluster"] = n.Cluster var agentType string if n.Server { agentType = "server" } else { agentType = "client" } m["devconsul.agentType"] = agentType m["devconsul.node"] = n.Name } func (n *Node) TokenName() string { return "agent--" + n.Name } func (n *Node) LocalAddress() string { for _, a := range n.Addresses { switch a.Network { case n.Cluster, "lan": return a.IPAddress } } panic("node has no local address") } func (n *Node) PublicAddress() string { for _, a := range n.Addresses { if a.Network == "wan" { return a.IPAddress } } panic("node has no public address") } type Address struct { Network string IPAddress string } type Service struct { ID util.Identifier // Name string // Namespace string // will not be empty // Partition string // will be not empty Port int UpstreamID util.Identifier UpstreamPeer string UpstreamDatacenter string UpstreamLocalPort int UpstreamExtraHCL string Meta map[string]string }
infra/topology.go
0.59796
0.457985
topology.go
starcoder
package phomath import "math" func qNoop(_ *Quaternion) { /* no operation, the default OnChangeCallback */ } func NewQuaternion(x, y, z, w float64) *Quaternion { return &Quaternion{ X: x, Y: y, Z: z, W: w, OnChangeCallback: qNoop, } } // Quaternion is a quaternion. :) type Quaternion struct { X, Y, Z, W float64 // This callback is invoked, if set, each time a value in this quaternion is changed. // The callback is passed one argument, a reference to this quaternion. OnChangeCallback func(*Quaternion) } // XY returns the x and y components of the quaternion func (q *Quaternion) XY() (float64, float64) { return q.X, q.Y } // XYZ returns the x, y and z components of the quaternion func (q *Quaternion) XYZ() (x, y, z float64) { return q.X, q.Y, q.Z } // XYZW returns the x, y, z, and w components of the quaternion func (q *Quaternion) XYZW() (x, y, z, w float64) { return q.X, q.Y, q.Z, q.W } // SetX sets the x component and calls the OnChangeCallback function func (q *Quaternion) SetX(v float64) *Quaternion { return q.Set(v, q.Y, q.Z, q.W) } // SetY sets the y component and calls the OnChangeCallback function func (q *Quaternion) SetY(v float64) *Quaternion { return q.Set(q.X, v, q.Z, q.W) } // SetZ sets the z component and calls the OnChangeCallback function func (q *Quaternion) SetZ(v float64) *Quaternion { return q.Set(q.X, q.Y, v, q.W) } // SetW sets the w component and calls the OnChangeCallback function func (q *Quaternion) SetW(v float64) *Quaternion { return q.Set(q.X, q.Y, q.Z, v) } // Set the x, y, z, and w components of this quaternion and call the OnChangeCallback function func (q *Quaternion) Set(x, y, z, w float64) *Quaternion { q.X, q.Y, q.Z, q.W = x, y, z, w q.OnChangeCallback(q) return q } // Clone creates a clone of this quaternion func (q *Quaternion) Clone() *Quaternion { return NewQuaternion(q.XYZW()) } // Copy the values of the given quaternion func (q *Quaternion) Copy(other *Quaternion) *Quaternion { return q.Set(other.XYZW()) } // Add (sum) the given quaternion components to this quaternion func (q *Quaternion) Add(other *Quaternion) *Quaternion { return q.Set( q.X+other.X, q.Y+other.Y, q.Z+other.Z, q.W+other.W, ) } // Subtract the given quaternion components from this quaternion func (q *Quaternion) Subtract(other *Quaternion) *Quaternion { return q.Set( q.X-other.X, q.Y-other.Y, q.Z-other.Z, q.W-other.W, ) } // Scale this quaternion's component values by a scalar func (q *Quaternion) Scale(s float64) *Quaternion { return q.Set( q.X*s, q.Y*s, q.Z*s, q.W*s, ) } // Length returns the length, or magnitude, of this quaternion func (q *Quaternion) Length() float64 { return math.Sqrt(q.LengthSquared()) } // LengthSquared returns the length, or magnitude, of this quaternion, squared func (q *Quaternion) LengthSquared() float64 { return q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W } // Normalize this quaternion to length of 1 func (q *Quaternion) Normalize() *Quaternion { l := q.LengthSquared() if l > 0 { q.Scale(1 / math.Sqrt(l)) } return q } // Dot calculates the dot product with the given quaternion func (q *Quaternion) Dot(other *Quaternion) float64 { return q.X*other.X + q.Y*other.Y + q.Z*other.Z + q.W*other.W } // Lerp linearly interpolates to the given quaternion func (q *Quaternion) Lerp(other *Quaternion, t float64) *Quaternion { return q.Set( q.X+t*(other.X-q.X), q.Y+t*(other.Y-q.Y), q.Z+t*(other.Z-q.Z), q.W+t*(other.W-q.W), ) } // RotationTo rotates this Quaternion based on the two given vectors. func (q *Quaternion) RotationTo(a, b *Vector3) *Quaternion { dot := a.Dot(b) if dot < (-1 + Epsilon) { tmpVec, xunit, yunit := NewVector3(0, 0, 0), NewVector3Right(), NewVector3Down() if tmpVec.Copy(xunit).Cross(a).Length() < Epsilon { tmpVec.Copy(yunit).Cross(a) } tmpVec.Normalize() return q.SetAxisAngle(tmpVec, PI) } else if dot > (1 - Epsilon) { return q.Identity() } else { tmpVec := NewVector3(0, 0, 0).Copy(a).Cross(b) q.Set( tmpVec.X, tmpVec.Y, tmpVec.Z, 1+dot, ) return q.Normalize() } } // SetAxes sets the axes of this Quaternion. func (q *Quaternion) SetAxes(view, right, up *Vector3) *Quaternion { tmpMat3 := NewMatrix3(nil) m := tmpMat3.Values m[0] = right.X m[3] = right.Y m[6] = right.Z m[1] = up.X m[4] = up.Y m[7] = up.Z m[2] = -view.X m[5] = -view.Y m[8] = -view.Z return q.FromMatrix3(tmpMat3).Normalize() } // Identity returns the identity quaternion func (q *Quaternion) Identity() *Quaternion { return q.Set(0, 0, 0, 1) } // SetAxisAngle sets the axis angle of this Quaternion. func (q *Quaternion) SetAxisAngle(axis *Vector3, radians float64) *Quaternion { radians = radians / 2 s := math.Sin(radians) return q.Set( s*axis.X, s*axis.Y, s*axis.Z, math.Cos(radians), ) } // Multiply this quaternion by the given quaternion func (q *Quaternion) Multiply(other *Quaternion) *Quaternion { return q.Set( q.X*other.W+q.W*other.X+q.Y*other.Z-q.Z*other.Y, q.Y*other.W+q.W*other.Y+q.Z*other.X-q.X*other.Z, q.Z*other.W+q.W*other.Z+q.X*other.Y-q.Y*other.X, q.W*other.W-q.X*other.X-q.Y*other.Y-q.Z*other.Z, ) } // Slerp smoothly linaerly interpolate this Quaternion towards the given Quaternion or Vector. func (q *Quaternion) Slerp(other Vector4Like, t float64) *Quaternion { ax, ay, az, aw := q.XYZW() bx, by, bz, bw := other.XYZW() // calc cosine cosom := ax*bx + ay*by + az*bz + aw*bw // adjust signs (if necessary) if cosom < 0 { cosom = -cosom bx = -bx by = -by bz = -bz bw = -bw } // "from" and "to" quaternions are very close ... so we can do a linear interpolation scale0 := 1 - t scale1 := t // calculate coefficients if (1 - cosom) > Epsilon { // standard case (slerp) var omega = math.Acos(cosom) var sinom = math.Sin(omega) scale0 = math.Sin((1.0-t)*omega) / sinom scale1 = math.Sin(t*omega) / sinom } return q.Set( scale0*ax+scale1*bx, scale0*ay+scale1*by, scale0*az+scale1*bz, scale0*aw+scale1*bw, ) } // Invert this quaternion func (q *Quaternion) Invert() *Quaternion { dot := q.Clone().Dot(q) if dot != 0 { dot = 1 / dot } return q.Conjugate().Scale(dot) } // Conjugate converts this Quaternion into its conjugate. func (q *Quaternion) Conjugate() *Quaternion { return q.Set(-q.X, -q.Y, -q.Z, q.W) } // RotateX rotates this quaternion on the x-axis. func (q *Quaternion) RotateX(radians float64) *Quaternion { radians /= 2 bx, bw := math.Sin(radians), math.Cos(radians) return q.Set( q.X*bw+q.W*bx, q.Y*bw+q.Z*bx, q.Z*bw-q.Y*bx, q.W*bw-q.X*bx, ) } // RotateY rotates this quaternion on the y-axis. func (q *Quaternion) RotateY(radians float64) *Quaternion { radians /= 2 by, bw := math.Sin(radians), math.Cos(radians) return q.Set( q.X*bw-q.Z*by, q.Y*bw+q.W*by, q.Z*bw+q.X*by, q.W*bw-q.Y*by, ) } // RotateZ rotates this quaternion on the z-axis. func (q *Quaternion) RotateZ(radians float64) *Quaternion { radians /= 2 bz, bw := math.Sin(radians), math.Cos(radians) return q.Set( q.X*bw+q.Y*bz, q.Y*bw-q.X*bz, q.Z*bw+q.W*bz, q.W*bw-q.Z*bz, ) } // CalculateW creates a unit (or rotation) Quaternion from its x, y, and z components. func (q *Quaternion) CalculateW() *Quaternion { x, y, z := q.XYZ() return q.SetW(-math.Sqrt(1.0 - x*x - y*y - z*z)) } // SetFromEuler sets this Quaternion from the given Euler, based on Euler order. func (q *Quaternion) SetFromEuler(e *Euler) *Quaternion { x, y, z := e.X/2, e.Y/2, e.Z/2 c1, c2, c3 := math.Cos(x), math.Cos(y), math.Cos(z) s1, s2, s3 := math.Sin(x), math.Sin(y), math.Sin(z) switch e.Order { case EulerOrderYXZ: q.Set( s1*c2*c3+c1*s2*s3, c1*s2*c3-s1*c2*s3, c1*c2*s3-s1*s2*c3, c1*c2*c3+s1*s2*s3, ) case EulerOrderZXY: q.Set( s1*c2*c3-c1*s2*s3, c1*s2*c3+s1*c2*s3, c1*c2*s3+s1*s2*c3, c1*c2*c3-s1*s2*s3, ) case EulerOrderZYX: q.Set( s1*c2*c3-c1*s2*s3, c1*s2*c3+s1*c2*s3, c1*c2*s3-s1*s2*c3, c1*c2*c3+s1*s2*s3, ) case EulerOrderYZX: q.Set( s1*c2*c3+c1*s2*s3, c1*s2*c3+s1*c2*s3, c1*c2*s3-s1*s2*c3, c1*c2*c3-s1*s2*s3, ) case EulerOrderXZY: q.Set( s1*c2*c3-c1*s2*s3, c1*s2*c3-s1*c2*s3, c1*c2*s3+s1*s2*c3, c1*c2*c3+s1*s2*s3, ) case EulerOrderXYZ: fallthrough default: q.Set( s1*c2*c3+c1*s2*s3, c1*s2*c3-s1*c2*s3, c1*c2*s3+s1*s2*c3, c1*c2*c3-s1*s2*s3, ) } return q } // SetFromRotationMatrix sets the rotation of this Quaternion from the given Matrix4. func (q *Quaternion) SetFromRotationMatrix(m4 *Matrix4) *Quaternion { m := m4.Values m11 := m[0] m12 := m[4] m13 := m[8] m21 := m[1] m22 := m[5] m23 := m[9] m31 := m[2] m32 := m[6] m33 := m[10] trace := m11 + m22 + m33 var s float64 if trace > 0 { s = 0.5 / math.Sqrt(trace+1.0) return q.Set( (m32-m23)*s, (m13-m31)*s, (m21-m12)*s, 0.25/s, ) } else if m11 > m22 && m11 > m33 { s = 2.0 * math.Sqrt(1.0+m11-m22-m33) return q.Set( 0.25*s, (m12+m21)/s, (m13+m31)/s, (m32-m23)/s, ) } else if m22 > m33 { s = 2.0 * math.Sqrt(1.0+m22-m11-m33) return q.Set( (m12+m21)/s, 0.25*s, (m23+m32)/s, (m13-m31)/s, ) } s = 2.0 * math.Sqrt(1.0+m33-m11-m22) return q.Set( (m13+m31)/s, (m23+m32)/s, 0.25*s, (m21-m12)/s, ) } // FromMatrix3 converts the given Matrix into this Quaternion. func (q *Quaternion) FromMatrix3(m3 *Matrix3) *Quaternion { m := m3.Values fTrace := m[0] + m[4] + m[8] var fRoot float64 siNext, tmp := []int{1, 2, 0}, []float64{0, 0, 0} if fTrace > 0 { // |w| > 1/2, may as well choose w > 1/2 fRoot = math.Sqrt(fTrace + 1.0) // 2w q.W = 0.5 * fRoot fRoot = 0.5 / fRoot // 1/(4w) q.X = (m[7] - m[5]) * fRoot q.Y = (m[2] - m[6]) * fRoot q.Z = (m[3] - m[1]) * fRoot } else { // |w| <= 1/2 var i = 0 if m[4] > m[0] { i = 1 } if m[8] > m[i*3+i] { i = 2 } var j = siNext[i] var k = siNext[j] // This isn't quite as clean without array access fRoot = math.Sqrt(m[i*3+i] - m[j*3+j] - m[k*3+k] + 1) tmp[i] = 0.5 * fRoot fRoot = 0.5 / fRoot tmp[j] = (m[j*3+i] + m[i*3+j]) * fRoot tmp[k] = (m[k*3+i] + m[i*3+k]) * fRoot q.X = tmp[0] q.Y = tmp[1] q.Z = tmp[2] q.W = (m[k*3+j] - m[j*3+k]) * fRoot } q.OnChangeCallback(q) return q }
phomath/quaternion.go
0.910512
0.684898
quaternion.go
starcoder
package gl import ( "errors" "github.com/alivesay/modex/core" ) // Mesh manages structured vertex data. type Mesh struct { vertices []Vertex VBO *VBO attribs []VertexAttrib primitiveType GLPrimitiveType } var DefaultVertexAttribs = []VertexAttrib{ VertexAttrib{0, 3, GLFloat, false, 5 * 4, 0}, VertexAttrib{1, 2, GLFloat, false, 5 * 4, 3 * 4}, } // NewMesh creates a new Mesh struct with a VBO capacity equal to initialCapacity. func NewMesh(primitiveType GLPrimitiveType, usage VBOUsage, initialCapacity int) (*Mesh, error) { var vertices = make([]Vertex, 0, initialCapacity) // TODO: usage state mesh := &Mesh{ primitiveType: primitiveType, vertices: vertices, attribs: DefaultVertexAttribs, } var err error mesh.VBO, err = NewVBO(mesh.vertices, mesh.primitiveType, mesh.attribs, usage) if err != nil { return nil, err } return mesh, nil } // Destroy implements a Mesh destructor. func (mesh *Mesh) Destroy() { mesh.VBO.Destroy() } // TODO: why have the buffer and attribs both here and in VBO? // AddVertexAttrib pushes a new VertexAttrib for use with this Mesh's VBO. // Will replace DefaultVertices when called. func (mesh *Mesh) AddVertexAttrib(attrib VertexAttrib) error { if &mesh.attribs == &DefaultVertexAttribs { mesh.attribs = make([]VertexAttrib, 0, int(GetInstanceInfo().MaxVertexAttribs)) } if len(mesh.attribs) < int(GetInstanceInfo().MaxVertexAttribs) { mesh.attribs = append(mesh.attribs, attrib) if err := mesh.VBO.SetAttribs(mesh.attribs); err != nil { return err } return nil } return errors.New("GL_MAX_VERTEX_ATTRIBS exceeded") } // AddVertex appends current Vertex Data with new Vertex. func (mesh *Mesh) AddVertex(vertex Vertex) { dataLen := len(mesh.vertices) capLen := cap(mesh.vertices) if dataLen == capLen { newData := make([]Vertex, dataLen, core.NP2(uint(capLen+1))) copy(newData, mesh.vertices) mesh.vertices = newData } mesh.vertices = append(mesh.vertices, vertex) } // SyncBuffer sets VBO buffer source to Mesh Data, possibly creating a new VBO. func (mesh *Mesh) SyncBuffer() { mesh.VBO.UpdateBuffer(mesh.vertices) } // ClearBuffer removes all Mesh vertices. func (mesh *Mesh) ClearBuffer() { mesh.vertices = mesh.vertices[:0] }
gfx/gl/mesh.go
0.537041
0.44354
mesh.go
starcoder
package unassert // ErrorHandler handles an error. // See unassert_panic & unassert_stderr type ErrorHandler func(format string, v ...interface{}) // Error promotes an error according to 'unassert_' build tags. // Formats according to a format specifier. func Error(format string, v ...interface{}) { if !enabled { // NOP return } errorHandler(format, v...) } // True checks if b is true. // Behaves according to 'unassert_' build tags. func True(b bool) { if !enabled { // NOP return } Truef(b, "assertion failed: expected true, got false") } // Truef checks if b is true. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func Truef(b bool, format string, v ...interface{}) { if !enabled { // NOP return } if !b { Error(format, v...) } } // False checks if b is false. // Behaves according to 'unassert_' build tags. func False(b bool) { if !enabled { // NOP return } Falsef(b, "assertion failed: expected false, got true") } // Falsef checks if b is false. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func Falsef(b bool, format string, v ...interface{}) { if !enabled { // NOP return } if b { Error(format, v...) } } // Nil checks if v is nil. // Behaves according to 'unassert_' build tags. func Nil(o interface{}) { if !enabled { // NOP return } Nilf(o, "assertion failed: expected nil, got %v", o) } // Nilf checks if v is nil. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func Nilf(o interface{}, format string, v ...interface{}) { if !enabled { // NOP return } if o != nil { Error(format, v...) } } // NotNil checks if v is not nil. // Behaves according to 'unassert_' build tags. func NotNil(o interface{}) { if !enabled { // NOP return } NotNilf(o, "assertion failed: expected non-nil, got nil") } // NotNilf checks if v is not nil. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func NotNilf(o interface{}, format string, v ...interface{}) { if !enabled { // NOP return } if o == nil { Error(format, v...) } } // Same checks if a == b. // Behaves according to 'unassert_' build tags. func Same(a interface{}, b interface{}) { if !enabled { // NOP return } Samef(a, b, "assertion failed: expected same values, got %v != %v", a, b) } // Samef checks if a == b. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func Samef(a interface{}, b interface{}, format string, v ...interface{}) { if !enabled { // NOP return } if a != b { Error(format, v...) } } // NotSame checks if a != b. // Behaves according to 'unassert_' build tags. func NotSame(a interface{}, b interface{}) { if !enabled { // NOP return } NotSamef(a, b, "assertion failed: expected two different values, got %v", a, b) } // NotSamef checks if a != b. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func NotSamef(a interface{}, b interface{}, format string, v ...interface{}) { if !enabled { // NOP return } if a == b { Error(format, v...) } } // Predicate is a function type used for lazy evaluation in assertions. // It takes one argument and returns true if that argument matches a given predicate. // See Matches(). type Predicate func(interface{}) bool // Matches checks if predicate(v) is true. // Useful for lazy evaluation of complex assertions. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func Matches(predicate Predicate, x interface{}) { if !enabled { // NOP return } Matchesf(predicate, x, "assertion failed: predicate(x) did not return true; x = %v", x) } // Matchesf checks if predicate(v) is true. // Useful for lazy evaluation of complex assertions. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func Matchesf(predicate Predicate, x interface{}, format string, v ...interface{}) { if !enabled { // NOP return } if !predicate(x) { Error(format, v...) } } // Evaluator is a function type used for lazy evaluation in assertions. // Mostly used for function closures. // See ReturnsTrue(). type Evaluator func() bool // ReturnsTrue checks if evaluator() returns true. // Useful for lazy evaluation of complex assertions. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func ReturnsTrue(evaluator Evaluator) { if !enabled { // NOP return } ReturnsTruef(evaluator, "assertion failed: evaluator() did not return true") } // ReturnsTrue checks if evaluator() returns true. // Useful for lazy evaluation of complex assertions. // Behaves according to 'unassert_' build tags. // Formats according to a format specifier. func ReturnsTruef(evaluator Evaluator, format string, v ...interface{}) { if !enabled { // NOP return } if !evaluator() { Error(format, v...) } }
unassert.go
0.808672
0.482185
unassert.go
starcoder
package option import ( m "../measures" ) func FiniteDifferenceGrid(NAS int, SInf float64) func(option Option, t m.Time, sigma m.Return, rf m.Rate) (S []float64, V [][]float64) { return func(option Option, t m.Time, sigma m.Return, rf m.Rate) (S []float64, V [][]float64) { Vol := float64(sigma) RF := float64(rf) dS, dt, NTS := gridParameters(SInf, NAS, Vol, float64(option.Expiration()-t)) S, V = grids(NAS, NTS) initializeBoundaryCondition(V, S, dS, option) for k := 1; k <= NTS; k++ { updateGridInteriorAtTime(k, V, S, dS, Vol, RF, dt) updateGridBoundaryAtTime(k, V, RF, dt) updateForEarlyExcerciseAtTime(k, option, V, S) } return S, V } } func initializeBoundaryCondition(V [][]float64, S []float64, dS float64, option Option) { NAS := len(V) - 1 for i := 0; i <= NAS; i++ { S[i] = float64(i) * dS V[i][0] = float64(option.Payoff(m.Money(S[i]))) } } func updateGridBoundaryAtTime(k int, V [][]float64, RF float64, dt float64) { NAS := len(V) - 1 // Boundary condition at S=0 V[0][k] = V[0][k-1] * (1 - RF*dt) // Boundary condition at S=infinity V[NAS][k] = 2*V[NAS-1][k] - V[NAS-2][k] } func updateGridInteriorAtTime(k int, V [][]float64, S []float64, dS float64, Vol float64, RF float64, dt float64) { for i := 1; i < len(V)-1; i++ { Delta := (V[i+1][k-1] - V[i-1][k-1]) / (2.0 * dS) Gamma := (V[i+1][k-1] - 2*V[i][k-1] + V[i-1][k-1]) / (dS * dS) // Black-Scholes to derive Theta Theta := (-0.5 * Vol * Vol * S[i] * S[i] * Gamma) - (RF * S[i] * Delta) + (RF * V[i][k-1]) V[i][k] = V[i][k-1] - dt*Theta } } func updateForEarlyExcerciseAtTime(k int, option Option, V [][]float64, S []float64) { for i := 0; i < len(V); i++ { V[i][k] = float64(option.EarlyExcercise(option.Payoff(m.Money(S[i])), m.Money(V[i][k]))) } } func grids(NAS int, NTS int) ([]float64, [][]float64) { S := make([]float64, NAS+1) V := make([][]float64, NAS+1) for n := 0; n <= NAS; n++ { V[n] = make([]float64, NTS+1) } return S, V } func gridParameters(SInf float64, NAS int, Vol float64, TimeToExpiration float64) (float64, float64, int) { dS := SInf / float64(NAS) wantedDt := 0.9 / (Vol * Vol * float64(NAS) * float64(NAS)) NTS := int(TimeToExpiration/wantedDt + 1) dt := TimeToExpiration / float64(NTS) return dS, dt, NTS }
src/option/grid.go
0.721841
0.45417
grid.go
starcoder
package main import ( "encoding/base64" "encoding/binary" "fmt" "net" ) // ChainState represent the state of the current chain type ChainState byte const ( // ChainCreating means that the chain got created but not completly filled yet ChainCreating ChainState = 0x00 // ChainCreated means that everything is added to the chain ChainCreated ChainState = 0x01 ) func (c ChainState) String() string { switch c { case ChainCreating: return "creating" case ChainCreated: return "created" default: return "unknown" } } const chainIDPrefix = "LB$-" // 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // +CR|PR| IP | Port|Last Update|St|ContentHash| // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ // \__________________/ // =CR // ChainID represents the name of a chain which contains the most important data of it type ChainID struct { CRC uint8 Protocol Protocol IP net.IP Port uint16 LastUpdate uint32 State ChainState ContentHash uint32 } // NewChainID creates a new chain identification func NewChainID(protocol Protocol, ip net.IP, port uint16, lastUpdate uint32, state ChainState, contentHash uint32) ChainID { id := ChainID{} crcBuf := make([]byte, 7) crcBuf[0] = byte(protocol) ipv4 := ip.To4() crcBuf[1] = ipv4[0] crcBuf[2] = ipv4[1] crcBuf[3] = ipv4[2] crcBuf[4] = ipv4[3] binary.BigEndian.PutUint16(crcBuf[5:], port) id.CRC = PearsonHash(crcBuf) id.Protocol = protocol id.IP = ip id.Port = port id.LastUpdate = lastUpdate id.State = state id.ContentHash = contentHash return id } // TryParseChainID tries to parse the passed chainname as ChainID func TryParseChainID(chain string) (ChainID, error) { id := ChainID{} nameLength := len(chain) if len(chain) != 28 { return ChainID{}, fmt.Errorf("chain `%s` has invalid length, got %d expected 28", chain, nameLength) } if chain[0:len(chainIDPrefix)] != chainIDPrefix { return ChainID{}, fmt.Errorf("chain `%s` doens't start with prefix `%s`", chain, chainIDPrefix) } data, err := base64.StdEncoding.DecodeString(chain[len(chainIDPrefix):]) if err != nil { return ChainID{}, fmt.Errorf("chain `%s` isn't valid base64", chain) } id.CRC = data[0] id.Protocol = Protocol(data[1]) id.IP = net.IPv4(data[2], data[3], data[4], data[5]) id.Port = binary.BigEndian.Uint16(data[6:8]) id.LastUpdate = binary.BigEndian.Uint32(data[8:12]) id.State = ChainState(data[12]) id.ContentHash = binary.BigEndian.Uint32(data[13:17]) checksum := PearsonHash(data[1:8]) if checksum != id.CRC { return ChainID{}, fmt.Errorf("chain `%s` has invalid CRC, got %d expected %d", chain, id.CRC, checksum) } return id, nil } // AsLoadbalancerKey creates a token which can be used to match ChainID to loadbalancers func (c ChainID) AsLoadbalancerKey() string { return fmt.Sprintf("%s://%s:%d", c.Protocol.String(), c.IP.String(), c.Port) } // String serializes the id to a iptables compatible chain name func (c ChainID) String() string { buf := make([]byte, 17) buf[0] = c.CRC buf[1] = byte(c.Protocol) ipv4 := c.IP.To4() buf[2] = ipv4[0] buf[3] = ipv4[1] buf[4] = ipv4[2] buf[5] = ipv4[3] binary.BigEndian.PutUint16(buf[6:], c.Port) binary.BigEndian.PutUint32(buf[8:], c.LastUpdate) buf[12] = byte(c.State) binary.BigEndian.PutUint32(buf[13:], c.ContentHash) b64 := base64.StdEncoding.EncodeToString(buf) chainName := chainIDPrefix + b64 return chainName }
chainid.go
0.601125
0.416263
chainid.go
starcoder
package fp func (q BoolQueue) FoldLeftBool(z bool, f func(bool, bool) bool) bool { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftString(z string, f func(string, bool) string) string { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftInt(z int, f func(int, bool) int) int { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftInt64(z int64, f func(int64, bool) int64) int64 { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftByte(z byte, f func(byte, bool) byte) byte { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftRune(z rune, f func(rune, bool) rune) rune { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftFloat32(z float32, f func(float32, bool) float32) float32 { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftFloat64(z float64, f func(float64, bool) float64) float64 { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftAny(z Any, f func(Any, bool) Any) Any { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, bool) Tuple2) Tuple2 { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, bool) BoolQueue) BoolQueue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, bool) StringQueue) StringQueue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, bool) IntQueue) IntQueue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, bool) Int64Queue) Int64Queue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, bool) ByteQueue) ByteQueue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, bool) RuneQueue) RuneQueue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, bool) Float32Queue) Float32Queue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, bool) Float64Queue) Float64Queue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, bool) AnyQueue) AnyQueue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q BoolQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, bool) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e bool) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftBool(z bool, f func(bool, string) bool) bool { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftString(z string, f func(string, string) string) string { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftInt(z int, f func(int, string) int) int { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftInt64(z int64, f func(int64, string) int64) int64 { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftByte(z byte, f func(byte, string) byte) byte { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftRune(z rune, f func(rune, string) rune) rune { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftFloat32(z float32, f func(float32, string) float32) float32 { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftFloat64(z float64, f func(float64, string) float64) float64 { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftAny(z Any, f func(Any, string) Any) Any { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, string) Tuple2) Tuple2 { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, string) BoolQueue) BoolQueue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, string) StringQueue) StringQueue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, string) IntQueue) IntQueue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, string) Int64Queue) Int64Queue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, string) ByteQueue) ByteQueue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, string) RuneQueue) RuneQueue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, string) Float32Queue) Float32Queue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, string) Float64Queue) Float64Queue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, string) AnyQueue) AnyQueue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q StringQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, string) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e string) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftBool(z bool, f func(bool, int) bool) bool { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftString(z string, f func(string, int) string) string { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftInt(z int, f func(int, int) int) int { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftInt64(z int64, f func(int64, int) int64) int64 { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftByte(z byte, f func(byte, int) byte) byte { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftRune(z rune, f func(rune, int) rune) rune { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftFloat32(z float32, f func(float32, int) float32) float32 { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftFloat64(z float64, f func(float64, int) float64) float64 { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftAny(z Any, f func(Any, int) Any) Any { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, int) Tuple2) Tuple2 { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, int) BoolQueue) BoolQueue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, int) StringQueue) StringQueue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, int) IntQueue) IntQueue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, int) Int64Queue) Int64Queue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, int) ByteQueue) ByteQueue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, int) RuneQueue) RuneQueue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, int) Float32Queue) Float32Queue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, int) Float64Queue) Float64Queue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, int) AnyQueue) AnyQueue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q IntQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, int) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e int) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftBool(z bool, f func(bool, int64) bool) bool { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftString(z string, f func(string, int64) string) string { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftInt(z int, f func(int, int64) int) int { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftInt64(z int64, f func(int64, int64) int64) int64 { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftByte(z byte, f func(byte, int64) byte) byte { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftRune(z rune, f func(rune, int64) rune) rune { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftFloat32(z float32, f func(float32, int64) float32) float32 { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftFloat64(z float64, f func(float64, int64) float64) float64 { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftAny(z Any, f func(Any, int64) Any) Any { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftTuple2(z Tuple2, f func(Tuple2, int64) Tuple2) Tuple2 { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, int64) BoolQueue) BoolQueue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, int64) StringQueue) StringQueue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, int64) IntQueue) IntQueue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, int64) Int64Queue) Int64Queue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, int64) ByteQueue) ByteQueue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, int64) RuneQueue) RuneQueue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, int64) Float32Queue) Float32Queue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, int64) Float64Queue) Float64Queue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, int64) AnyQueue) AnyQueue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q Int64Queue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, int64) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e int64) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftBool(z bool, f func(bool, byte) bool) bool { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftString(z string, f func(string, byte) string) string { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftInt(z int, f func(int, byte) int) int { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftInt64(z int64, f func(int64, byte) int64) int64 { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftByte(z byte, f func(byte, byte) byte) byte { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftRune(z rune, f func(rune, byte) rune) rune { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftFloat32(z float32, f func(float32, byte) float32) float32 { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftFloat64(z float64, f func(float64, byte) float64) float64 { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftAny(z Any, f func(Any, byte) Any) Any { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, byte) Tuple2) Tuple2 { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, byte) BoolQueue) BoolQueue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, byte) StringQueue) StringQueue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, byte) IntQueue) IntQueue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, byte) Int64Queue) Int64Queue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, byte) ByteQueue) ByteQueue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, byte) RuneQueue) RuneQueue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, byte) Float32Queue) Float32Queue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, byte) Float64Queue) Float64Queue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, byte) AnyQueue) AnyQueue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q ByteQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, byte) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e byte) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftBool(z bool, f func(bool, rune) bool) bool { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftString(z string, f func(string, rune) string) string { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftInt(z int, f func(int, rune) int) int { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftInt64(z int64, f func(int64, rune) int64) int64 { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftByte(z byte, f func(byte, rune) byte) byte { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftRune(z rune, f func(rune, rune) rune) rune { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftFloat32(z float32, f func(float32, rune) float32) float32 { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftFloat64(z float64, f func(float64, rune) float64) float64 { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftAny(z Any, f func(Any, rune) Any) Any { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, rune) Tuple2) Tuple2 { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, rune) BoolQueue) BoolQueue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, rune) StringQueue) StringQueue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, rune) IntQueue) IntQueue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, rune) Int64Queue) Int64Queue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, rune) ByteQueue) ByteQueue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, rune) RuneQueue) RuneQueue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, rune) Float32Queue) Float32Queue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, rune) Float64Queue) Float64Queue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, rune) AnyQueue) AnyQueue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q RuneQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, rune) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e rune) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftBool(z bool, f func(bool, float32) bool) bool { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftString(z string, f func(string, float32) string) string { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftInt(z int, f func(int, float32) int) int { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftInt64(z int64, f func(int64, float32) int64) int64 { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftByte(z byte, f func(byte, float32) byte) byte { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftRune(z rune, f func(rune, float32) rune) rune { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftFloat32(z float32, f func(float32, float32) float32) float32 { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftFloat64(z float64, f func(float64, float32) float64) float64 { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftAny(z Any, f func(Any, float32) Any) Any { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftTuple2(z Tuple2, f func(Tuple2, float32) Tuple2) Tuple2 { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, float32) BoolQueue) BoolQueue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, float32) StringQueue) StringQueue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, float32) IntQueue) IntQueue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, float32) Int64Queue) Int64Queue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, float32) ByteQueue) ByteQueue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, float32) RuneQueue) RuneQueue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, float32) Float32Queue) Float32Queue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, float32) Float64Queue) Float64Queue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, float32) AnyQueue) AnyQueue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float32Queue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, float32) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e float32) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftBool(z bool, f func(bool, float64) bool) bool { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftString(z string, f func(string, float64) string) string { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftInt(z int, f func(int, float64) int) int { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftInt64(z int64, f func(int64, float64) int64) int64 { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftByte(z byte, f func(byte, float64) byte) byte { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftRune(z rune, f func(rune, float64) rune) rune { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftFloat32(z float32, f func(float32, float64) float32) float32 { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftFloat64(z float64, f func(float64, float64) float64) float64 { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftAny(z Any, f func(Any, float64) Any) Any { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftTuple2(z Tuple2, f func(Tuple2, float64) Tuple2) Tuple2 { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, float64) BoolQueue) BoolQueue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, float64) StringQueue) StringQueue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, float64) IntQueue) IntQueue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, float64) Int64Queue) Int64Queue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, float64) ByteQueue) ByteQueue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, float64) RuneQueue) RuneQueue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, float64) Float32Queue) Float32Queue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, float64) Float64Queue) Float64Queue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, float64) AnyQueue) AnyQueue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q Float64Queue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, float64) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e float64) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftBool(z bool, f func(bool, Any) bool) bool { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftString(z string, f func(string, Any) string) string { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftInt(z int, f func(int, Any) int) int { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftInt64(z int64, f func(int64, Any) int64) int64 { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftByte(z byte, f func(byte, Any) byte) byte { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftRune(z rune, f func(rune, Any) rune) rune { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftFloat32(z float32, f func(float32, Any) float32) float32 { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftFloat64(z float64, f func(float64, Any) float64) float64 { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftAny(z Any, f func(Any, Any) Any) Any { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, Any) Tuple2) Tuple2 { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, Any) BoolQueue) BoolQueue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, Any) StringQueue) StringQueue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, Any) IntQueue) IntQueue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, Any) Int64Queue) Int64Queue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, Any) ByteQueue) ByteQueue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, Any) RuneQueue) RuneQueue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, Any) Float32Queue) Float32Queue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, Any) Float64Queue) Float64Queue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, Any) AnyQueue) AnyQueue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q AnyQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, Any) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e Any) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftBool(z bool, f func(bool, Tuple2) bool) bool { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftString(z string, f func(string, Tuple2) string) string { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftInt(z int, f func(int, Tuple2) int) int { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftInt64(z int64, f func(int64, Tuple2) int64) int64 { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftByte(z byte, f func(byte, Tuple2) byte) byte { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftRune(z rune, f func(rune, Tuple2) rune) rune { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftFloat32(z float32, f func(float32, Tuple2) float32) float32 { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftFloat64(z float64, f func(float64, Tuple2) float64) float64 { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftAny(z Any, f func(Any, Tuple2) Any) Any { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftTuple2(z Tuple2, f func(Tuple2, Tuple2) Tuple2) Tuple2 { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, Tuple2) BoolQueue) BoolQueue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, Tuple2) StringQueue) StringQueue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, Tuple2) IntQueue) IntQueue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, Tuple2) Int64Queue) Int64Queue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, Tuple2) ByteQueue) ByteQueue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, Tuple2) RuneQueue) RuneQueue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, Tuple2) Float32Queue) Float32Queue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, Tuple2) Float64Queue) Float64Queue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, Tuple2) AnyQueue) AnyQueue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q Tuple2Queue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, Tuple2) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e Tuple2) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftBool(z bool, f func(bool, BoolOption) bool) bool { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftString(z string, f func(string, BoolOption) string) string { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftInt(z int, f func(int, BoolOption) int) int { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftInt64(z int64, f func(int64, BoolOption) int64) int64 { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftByte(z byte, f func(byte, BoolOption) byte) byte { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftRune(z rune, f func(rune, BoolOption) rune) rune { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftFloat32(z float32, f func(float32, BoolOption) float32) float32 { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftFloat64(z float64, f func(float64, BoolOption) float64) float64 { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftAny(z Any, f func(Any, BoolOption) Any) Any { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, BoolOption) Tuple2) Tuple2 { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, BoolOption) BoolQueue) BoolQueue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, BoolOption) StringQueue) StringQueue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, BoolOption) IntQueue) IntQueue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, BoolOption) Int64Queue) Int64Queue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, BoolOption) ByteQueue) ByteQueue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, BoolOption) RuneQueue) RuneQueue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, BoolOption) Float32Queue) Float32Queue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, BoolOption) Float64Queue) Float64Queue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, BoolOption) AnyQueue) AnyQueue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q BoolOptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, BoolOption) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e BoolOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftBool(z bool, f func(bool, StringOption) bool) bool { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftString(z string, f func(string, StringOption) string) string { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftInt(z int, f func(int, StringOption) int) int { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftInt64(z int64, f func(int64, StringOption) int64) int64 { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftByte(z byte, f func(byte, StringOption) byte) byte { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftRune(z rune, f func(rune, StringOption) rune) rune { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftFloat32(z float32, f func(float32, StringOption) float32) float32 { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftFloat64(z float64, f func(float64, StringOption) float64) float64 { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftAny(z Any, f func(Any, StringOption) Any) Any { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, StringOption) Tuple2) Tuple2 { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, StringOption) BoolQueue) BoolQueue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, StringOption) StringQueue) StringQueue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, StringOption) IntQueue) IntQueue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, StringOption) Int64Queue) Int64Queue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, StringOption) ByteQueue) ByteQueue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, StringOption) RuneQueue) RuneQueue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, StringOption) Float32Queue) Float32Queue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, StringOption) Float64Queue) Float64Queue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, StringOption) AnyQueue) AnyQueue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q StringOptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, StringOption) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e StringOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftBool(z bool, f func(bool, IntOption) bool) bool { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftString(z string, f func(string, IntOption) string) string { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftInt(z int, f func(int, IntOption) int) int { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftInt64(z int64, f func(int64, IntOption) int64) int64 { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftByte(z byte, f func(byte, IntOption) byte) byte { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftRune(z rune, f func(rune, IntOption) rune) rune { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftFloat32(z float32, f func(float32, IntOption) float32) float32 { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftFloat64(z float64, f func(float64, IntOption) float64) float64 { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftAny(z Any, f func(Any, IntOption) Any) Any { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, IntOption) Tuple2) Tuple2 { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, IntOption) BoolQueue) BoolQueue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, IntOption) StringQueue) StringQueue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, IntOption) IntQueue) IntQueue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, IntOption) Int64Queue) Int64Queue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, IntOption) ByteQueue) ByteQueue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, IntOption) RuneQueue) RuneQueue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, IntOption) Float32Queue) Float32Queue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, IntOption) Float64Queue) Float64Queue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, IntOption) AnyQueue) AnyQueue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q IntOptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, IntOption) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e IntOption) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftBool(z bool, f func(bool, Int64Option) bool) bool { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftString(z string, f func(string, Int64Option) string) string { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftInt(z int, f func(int, Int64Option) int) int { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftInt64(z int64, f func(int64, Int64Option) int64) int64 { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftByte(z byte, f func(byte, Int64Option) byte) byte { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftRune(z rune, f func(rune, Int64Option) rune) rune { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftFloat32(z float32, f func(float32, Int64Option) float32) float32 { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftFloat64(z float64, f func(float64, Int64Option) float64) float64 { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftAny(z Any, f func(Any, Int64Option) Any) Any { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, Int64Option) Tuple2) Tuple2 { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, Int64Option) BoolQueue) BoolQueue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, Int64Option) StringQueue) StringQueue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, Int64Option) IntQueue) IntQueue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, Int64Option) Int64Queue) Int64Queue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, Int64Option) ByteQueue) ByteQueue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, Int64Option) RuneQueue) RuneQueue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, Int64Option) Float32Queue) Float32Queue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, Int64Option) Float64Queue) Float64Queue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, Int64Option) AnyQueue) AnyQueue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q Int64OptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, Int64Option) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e Int64Option) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftBool(z bool, f func(bool, ByteOption) bool) bool { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftString(z string, f func(string, ByteOption) string) string { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftInt(z int, f func(int, ByteOption) int) int { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftInt64(z int64, f func(int64, ByteOption) int64) int64 { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftByte(z byte, f func(byte, ByteOption) byte) byte { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftRune(z rune, f func(rune, ByteOption) rune) rune { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftFloat32(z float32, f func(float32, ByteOption) float32) float32 { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftFloat64(z float64, f func(float64, ByteOption) float64) float64 { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftAny(z Any, f func(Any, ByteOption) Any) Any { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, ByteOption) Tuple2) Tuple2 { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, ByteOption) BoolQueue) BoolQueue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, ByteOption) StringQueue) StringQueue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, ByteOption) IntQueue) IntQueue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, ByteOption) Int64Queue) Int64Queue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, ByteOption) ByteQueue) ByteQueue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, ByteOption) RuneQueue) RuneQueue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, ByteOption) Float32Queue) Float32Queue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, ByteOption) Float64Queue) Float64Queue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, ByteOption) AnyQueue) AnyQueue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q ByteOptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, ByteOption) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e ByteOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftBool(z bool, f func(bool, RuneOption) bool) bool { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftString(z string, f func(string, RuneOption) string) string { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftInt(z int, f func(int, RuneOption) int) int { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftInt64(z int64, f func(int64, RuneOption) int64) int64 { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftByte(z byte, f func(byte, RuneOption) byte) byte { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftRune(z rune, f func(rune, RuneOption) rune) rune { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftFloat32(z float32, f func(float32, RuneOption) float32) float32 { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftFloat64(z float64, f func(float64, RuneOption) float64) float64 { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftAny(z Any, f func(Any, RuneOption) Any) Any { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, RuneOption) Tuple2) Tuple2 { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, RuneOption) BoolQueue) BoolQueue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, RuneOption) StringQueue) StringQueue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, RuneOption) IntQueue) IntQueue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, RuneOption) Int64Queue) Int64Queue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, RuneOption) ByteQueue) ByteQueue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, RuneOption) RuneQueue) RuneQueue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, RuneOption) Float32Queue) Float32Queue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, RuneOption) Float64Queue) Float64Queue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, RuneOption) AnyQueue) AnyQueue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q RuneOptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, RuneOption) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e RuneOption) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftBool(z bool, f func(bool, Float32Option) bool) bool { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftString(z string, f func(string, Float32Option) string) string { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftInt(z int, f func(int, Float32Option) int) int { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftInt64(z int64, f func(int64, Float32Option) int64) int64 { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftByte(z byte, f func(byte, Float32Option) byte) byte { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftRune(z rune, f func(rune, Float32Option) rune) rune { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftFloat32(z float32, f func(float32, Float32Option) float32) float32 { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftFloat64(z float64, f func(float64, Float32Option) float64) float64 { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftAny(z Any, f func(Any, Float32Option) Any) Any { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, Float32Option) Tuple2) Tuple2 { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, Float32Option) BoolQueue) BoolQueue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, Float32Option) StringQueue) StringQueue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, Float32Option) IntQueue) IntQueue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, Float32Option) Int64Queue) Int64Queue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, Float32Option) ByteQueue) ByteQueue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, Float32Option) RuneQueue) RuneQueue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, Float32Option) Float32Queue) Float32Queue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, Float32Option) Float64Queue) Float64Queue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, Float32Option) AnyQueue) AnyQueue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float32OptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, Float32Option) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e Float32Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftBool(z bool, f func(bool, Float64Option) bool) bool { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftString(z string, f func(string, Float64Option) string) string { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftInt(z int, f func(int, Float64Option) int) int { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftInt64(z int64, f func(int64, Float64Option) int64) int64 { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftByte(z byte, f func(byte, Float64Option) byte) byte { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftRune(z rune, f func(rune, Float64Option) rune) rune { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftFloat32(z float32, f func(float32, Float64Option) float32) float32 { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftFloat64(z float64, f func(float64, Float64Option) float64) float64 { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftAny(z Any, f func(Any, Float64Option) Any) Any { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, Float64Option) Tuple2) Tuple2 { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, Float64Option) BoolQueue) BoolQueue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, Float64Option) StringQueue) StringQueue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, Float64Option) IntQueue) IntQueue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, Float64Option) Int64Queue) Int64Queue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, Float64Option) ByteQueue) ByteQueue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, Float64Option) RuneQueue) RuneQueue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, Float64Option) Float32Queue) Float32Queue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, Float64Option) Float64Queue) Float64Queue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, Float64Option) AnyQueue) AnyQueue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q Float64OptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, Float64Option) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e Float64Option) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftBool(z bool, f func(bool, AnyOption) bool) bool { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftString(z string, f func(string, AnyOption) string) string { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftInt(z int, f func(int, AnyOption) int) int { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftInt64(z int64, f func(int64, AnyOption) int64) int64 { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftByte(z byte, f func(byte, AnyOption) byte) byte { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftRune(z rune, f func(rune, AnyOption) rune) rune { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftFloat32(z float32, f func(float32, AnyOption) float32) float32 { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftFloat64(z float64, f func(float64, AnyOption) float64) float64 { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftAny(z Any, f func(Any, AnyOption) Any) Any { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, AnyOption) Tuple2) Tuple2 { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, AnyOption) BoolQueue) BoolQueue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, AnyOption) StringQueue) StringQueue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, AnyOption) IntQueue) IntQueue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, AnyOption) Int64Queue) Int64Queue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, AnyOption) ByteQueue) ByteQueue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, AnyOption) RuneQueue) RuneQueue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, AnyOption) Float32Queue) Float32Queue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, AnyOption) Float64Queue) Float64Queue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, AnyOption) AnyQueue) AnyQueue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q AnyOptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, AnyOption) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e AnyOption) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftBool(z bool, f func(bool, Tuple2Option) bool) bool { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftString(z string, f func(string, Tuple2Option) string) string { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftInt(z int, f func(int, Tuple2Option) int) int { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftInt64(z int64, f func(int64, Tuple2Option) int64) int64 { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftByte(z byte, f func(byte, Tuple2Option) byte) byte { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftRune(z rune, f func(rune, Tuple2Option) rune) rune { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftFloat32(z float32, f func(float32, Tuple2Option) float32) float32 { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftFloat64(z float64, f func(float64, Tuple2Option) float64) float64 { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftAny(z Any, f func(Any, Tuple2Option) Any) Any { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftTuple2(z Tuple2, f func(Tuple2, Tuple2Option) Tuple2) Tuple2 { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftBoolQueue(z BoolQueue, f func(BoolQueue, Tuple2Option) BoolQueue) BoolQueue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftStringQueue(z StringQueue, f func(StringQueue, Tuple2Option) StringQueue) StringQueue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftIntQueue(z IntQueue, f func(IntQueue, Tuple2Option) IntQueue) IntQueue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftInt64Queue(z Int64Queue, f func(Int64Queue, Tuple2Option) Int64Queue) Int64Queue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftByteQueue(z ByteQueue, f func(ByteQueue, Tuple2Option) ByteQueue) ByteQueue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftRuneQueue(z RuneQueue, f func(RuneQueue, Tuple2Option) RuneQueue) RuneQueue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftFloat32Queue(z Float32Queue, f func(Float32Queue, Tuple2Option) Float32Queue) Float32Queue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftFloat64Queue(z Float64Queue, f func(Float64Queue, Tuple2Option) Float64Queue) Float64Queue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftAnyQueue(z AnyQueue, f func(AnyQueue, Tuple2Option) AnyQueue) AnyQueue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc } func (q Tuple2OptionQueue) FoldLeftTuple2Queue(z Tuple2Queue, f func(Tuple2Queue, Tuple2Option) Tuple2Queue) Tuple2Queue { acc := z q.Foreach(func(e Tuple2Option) { acc = f(acc, e) }) return acc }
fp/bootstrap_queue_foldleft.go
0.764276
0.458349
bootstrap_queue_foldleft.go
starcoder
package forGraphBLASGo import ( "math" "reflect" ) type ( Signed interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 } Unsigned interface { ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr } Integer interface { Signed | Unsigned } Float interface { ~float32 | ~float64 } Number interface { Integer | Float } Ordered interface { Number | ~string } ) func Identity[T any](x T) T { return x } func Abs[T Number](x T) T { return T(math.Abs(float64(x))) } func AInv[T Number](x T) T { return -x } func MInv[T Float](x T) T { return 1 / x } func LNot(x bool) bool { return !x } func BNot[T Integer](x T) T { return ^x } func LOr(x, y bool) bool { return x || y } func LAnd(x, y bool) bool { return x && y } func LXor(x, y bool) bool { return x != y } func LXNor(x, y bool) bool { return x == y } func BOr[T Integer](x, y T) T { return x | y } func BAnd[T Integer](x, y T) T { return x & y } func BXor[T Integer](x, y T) T { return x ^ y } func BXNor[T Integer](x, y T) T { return ^(x ^ y) } func Eq[T comparable](x, y T) bool { return x == y } func Ne[T comparable](x, y T) bool { return x != y } func Gt[T Ordered](x, y T) bool { return x > y } func Lt[T Ordered](x, y T) bool { return x < y } func Ge[T Ordered](x, y T) bool { return x >= y } func Le[T Ordered](x, y T) bool { return x <= y } func Oneb[Dout Number, Din1, Din2 any](_ Din1, _ Din2) Dout { return 1 } func Trueb[Din1, Din2 any](_ Din1, _ Din2) bool { return true } func First[Din1, Din2 any](x Din1, _ Din2) Din1 { return x } func Second[Din1, Din2 any](_ Din1, y Din2) Din2 { return y } func Min[T Ordered](x, y T) T { if x < y { return x } return y } func Max[T Ordered](x, y T) T { if x > y { return x } return y } func Plus[T Number](x, y T) T { return x + y } func Minus[T Number](x, y T) T { return x - y } func Times[T Number](x, y T) T { return x * y } func Div[T Number](x, y T) T { return x / y } func RowIndex[D Number, Din any](_ Din, i, _, s int) D { return D(i + s) } func ColIndex[D Number, Din any](_ Din, _, j, s int) D { return D(j + s) } func DiagIndex[D Number, Din any](_ Din, i, j, s int) D { return D(j - i + s) } func TriL[Din any](_ Din, i, j, s int) bool { return j <= i+s } func TriU[Din any](_ Din, i, j, s int) bool { return j >= i+s } func Diag[Din any](_ Din, i, j, s int) bool { return j == i+s } func OffDiag[Din any](_ Din, i, j, s int) bool { return j != i+s } func ColLE[Din any](_ Din, _, j, s int) bool { return j <= s } func ColGT[Din any](_ Din, _, j, s int) bool { return j > s } func RowLE[Din any](_ Din, i, _, s int) bool { return i <= s } func RowGT[Din any](_ Din, i, _, s int) bool { return i > s } func ValueEq[Din comparable](value Din, _, _ int, s Din) bool { return value == s } func ValueNE[Din comparable](value Din, _, _ int, s Din) bool { return value != s } func ValueLT[Din Ordered](value Din, _, _ int, s Din) bool { return value < s } func ValueLE[Din Ordered](value Din, _, _ int, s Din) bool { return value <= s } func ValueGT[Din Ordered](value Din, _, _ int, s Din) bool { return value > s } func ValueGE[Din Ordered](value Din, _, _ int, s Din) bool { return value >= s } func PlusMonoid[T Number]() (addition BinaryOp[T, T, T], identity T) { return Plus[T], 0 } func TimesMonoid[T Number]() (multiplication BinaryOp[T, T, T], identity T) { return Times[T], 1 } func max[T Number]() T { switch reflect.ValueOf(T(0)).Kind() { case reflect.Int: x := int(math.MaxInt) return T(x) case reflect.Int8: x := int8(math.MaxInt8) return T(x) case reflect.Int16: x := int16(math.MaxInt16) return T(x) case reflect.Int32: x := int32(math.MaxInt32) return T(x) case reflect.Int64: x := int64(math.MaxInt64) return T(x) case reflect.Uint: x := uint(math.MaxUint) return T(x) case reflect.Uint8: x := uint8(math.MaxUint8) return T(x) case reflect.Uint16: x := uint16(math.MaxUint16) return T(x) case reflect.Uint32: x := uint32(math.MaxUint32) return T(x) case reflect.Uint64: x := uint64(math.MaxUint64) return T(x) case reflect.Uintptr: x := ^uintptr(0) return T(x) case reflect.Float32: x := float32(math.Inf(1)) return T(x) case reflect.Float64: x := math.Inf(1) return T(x) default: panic("invalid type") } } func MinMonoid[T Number]() (minimum BinaryOp[T, T, T], identity T) { return Min[T], max[T]() } func min[T Number]() T { switch reflect.ValueOf(T(0)).Kind() { case reflect.Int: x := int(math.MinInt) return T(x) case reflect.Int8: x := int8(math.MinInt8) return T(x) case reflect.Int16: x := int16(math.MinInt16) return T(x) case reflect.Int32: x := int32(math.MinInt32) return T(x) case reflect.Int64: x := int64(math.MinInt64) return T(x) case reflect.Uint: x := 0 return T(x) case reflect.Uint8: x := uint8(0) return T(x) case reflect.Uint16: x := uint16(0) return T(x) case reflect.Uint32: x := uint32(0) return T(x) case reflect.Uint64: x := uint64(0) return T(x) case reflect.Uintptr: x := uintptr(0) return T(x) case reflect.Float32: x := float32(math.Inf(-1)) return T(x) case reflect.Float64: x := math.Inf(-1) return T(x) default: panic("invalid type") } } func MaxMonoid[T Number]() (maximum BinaryOp[T, T, T], identity T) { return Max[T], min[T]() } func LOrMonoid() (or BinaryOp[bool, bool, bool], identity bool) { return LOr, false } func LAndMonoid() (and BinaryOp[bool, bool, bool], identity bool) { return LAnd, true } func LXorMonoid() (xor BinaryOp[bool, bool, bool], identity bool) { return LXor, false } func LXNorMonoid() (xnor BinaryOp[bool, bool, bool], identity bool) { return LXNor, true } func PlusTimesSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return PlusMonoid[T], Times[T], 0 } func MinPlusSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return MinMonoid[T], Plus[T], max[T]() } func MaxPlusSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return MaxMonoid[T], Plus[T], min[T]() } func MinTimesSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return MinMonoid[T], Times[T], max[T]() } func MinMaxSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return MinMonoid[T], Max[T], max[T]() } func MaxMinSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return MaxMonoid[T], Min[T], min[T]() } func MaxTimesSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return MaxMonoid[T], Times[T], min[T]() } func PlusMinSemiring[T Number]() (addition Monoid[T], multiplication BinaryOp[T, T, T], identity T) { return PlusMonoid[T], Min[T], 0 } func LOrLAndSemiring() (addition Monoid[bool], multiplication BinaryOp[bool, bool, bool], identity bool) { return LOrMonoid, LAnd, false } func LAndLOrSemiring() (addition Monoid[bool], multiplication BinaryOp[bool, bool, bool], identity bool) { return LAndMonoid, LOr, true } func LXorLAndSemiring() (addition Monoid[bool], multiplication BinaryOp[bool, bool, bool], identity bool) { return LXorMonoid, LAnd, false } func LXNorLOrSemiring() (addition Monoid[bool], multiplication BinaryOp[bool, bool, bool], identity bool) { return LXNorMonoid, LOr, true } func MinFirstSemiring[T Number, Din2 any]() (addition Monoid[T], multiplication BinaryOp[T, T, Din2], identity T) { return MinMonoid[T], First[T, Din2], 0 } func MinSecondSemiring[T Number, Din1 any]() (addition Monoid[T], multiplication BinaryOp[T, Din1, T], identity T) { return MinMonoid[T], Second[Din1, T], 0 } func MaxFirstSemiring[T Number, Din2 any]() (addition Monoid[T], multiplication BinaryOp[T, T, Din2], identity T) { return MaxMonoid[T], First[T, Din2], 0 } func MaxSecondSemiring[T Number, Din1 any]() (addition Monoid[T], multiplication BinaryOp[T, Din1, T], identity T) { return MaxMonoid[T], Second[Din1, T], 0 }
api_operators.go
0.650911
0.666497
api_operators.go
starcoder
package cvefeed import ( "encoding/json" "math/bits" "github.com/facebookincubator/nvdtools/cvefeed/nvd" "github.com/facebookincubator/nvdtools/cvefeed/nvd/schema" ) type bag map[string]interface{} // ChunkKind is the type of chunks produced by a diff. type ChunkKind string const ( // ChunkDescription indicates a difference in the description of a // vulnerability. ChunkDescription ChunkKind = "description" // ChunkScore indicates a difference in the score of a vulnerability. ChunkScore = "score" ) type chunk uint32 const ( chunkDescriptionShift = iota chunkScoreShift chunkMaxShift ) const ( chunkDescription chunk = 1 << iota chunkScore ) var chunkKind = [chunkMaxShift]ChunkKind{ ChunkDescription, ChunkScore, } func (kind ChunkKind) shift() int { for i, v := range chunkKind { if v == kind { return i } } return chunkMaxShift } type diffEntry struct { id string bits chunk } type diffFeed struct { name string dict Dictionary } type diff struct { a, b diffFeed } func newDiff(a, b diffFeed) *diff { return &diff{ a: a, b: b, } } // DiffStats is the result of a diff. type DiffStats struct { diff *diff // back pointer to the diff these stats are for numVulnsA, numVulnsB int aNotB []string // ids of vulns that are in a but not in b bNotA []string // ids of vulns that are in b but not in a entries []diffEntry bitCounts [chunkMaxShift]int } // NumVulnsA returns the vulnerability in A (the first input to Diff). func (s *DiffStats) NumVulnsA() int { return s.numVulnsA } // NumVulnsB returns the vulnerability in A (the first input to Diff). func (s *DiffStats) NumVulnsB() int { return s.numVulnsB } // VulnsANotB returns the vulnerabilities that are A (the first input to Diff) but // are not in B (the second input to Diff). func (s *DiffStats) VulnsANotB() []string { return s.aNotB } // NumVulnsANotB returns the numbers of vulnerabilities that are A (the first input // to Diff) but are not in B (the second input to Diff). func (s *DiffStats) NumVulnsANotB() int { return len(s.aNotB) } // VulnsBNotA returns the vulnerabilities that are A (the first input to Diff) but // are not in B (the second input to Diff). func (s *DiffStats) VulnsBNotA() []string { return s.bNotA } // NumVulnsBNotA returns the numbers of vulnerabilities that are B (the second input // to Diff) but are not in A (the first input to Diff). func (s *DiffStats) NumVulnsBNotA() int { return len(s.bNotA) } // NumDiffVulns returns the number of vulnerability that are in both A and B but // are different (eg. different description, score, ...). func (s *DiffStats) NumDiffVulns() int { return len(s.entries) } // NumChunk returns the number of different vulnerabilities that have a specific chunk. func (s *DiffStats) NumChunk(chunk ChunkKind) int { return s.bitCounts[chunk.shift()] } // PercentChunk returns the percentage of different vulnerabilities that have a specific chunk. func (s *DiffStats) PercentChunk(chunk ChunkKind) float64 { return float64(s.bitCounts[chunk.shift()]) / float64(len(s.entries)) * 100 } func diffDetails(s *schema.NVDCVEFeedJSON10DefCVEItem, bit chunk) bag { var v interface{} switch bit { case chunkDescription: v = bag{ "description": englishDescription(s), } case chunkScore: v = s.Impact } var data bag tmp, _ := json.Marshal(v) _ = json.Unmarshal(tmp, &data) return data } func genEntryDiffOutput(aFeed, bFeed *diffFeed, entry *diffEntry) []bag { a := aFeed.dict[entry.id].(*nvd.Vuln).Schema() b := bFeed.dict[entry.id].(*nvd.Vuln).Schema() outputs := make([]bag, bits.OnesCount32(uint32(entry.bits))) for i := 0; i < chunkMaxShift; i++ { if entry.bits&(1<<i) != 0 { outputs[i] = bag{ "kind": chunkKind[i], aFeed.name: diffDetails(a, 1<<i), bFeed.name: diffDetails(b, 1<<i), } } } return outputs } // MarshalJSON implements a custom JSON marshaller. func (s *DiffStats) MarshalJSON() ([]byte, error) { var differences []bag for _, entry := range s.entries { differences = append(differences, bag{ "id": entry.id, "chunks": genEntryDiffOutput(&s.diff.a, &s.diff.b, &entry), }) } return json.Marshal(bag{ "differences": differences, }) } func englishDescription(s *schema.NVDCVEFeedJSON10DefCVEItem) string { for _, d := range s.CVE.Description.DescriptionData { if d.Lang == "en" { return d.Value } } return "" } func sameDescription(a, b *schema.NVDCVEFeedJSON10DefCVEItem) bool { return englishDescription(a) == englishDescription(b) } func sameScoreCVSSV2(a, b *schema.NVDCVEFeedJSON10DefCVEItem) bool { var aScore, bScore float64 var aVector, bVector string if a.Impact.BaseMetricV2 != nil && a.Impact.BaseMetricV2.CVSSV2 != nil { aScore = a.Impact.BaseMetricV2.CVSSV2.BaseScore aVector = a.Impact.BaseMetricV2.CVSSV2.VectorString } if b.Impact.BaseMetricV2 != nil && b.Impact.BaseMetricV2.CVSSV2 != nil { bScore = b.Impact.BaseMetricV2.CVSSV2.BaseScore bVector = b.Impact.BaseMetricV2.CVSSV2.VectorString } return aScore == bScore && aVector == bVector } func sameScoreCVSSV3(a, b *schema.NVDCVEFeedJSON10DefCVEItem) bool { var aScore, bScore float64 var aVector, bVector string if a.Impact.BaseMetricV3 != nil && a.Impact.BaseMetricV3.CVSSV3 != nil { aScore = a.Impact.BaseMetricV3.CVSSV3.BaseScore aVector = a.Impact.BaseMetricV3.CVSSV3.VectorString } if b.Impact.BaseMetricV3 != nil && b.Impact.BaseMetricV3.CVSSV3 != nil { bScore = b.Impact.BaseMetricV3.CVSSV3.BaseScore bVector = b.Impact.BaseMetricV3.CVSSV3.VectorString } return aScore == bScore && aVector == bVector } func sameScore(a, b *schema.NVDCVEFeedJSON10DefCVEItem) bool { return sameScoreCVSSV2(a, b) && sameScoreCVSSV3(a, b) } func (d *diff) stats() *DiffStats { stats := DiffStats{ diff: d, numVulnsA: len(d.a.dict), numVulnsB: len(d.b.dict), } // List of vulns that are in a but not in b. for key := range d.a.dict { if _, ok := d.b.dict[key]; !ok { stats.aNotB = append(stats.aNotB, key) continue } // key is in both a and b, let's compare further! a := d.a.dict[key].(*nvd.Vuln).Schema() b := d.b.dict[key].(*nvd.Vuln).Schema() var entry diffEntry if !sameDescription(a, b) { entry.bits |= chunkDescription stats.bitCounts[chunkDescriptionShift]++ } if !sameScore(a, b) { entry.bits |= chunkScore stats.bitCounts[chunkScoreShift]++ } if entry.bits != 0 { entry.id = key stats.entries = append(stats.entries, entry) } } // List of vulns that are in b but not in a. for key := range d.b.dict { if _, ok := d.a.dict[key]; !ok { stats.bNotA = append(stats.bNotA, key) } } return &stats } // Diff performs a diff between two Dictionaries. func Diff(aName string, aDict Dictionary, bName string, bDict Dictionary) *DiffStats { diff := newDiff(diffFeed{aName, aDict}, diffFeed{bName, bDict}) return diff.stats() }
cvefeed/diff.go
0.635109
0.431764
diff.go
starcoder
// Package nulls wrap up functions for the manipulation of bitmap library roaring. // MatrixOne uses nulls to store all NULL values in a column. // You can think of Nulls as a bitmap. package nulls import ( "bytes" "fmt" "unsafe" roaring "github.com/RoaringBitmap/roaring/roaring64" ) // Or performs union operation on Nulls n,m and store the result in r func Or(n, m, r *Nulls) { if (n == nil || (n != nil && n.Np == nil)) && m != nil && m.Np != nil { if r.Np == nil { r.Np = roaring.NewBitmap() } r.Np.Or(m.Np) return } if (m == nil || (m != nil && m.Np == nil)) && n != nil && n.Np != nil { if r.Np == nil { r.Np = roaring.NewBitmap() } r.Np.Or(n.Np) return } if m != nil && m.Np != nil && n != nil && n.Np != nil { if r.Np == nil { r.Np = roaring.NewBitmap() } r.Np.Or(n.Np) r.Np.Or(m.Np) } } func Reset(n *Nulls) { if n.Np != nil { n.Np.Clear() } } // Any returns true if any bit in the Nulls is set, otherwise it will return false. func Any(n *Nulls) bool { if n.Np == nil { return false } return !n.Np.IsEmpty() } // Size estimates the memory usage of the Nulls. func Size(n *Nulls) int { if n.Np == nil { return 0 } return int(n.Np.GetSizeInBytes()) } // Length returns the number of integers contained in the Nulls func Length(n *Nulls) int { if n.Np == nil { return 0 } return int(n.Np.GetCardinality()) } func String(n *Nulls) string { if n.Np == nil { return "[]" } return fmt.Sprintf("%v", n.Np.ToArray()) } // Contains returns true if the integer is contained in the Nulls func Contains(n *Nulls, row uint64) bool { if n.Np != nil { return n.Np.Contains(row) } return false } func Add(n *Nulls, rows ...uint64) { if n.Np == nil { n.Np = roaring.BitmapOf(rows...) return } n.Np.AddMany(rows) } func Del(n *Nulls, rows ...uint64) { if n.Np == nil { return } for _, row := range rows { n.Np.Remove(row) } } // Set performs union operation on Nulls n,m and store the result in n func Set(n, m *Nulls) { if m != nil && m.Np != nil { if n.Np == nil { n.Np = roaring.NewBitmap() } n.Np.Or(m.Np) } } // FilterCount returns the number count that appears in both n and sel func FilterCount(n *Nulls, sels []int64) int { var cnt int if n.Np == nil { return cnt } var sp []uint64 if len(sels) > 0 { sp = unsafe.Slice((*uint64)(unsafe.Pointer(&sels[0])), cap(sels))[:len(sels)] } for _, sel := range sp { if n.Np.Contains(sel) { cnt++ } } return cnt } func RemoveRange(n *Nulls, start, end uint64) { if n.Np != nil { n.Np.RemoveRange(start, end) } } // Range adds the numbers in n starting at start and ending at end to m. // Return the result func Range(n *Nulls, start, end uint64, m *Nulls) *Nulls { switch { case n.Np == nil && m.Np == nil: case n.Np != nil && m.Np == nil: m.Np = roaring.NewBitmap() for ; start < end; start++ { if n.Np.Contains(start) { m.Np.Add(start) } } case n.Np != nil && m.Np != nil: m.Np.Clear() for ; start < end; start++ { if n.Np.Contains(start) { m.Np.Add(start) } } } return m } func Filter(n *Nulls, sels []int64) *Nulls { if n.Np == nil { return n } var sp []uint64 if len(sels) > 0 { sp = unsafe.Slice((*uint64)(unsafe.Pointer(&sels[0])), cap(sels))[:len(sels)] } np := roaring.NewBitmap() for i, sel := range sp { if n.Np.Contains(sel) { np.Add(uint64(i)) } } n.Np = np return n } func (n *Nulls) Show() ([]byte, error) { var buf bytes.Buffer if n.Np == nil { return nil, nil } if _, err := n.Np.WriteTo(&buf); err != nil { return nil, err } return buf.Bytes(), nil } func (n *Nulls) Read(data []byte) error { if len(data) == 0 { return nil } n.Np = roaring.NewBitmap() if err := n.Np.UnmarshalBinary(data); err != nil { n.Np = nil return err } return nil } func (n *Nulls) Or(m *Nulls) *Nulls { switch { case m == nil: return n case n.Np == nil && m.Np == nil: return n case n.Np != nil && m.Np == nil: return n case n.Np == nil && m.Np != nil: return m default: n.Np.Or(m.Np) return n } }
pkg/container/nulls/nulls.go
0.700485
0.472805
nulls.go
starcoder
package bit import "io" // ReadBit return bit from special offset of byte. // If offset outside byt length(0 - 7), return zero. // Byte 0b10000000 get by offset - 0 return One, other is Zero func ReadBit(byt byte, offset int) Bit { if offset < ByteMinBit || offset >= ByteMaxBit { return Zero } return (byt >> (ByteMaxBit - 1 - offset) & 1) == 1 } // WriteBit return new byte with be written bit. // If offset outside byt length(0 - 7), return old byte. // Byte 0b10000000 write One by offset 2 return 0b10100000 func WriteBit(byt byte, bit Bit, offset int) byte { if offset < ByteMinBit || offset >= ByteMaxBit { return byt } if bit { return byt | 1<<(ByteMaxBit-1-offset) } else { return byt & (^(1 << (ByteMaxBit - 1 - offset))) } } // ReverseByte return the reverse bits in special byte. // If input is 11001100, the return is 00110011 func ReverseByte(byt byte) byte { nb := byte(0) old := byt for i := ByteMinBit; i < ByteMaxBit; i++ { nb <<= 1 nb |= old % 2 old >>= 1 } return nb } type BitStream struct { stream []byte endOffset int8 // the index of be written next bit startOffset int8 // the index of be read next bit } // ByteLength return the length of BitStream in byte func (bs *BitStream) ByteLength() int { return len(bs.stream) } // BitLength return the length of BitStream in bit func (bs *BitStream) BitLength() int { return (len(bs.stream)-1)*8 - int(bs.startOffset) + int(bs.endOffset) } // WriteBit write a bit to BitStream. // WriteBit will append special bit to end of BitStream. And WriteBit is not thread-safe. func (bs *BitStream) WriteBit(bit Bit) { if len(bs.stream) == 0 { bs.stream = append(bs.stream, 0) bs.endOffset = 0 } if bs.endOffset == ByteMaxBit { bs.endOffset = 0 bs.stream = append(bs.stream, 0) } currentByteIndex := len(bs.stream) - 1 // because default bit is zero, so if write zero, can skip it if bit { // 01-23-45-67 (index) //-00-00-00-00, write pos = 0, write bit 1: // 00-00-00-00 | 10-00-00-00, (1 << (7-0=)7) => 10-00-00-00 //-10-00-00-00, write pos = 3, write bit 1: // 10-00-00-00 | 1-00-00, (1 << (7-3=)4) => 10-01-00-00 //-10-01-00-00, write pos = 7, write bit 1: // 10-01-00-00 | 1, (1 << (7-7=)0) => 10-01-00-01 bs.stream[currentByteIndex] |= 1 << (ByteMaxBit - 1 - bs.endOffset) } bs.endOffset++ } // ReadBit return a bit from head of BitStream. // ReadBit see BitStream as a queue. The ReadBit is not thread-safe. When BitStream.BitLength() is zero, return // Zero and io.EOF. func (bs *BitStream) ReadBit() (Bit, error) { if bs.BitLength() == 0 { return Zero, io.EOF } if bs.startOffset == ByteMaxBit { bs.stream = bs.stream[1:] bs.startOffset = ByteMinBit } // 01234567 (index) // 01000000 1 : >> 6(=7-1) 01 & 1 => 1 // 11000000 1 : >> 6(=7-1) 11 & 1 => 1 // 11010100 5 : >> 2(=7-5) 110101 & 1 => 1 // 11010100 6 : >> 1(=7-6) 1101010 & 1 => 0 d := bs.stream[0] >> (ByteMaxBit - 1 - bs.startOffset) bs.startOffset++ return d&0b1 == 1, nil } // WriteByte always return nil, and write byt to end of BitStream. // WriteByte is not thread-safe. WriteByte always see byt as 8 bits, it writes 8 bit to stream. func (bs *BitStream) WriteByte(byt byte) error { if len(bs.stream) == 0 || bs.endOffset == ByteMaxBit { bs.stream = append(bs.stream, 0) bs.endOffset = 0 } writeIndex := len(bs.stream) - 1 bs.stream[writeIndex] |= byt >> (bs.endOffset) bs.stream = append(bs.stream, 0) writeIndex++ bs.stream[writeIndex] = byt << (ByteMaxBit - bs.endOffset) return nil } // ReadByte return the byt from head of BitStream. // ReadByte see BitStream as a queue, and is not thread-safe. If BitStream.BitLength < 8, it always returns 0 and // io.EOF. ReadByte will try to return 8 bits as a byte. func (bs *BitStream) ReadByte() (byte, error) { if bs.ByteLength() == 0 { return 0, io.EOF } if bs.startOffset == ByteMaxBit { bs.stream = bs.stream[1:] if bs.ByteLength() == 0 { return 0, io.EOF } bs.startOffset = 0 } if bs.startOffset == 0 { return bs.stream[0], nil } byt := bs.stream[0] << bs.startOffset bs.stream = bs.stream[1:] if len(bs.stream) == 0 { return 0, io.EOF } byt |= bs.stream[0] >> (ByteMaxBit - bs.startOffset) return byt, nil } func (bs *BitStream) PopBit() (Bit, error) { if bs.BitLength() == 0 { return Zero, io.EOF } if bs.endOffset == ByteMinBit { bs.stream = bs.stream[:len(bs.stream)-1] bs.endOffset = ByteMaxBit } bs.endOffset-- return bs.stream[bs.endOffset]&1 == 1, nil }
bit.go
0.621196
0.420957
bit.go
starcoder
package bloom import ( "bytes" "errors" "math" "sync" conv "github.com/BOXFoundation/boxd/p2p/convert" "github.com/BOXFoundation/boxd/util" "github.com/BOXFoundation/boxd/util/murmur3" ) const ln2Squared = math.Ln2 * math.Ln2 const ( // MaxFilterHashFuncs is the maximum number of hash functions of bloom filter. MaxFilterHashFuncs = 256 // MaxFilterSize is the maximum byte size in bytes a filter may be. MaxFilterSize = 32 * 1024 * 1024 // DefaultConflictRate is the default conflict rate for any key. DefaultConflictRate = 0.001 ) // Filter defines bloom filter interface type Filter interface { Matches(data []byte) bool Add(data []byte) MatchesAndAdd(data []byte) bool Merge(f Filter) error Reset() Copy(f Filter) error Size() uint32 K() uint32 Tweak() uint32 FPRate() float64 GetByte(i uint32) byte Indexes() []uint32 IsEmpty() bool conv.Serializable } // filter implements the bloom-filter type filter struct { sm sync.Mutex filter []byte hashFuncs uint32 tweak uint32 } // NewFilterWithMK returns a Filter. // M is the cap of the bloom filter // K is the number of hash functions func NewFilterWithMK(m uint32, k uint32) Filter { return newFilter(m, k, 0) } // NewFilterWithMKAndTweak returns a Filter with specific tweak for hash seed. // M is the cap of the bloom filter // K is the number of hash functions func NewFilterWithMKAndTweak(m uint32, k uint32, tweak uint32) Filter { return newFilter(m, k, tweak) } func newFilter(m uint32, k uint32, tweak uint32) Filter { if m <= 0 { m = 1 } if k <= 0 { k = 1 } dataLen := uint32(math.Ceil(float64(m) / 8.)) if MaxFilterSize < dataLen { dataLen = MaxFilterSize } hashFuncs := k if MaxFilterHashFuncs < hashFuncs { hashFuncs = MaxFilterHashFuncs } data := make([]byte, dataLen) return &filter{ filter: data, hashFuncs: hashFuncs, tweak: tweak, } } // NewFilter returns a Filter func NewFilter(elements uint32, fprate float64) Filter { return NewFilterWithTweak(elements, fprate, 0) } // NewFilterWithTweak returns a Filter with with specific tweak for hash seed func NewFilterWithTweak(elements uint32, fprate float64, tweak uint32) Filter { // Massage the false positive rate to sane values. if fprate > 1.0 { fprate = 1.0 } else if fprate < 1e-9 { fprate = 1e-9 } // Calculate the size of the filter in bits for the given number of // elements and false positive rate. m := uint32(math.Ceil(float64(-1 * float64(elements) * math.Log(fprate) / ln2Squared))) // Calculate the number of hash functions based on the size of the // filter calculated above and the number of elements. k := uint32(math.Ceil(math.Ln2 * float64(m) / float64(elements))) return newFilter(m, k, tweak) } // LoadFilter loads bloom filter from serialized data. func LoadFilter(data []byte) (Filter, error) { var f = &filter{} if err := f.Unmarshal(data); err != nil { return nil, err } return f, nil } // hash returns the bit offset in the bloom filter which corresponds to the // passed data for the given indepedent hash function number. func (bf *filter) hash(hashFuncNum uint32, data []byte) uint32 { h32 := murmur3.MurmurHash3WithSeed(data, hashFuncNum*0xfba4c795+bf.tweak) return h32 % (uint32(len(bf.filter)) << 3) } // matches returns true if the bloom filter might contain the passed data and // false if it definitely does not. func (bf *filter) matches(data []byte) bool { // idx >> 3 = idx / 8 : byte index in the byte slice // 1<<(idx&7) = idx % 8 : bit index in the byte for i := uint32(0); i < bf.hashFuncs; i++ { idx := bf.hash(i, data) if bf.filter[idx>>3]&(1<<(idx&7)) == 0 { return false } } return true } // Matches returns true if the bloom filter might contain the passed data and // false if it definitely does not. func (bf *filter) Matches(data []byte) bool { bf.sm.Lock() match := bf.matches(data) bf.sm.Unlock() return match } // add adds the passed byte slice to the bloom filter. func (bf *filter) add(data []byte) { for i := uint32(0); i < bf.hashFuncs; i++ { idx := bf.hash(i, data) bf.filter[idx>>3] |= (1 << (7 & idx)) } } // Add adds the passed byte slice to the bloom filter. func (bf *filter) Add(data []byte) { bf.sm.Lock() bf.add(data) bf.sm.Unlock() } // matchesAndAdd adds the passed byte slice to the bloom filter. func (bf *filter) matchesAndAdd(data []byte) (r bool) { r = true for i := uint32(0); i < bf.hashFuncs; i++ { idx := bf.hash(i, data) if bf.filter[idx>>3]&(1<<(idx&7)) == 0 { bf.filter[idx>>3] |= (1 << (7 & idx)) r = false } } return r } // MatchesAndAdd matchs the passed data, and add it to the bloom filter in case of false func (bf *filter) MatchesAndAdd(data []byte) (r bool) { bf.sm.Lock() match := bf.matchesAndAdd(data) bf.sm.Unlock() return match } // merge merges the passed one with the bloom filter. func (bf *filter) merge(f Filter) error { var rf, ok = f.(*filter) if !ok { return errors.New("unknown bloom filter") } rf.sm.Lock() defer rf.sm.Unlock() if bf.hashFuncs != rf.hashFuncs { return errors.New("HashFuncs doesn't match") } if len(bf.filter) != len(rf.filter) { return errors.New("Size of filter bits doesn't match") } if bf.tweak != rf.tweak { return errors.New("Seed of hash doesn't match") } for i := 0; i < len(bf.filter); i++ { bf.filter[i] |= rf.filter[i] } return nil } // Merge merges the passed one with the bloom filter. func (bf *filter) Merge(f Filter) error { bf.sm.Lock() err := bf.merge(f) bf.sm.Unlock() return err } // Reset reset all flag bits of the bloom filter. func (bf *filter) Reset() { bf.sm.Lock() for i := 0; i < len(bf.filter); i++ { bf.filter[i] = byte(0) } bf.sm.Unlock() } func (bf *filter) Copy(f Filter) error { bf = NewFilterWithMK(f.Size(), f.K()).(*filter) return bf.Merge(f) } // GetByte get the specified byte. func (bf *filter) GetByte(i uint32) byte { return bf.filter[i] } // Size returns the length of filter in bits. func (bf *filter) Size() uint32 { bf.sm.Lock() s := uint32(len(bf.filter)) << 3 bf.sm.Unlock() return s } // Size returns the number of hash functions. func (bf *filter) K() uint32 { return bf.hashFuncs } // Tweak returns the random value added to the hash seed. func (bf *filter) Tweak() uint32 { return bf.tweak } // FPRate returns the false positive probability func (bf *filter) FPRate() float64 { bf.sm.Lock() var size = uint32(len(bf.filter)) << 3 var bits = bf.bitsFilled() var frate = float64(bits) / float64(size) var fprate = frate for i := uint32(1); i < bf.hashFuncs; i++ { fprate *= frate } bf.sm.Unlock() return fprate } // bitsFilled returns how many bits were set func (bf *filter) bitsFilled() uint32 { var bits uint32 for i := 0; i < len(bf.filter); i++ { b := bf.filter[i] for idx := uint8(0); idx < 8; idx++ { if b&(1<<idx) != 0 { bits++ } } } return bits } // Marshal marshals the bloom filter to a binary representation of it. func (bf *filter) Marshal() (data []byte, err error) { var w bytes.Buffer if err := util.WriteUint32(&w, bf.hashFuncs); err != nil { return nil, err } if err := util.WriteUint32(&w, bf.tweak); err != nil { return nil, err } if err := util.WriteVarBytes(&w, bf.filter); err != nil { return nil, err } return w.Bytes(), nil } // Unmarshal unmarshals a bloom filter from binary data. func (bf *filter) Unmarshal(data []byte) error { var err error var r = bytes.NewBuffer(data) if bf.hashFuncs, err = util.ReadUint32(r); err != nil { return err } if bf.tweak, err = util.ReadUint32(r); err != nil { return err } bf.filter, err = util.ReadVarBytes(r) return err } // Indexes return marked indexes. func (bf *filter) Indexes() []uint32 { return util.BitIndexes(bf.filter) } // IsEmpty return whether it is empty. func (bf *filter) IsEmpty() bool { for _, b := range bf.filter { if b != byte(0) { return false } } return true }
util/bloom/filter.go
0.699254
0.451992
filter.go
starcoder
package unicornify import ( . "github.com/balpha/go-unicornify/unicornify/core" . "github.com/balpha/go-unicornify/unicornify/elements" . "github.com/balpha/go-unicornify/unicornify/rendering" "github.com/balpha/gopyrand" "image" "math" ) func MakeAvatar(hash string, size int, withBackground bool, zoomOut bool, shading bool, grass bool, parallelize bool, yCallback func(int)) (error, *image.RGBA) { rand := pyrand.NewRandom() err := rand.SeedFromHexString(hash) if err != nil { return err, nil } data := UnicornData{} bgdata := BackgroundData{} grassdata := GrassData{} // begin randomization // To keep consistency of unicorns between versions, // new Random() calls should always be added at the end data.Randomize1(rand) bgdata.Randomize1(rand) unicornScaleFactor := .5 + math.Pow(rand.Random(), 2)*2.5 if zoomOut { unicornScaleFactor = .5 } sign := rand.Choice(2)*2 - 1 abs := rand.RandInt(10, 75) yAngle := float64(90+sign*abs) * DEGREE xAngle := float64(rand.RandInt(-20, 20)) * DEGREE data.Randomize2(rand) bgdata.Randomize2(rand) data.Randomize3(rand) grassdata.Randomize(rand) _ = rand.Random() focalLength := 250 + rand.Random()*250 data.Randomize4(rand) lightDirection := Vector{rand.Random()*16 - 8, 10, rand.Random() * 3} lightDirection = Vector{lightDirection.Z(), lightDirection.Y(), -lightDirection.X()} // end randomization grassdata.Horizon = bgdata.Horizon grassdata.Color1 = bgdata.Color("Land", bgdata.LandLight) grassdata.Color2 = bgdata.Color("Land", bgdata.LandLight/2) if (yAngle-90*DEGREE)*data.NeckTilt > 0 { // The unicorn should look at the camera. data.NeckTilt *= -1 data.FaceTilt *= -1 } uni := NewUnicorn(data) if data.PoseKindIndex == 1 /*Walk*/ { lowFront := uni.Legs[0].Hoof.Center if uni.Legs[1].Hoof.Center.Y() > uni.Legs[0].Hoof.Center.Y() { lowFront = uni.Legs[1].Hoof.Center } lowBack := uni.Legs[2].Hoof.Center if uni.Legs[3].Hoof.Center.Y() > uni.Legs[2].Hoof.Center.Y() { lowBack = uni.Legs[3].Hoof.Center } angle := math.Atan((lowBack.Y() - lowFront.Y()) / (lowBack.X() - lowFront.X())) for b := range uni.BallSet() { b.RotateAround(*uni.Shoulder, -angle, 2) } } if xAngle < 0 { for b := range uni.BallSet() { b.RotateAround(*uni.Shoulder, yAngle, 1) b.RotateAround(*uni.Shoulder, xAngle, 0) b.RotateAround(*uni.Shoulder, -yAngle, 1) } xAngle = 0 } fsize := float64(size) // factor = 1 means center the head at (1/2, 1/3); factor = 0 means // center the shoulder at (1/2, 1/2) factor := math.Sqrt((unicornScaleFactor - .5) / 2.5) lookAtPoint := uni.Shoulder.Center.Plus(uni.Head.Center.Plus(uni.Shoulder.Center.Neg()).Times(factor)) cp := lookAtPoint.Plus(Vector{0, 0, -3 * focalLength}).RotatedAround(uni.Head.Center, -xAngle, 0).RotatedAround(uni.Head.Center, -yAngle, 1) wv := WorldView{ CameraPosition: cp, LookAtPoint: lookAtPoint, FocalLength: focalLength, } Shift := Point2d{0.5 * fsize, factor*fsize/3 + (1-factor)*fsize/2} Scale := ((unicornScaleFactor-0.5)/2.5*2 + 0.5) * fsize / 140.0 wv.Init() img := image.NewRGBA(image.Rect(0, 0, size, size)) if withBackground { bgdata.Draw(img, shading) } scaleAndShift := func(t Tracer) Tracer { t = NewScalingTracer(wv, t, Scale) return NewTranslatingTracer(wv, t, Shift[0], Shift[1]) } uniAndMaybeGrass := &Figure{} uniAndMaybeGrass.Add(uni) if grass { ymaxhoof := -99999.0 for _, l := range uni.Legs { if l.Hoof.Center.Y() > ymaxhoof { ymaxhoof = l.Hoof.Center.Y() } } floory := ymaxhoof + uni.Legs[0].Hoof.Radius hx := (0 - Shift[0]) / Scale hy := (bgdata.Horizon*float64(size) - Shift[1]) / Scale var hdist float64 = 100 for wv.UnProject(Vector{hx, hy, hdist}).Y() < floory { hdist += 10 } grassSandwich := GrassSandwich(floory, bgdata, grassdata, Shift, Scale, size) // center can't be exactly the camera position -- haven't yet dug into where exactly this is creating edge case behavior crop := NewBallP(wv.CameraPosition.Plus(Vector{0, 0, 1}), hdist, Color{255, 0, 0}) uniAndMaybeGrass.Add(NewIntersection(grassSandwich, crop)) } tracer := uniAndMaybeGrass.GetTracer(wv) if shading { p := Vector{0, 0, 1000} pp := wv.ProjectSphere(p, 0).CenterCS ldp := wv.ProjectSphere(p.Plus(lightDirection), 0).CenterCS.Minus(pp) lt := NewDirectionalLightTracer(tracer, ldp, 32, 80) sc := NewShadowCastingTracer(lt, wv, uniAndMaybeGrass, uni.Head.Center.Minus(lightDirection.Times(1000)), uni.Head.Center, 16, 16) tracer = sc } tracer = scaleAndShift(tracer) if parallelize { parts := size / 128 if parts < 8 { parts = 8 } DrawTracerParallel(tracer, wv, img, yCallback, parts) } else { DrawTracer(tracer, wv, img, yCallback) } return nil, img }
unicornify/avatar.go
0.563378
0.463748
avatar.go
starcoder
package main import ( "fmt" "github.com/emer/emergent/patgen" "github.com/emer/etable/etensor" ) // Proof of concept for replacing the environment with a simpler environment that uses the network. type ExampleWorld struct { WorldInterface Nm string `desc:"name of this environment"` Dsc string `desc:"description of this environment"` observationShape map[string][]int observations map[string]*etensor.Float32 } //Display displays the environmnet func (world *ExampleWorld) Display() { fmt.Println("This world state") } // Init Initializes or reinitialize the world, todo, change from being hardcoded for emery func (world *ExampleWorld) Init(details string) { fmt.Println("Init Dworld: " + details) world.observationShape = make(map[string][]int) world.observations = make(map[string]*etensor.Float32) } func (world *ExampleWorld) GetObservationSpace() map[string][]int { return world.observationShape //todo need to instantitate } func (world *ExampleWorld) GetActionSpace() map[string][]int { return nil } func (world *ExampleWorld) DecodeAndTakeAction(action string, vt *etensor.Float32) string { fmt.Printf("Prediciton of the network") fmt.Printf(vt.String()) fmt.Println("\n Expected Output") fmt.Printf(world.observations["VL"].String()) return "Taking in info from model and moving forward" } // StepN Updates n timesteps (e.g. milliseconds) func (world *ExampleWorld) StepN(n int) {} // Step 1 func (world *ExampleWorld) Step() { fmt.Println("I'm taking a step") } // Observe Returns a tensor for the named modality. E.g. “x” or “vision” or “reward” func (world *ExampleWorld) Observe(name string) etensor.Tensor { return nil } func (world *ExampleWorld) ObserveWithShape(name string, shape []int) etensor.Tensor { return nil } func (world *ExampleWorld) ObserveWithShapeStride(name string, shape []int, strides []int) etensor.Tensor { if name == "Output" { if world.observations[name] == nil { world.observations[name] = etensor.NewFloat32(shape, strides, nil) patgen.PermutedBinary(world.observations[name], 6, 1, 0) } return world.observations[name] } world.observations[name] = etensor.NewFloat32(shape, strides, nil) patgen.PermutedBinary(world.observations[name], 6, 1, 0) return world.observations[name] } // Action Output action to the world with details. Details might contain a number or array. So this might be Action(“move”, “left”) or Action(“LeftElbow”, “0.4”) or Action("Log", "[0.1, 0.9]") func (world *ExampleWorld) Action(action, details string) {} // Done Returns true if episode has ended, e.g. when exiting maze func (world *ExampleWorld) Done() bool { return false } // Info Returns general information about the world, for debugging purposes. Should not be used for actual learning. func (world *ExampleWorld) Info() string { return "God is dead" }
examples/ra25example_world/example_world.go
0.7478
0.4575
example_world.go
starcoder
package engine import ( "fmt" "image" "image/color" "image/draw" "math" ) // ChannelImage represents a discrete image. type ChannelImage struct { Width int Height int Buffer []uint8 } // NewChannelImageWidthHeight returns a channel image of specific width and height. func NewChannelImageWidthHeight(width, height int) ChannelImage { return ChannelImage{ Width: width, Height: height, Buffer: make([]uint8, width*height), // note. it is necessary to register all values less than 0 as 0 and greater than 255 as 255 } } // NewChannelImage returns a channel image corresponding to the specified image. func NewChannelImage(img image.Image) (ChannelImage, bool, error) { var ( b []uint8 opaque bool ) switch t := img.(type) { case *image.RGBA: b = t.Pix opaque = t.Opaque() case *image.NRGBA: b = t.Pix opaque = t.Opaque() case *image.YCbCr: r := t.Rect for y := 0; y < r.Dy(); y++ { for x := 0; x < r.Dx(); x++ { R, G, B, A := t.At(x, y).RGBA() b = append(b, uint8(R>>8), uint8(G>>8), uint8(B>>8), uint8(A>>8)) } } opaque = t.Opaque() case *image.Paletted: r := t.Rect for y := 0; y < r.Dy(); y++ { for x := 0; x < r.Dx(); x++ { R, G, B, A := t.At(x, y).RGBA() b = append(b, uint8(R>>8), uint8(G>>8), uint8(B>>8), uint8(A>>8)) } } opaque = t.Opaque() default: return ChannelImage{}, false, fmt.Errorf("unknown image format: %T", t) } return ChannelImage{ Width: img.Bounds().Max.X, Height: img.Bounds().Max.Y, Buffer: b, }, opaque, nil } // NewDenormalizedChannelImage returns a channel image corresponding to the image plane. func NewDenormalizedChannelImage(p ImagePlane) ChannelImage { img := NewChannelImageWidthHeight(p.Width, p.Height) for i := range p.Buffer { v := int(math.Round(float64(p.Buffer[i]) * 255.0)) if v < 0 { v = 0 } else if v > 255 { v = 255 } img.Buffer[i] = uint8(v) } return img } // ImageRGBA converts the channel image to an image.RGBA and return it. func (c ChannelImage) ImageRGBA() image.RGBA { r := image.Rect(0, 0, c.Width, c.Height) return image.RGBA{ Pix: c.Buffer, Stride: r.Dx() * 4, Rect: r, } } // ImagePaletted converts the chanel image to an image.Paletted and return it. func (c ChannelImage) ImagePaletted(p color.Palette) *image.Paletted { rgba := c.ImageRGBA() ret := image.NewPaletted(rgba.Bounds(), p) draw.DrawMask(ret, image.Rect(0, 0, ret.Bounds().Max.X, ret.Bounds().Max.Y), &rgba, image.Point{}, nil, image.Point{}, draw.Src) return ret } // ChannelDecompose decomposes a channel image to R, G, B and Alpha channels. func ChannelDecompose(img ChannelImage) (r, g, b, a ChannelImage) { r = NewChannelImageWidthHeight(img.Width, img.Height) g = NewChannelImageWidthHeight(img.Width, img.Height) b = NewChannelImageWidthHeight(img.Width, img.Height) a = NewChannelImageWidthHeight(img.Width, img.Height) for w := 0; w < img.Width; w++ { for h := 0; h < img.Height; h++ { i := w + h*img.Width r.Buffer[i] = img.Buffer[(w*4)+(h*img.Width*4)] g.Buffer[i] = img.Buffer[(w*4)+(h*img.Width*4)+1] b.Buffer[i] = img.Buffer[(w*4)+(h*img.Width*4)+2] a.Buffer[i] = img.Buffer[(w*4)+(h*img.Width*4)+3] } } return r, g, b, a } // ChannelCompose composes R, G, B and Alpha channels to the one channel image. func ChannelCompose(r, g, b, a ChannelImage) ChannelImage { width := r.Width height := r.Height img := make([]uint8, width*height*4) for i := 0; i < width*height; i++ { img[i*4] = r.Buffer[i] img[i*4+1] = g.Buffer[i] img[i*4+2] = b.Buffer[i] img[i*4+3] = a.Buffer[i] } return ChannelImage{ Width: width, Height: height, Buffer: img, } } // Extrapolation calculates an extrapolation algorithm. func (c ChannelImage) Extrapolation(px int) ChannelImage { width := c.Width height := c.Height toIndex := func(w, h int) int { return w + h*width } imageEx := NewChannelImageWidthHeight(width+(2*px), height+(2*px)) for h := 0; h < height+(px*2); h++ { for w := 0; w < width+(px*2); w++ { index := w + h*(width+(px*2)) if w < px { // Left outer area if h < px { // Left upper area imageEx.Buffer[index] = c.Buffer[toIndex(0, 0)] } else if px+height <= h { // Left lower area imageEx.Buffer[index] = c.Buffer[toIndex(0, height-1)] } else { // Left outer area imageEx.Buffer[index] = c.Buffer[toIndex(0, h-px)] } } else if px+width <= w { // Right outer area if h < px { // Right upper area imageEx.Buffer[index] = c.Buffer[toIndex(width-1, 0)] } else if px+height <= h { // Right lower area imageEx.Buffer[index] = c.Buffer[toIndex(width-1, height-1)] } else { // Right outer area imageEx.Buffer[index] = c.Buffer[toIndex(width-1, h-px)] } } else if h < px { // Upper outer area imageEx.Buffer[index] = c.Buffer[toIndex(w-px, 0)] } else if px+height <= h { // Lower outer area imageEx.Buffer[index] = c.Buffer[toIndex(w-px, height-1)] } else { // Inner area imageEx.Buffer[index] = c.Buffer[toIndex(w-px, h-px)] } } } return imageEx } // Resize returns a resized image. func (c ChannelImage) Resize(scale float64) ChannelImage { if scale == 1.0 { return c } width := c.Width height := c.Height scaledWidth := int(math.Round(float64(width) * scale)) scaledHeight := int(math.Round(float64(height) * scale)) scaledImage := NewChannelImageWidthHeight(scaledWidth, scaledHeight) for w := 0; w < scaledWidth; w++ { for h := 0; h < scaledHeight; h++ { scaledIndex := w + (h * scaledWidth) wOriginal := int(math.Round(float64(w+1)/scale) - 1) if wOriginal < 0 { wOriginal = 0 } hOriginal := int(math.Round(float64(h+1)/scale) - 1) if hOriginal < 0 { hOriginal = 0 } indexOriginal := wOriginal + (hOriginal * width) scaledImage.Buffer[scaledIndex] = c.Buffer[indexOriginal] } } return scaledImage }
engine/channel_image.go
0.773216
0.427456
channel_image.go
starcoder
package stats import ( "errors" "math" ) // Normal is used to represent the normal distribution parameters. // Mu is the mean. // Sigma is the standard deviation. type Normal struct { Mu float64 Sigma float64 } // NewNormal is used to initialize normal parameters. What is different from // Normal type is that here the parameters are validated. // Mu must be a real number (+ or -) and Sigma > 0. func NewNormal(mu float64, sigma float64) (Normal, error) { if sigma <= 0 { return Normal{}, errors.New("stats: invalid Normal parameters. Check Sigma > 0") } return Normal{Mu: mu, Sigma: sigma}, nil } // PDF returns the probability density function output of the normal distribution for a given x. func (norm Normal) PDF(x float64) float64 { return math.Exp(-(x-norm.Mu)*(x-norm.Mu)/(2*norm.Sigma*norm.Sigma)) / (norm.Sigma * math.Sqrt(2*math.Pi)) } // CDF returns the cumulative distribution function output of the normal distribution for a given x. func (norm Normal) CDF(x float64) float64 { return 0.5 * (1 + math.Erf((x-norm.Mu)/(math.Sqrt(2)*norm.Sigma))) } // Mean returns the mean of the normal distribution. func (norm Normal) Mean() float64 { return norm.Mu } // Median returns the median of the normal distribution. func (norm Normal) Median() float64 { return norm.Mu } // StdDev returns the standard deviation of the normal distribution. func (norm Normal) StdDev() float64 { return norm.Sigma } // Variance returns the Variance of the normal distribution. func (norm Normal) Variance() float64 { return math.Pow(norm.Sigma, 2.0) } //Data from: https://www.itl.nist.gov/div898/handbook/eda/section3/eda3671.htm. var zStandardNormal statsTable = statsTable{ [][]float64{ []float64{0.00000, 0.00399, 0.00798, 0.01197, 0.01595, 0.01994, 0.02392, 0.02790, 0.03188, 0.03586}, []float64{0.03983, 0.04380, 0.04776, 0.05172, 0.05567, 0.05962, 0.06356, 0.06749, 0.07142, 0.07535}, []float64{0.07926, 0.08317, 0.08706, 0.09095, 0.09483, 0.09871, 0.10257, 0.10642, 0.11026, 0.11409}, []float64{0.11791, 0.12172, 0.12552, 0.12930, 0.13307, 0.13683, 0.14058, 0.14431, 0.14803, 0.15173}, []float64{0.15542, 0.15910, 0.16276, 0.16640, 0.17003, 0.17364, 0.17724, 0.18082, 0.18439, 0.18793}, []float64{0.19146, 0.19497, 0.19847, 0.20194, 0.20540, 0.20884, 0.21226, 0.21566, 0.21904, 0.22240}, []float64{0.22575, 0.22907, 0.23237, 0.23565, 0.23891, 0.24215, 0.24537, 0.24857, 0.25175, 0.25490}, []float64{0.25804, 0.26115, 0.26424, 0.26730, 0.27035, 0.27337, 0.27637, 0.27935, 0.28230, 0.28524}, []float64{0.28814, 0.29103, 0.29389, 0.29673, 0.29955, 0.30234, 0.30511, 0.30785, 0.31057, 0.31327}, []float64{0.31594, 0.31859, 0.32121, 0.32381, 0.32639, 0.32894, 0.33147, 0.33398, 0.33646, 0.33891}, []float64{0.34134, 0.34375, 0.34614, 0.34849, 0.35083, 0.35314, 0.35543, 0.35769, 0.35993, 0.36214}, []float64{0.36433, 0.36650, 0.36864, 0.37076, 0.37286, 0.37493, 0.37698, 0.37900, 0.38100, 0.38298}, []float64{0.38493, 0.38686, 0.38877, 0.39065, 0.39251, 0.39435, 0.39617, 0.39796, 0.39973, 0.40147}, []float64{0.40320, 0.40490, 0.40658, 0.40824, 0.40988, 0.41149, 0.41308, 0.41466, 0.41621, 0.41774}, []float64{0.41924, 0.42073, 0.42220, 0.42364, 0.42507, 0.42647, 0.42785, 0.42922, 0.43056, 0.43189}, []float64{0.43319, 0.43448, 0.43574, 0.43699, 0.43822, 0.43943, 0.44062, 0.44179, 0.44295, 0.44408}, []float64{0.44520, 0.44630, 0.44738, 0.44845, 0.44950, 0.45053, 0.45154, 0.45254, 0.45352, 0.45449}, []float64{0.45543, 0.45637, 0.45728, 0.45818, 0.45907, 0.45994, 0.46080, 0.46164, 0.46246, 0.46327}, []float64{0.46407, 0.46485, 0.46562, 0.46638, 0.46712, 0.46784, 0.46856, 0.46926, 0.46995, 0.47062}, []float64{0.47128, 0.47193, 0.47257, 0.47320, 0.47381, 0.47441, 0.47500, 0.47558, 0.47615, 0.47670}, []float64{0.47725, 0.47778, 0.47831, 0.47882, 0.47932, 0.47982, 0.48030, 0.48077, 0.48124, 0.48169}, []float64{0.48214, 0.48257, 0.48300, 0.48341, 0.48382, 0.48422, 0.48461, 0.48500, 0.48537, 0.48574}, []float64{0.48610, 0.48645, 0.48679, 0.48713, 0.48745, 0.48778, 0.48809, 0.48840, 0.48870, 0.48899}, []float64{0.48928, 0.48956, 0.48983, 0.49010, 0.49036, 0.49061, 0.49086, 0.49111, 0.49134, 0.49158}, []float64{0.49180, 0.49202, 0.49224, 0.49245, 0.49266, 0.49286, 0.49305, 0.49324, 0.49343, 0.49361}, []float64{0.49379, 0.49396, 0.49413, 0.49430, 0.49446, 0.49461, 0.49477, 0.49492, 0.49506, 0.49520}, []float64{0.49534, 0.49547, 0.49560, 0.49573, 0.49585, 0.49598, 0.49609, 0.49621, 0.49632, 0.49643}, []float64{0.49653, 0.49664, 0.49674, 0.49683, 0.49693, 0.49702, 0.49711, 0.49720, 0.49728, 0.49736}, []float64{0.49744, 0.49752, 0.49760, 0.49767, 0.49774, 0.49781, 0.49788, 0.49795, 0.49801, 0.49807}, []float64{0.49813, 0.49819, 0.49825, 0.49831, 0.49836, 0.49841, 0.49846, 0.49851, 0.49856, 0.49861}, []float64{0.49865, 0.49869, 0.49874, 0.49878, 0.49882, 0.49886, 0.49889, 0.49893, 0.49896, 0.49900}, []float64{0.49903, 0.49906, 0.49910, 0.49913, 0.49916, 0.49918, 0.49921, 0.49924, 0.49926, 0.49929}, []float64{0.49931, 0.49934, 0.49936, 0.49938, 0.49940, 0.49942, 0.49944, 0.49946, 0.49948, 0.49950}, []float64{0.49952, 0.49953, 0.49955, 0.49957, 0.49958, 0.49960, 0.49961, 0.49962, 0.49964, 0.49965}, []float64{0.49966, 0.49968, 0.49969, 0.49970, 0.49971, 0.49972, 0.49973, 0.49974, 0.49975, 0.49976}, []float64{0.49977, 0.49978, 0.49978, 0.49979, 0.49980, 0.49981, 0.49981, 0.49982, 0.49983, 0.49983}, []float64{0.49984, 0.49985, 0.49985, 0.49986, 0.49986, 0.49987, 0.49987, 0.49988, 0.49988, 0.49989}, []float64{0.49989, 0.49990, 0.49990, 0.49990, 0.49991, 0.49991, 0.49992, 0.49992, 0.49992, 0.49992}, []float64{0.49993, 0.49993, 0.49993, 0.49994, 0.49994, 0.49994, 0.49994, 0.49995, 0.49995, 0.49995}, []float64{0.49995, 0.49995, 0.49996, 0.49996, 0.49996, 0.49996, 0.49996, 0.49996, 0.49997, 0.49997}, []float64{0.49997, 0.49997, 0.49997, 0.49997, 0.49997, 0.49997, 0.49998, 0.49998, 0.49998, 0.49998}, }, []float64{ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4.0, }, []float64{0.00, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09}, }
probdist/normal.go
0.848267
0.716367
normal.go
starcoder
package utils /*findPosition returns the position and insert position of the given character in the PCArray. -> If character found, then its position and insert position -1 is returned -> If character not found, then its position would be -1 and its insert position is returned -> insert Position would be -1 if the character has to be inserted at the end of the array -> In error case like the array and map is not in sync it will return -1 and -2 */ func (data *ODSAData) findPosition(char byte) (int, int) { /*Checking whether the character exists in the PMap. If missing in the PMap, then it won't exist in PCArray as PCArray would be in sync with PMap */ if val, ok := data.pMap[char]; ok { return val, -1 } /*The given character is not existing in the PCArray. Now searching for the position to insert the character */ if data.lLetter < char { //Character has to be inserted at the end return -1, -1 } if len(data.pCArray) == 0 || char < data.pCArray[0] { return -1, -3 } var length = len(data.pCArray) for i := 0; i < length-1; i++ { //Character has to be inserted in the sorted manner if char > data.pCArray[i] && char < data.pCArray[i+1] { return -1, i + 1 } } //Error state return -1, -2 } /*AddData adds a character to the ODSAData It returns true if character addition was sucessfull */ func (data *ODSAData) AddData(char byte) bool { pos, iPos := data.findPosition(char) //Error state if iPos == -2 { return false } //Character not present in the Array. So adding it to the ODSA data if pos == -1 && iPos == -1 { data.pCArray = append(data.pCArray, char) //Updating the PCArray data.pIArray = append(data.pIArray, data.lPosition+1) //Updating the PIArray with the index of the entry data.pMap[char] = len(data.pCArray) - 1 ///Syncing up the PMap w.r.t. the arrays return true } /*Character is present in the array. So put the offset of 1 to all the characters after it as the array is in sorted state */ if pos != -1 { data.updatePos(pos+1, 1, false, true) //Updating the indices if data.lLetter > char { //Recording the noise information data.nCArray = append(data.nCArray, char) data.nIArray = append(data.nIArray, data.lPosition+1) } return true } //Inserting the character at the begining of the position array if iPos == -3 { data.pCArray = append([]byte{char}, data.pCArray[:]...) data.pIArray = append([]int{0}, data.pIArray[:]...) data.pMap[char] = 0 data.updatePos(1, 1, true, true) //Recording the noise information data.nCArray = append(data.nCArray, char) data.nIArray = append(data.nIArray, data.lPosition+1) return true } //appending in the given insert position`` data.pCArray = append(data.pCArray[0:iPos], append([]byte{char}, data.pCArray[iPos:]...)...) //Updating the PIArray with insert and updated indices that comes after the same data.pIArray = append(data.pIArray[0:iPos], append([]int{data.pIArray[iPos]}, data.pIArray[iPos:]...)...) //Updating the trailing indicies with new value after the addition of new element data.updatePos(iPos+1, 1, true, true) //Updating the map to sync up the data with the arrays data.pMap[char] = iPos //Recording the noise information data.nCArray = append(data.nCArray, char) data.nIArray = append(data.nIArray, data.lPosition+1) return true } /*GetData returns the original data that was transformed and compressed */ func (data *ODSAData) GetData() []byte { //Initializing the sorted variable sorted := []byte{} length := len(data.pCArray) - 1 /*Building the sorted string by picking the psoiton index array and position index array */ for i := 0; i < length; i++ { for j := 0; j < (data.pIArray[i+1] - data.pIArray[i]); j++ { sorted = append(sorted, data.pCArray[i]) } } //Handling the last character in the psotion array with lastPosition for j := 0; j < (data.lPosition + 1 - data.pIArray[length]); j++ { sorted = append(sorted, data.pCArray[length]) } //Rebuilding the string from the noise fingerprint length = len(data.nCArray) - 1 pLen := len(sorted) for i := length; i >= 0; i-- { /*Repositioning the noise character to its original postion from the sorted position */ splitPos := data.pIArray[data.pMap[data.nCArray[i]]] //Note the nIArray[i] will always be greater than splitPos sorted = append(sorted[0:splitPos], sorted[splitPos+1:]...) if data.nIArray[i] < pLen { sorted = append(sorted[0:data.nIArray[i]], append([]byte{data.nCArray[i]}, sorted[data.nIArray[i]:]...)...) } else { sorted = append(sorted, data.nCArray[i]) //appending to the end if position is last } /*/Although the positions pIArray[i] gets updated it won't affect the remaining alogirthm as the positions past pIArray[i] are not referenced again */ data.updatePos(data.pMap[data.nCArray[i]]+1, -1, false, true) } return sorted } //NewODSAData is the constructor function for ODSAData func NewODSAData() Data { data := new(ODSAData) data.lPosition = 0 data.pMap = make(map[byte]int) return data } /*updatePos updates the position of the data. The arguments startValue denotes the position from which the updation has to start from. Increament denotes the amount with which the data has to be updated. mMap and pIArray boolean variables indicate whether the map/pIArray of the data has to be updated */ func (data *ODSAData) updatePos(startValue, increament int, pMap, pIArray bool) { length := len(data.pIArray) for i := startValue; i < length; i++ { //Updating the map/array witn the increament if pIArray { data.pIArray[i] += increament } if pMap { data.pMap[data.pCArray[i]] += increament } } }
utils/utils.go
0.575827
0.543469
utils.go
starcoder
package go3mf import ( "errors" "github.com/qmuntal/go3mf/geo" ) // SliceResolution defines the resolutions for a slice. type SliceResolution uint8 const ( // ResolutionFull defines a full resolution slice. ResolutionFull SliceResolution = iota // ResolutionLow defines a low resolution slice. ResolutionLow ) func (c SliceResolution) String() string { return map[SliceResolution]string{ ResolutionFull: "fullres", ResolutionLow: "lowres", }[c] } // IsValidForSlices checks if the component resource and all its child are valid to be used with slices. func (c *ComponentsResource) IsValidForSlices(transform geo.Matrix) bool { if len(c.Components) == 0 { return true } for _, comp := range c.Components { if !comp.Object.IsValidForSlices(transform.Mul(comp.Transform)) { return false } } return true } // IsValidForSlices checks if the build object is valid to be used with slices. func (b *BuildItem) IsValidForSlices() bool { return b.Object.IsValidForSlices(b.Transform) } // IsValidForSlices checks if the mesh resource are valid for slices. func (c *MeshResource) IsValidForSlices(t geo.Matrix) bool { return c.SliceStackID == 0 || t[2] == 0 && t[6] == 0 && t[8] == 0 && t[9] == 0 && t[10] == 1 } // SliceRef reference to a slice stack. type SliceRef struct { SliceStackID uint32 Path string } // SliceStack defines an stack of slices. // It can either contain Slices or a Refs. type SliceStack struct { BottomZ float32 Slices []*geo.Slice Refs []SliceRef } // AddSlice adds an slice to the stack and returns its index. func (s *SliceStack) AddSlice(slice *geo.Slice) (int, error) { if slice.TopZ < s.BottomZ || (len(s.Slices) != 0 && slice.TopZ < s.Slices[0].TopZ) { return 0, errors.New("the z-coordinates of slices within a slicestack are not increasing") } s.Slices = append(s.Slices, slice) return len(s.Slices) - 1, nil } // SliceStackResource defines a slice stack resource. // It can either contain a SliceStack or a Refs slice. type SliceStackResource struct { Stack SliceStack ID uint32 ModelPath string } // Identify returns the unique ID of the resource. func (s *SliceStackResource) Identify() (string, uint32) { return s.ModelPath, s.ID }
slices.go
0.800887
0.476945
slices.go
starcoder
package diff // ConvertTypes enables values that are convertible to the target type to be converted when patching func ConvertCompatibleTypes() func(d *Differ) error { return func(d *Differ) error { d.ConvertCompatibleTypes = true return nil } } // FlattenEmbeddedStructs determines whether fields of embedded structs should behave as if they are directly under the parent func FlattenEmbeddedStructs() func(d *Differ) error { return func(d *Differ) error { d.FlattenEmbeddedStructs = true return nil } } // SliceOrdering determines whether the ordering of items in a slice results in a change func SliceOrdering(enabled bool) func(d *Differ) error { return func(d *Differ) error { d.SliceOrdering = enabled return nil } } // TagName sets the tag name to use when getting field names and options func TagName(tag string) func(d *Differ) error { return func(d *Differ) error { d.TagName = tag return nil } } // DisableStructValues disables populating a separate change for each item in a struct, // where the struct is being compared to a nil value func DisableStructValues() func(d *Differ) error { return func(d *Differ) error { d.DisableStructValues = true return nil } } // CustomValueDiffers allows you to register custom differs for specific types func CustomValueDiffers(vd ...ValueDiffer) func(d *Differ) error { return func(d *Differ) error { d.customValueDiffers = append(d.customValueDiffers, vd...) for k := range d.customValueDiffers { d.customValueDiffers[k].InsertParentDiffer(d.diff) } return nil } } // AllowTypeMismatch changed behaviour to report value as "updated" when its type has changed instead of error func AllowTypeMismatch(enabled bool) func(d *Differ) error { return func(d *Differ) error { d.AllowTypeMismatch = enabled return nil } } //StructMapKeySupport - Changelog paths do not provided structured object values for maps that contain complex //keys (such as other structs). You must enable this support via an option and it then uses msgpack to encode //path elements that are structs. If you don't have this on, and try to patch, your apply will fail for that //element. func StructMapKeySupport() func(d *Differ) error { return func(d *Differ) error { d.StructMapKeys = true return nil } } //DiscardComplexOrigin - by default, we are now keeping the complex struct associated with a create entry. //This allows us to fix the merge to new object issue of not having enough change log details when allocating //new objects. This however is a trade off of memory size and complexity vs correctness which is often only //necessary when embedding structs in slices and arrays. It memory constrained environments, it may be desirable //to turn this feature off however from a computational perspective, keeping the complex origin is actually quite //cheap so, make sure you're extremely clear on the pitfalls of turning this off prior to doing so. func DiscardComplexOrigin() func(d *Differ) error { return func(d *Differ) error { d.DiscardParent = true return nil } } // Filter allows you to determine which fields the differ descends into func Filter(f FilterFunc) func(d *Differ) error { return func(d *Differ) error { d.Filter = f return nil } }
vendor/github.com/r3labs/diff/v2/options.go
0.83508
0.477981
options.go
starcoder
package spriter import ( "math" ) func ternary(c bool, a float64, b float64) float64 { if c { return a } else { return b } } func signum(f float64) float64 { return ternary(f == 0.0 || math.IsNaN(f), f, math.Copysign(1.0, f)) } func angleDifference(a float64, b float64) float64 { return math.Min((2*math.Pi)-math.Abs(a-b), math.Abs(a-b)) } // From https://github.com/Trixt0r/spriter func solveCubic(a float64, b float64, c float64, d float64) float64 { if a == 0 { return solveQuadratic(b, c, d) } if d == 0 { return 0 } b /= a c /= a d /= a squaredB := b * b q := (3.0*c - squaredB) / 9.0 r := (-27.0*d + b*(9.0*c-2.0*squaredB)) / 54.0 discriminant := (q * q * q) + (r * r) term1 := b / 3.0 if discriminant > 0 { sqrtDisc := math.Sqrt(discriminant) s := r + sqrtDisc s = ternary(s < 0, -math.Cbrt(-s), math.Cbrt(s)) t := r - sqrtDisc t = ternary(t < 0, -math.Cbrt(-t), math.Cbrt(t)) result := -term1 + s + t if result >= 0 && result <= 1 { return result } } else if discriminant == 0 { r13 := ternary(r < 0, -math.Cbrt(-r), math.Cbrt(r)) result := -term1 + 2.0*r13 if result >= 0 && result <= 1 { return result } result = -(r13 + term1) if result >= 0 && result <= 1 { return result } } else { q = -q dum1 := q * q * q dum1 = math.Acos(r / math.Sqrt(dum1)) r13 := 2.0 * math.Sqrt(q) result := -term1 + r13*math.Cos(dum1/3.0) if result >= 0 && result <= 1 { return result } result = -term1 + r13*math.Cos((dum1+2.0*math.Pi)/3.0) if result >= 0 && result <= 1 { return result } result = -term1 + r13*math.Cos((dum1+4.0*math.Pi)/3.0) if result >= 0 && result <= 1 { return result } } return -1 } func solveQuadratic(a float64, b float64, c float64) float64 { squaredB := b * b twoA := 2 * a fourAC := 4 * a * c squareRoot := math.Sqrt(squaredB - fourAC) result := (-b + squareRoot) / twoA if result >= 0 && result <= 1 { return result } result = (-b - squareRoot) / twoA if result >= 0 && result <= 1 { return result } return -1 } func Linear(a float64, b float64, t float64) float64 { return (b-a)*t + a } func InverseLinear(a float64, b float64, x float64) float64 { return (x - a) / (b - a) } func Quadratic(a float64, b float64, c float64, t float64) float64 { return Linear(Linear(a, b, t), Linear(b, c, t), t) } func Cubic(a float64, b float64, c float64, d float64, t float64) float64 { return Linear(Quadratic(a, b, c, t), Quadratic(b, c, d, t), t) } func Quartic(a float64, b float64, c float64, d float64, e float64, t float64) float64 { return Linear(Cubic(a, b, c, d, t), Cubic(b, c, d, e, t), t) } func Quintic(a float64, b float64, c float64, d float64, e float64, f float64, t float64) float64 { return Linear(Quartic(a, b, c, d, e, t), Quartic(b, c, d, e, f, t), t) } func LinearAngle(a float64, b float64, t float64) float64 { return a + angleDifference(b, a)*t } func QuadraticAngle(a float64, b float64, c float64, t float64) float64 { return LinearAngle(LinearAngle(a, b, t), LinearAngle(b, c, t), t) } func CubicAngle(a float64, b float64, c float64, d float64, t float64) float64 { return LinearAngle(QuadraticAngle(a, b, c, t), QuadraticAngle(b, c, d, t), t) } func QuarticAngle(a float64, b float64, c float64, d float64, e float64, t float64) float64 { return LinearAngle(CubicAngle(a, b, c, d, t), CubicAngle(b, c, d, e, t), t) } func QuinticAngle(a float64, b float64, c float64, d float64, e float64, f float64, t float64) float64 { return LinearAngle(QuarticAngle(a, b, c, d, e, t), QuarticAngle(b, c, d, e, f, t), t) } func Bezier(t float64, x1 float64, x2 float64, x3 float64, x4 float64) float64 { temp := t * t bezier0 := -temp*t + 3*temp - 3*t + 1 bezier1 := 3*t*temp - 6*temp + 3*t bezier2 := -3*temp*t + 3*temp bezier3 := t * t * t return bezier0*x1 + bezier1*x2 + bezier2*x3 + bezier3*x4 }
math.go
0.845656
0.675855
math.go
starcoder
package maths import ( "fmt" "math" "github.com/wdevore/RangerGo/api" ) type vector struct { x, y float64 } // NewVector constructs a new IVector func NewVector() api.IVector { o := new(vector) return o } // NewVectorUsing constructs a new IVector using components func NewVectorUsing(x, y float64) api.IVector { o := new(vector) o.x = x o.y = y return o } func (v *vector) Components() (x, y float64) { return v.x, v.y } func (v *vector) X() float64 { return v.x } func (v *vector) Y() float64 { return v.y } func (v *vector) SetByComp(x, y float64) { v.x = x v.y = y } func (v *vector) SetByPoint(ip api.IPoint) { v.x = ip.X() v.y = ip.Y() } func (v *vector) SetByAngle(radians float64) { v.x = math.Cos(radians) v.y = math.Sin(radians) } func (v *vector) SetByVector(ip api.IVector) { v.x = ip.X() v.y = ip.Y() } func (v *vector) Length() float64 { return math.Sqrt(v.x*v.x + v.y*v.y) } func (v *vector) LengthSqr() float64 { return v.x*v.x + v.y*v.y } func (v *vector) Add(x, y float64) { v.x += x v.y += y } func (v *vector) Sub(x, y float64) { v.x -= x v.y -= y } func (v *vector) AddV(iv api.IVector) { v.x += iv.X() v.y += iv.Y() } func (v *vector) SubV(iv api.IVector) { v.x -= iv.X() v.y -= iv.Y() } // Add performs: out = v1 + v2 func Add(v1, v2, out api.IVector) { out.SetByComp(v1.X()+v2.X(), v1.Y()+v2.Y()) } // Sub performs: out = v1 - v2 func Sub(v1, v2, out api.IVector) { out.SetByComp(v1.X()-v2.X(), v1.Y()-v2.Y()) } func (v *vector) Scale(s float64) { v.x = v.x * s v.y = v.y * s } // ScaleBy performs: out = v * s func ScaleBy(v api.IVector, s float64, out api.IVector) { out.SetByComp(v.X()*s, v.Y()*s) } func (v *vector) Div(d float64) { v.x = v.x / d v.y = v.y / d } var tmp = NewVector() // Distance between two vectors func Distance(v1, v2 api.IVector) float64 { Sub(v1, v2, tmp) return tmp.Length() } func (v *vector) AngleX(vo api.IVector) float64 { return math.Atan2(vo.Y(), vo.X()) } func (v *vector) Normalize() { len := v.Length() if len != 0.0 { v.Div(len) } } func (v *vector) SetDirection(radians float64) { v.SetByComp(math.Cos(radians), math.Sin(radians)) } // Dot computes the dot-product between the vectors func Dot(v1, v2 api.IVector) float64 { return v1.X()*v2.X() + v1.Y()*v2.Y() } // Cross computes the cross-product of two vectors func Cross(v1, v2 api.IVector) float64 { return v1.X()*v2.Y() - v1.Y()*v2.X() } func (v *vector) CrossCW() { v.SetByComp(v.Y(), -v.X()) } func (v *vector) CrossCCW() { v.SetByComp(-v.Y(), v.X()) } var tmp2 = NewVector() // Angle computes the angle in radians between two vector directions func Angle(v1, v2 api.IVector) float64 { tmp.SetByVector(v1) tmp2.SetByVector(v2) tmp.Normalize() // a2 tmp2.Normalize() // b2 angle := math.Atan2(Cross(tmp, tmp2), Dot(tmp, tmp2)) if math.Abs(angle) < Epsilon { return 0.0 } return angle } func (v vector) String() string { return fmt.Sprintf("<%0.3f,%0.3f>", v.x, v.y) }
engine/maths/vector.go
0.830663
0.516656
vector.go
starcoder
package billsutil import ( "sort" ) /* These are "mapping" functions common to collections classes in other languages I need t think about how to make these more elegant in the absence of generics in Go See: https://gobyexample.com/collection-functions for good examples */ // MapInt returns a new slice containing the results of applying the function f to each int in the original slice. func MapInt(vs []int, f func(int) int) []int { vsm := make([]int, len(vs)) for i, v := range vs { vsm[i] = f(v) } return vsm } // MapChar returns a new slice containing the results of applying the function f to each string in the original slice. func MapChar(vs string, f func(rune) rune) string { str := "" for _, char := range vs { str += string(f(char)) } return str } // ReduceInt returns the result of a pairwise application of the function through the slice // The input slice must be at least length 2 func ReduceInt(vs []int, f func(int, int) int) int { if len(vs) < 1 { panic("Slice must be at least 1 element long") } if len(vs) == 1 { return vs[0] // This may be wrong! It's up to the caller to decide! } accum := vs[0] for i := 1; i < len(vs); i++ { accum = f(accum, vs[i]) } return accum } // AllInt returns true if all of the ints in the slice satisfy the predicate f. // The slice must be non empty func AllInt(vs []int, f func(int) bool) bool { for _, v := range vs { if !f(v) { return false } } return true } // FindInt returns a slice of all positions of val in the slice vs. If there are no occurrences, an empty slice is returned. func FindInt(vs []int, val int) []int { var result = []int{} for i, n := range vs { if n == val { result = append(result, i) } } return result } // Reverse reverses any sortable collection and is very efficient. // Note that it reverse in place, so it modifies the slice passed in // This is the implementation of the stringutil.Reverse example at https://github.com/golang/example func Reverse(s sort.Interface) { len := s.Len() for front, back := 0, len-1; front < len/2; front, back = front+1, back-1 { s.Swap(front, back) } } // RuneSlice attaches the methods of sort.Interface to []rune, for sorting and reversing type RuneSlice []rune func (p RuneSlice) Len() int { return len(p) } func (p RuneSlice) Less(i, j int) bool { return p[i] < p[j] } func (p RuneSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // ReverseStr is a convenience method for reversing strings func ReverseStr(str string) string { r := RuneSlice([]rune(str)) Reverse(r) return string(r) } // ReverseInt is a convenience method for reversing Int slices // It makes a copy of the input to avoid mutating it. func ReverseInt(is []int) []int { js := sort.IntSlice(append(is[:0:0], is...)) Reverse(js) return js }
billsutil/sliceutil.go
0.746046
0.497498
sliceutil.go
starcoder
package ast import ( "github.com/magic003/liza/token" ) // Type is the base type for all type tree node. type Type interface { Node typeNode() } // BasicType node represents a basic type provided by the language. type BasicType struct { Ident *token.Token // identifier for a basic type } // Pos implementation for Node. func (basic *BasicType) Pos() token.Position { return basic.Ident.Position } // End implementation for Node. func (basic *BasicType) End() token.Position { return token.Position{ Filename: basic.Ident.Position.Filename, Line: basic.Ident.Position.Line, Column: basic.Ident.Position.Column + len(basic.Ident.Content), } } func (basic *BasicType) typeNode() {} // SelectorType node represents a type defined in a package. type SelectorType struct { Package *token.Token // package identifier Sel *token.Token // type selector } // Pos implementation for Node. func (selector *SelectorType) Pos() token.Position { return selector.Package.Position } // End implementation for Node. func (selector *SelectorType) End() token.Position { return token.Position{ Filename: selector.Sel.Position.Filename, Line: selector.Sel.Position.Line, Column: selector.Sel.Position.Column + len(selector.Sel.Content), } } func (selector *SelectorType) typeNode() {} // ArrayType node represents an array type. type ArrayType struct { Lbrack token.Position // position of "[" Rbrack token.Position // position of "]" Elt Type // element type } // Pos implementation for Node. func (array *ArrayType) Pos() token.Position { return array.Lbrack } // End implementation for Node. func (array *ArrayType) End() token.Position { return array.Elt.End() } func (array *ArrayType) typeNode() {} // MapType node represents a map type. type MapType struct { Lbrace token.Position // position of "{" Key Type // key type Value Type // value type Rbrace token.Position // position of "}" } // Pos implementation for Node. func (mapType *MapType) Pos() token.Position { return mapType.Lbrace } // End implementation for Node. func (mapType *MapType) End() token.Position { return token.Position{ Filename: mapType.Rbrace.Filename, Line: mapType.Rbrace.Line, Column: mapType.Rbrace.Column + 1, } } func (mapType *MapType) typeNode() {} // TupleType node represents a tuple type. type TupleType struct { Lparen token.Position // position of "(" Elts []Type // element types Rparen token.Position // position of ")" } // Pos implementation for Node. func (tuple *TupleType) Pos() token.Position { return tuple.Lparen } // End implementation for Node. func (tuple *TupleType) End() token.Position { return token.Position{ Filename: tuple.Rparen.Filename, Line: tuple.Rparen.Line, Column: tuple.Rparen.Column + 1, } } func (tuple *TupleType) typeNode() {}
ast/type.go
0.798305
0.514339
type.go
starcoder
package man import ( . "github.com/gocircuit/circuit/gocircuit.org/render" ) func RenderElementDnsPage() string { return RenderHtml("Circuit DNS element", Render(dnsBody, nil)) } const dnsBody = ` <h2>Example: Make a DNS server element</h2> <p>Circuit allows you to create and dynamically configure one or more DNS server elements on any circuit server. <p>As before, pick an available circuit server, say <code>X88550014d4c82e4d</code>. Create a new DNS server element, like so <pre> circuit mkdns /X88550014d4c82e4d/mydns </pre> <p>This will start a new DNS server on the host of the given circuit server, binding it to an available port. Alternatively, you can supply an IP address argument specifying the bind address, as in <pre> circuit mkdns /X88550014d4c82e4d/mydns 127.0.0.1:7711 </pre> <p>Either way, you can always retrieve the address on which the DNS server is listening by peeking into the corresponding circuit element: <pre> circuit peek /X88550014d4c82e4d/mydns </pre> <p>This command will produce an output similar to this <pre> { "Address": "127.0.0.1:7711", "Records": {} } </pre> <p>Once the DNS server element has been created, you can add resource records to it, one at a time, using <pre> circuit set /X88550014d4c82e4d/mydns "miek.nl. 3600 IN MX 10 mx.miek.nl." </pre> <p>Resource records use the canonical syntax, described in various RFCs. You can find a list of such RFCs as well as examples in the DNS Go library that underlies our implementation: <code>github.com/miekg/dns/dns.go</code> <p>All records, associated with a given name can be removed with a single command: <pre> circuit unset /X88550014d4c82e4d/mydns miek.nl. </pre> <p>The current set of active records can be retrieved by peeking into the element: <pre> circuit peek /X88550014d4c82e4d/mydns </pre> <p>Assuming that a name has multiple records associated with it, peeking would produce an output similar to this one: <pre> { "Address": "127.0.0.1:7711", "Records": { "miek.nl.": [ "miek.nl.\t3600\tIN\tMX\t10 mx.miek.nl.", "miek.nl.\t3600\tIN\tMX\t20 mx2.miek.nl." ] } } </pre> `
gocircuit.org/man/element-dns.go
0.632049
0.47457
element-dns.go
starcoder
package histogram import ( "image" "math" "runtime" "github.com/AlessandroPomponio/hsv/conversion" ) // With64Bins returns a color histogram with 64 bins for the input image. // The values in the bins will represent the percentage of pixels mapped // to a certain Hue, Saturation and Value level. The output can be considered // as two 32 bin histograms, where the second batch of 32 bins represents // colors with Value above 50. // It is VERY IMPORTANT TO NOTICE that the percentages are rounded, so the // sum of all percentages may not be equal to 100. // The Hue will be mapped to 8 levels, indexes {0,4,8,12,16,20,24,28}. // The Saturation will be mapped to 4 levels, indexes H_level + {0,1,2,3}. // The Value will be mapped to 2 levels, indexes H_level + S_level + {0,32}. func With64Bins(img image.Image, roundType int) []float64 { bins := make([]float64, 64) xBound := img.Bounds().Dx() yBound := img.Bounds().Dy() for x := 0; x < xBound; x++ { for y := 0; y < yBound; y++ { h, s, v := conversion.RGBAToHSV(img.At(x, y).RGBA()) // hueBin in [0,7]. // Try to map hue in equally-sized // levels by dividing it for 360/7. hueBin := int(h / 51.42857142857143) // saturationBin in [0,3] // Try to map saturation in equally-sized // levels by dividing it for 100/3. saturationBin := int(s / 33.33333333333333) // valueBin in [0,1] // Try to map value in equally-sized // levels by dividing it for a value // that's just above 50. valueBin := int(v / 50.0000000001) //valueBin = 0 index := 4*hueBin + saturationBin + 32*valueBin bins[index]++ } } return normalize64BinsHistogram(roundType, xBound, yBound, bins) } // With64BinsConcurrent returns a color histogram with 64 bins for the input image. // This concurrent version will check whether the image is taller or wider and iterate // over the biggest dimension of the two, using use one goroutine per column/row. // The values in the bins will represent the percentage of pixels mapped to a certain // Hue, Saturation and Value level. The output can be considered as two 32 bin histograms, // where the second batch of 32 bins represents colors with Value above 50. // It is VERY IMPORTANT TO NOTICE that the percentages are rounded, so the sum of all // percentages may not be equal to 100. // The Hue will be mapped to 8 levels, indexes {0,4,8,12,16,20,24,28}. // The Saturation will be mapped to 4 levels, indexes H_level + {0,1,2,3}. // The Value will be mapped to 2 levels, indexes H_level + S_level + {0,32}. func With64BinsConcurrent(img image.Image, roundType int) []float64 { bins := make([]float64, 64) cpuAmt := runtime.NumCPU() binChannel := make(chan []float64, cpuAmt/2) // Split image into NumCPU sub-images to help speed up the computation. rectangles := splitInto(cpuAmt, img.Bounds()) for _, rectangle := range rectangles { go calculate64BinsForRectangle(rectangle, img, binChannel) } // Gather the results from all goroutines and sum them. for i := 0; i < len(rectangles); i++ { currentBins := <-binChannel for i := 0; i < 64; i++ { bins[i] += currentBins[i] } } return normalize64BinsHistogram(roundType, img.Bounds().Dx(), img.Bounds().Dy(), bins) } func calculate64BinsForRectangle(rectangle image.Rectangle, img image.Image, outputChan chan []float64) { bins := make([]float64, 64) for x := rectangle.Min.X; x <= rectangle.Max.X; x++ { for y := rectangle.Min.Y; y <= rectangle.Max.Y; y++ { h, s, v := conversion.RGBAToHSV(img.At(x, y).RGBA()) // hueBin in [0,7]. // Try to map hue in equally-sized // levels by dividing it for 360/7. hueBin := int(h / 51.42857142857143) // saturationBin in [0,3] // Try to map saturation in equally-sized // levels by dividing it for 100/3. saturationBin := int(s / 33.333333333) // valueBin in [0,1] // Try to map value in equally-sized // levels by dividing it for a value // that's just above 50. valueBin := int(v / 50.0000000000001) index := 4*hueBin + saturationBin + 32*valueBin bins[index]++ } } outputChan <- bins } // normalize64BinsHistogram normalizes 64-bin histograms by the amount of pixels in the image. // It also makes sure that the sum of the percentages in bins[i] and bins[i+32] is equal to // the rounded value of the percentage of their sum. // bins[i] + bins[i+32] = round((bins[i] + bins[i+32]) * 100 / pixels) func normalize64BinsHistogram(roundType int, width, height int, bins []float64) []float64 { pixels := float64(width * height) var roundFunction func(x float64) float64 switch roundType { case RoundClosest: roundFunction = math.Round case RoundUp: roundFunction = math.Ceil case RoundDown: roundFunction = math.Trunc default: return nil } for i := 0; i < 32; i++ { totalPercentage := roundFunction((bins[i] + bins[i+32]) * 100 / pixels) firstHalfPercentage := roundFunction(bins[i] * 100 / pixels) bins[i] = firstHalfPercentage bins[i+32] = totalPercentage - firstHalfPercentage } return bins }
histogram/64_bins.go
0.857723
0.593639
64_bins.go
starcoder
package day15 import ( "math" "github.com/mjm/advent-of-code-2019/pkg/point" ) // PathFinder finds paths between a start and goal point on a map. type PathFinder struct { canvas *Canvas start point.Point2D goal point.Point2D fs map[point.Point2D]int gs map[point.Point2D]int } // NewPathFinder creates a new path finder with a given map and goal. func NewPathFinder(canvas *Canvas, goal point.Point2D) *PathFinder { var start point.Point2D gs := make(map[point.Point2D]int) gs[start] = 0 fs := make(map[point.Point2D]int) pf := &PathFinder{ canvas: canvas, start: start, goal: goal, fs: fs, gs: gs, } fs[start] = pf.h(start) return pf } // ShortestPath finds the shortest path from (0, 0) to the path finder's // goal. Returns the list of points that form the path, starting from the // goal and ending with the start point, including both. func (pf *PathFinder) ShortestPath() []point.Point2D { open := make(map[point.Point2D]interface{}) open[pf.start] = struct{}{} prev := make(map[point.Point2D]point.Point2D) for len(open) > 0 { var current *point.Point2D for p := range open { if current == nil || pf.f(p) < pf.f(*current) { current = &p } } if *current == pf.goal { n := *current path := []point.Point2D{n} for { var ok bool n, ok = prev[n] if !ok { return path } path = append(path, n) } } delete(open, *current) for _, n := range pf.neighbors(*current) { if g := pf.g(*current) + 1; g < pf.g(n) { prev[n] = *current pf.gs[n] = g pf.fs[n] = g + pf.h(n) open[n] = struct{}{} } } } return nil } func (pf *PathFinder) neighbors(p point.Point2D) []point.Point2D { var ps []point.Point2D for _, dir := range []Direction{North, South, West, East} { if p := dir.offset(p); pf.canvas.At(p) != int(TileWall) { ps = append(ps, p) } } return ps } func (pf *PathFinder) f(p point.Point2D) int { if f, ok := pf.fs[p]; ok { return f } return math.MaxInt64 } func (pf *PathFinder) g(p point.Point2D) int { if g, ok := pf.gs[p]; ok { return g } return math.MaxInt64 } func (pf *PathFinder) h(p point.Point2D) int { return abs(p.X-pf.goal.X) + abs(p.Y-pf.goal.Y) } func abs(a int) int { if a < 0 { return -a } return a }
day15/path_finder.go
0.733261
0.5769
path_finder.go
starcoder
package day03 import ( "fmt" "math" "strconv" "strings" ) type direction rune const ( up direction = 'U' right direction = 'R' down direction = 'D' left direction = 'L' ) type segment struct { direction direction length int } type wire []segment type port struct { x, y int } var centralPort = port{ x: 0, y: 0, } type circuit struct { ports1 map[port]int ports2 map[port]int } type distance uint type signalDelay uint // Day holds the data needed to solve part one and part two type Day struct { wire1 wire wire2 wire } // NewDay returns a new Day that solves part one and two for the given input func NewDay(input string) (*Day, error) { paths := strings.Split(input, "\n") if len(paths) != 2 { return nil, fmt.Errorf("invalid number of wire paths %d", len(paths)) } path1, err := parseWire(paths[0]) if err != nil { return nil, fmt.Errorf("invalid wire path %s: %w", paths[0], err) } path2, err := parseWire(paths[1]) if err != nil { return nil, fmt.Errorf("invalid wire path %s: %w", paths[1], err) } return &Day{ wire1: path1, wire2: path2, }, nil } // SolvePartOne solves part one func (d Day) SolvePartOne() (string, error) { circuit := circuit{ ports1: getPortsFromWire(d.wire1), ports2: getPortsFromWire(d.wire2), } distance, err := circuit.findMinimumDistance() if err != nil { return "", err } return fmt.Sprintf("%d", distance), nil } // SolvePartTwo solves part two func (d Day) SolvePartTwo() (string, error) { circuit := circuit{ ports1: getPortsFromWire(d.wire1), ports2: getPortsFromWire(d.wire2), } signalDelay, err := circuit.findMinimumSignalDelay() if err != nil { return "", err } return fmt.Sprintf("%d", signalDelay), nil } func parseWire(wireString string) (wire, error) { segmentsString := strings.Split(wireString, ",") wire := make(wire, 0, len(segmentsString)) for _, segmentString := range segmentsString { segment, err := parseSegment(segmentString) if err != nil { return nil, fmt.Errorf("invalid segment %s: %w", segmentString, err) } wire = append(wire, segment) } return wire, nil } func parseSegment(segmentString string) (segment, error) { if len(segmentString) < 2 { return segment{}, fmt.Errorf("invalid segment %s", segmentString) } direction := direction(segmentString[0]) switch direction { case up, left, right, down: default: return segment{}, fmt.Errorf("invalid direction %c", segmentString[0]) } length, err := strconv.Atoi(segmentString[1:]) if err != nil { return segment{}, fmt.Errorf("invalid length %s: %w", segmentString[1:], err) } return segment{ direction: direction, length: length, }, nil } func getPortsFromWire(wire wire) map[port]int { ports := make(map[port]int, len(wire)) currentPort := centralPort steps := 1 for _, segment := range wire { for i := 0; i < segment.length; i++ { currentPort = currentPort.nextPort(segment.direction) if _, ok := ports[currentPort]; !ok { ports[currentPort] = steps } steps++ } } return ports } func (p port) nextPort(direction direction) port { switch direction { case up: return port{x: p.x, y: p.y + 1} case down: return port{x: p.x, y: p.y - 1} case right: return port{x: p.x + 1, y: p.y} case left: return port{x: p.x - 1, y: p.y} } return p } func (c circuit) findMinimumDistance() (distance, error) { costFunction := func(port port) uint { return uint(port.distanceToCentralPort()) } res, err := c.minimizeCostFunction(costFunction) return distance(res), err } func (c circuit) findMinimumSignalDelay() (signalDelay, error) { costFunction := func(port port) uint { return uint(c.signalDelay(port)) } res, err := c.minimizeCostFunction(costFunction) return signalDelay(res), err } type costFunction func(port port) uint func (c circuit) minimizeCostFunction(costFunction costFunction) (uint, error) { intersections := c.findIntersections() if len(intersections) == 0 { return 0, fmt.Errorf("there are no intersections between the two wires") } minimumCost := costFunction(intersections[0]) for _, intersection := range intersections { currentCost := costFunction(intersection) if currentCost < minimumCost { minimumCost = currentCost } } return minimumCost, nil } func (c circuit) findIntersections() []port { var intersections []port for port := range c.ports1 { if _, ok := c.ports2[port]; ok { intersections = append(intersections, port) } } return intersections } func (p port) distanceToCentralPort() distance { return distance(math.Abs(float64(p.x)) + math.Abs(float64(p.y))) } func (c circuit) signalDelay(port port) signalDelay { return signalDelay(c.ports1[port] + c.ports2[port]) }
day03/day03.go
0.775009
0.410166
day03.go
starcoder
package Test var clipPlanes = []clipPlane{ {VectorW{1, 0, 0, 1}, VectorW{-1, 0, 0, 1}}, {VectorW{-1, 0, 0, 1}, VectorW{1, 0, 0, 1}}, {VectorW{0, 1, 0, 1}, VectorW{0, -1, 0, 1}}, {VectorW{0, -1, 0, 1}, VectorW{0, 1, 0, 1}}, {VectorW{0, 0, 1, 1}, VectorW{0, 0, -1, 1}}, {VectorW{0, 0, -1, 1}, VectorW{0, 0, 1, 1}}, } type clipPlane struct { P, N VectorW } func (p clipPlane) pointInFront(v VectorW) bool { return v.Sub(p.P).Dot(p.N) > 0 } func (p clipPlane) intersectSegment(v0, v1 VectorW) VectorW { u := v1.Sub(v0) w := v0.Sub(p.P) d := p.N.Dot(u) n := -p.N.Dot(w) return v0.Add(u.MulScalar(n / d)) } func sutherlandHodgman(points []VectorW, planes []clipPlane) []VectorW { output := points for _, plane := range planes { input := output output = nil if len(input) == 0 { return nil } s := input[len(input)-1] for _, e := range input { if plane.pointInFront(e) { if !plane.pointInFront(s) { x := plane.intersectSegment(s, e) output = append(output, x) } output = append(output, e) } else if plane.pointInFront(s) { x := plane.intersectSegment(s, e) output = append(output, x) } s = e } } return output } func ClipTriangle(t *Triangle) []*Triangle { w1 := t.V1.Output w2 := t.V2.Output w3 := t.V3.Output p1 := w1.Vector() p2 := w2.Vector() p3 := w3.Vector() points := []VectorW{w1, w2, w3} newPoints := sutherlandHodgman(points, clipPlanes) var result []*Triangle for i := 2; i < len(newPoints); i++ { b1 := Barycentric(p1, p2, p3, newPoints[0].Vector()) b2 := Barycentric(p1, p2, p3, newPoints[i-1].Vector()) b3 := Barycentric(p1, p2, p3, newPoints[i].Vector()) v1 := InterpolateVertexes(t.V1, t.V2, t.V3, b1) v2 := InterpolateVertexes(t.V1, t.V2, t.V3, b2) v3 := InterpolateVertexes(t.V1, t.V2, t.V3, b3) result = append(result, NewTriangle(v1, v2, v3)) } return result } func ClipLine(l *Line) *Line { // TODO: interpolate vertex attributes when clipped w1 := l.V1.Output w2 := l.V2.Output for _, plane := range clipPlanes { f1 := plane.pointInFront(w1) f2 := plane.pointInFront(w2) if f1 && f2 { continue } else if f1 { w2 = plane.intersectSegment(w1, w2) } else if f2 { w1 = plane.intersectSegment(w2, w1) } else { return nil } } v1 := l.V1 v2 := l.V2 v1.Output = w1 v2.Output = w2 return NewLine(v1, v2) }
clipping.go
0.503418
0.603581
clipping.go
starcoder
package gl import ( "fyne.io/fyne" "fyne.io/fyne/canvas" "fyne.io/fyne/widget" "github.com/go-gl/gl/v3.2-core/gl" ) func walkObjects(obj fyne.CanvasObject, pos fyne.Position, f func(object fyne.CanvasObject, pos fyne.Position)) { switch co := obj.(type) { case *fyne.Container: offset := co.Position().Add(pos) f(obj, offset) for _, child := range co.Objects { walkObjects(child, offset, f) } case fyne.Widget: offset := co.Position().Add(pos) f(obj, offset) for _, child := range widget.Renderer(co).Objects() { walkObjects(child, offset, f) } default: f(obj, pos) } } func rectInnerCoords(size fyne.Size, pos fyne.Position, fill canvas.ImageFill, aspect float32) (fyne.Size, fyne.Position) { if fill == canvas.ImageFillContain || fill == canvas.ImageFillOriginal { // change pos and size accordingly viewAspect := float32(size.Width) / float32(size.Height) newWidth, newHeight := size.Width, size.Height widthPad, heightPad := 0, 0 if viewAspect > aspect { newWidth = int(float32(size.Height) * aspect) widthPad = (size.Width - newWidth) / 2 } else if viewAspect < aspect { newHeight = int(float32(size.Width) / aspect) heightPad = (size.Height - newHeight) / 2 } return fyne.NewSize(newWidth, newHeight), fyne.NewPos(pos.X+widthPad, pos.Y+heightPad) } return size, pos } // rectCoords calculates the openGL coordinate space of a rectangle func (c *glCanvas) rectCoords(size fyne.Size, pos fyne.Position, frame fyne.Size, fill canvas.ImageFill, aspect float32) []float32 { size, pos = rectInnerCoords(size, pos, fill, aspect) xPos := float32(pos.X) / float32(frame.Width) x1 := -1 + xPos*2 x2Pos := float32(pos.X+size.Width) / float32(frame.Width) x2 := -1 + x2Pos*2 yPos := float32(pos.Y) / float32(frame.Height) y1 := 1 - yPos*2 y2Pos := float32(pos.Y+size.Height) / float32(frame.Height) y2 := 1 - y2Pos*2 points := []float32{ // coord x, y, x texture x, y x1, y2, 0, 0.0, 1.0, // top left x1, y1, 0, 0.0, 0.0, // bottom left x2, y2, 0, 1.0, 1.0, // top right x2, y1, 0, 1.0, 0.0, // bottom right } var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) gl.EnableVertexAttribArray(0) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, 4*len(points), gl.Ptr(points), gl.STATIC_DRAW) textureUniform := gl.GetUniformLocation(c.program, gl.Str("tex\x00")) gl.Uniform1i(textureUniform, 0) vertAttrib := uint32(gl.GetAttribLocation(c.program, gl.Str("vert\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 5*4, gl.PtrOffset(0)) texCoordAttrib := uint32(gl.GetAttribLocation(c.program, gl.Str("vertTexCoord\x00"))) gl.EnableVertexAttribArray(texCoordAttrib) gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, false, 5*4, gl.PtrOffset(3*4)) return points } func (c *glCanvas) drawTexture(texture uint32, points []float32) { gl.ActiveTexture(gl.TEXTURE0) gl.BindTexture(gl.TEXTURE_2D, texture) gl.DrawArrays(gl.TRIANGLE_STRIP, 0, int32(len(points)/5)) } func (c *glCanvas) drawWidget(box fyne.CanvasObject, pos fyne.Position, frame fyne.Size) { if !box.Visible() { return } points := c.rectCoords(box.Size(), pos, frame, canvas.ImageFillStretch, 0.0) texture := getTexture(box, c.newGlRectTexture) c.drawTexture(texture, points) } func (c *glCanvas) drawRectangle(rect *canvas.Rectangle, pos fyne.Position, frame fyne.Size) { if !rect.Visible() { return } points := c.rectCoords(rect.Size(), pos, frame, canvas.ImageFillStretch, 0.0) texture := getTexture(rect, c.newGlRectTexture) c.drawTexture(texture, points) } func (c *glCanvas) drawImage(img *canvas.Image, pos fyne.Position, frame fyne.Size) { if !img.Visible() { return } texture := getTexture(img, c.newGlImageTexture) if texture == 0 { return } points := c.rectCoords(img.Size(), pos, frame, img.FillMode, img.PixelAspect) c.drawTexture(texture, points) } func (c *glCanvas) drawText(text *canvas.Text, pos fyne.Position, frame fyne.Size) { if !text.Visible() || text.Text == "" { return } size := text.MinSize() containerSize := text.Size() switch text.Alignment { case fyne.TextAlignTrailing: pos = fyne.NewPos(pos.X+containerSize.Width-size.Width, pos.Y) case fyne.TextAlignCenter: pos = fyne.NewPos(pos.X+(containerSize.Width-size.Width)/2, pos.Y) } if text.Size().Height > text.MinSize().Height { pos = fyne.NewPos(pos.X, pos.Y+(text.Size().Height-text.MinSize().Height)/2) } points := c.rectCoords(size, pos, frame, canvas.ImageFillStretch, 0.0) texture := c.newGlTextTexture(text) c.drawTexture(texture, points) } func (c *glCanvas) drawObject(o fyne.CanvasObject, offset fyne.Position, frame fyne.Size) { canvasMutex.Lock() canvases[o] = c canvasMutex.Unlock() pos := o.Position().Add(offset) switch obj := o.(type) { case *canvas.Rectangle: c.drawRectangle(obj, pos, frame) case *canvas.Image: c.drawImage(obj, pos, frame) case *canvas.Text: c.drawText(obj, pos, frame) case fyne.Widget: c.drawWidget(obj, offset, frame) } }
driver/gl/draw.go
0.68658
0.419826
draw.go
starcoder
package datadog import ( "encoding/json" ) // SLOResponse A service level objective response containing a single service level objective. type SLOResponse struct { Data *SLOResponseData `json:"data,omitempty"` // An array of error messages. Each endpoint documents how/whether this field is used. Errors *[]string `json:"errors,omitempty"` } // NewSLOResponse instantiates a new SLOResponse 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 NewSLOResponse() *SLOResponse { this := SLOResponse{} return &this } // NewSLOResponseWithDefaults instantiates a new SLOResponse 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 NewSLOResponseWithDefaults() *SLOResponse { this := SLOResponse{} return &this } // GetData returns the Data field value if set, zero value otherwise. func (o *SLOResponse) GetData() SLOResponseData { if o == nil || o.Data == nil { var ret SLOResponseData return ret } return *o.Data } // GetDataOk returns a tuple with the Data field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SLOResponse) GetDataOk() (*SLOResponseData, bool) { if o == nil || o.Data == nil { return nil, false } return o.Data, true } // HasData returns a boolean if a field has been set. func (o *SLOResponse) HasData() bool { if o != nil && o.Data != nil { return true } return false } // SetData gets a reference to the given SLOResponseData and assigns it to the Data field. func (o *SLOResponse) SetData(v SLOResponseData) { o.Data = &v } // GetErrors returns the Errors field value if set, zero value otherwise. func (o *SLOResponse) GetErrors() []string { if o == nil || o.Errors == nil { var ret []string return ret } return *o.Errors } // GetErrorsOk returns a tuple with the Errors field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SLOResponse) GetErrorsOk() (*[]string, bool) { if o == nil || o.Errors == nil { return nil, false } return o.Errors, true } // HasErrors returns a boolean if a field has been set. func (o *SLOResponse) HasErrors() bool { if o != nil && o.Errors != nil { return true } return false } // SetErrors gets a reference to the given []string and assigns it to the Errors field. func (o *SLOResponse) SetErrors(v []string) { o.Errors = &v } func (o SLOResponse) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Data != nil { toSerialize["data"] = o.Data } if o.Errors != nil { toSerialize["errors"] = o.Errors } return json.Marshal(toSerialize) } type NullableSLOResponse struct { value *SLOResponse isSet bool } func (v NullableSLOResponse) Get() *SLOResponse { return v.value } func (v *NullableSLOResponse) Set(val *SLOResponse) { v.value = val v.isSet = true } func (v NullableSLOResponse) IsSet() bool { return v.isSet } func (v *NullableSLOResponse) Unset() { v.value = nil v.isSet = false } func NewNullableSLOResponse(val *SLOResponse) *NullableSLOResponse { return &NullableSLOResponse{value: val, isSet: true} } func (v NullableSLOResponse) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableSLOResponse) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/v1/datadog/model_slo_response.go
0.762689
0.410638
model_slo_response.go
starcoder
package board import ( "math/rand" "time" "stabbey/interfaces" ) /* How many rooms can spawn on a wall (will be 0 to max_wal_rooms-1) */ const max_wall_rooms int = 3 const max_rooms int = (max_wall_rooms - 1) * 4 + 1 type growingGen struct { board *Board } /* Idea of this generator is to pick semi-random starting seeds for * a bunch of rooms, and then randomly grow them out until they collide */ func NewGrowingGenerator(b *Board) interfaces.BoardGenerator { return &growingGen{b} } func (me *growingGen) LoadEntities(game interfaces.Game) { } func (me *growingGen) Apply() { rand.Seed(time.Now().Unix()) totalRooms := 0 /* Generate some room seeds at the edges of the board * 0 = top * 1 = right * 2 = bottom * 3 = right */ for wall := 0; wall < 4; wall++ { var x, y int if wall == 0 { x = -1 y = 0 } else if wall == 1 { x = me.board.GetWidth() - 1 y = -1 } else if wall == 2 { x = -1 y = me.board.GetHeight() - 1 } else if wall == 3 { x = 0 y = -1 } for nRooms := rand.Intn(max_wall_rooms) - 1; nRooms >= 0; nRooms-- { for { r := &Room{} if x != -1 { r.StartingPointX = x if x == 0 { r.ConstrainedLeft = true } else { r.ConstrainedRight = true } } else { r.StartingPointX = rand.Intn(me.board.GetWidth()) } if y != -1 { r.StartingPointY = y if y == 0 { r.ConstrainedTop = true } else { r.ConstrainedBottom = true } } else { r.StartingPointY = rand.Intn(me.board.GetHeight()) } if me.AlreadyRoomThere(r) == false { me.board.RoomList[totalRooms] = r /* expand the room by 1 in every direciton right away */ for i := 0; i < 4; i++ { me.TryGrowRoom(totalRooms, i, 1) } totalRooms++ break } } } } /* Now generate some extra rooms in random places */ for nRooms := rand.Intn(max_rooms-totalRooms + 1); nRooms >= 0; nRooms-- { for { r := &Room{} r.StartingPointX = rand.Intn(me.board.GetWidth()) r.StartingPointY = rand.Intn(me.board.GetHeight()) if me.AlreadyRoomThere(r) == false { me.board.RoomList[totalRooms] = r /* expand the room by 1 in every direciton right away */ for i := 0; i < 4; i++ { me.TryGrowRoom(totalRooms, i, 1) } totalRooms++ break } } } /* Randomly grow the rooms a bit, define walls */ for i := 0; i < 5; i++ { for k, _ := range me.board.RoomList { me.TryGrowRoom(k, rand.Intn(4), 1) } } } /* Checks if a room's spawn point is close to any other room. Currently, * rooms must be at least 3 spaces away to count as sufficiently far away. */ func (me *growingGen) AlreadyRoomThere(r *Room) bool { minDist := 3 for _, room := range me.board.RoomList { if r.StartingPointX >= room.StartingPointX - minDist && r.StartingPointX <= room.StartingPointX + minDist && r.StartingPointY >= room.StartingPointY - minDist && r.StartingPointY <= room.StartingPointY + minDist { return true } } return false } /* Attempts to expand the given room by the given amount if possible */ func (me *growingGen) TryGrowRoom(roomNumber, direction, amount int) bool { room := me.board.RoomList[roomNumber] /* top */ if direction == 0 && room.StartingPointY - room.Top > 0 { room.Top += 1 /* right */ } else if direction == 1 && room.StartingPointX + room.Right < me.board.GetWidth() - 1 { room.Right += 1 /* bottom */ } else if direction == 2 && room.StartingPointY + room.Bottom < me.board.GetHeight() - 1 { room.Bottom += 1 /* left */ } else if direction == 3 && room.StartingPointX - room.Left > 0 { room.Left += 1 } return false }
src/stabbey/board/growing-generator.go
0.57081
0.419588
growing-generator.go
starcoder
package main import ( "fmt" "os" "strconv" "strings" ) type space struct { energy int flashing bool } type World struct { m [][]space flashes int } type coordinate struct { x int y int } func (w *World) Push(arr []space) { w.m = append(w.m, arr) } func (w *World) maxX() int { return len(w.m[0]) - 1 } func (w *World) maxY() int { return len(w.m) - 1 } func (w *World) Step() int { flashStack := []coordinate{} flashesThisStep := 0 for y := 0; y < len(w.m); y++ { for x := 0; x < len(w.m[y]); x++ { w.m[y][x].energy++ if w.m[y][x].energy == 10 { w.flashes++ flashesThisStep++ w.m[y][x].energy = 0 w.m[y][x].flashing = true flashStack = append(flashStack, coordinate{x, y}) } } } for { var flashed coordinate if len(flashStack) == 0 { break } flashed, flashStack = flashStack[0], flashStack[1:] for _, c := range w.Surrounding(flashed) { if w.m[c.y][c.x].flashing { continue } if w.m[c.y][c.x].energy == 9 { w.flashes++ flashesThisStep++ w.m[c.y][c.x].energy = 0 w.m[c.y][c.x].flashing = true flashStack = append(flashStack, c) } else { w.m[c.y][c.x].energy++ } } } for y := 0; y < len(w.m); y++ { for x := 0; x < len(w.m[y]); x++ { w.m[y][x].flashing = false } } return flashesThisStep } func (w *World) Surrounding(c coordinate) []coordinate { arr := []coordinate{} x, y := c.x, c.y // W. if x > 0 { arr = append(arr, coordinate{x - 1, y}) // NW. if y > 0 { arr = append(arr, coordinate{x - 1, y - 1}) } } // N. if y > 0 { arr = append(arr, coordinate{x, y - 1}) // NE. if x < w.maxX() { arr = append(arr, coordinate{x + 1, y - 1}) } } // E. if x < w.maxX() { arr = append(arr, coordinate{x + 1, y}) // SE. if y < w.maxY() { arr = append(arr, coordinate{x + 1, y + 1}) } } // S. if y < w.maxY() { arr = append(arr, coordinate{x, y + 1}) // SW. if x > 0 { arr = append(arr, coordinate{x - 1, y + 1}) } } return arr } func main() { lines := strings.Split(input, "\n") world := World{} for _, l := range lines { line := []space{} for _, c := range strings.Split(l, "") { line = append(line, space{energy: strToInt(c)}) } world.Push(line) } s := 0 for { f := world.Step() fmt.Printf("After step %d: %d\n", s+1, world.flashes) if f == 100 { fmt.Printf("Flashed everyone at step %d\n", s+1) break } s++ } } func logFatal(s string, args ...interface{}) { fmt.Printf(s, args...) os.Exit(1) } func strToInt(str string) int { v, err := strconv.Atoi(str) if err != nil { logFatal("Failed to convert %#q to int: %v", str, err) } return v } var sample = `5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526` var input = `4836484555 4663841772 3512484556 1481547572 7741183422 8683222882 4215244233 1544712171 5725855786 1717382281`
11/main.go
0.536799
0.412471
main.go
starcoder
package iso20022 // Specifies corporate action dates. type CorporateActionDate27 struct { // Date/time at which the issuer announced that a corporate action event will occur. AnnouncementDate *DateFormat19Choice `xml:"AnncmntDt,omitempty"` // Deadline by which the beneficial ownership of securities must be declared. CertificationDeadline *DateFormat19Choice `xml:"CertfctnDdln,omitempty"` // Date upon which the court provided approval. CourtApprovalDate *DateFormat19Choice `xml:"CrtApprvlDt,omitempty"` // First possible early closing date of an offer if different from the expiry date. EarlyClosingDate *DateFormat19Choice `xml:"EarlyClsgDt,omitempty"` // Date/time at which an event is officially effective from the issuer's perspective. EffectiveDate *DateFormat19Choice `xml:"FctvDt,omitempty"` // Date/Time on which all or part of any holding bought in a unit trust is subject to being treated as capital rather than income. This is normally one day after the previous distribution's ex date. EqualisationDate *DateFormat19Choice `xml:"EqulstnDt,omitempty"` // Date/time at which additional information on the event will be announced, for example, exchange ratio announcement date. FurtherDetailedAnnouncementDate *DateFormat19Choice `xml:"FrthrDtldAnncmntDt,omitempty"` // Date/time at which an index / rate / price / value will be determined. FixingDate *DateFormat19Choice `xml:"FxgDt,omitempty"` // Date/time on which the lottery is run and applied to the holder's positions. This is also applicable to partial calls. LotteryDate *DateFormat19Choice `xml:"LtryDt,omitempty"` // Date/time to which the maturity date of an interest bearing security is extended. NewMaturityDate *DateFormat19Choice `xml:"NewMtrtyDt,omitempty"` // Date/time on which the bondholder's or shareholder's meeting will take place. MeetingDate *DateFormat19Choice `xml:"MtgDt,omitempty"` // Date/time at which the margin rate will be determined . MarginFixingDate *DateFormat19Choice `xml:"MrgnFxgDt,omitempty"` // Date/time (and time) at which an issuer will determine the proration amount/quantity of an offer. ProrationDate *DateFormat19Choice `xml:"PrratnDt,omitempty"` // Date/time at which positions are struck at the end of the day to note which parties will receive the relevant amount of entitlement, due to be distributed on payment date. RecordDate *DateFormat19Choice `xml:"RcrdDt,omitempty"` // Date/time on which instructions to register or registration details will be accepted. RegistrationDeadline *DateFormat19Choice `xml:"RegnDdln,omitempty"` // Date/time on which results are published, for example, results of an offer. ResultsPublicationDate *DateFormat19Choice `xml:"RsltsPblctnDt,omitempty"` // Deadline by which instructions must be received to split securities, for example, of physical certificates. DeadlineToSplit *DateFormat19Choice `xml:"DdlnToSplt,omitempty"` // Date/time on until which tax breakdown instructions will be accepted. DeadlineForTaxBreakdownInstruction *DateFormat19Choice `xml:"DdlnForTaxBrkdwnInstr,omitempty"` // Date/time at which trading of a security is suspended as the result of an event. TradingSuspendedDate *DateFormat19Choice `xml:"TradgSspdDt,omitempty"` // Date/time upon which the terms of the take-over become unconditional as to acceptances. UnconditionalDate *DateFormat19Choice `xml:"UcondlDt,omitempty"` // Date/time at on which all conditions, including regulatory, legal etc. pertaining to the take-over, have been met. WhollyUnconditionalDate *DateFormat19Choice `xml:"WhlyUcondlDt,omitempty"` // Date/time as from which trading (including exchange and OTC trading) occurs on the underlying security without the benefit. ExDividendDate *DateFormat19Choice `xml:"ExDvddDt,omitempty"` // Date/time at which the corporate action is legally announced by an official body, for example, publication by a governmental administration. OfficialAnnouncementPublicationDate *DateFormat19Choice `xml:"OffclAnncmntPblctnDt,omitempty"` // Date/time as from which 'special processing' can start to be used by participants for that event. Special processing is a means of marking a transaction, that would normally be traded ex or cum, as being traded cum or ex respectively, for example, a transaction dealt 'special' after the ex date would result in the buyer being eligible for the entitlement. This is typically used in the UK and Irish markets. SpecialExDate *DateFormat19Choice `xml:"SpclExDt,omitempty"` // Last date/time by which a buying counterparty to a trade can be sure that it will have the right to participate in an event. GuaranteedParticipationDate *DateFormat19Choice `xml:"GrntedPrtcptnDt,omitempty"` // Deadline by which an entitled holder needs to advise their counterparty to a transaction of their election for a corporate action event, also known as Buyer Protection Deadline. ElectionToCounterpartyDeadline *DateFormat19Choice `xml:"ElctnToCtrPtyDdln,omitempty"` // Date/time at which an event/offer is terminated or lapsed. LapsedDate *DateFormat19Choice `xml:"LpsdDt,omitempty"` // Date/time at which the movement is due to take place (cash and/or securities). PaymentDate *DateFormat19Choice `xml:"PmtDt,omitempty"` // Date/Time by which the account owner must instruct directly another party, for example to provide documentation to an issuer agent. ThirdPartyDeadline *DateFormat19Choice `xml:"ThrdPtyDdln,omitempty"` // Date/Time set by the issuer agent as a first early deadline by which the account owner must instruct directly another party, possibly giving the holder eligibility to incentives. For example, to provide documentation to an issuer agent. EarlyThirdPartyDeadline *DateFormat19Choice `xml:"EarlyThrdPtyDdln,omitempty"` // Date by which the depository stops monitoring activities of the event, for instance, accounting and tracking activities for due bills end. MarketClaimTrackingEndDate *DateFormat19Choice `xml:"MktClmTrckgEndDt,omitempty"` // Last day an investor can become a lead plaintiff. LeadPlaintiffDeadline *DateFormat19Choice `xml:"LeadPlntffDdln,omitempty"` // Date on which the action was filed at the applicable court. FilingDate *DateFormat16Choice `xml:"FilgDt,omitempty"` // Date for the hearing between the plaintiff and defendant, as set by the court. HearingDate *DateFormat16Choice `xml:"HrgDt,omitempty"` } func (c *CorporateActionDate27) AddAnnouncementDate() *DateFormat19Choice { c.AnnouncementDate = new(DateFormat19Choice) return c.AnnouncementDate } func (c *CorporateActionDate27) AddCertificationDeadline() *DateFormat19Choice { c.CertificationDeadline = new(DateFormat19Choice) return c.CertificationDeadline } func (c *CorporateActionDate27) AddCourtApprovalDate() *DateFormat19Choice { c.CourtApprovalDate = new(DateFormat19Choice) return c.CourtApprovalDate } func (c *CorporateActionDate27) AddEarlyClosingDate() *DateFormat19Choice { c.EarlyClosingDate = new(DateFormat19Choice) return c.EarlyClosingDate } func (c *CorporateActionDate27) AddEffectiveDate() *DateFormat19Choice { c.EffectiveDate = new(DateFormat19Choice) return c.EffectiveDate } func (c *CorporateActionDate27) AddEqualisationDate() *DateFormat19Choice { c.EqualisationDate = new(DateFormat19Choice) return c.EqualisationDate } func (c *CorporateActionDate27) AddFurtherDetailedAnnouncementDate() *DateFormat19Choice { c.FurtherDetailedAnnouncementDate = new(DateFormat19Choice) return c.FurtherDetailedAnnouncementDate } func (c *CorporateActionDate27) AddFixingDate() *DateFormat19Choice { c.FixingDate = new(DateFormat19Choice) return c.FixingDate } func (c *CorporateActionDate27) AddLotteryDate() *DateFormat19Choice { c.LotteryDate = new(DateFormat19Choice) return c.LotteryDate } func (c *CorporateActionDate27) AddNewMaturityDate() *DateFormat19Choice { c.NewMaturityDate = new(DateFormat19Choice) return c.NewMaturityDate } func (c *CorporateActionDate27) AddMeetingDate() *DateFormat19Choice { c.MeetingDate = new(DateFormat19Choice) return c.MeetingDate } func (c *CorporateActionDate27) AddMarginFixingDate() *DateFormat19Choice { c.MarginFixingDate = new(DateFormat19Choice) return c.MarginFixingDate } func (c *CorporateActionDate27) AddProrationDate() *DateFormat19Choice { c.ProrationDate = new(DateFormat19Choice) return c.ProrationDate } func (c *CorporateActionDate27) AddRecordDate() *DateFormat19Choice { c.RecordDate = new(DateFormat19Choice) return c.RecordDate } func (c *CorporateActionDate27) AddRegistrationDeadline() *DateFormat19Choice { c.RegistrationDeadline = new(DateFormat19Choice) return c.RegistrationDeadline } func (c *CorporateActionDate27) AddResultsPublicationDate() *DateFormat19Choice { c.ResultsPublicationDate = new(DateFormat19Choice) return c.ResultsPublicationDate } func (c *CorporateActionDate27) AddDeadlineToSplit() *DateFormat19Choice { c.DeadlineToSplit = new(DateFormat19Choice) return c.DeadlineToSplit } func (c *CorporateActionDate27) AddDeadlineForTaxBreakdownInstruction() *DateFormat19Choice { c.DeadlineForTaxBreakdownInstruction = new(DateFormat19Choice) return c.DeadlineForTaxBreakdownInstruction } func (c *CorporateActionDate27) AddTradingSuspendedDate() *DateFormat19Choice { c.TradingSuspendedDate = new(DateFormat19Choice) return c.TradingSuspendedDate } func (c *CorporateActionDate27) AddUnconditionalDate() *DateFormat19Choice { c.UnconditionalDate = new(DateFormat19Choice) return c.UnconditionalDate } func (c *CorporateActionDate27) AddWhollyUnconditionalDate() *DateFormat19Choice { c.WhollyUnconditionalDate = new(DateFormat19Choice) return c.WhollyUnconditionalDate } func (c *CorporateActionDate27) AddExDividendDate() *DateFormat19Choice { c.ExDividendDate = new(DateFormat19Choice) return c.ExDividendDate } func (c *CorporateActionDate27) AddOfficialAnnouncementPublicationDate() *DateFormat19Choice { c.OfficialAnnouncementPublicationDate = new(DateFormat19Choice) return c.OfficialAnnouncementPublicationDate } func (c *CorporateActionDate27) AddSpecialExDate() *DateFormat19Choice { c.SpecialExDate = new(DateFormat19Choice) return c.SpecialExDate } func (c *CorporateActionDate27) AddGuaranteedParticipationDate() *DateFormat19Choice { c.GuaranteedParticipationDate = new(DateFormat19Choice) return c.GuaranteedParticipationDate } func (c *CorporateActionDate27) AddElectionToCounterpartyDeadline() *DateFormat19Choice { c.ElectionToCounterpartyDeadline = new(DateFormat19Choice) return c.ElectionToCounterpartyDeadline } func (c *CorporateActionDate27) AddLapsedDate() *DateFormat19Choice { c.LapsedDate = new(DateFormat19Choice) return c.LapsedDate } func (c *CorporateActionDate27) AddPaymentDate() *DateFormat19Choice { c.PaymentDate = new(DateFormat19Choice) return c.PaymentDate } func (c *CorporateActionDate27) AddThirdPartyDeadline() *DateFormat19Choice { c.ThirdPartyDeadline = new(DateFormat19Choice) return c.ThirdPartyDeadline } func (c *CorporateActionDate27) AddEarlyThirdPartyDeadline() *DateFormat19Choice { c.EarlyThirdPartyDeadline = new(DateFormat19Choice) return c.EarlyThirdPartyDeadline } func (c *CorporateActionDate27) AddMarketClaimTrackingEndDate() *DateFormat19Choice { c.MarketClaimTrackingEndDate = new(DateFormat19Choice) return c.MarketClaimTrackingEndDate } func (c *CorporateActionDate27) AddLeadPlaintiffDeadline() *DateFormat19Choice { c.LeadPlaintiffDeadline = new(DateFormat19Choice) return c.LeadPlaintiffDeadline } func (c *CorporateActionDate27) AddFilingDate() *DateFormat16Choice { c.FilingDate = new(DateFormat16Choice) return c.FilingDate } func (c *CorporateActionDate27) AddHearingDate() *DateFormat16Choice { c.HearingDate = new(DateFormat16Choice) return c.HearingDate }
CorporateActionDate27.go
0.786008
0.446072
CorporateActionDate27.go
starcoder
package ytypes import ( "fmt" "github.com/openconfig/goyang/pkg/yang" ) // Refer to: https://tools.ietf.org/html/rfc6020#section-9.5. // validateBool validates value, which must be a Go bool type, against the // given schema. func validateBool(schema *yang.Entry, value interface{}) error { // Check that the schema itself is valid. if err := validateBoolSchema(schema); err != nil { return err } // Check that type of value is the type expected from the schema. if _, ok := value.(bool); !ok { return fmt.Errorf("non bool type %T with value %v for schema %s", value, value, schema.Name) } return nil } // validateBoolSlice validates value, which must be a Go bool slice type, // against the given schema. func validateBoolSlice(schema *yang.Entry, value interface{}) error { // Check that the schema itself is valid. if err := validateBoolSchema(schema); err != nil { return err } // Check that type of value is the type expected from the schema. slice, ok := value.([]bool) if !ok { return fmt.Errorf("non []bool type %T with value: %v for schema %s", value, value, schema.Name) } // Each slice element must be valid and unique. tbl := make(map[bool]bool) for _, val := range slice { // A bool value is always valid. There is no need to validate each bool element. if tbl[val] { return fmt.Errorf("duplicate bool: %v for schema %s", val, schema.Name) } tbl[val] = true } return nil } // validateBoolSchema validates the given bool type schema. This is a sanity // check validation rather than a comprehensive validation against the RFC. // It is assumed that such a validation is done when the schema is parsed from // source YANG. func validateBoolSchema(schema *yang.Entry) error { if schema == nil { return fmt.Errorf("bool schema is nil") } if schema.Type == nil { return fmt.Errorf("bool schema %s Type is nil", schema.Name) } if schema.Type.Kind != yang.Ybool { return fmt.Errorf("bool schema %s has wrong type %v", schema.Name, schema.Type.Kind) } return nil }
ytypes/bool_type.go
0.758242
0.417539
bool_type.go
starcoder
Small library on top of reflect for make lookups to Structs or Maps. Using a very simple DSL you can access to any property, key or value of any value of Go. */ package lookup import ( "errors" "reflect" "strconv" "strings" ) const ( SplitToken = "." IndexCloseChar = "]" IndexOpenChar = "[" ) var ( ErrMalformedIndex = errors.New("Malformed index key") ErrInvalidIndexUsage = errors.New("Invalid index key usage") ErrKeyNotFound = errors.New("Unable to find the key") ) // LookupString performs a lookup into a value, using a string. Same as `Loookup` // but using a string with the keys separated by `.` func LookupString(i interface{}, path string) (reflect.Value, error) { return Lookup(i, strings.Split(path, SplitToken)...) } // Lookup performs a lookup into a value, using a path of keys. The key should // match with a Field or a MapIndex. For slice you can use the syntax key[index] // to access a specific index. If one key owns to a slice and an index is not // specificied the rest of the path will be apllied to evaley value of the // slice, and the value will be merged into a slice. func Lookup(i interface{}, path ...string) (reflect.Value, error) { value := reflect.ValueOf(i) var parent reflect.Value var err error for i, part := range path { parent = value value, err = getValueByName(value, part) if err == nil { continue } if !isAggregable(parent) { break } value, err = aggreateAggregableValue(parent, path[i:]) break } return value, err } func getValueByName(v reflect.Value, key string) (reflect.Value, error) { var value reflect.Value var index int var err error key, index, err = parseIndex(key) if err != nil { return value, err } switch v.Kind() { case reflect.Ptr, reflect.Interface: return getValueByName(v.Elem(), key) case reflect.Struct: if f, ok := ValueByTagName(v, key); ok { value = f } else { value = v.FieldByName(key) } case reflect.Map: kValue := reflect.Indirect(reflect.New(v.Type().Key())) kValue.SetString(key) value = v.MapIndex(kValue) } if !value.IsValid() { return reflect.Value{}, ErrKeyNotFound } if index != -1 { if value.Type().Kind() != reflect.Slice { return reflect.Value{}, ErrInvalidIndexUsage } value = value.Index(index) } if value.Kind() == reflect.Ptr || value.Kind() == reflect.Interface { value = value.Elem() } return value, nil } func aggreateAggregableValue(v reflect.Value, path []string) (reflect.Value, error) { values := make([]reflect.Value, 0) l := v.Len() if l == 0 { ty, ok := lookupType(v.Type(), path...) if !ok { return reflect.Value{}, ErrKeyNotFound } return reflect.MakeSlice(reflect.SliceOf(ty), 0, 0), nil } index := indexFunction(v) for i := 0; i < l; i++ { value, err := Lookup(index(i).Interface(), path...) if err != nil { return reflect.Value{}, err } values = append(values, value) } return mergeValue(values), nil } func indexFunction(v reflect.Value) func(i int) reflect.Value { switch v.Kind() { case reflect.Slice: return v.Index case reflect.Map: keys := v.MapKeys() return func(i int) reflect.Value { return v.MapIndex(keys[i]) } default: panic("unsuported kind for index") } } func mergeValue(values []reflect.Value) reflect.Value { values = removeZeroValues(values) l := len(values) if l == 0 { return reflect.Value{} } sample := values[0] mergeable := isMergeable(sample) t := sample.Type() if mergeable { t = t.Elem() } value := reflect.MakeSlice(reflect.SliceOf(t), 0, 0) for i := 0; i < l; i++ { if !values[i].IsValid() { continue } if mergeable { value = reflect.AppendSlice(value, values[i]) } else { value = reflect.Append(value, values[i]) } } return value } func removeZeroValues(values []reflect.Value) []reflect.Value { l := len(values) var v []reflect.Value for i := 0; i < l; i++ { if values[i].IsValid() { v = append(v, values[i]) } } return v } func isAggregable(v reflect.Value) bool { k := v.Kind() return k == reflect.Map || k == reflect.Slice } func isMergeable(v reflect.Value) bool { k := v.Kind() return k == reflect.Map || k == reflect.Slice } func hasIndex(s string) bool { return strings.Index(s, IndexOpenChar) != -1 } func parseIndex(s string) (string, int, error) { start := strings.Index(s, IndexOpenChar) end := strings.Index(s, IndexCloseChar) if start == -1 && end == -1 { return s, -1, nil } if (start != -1 && end == -1) || (start == -1 && end != -1) { return "", -1, ErrMalformedIndex } index, err := strconv.Atoi(s[start+1 : end]) if err != nil { return "", -1, ErrMalformedIndex } return s[:start], index, nil } func ValueByTagName(v reflect.Value, key string) (reflect.Value, bool) { if f, ok := FieldByTagName(v.Type(), key); ok { return v.FieldByName(f.Name), true } return reflect.Value{}, false } func FieldByTagName(ty reflect.Type, key string) (*reflect.StructField, bool) { switch ty.Kind() { case reflect.Struct: for i := 0; i < ty.NumField(); i++ { field := ty.Field(i) if yaml, ok := field.Tag.Lookup("yaml"); ok { if strings.Split(yaml, ",")[0] == key { return &field, true } } if json, ok := field.Tag.Lookup("json"); ok { if strings.Split(json, ",")[0] == key { return &field, true } } } } return nil, false } func lookupType(ty reflect.Type, path ...string) (reflect.Type, bool) { if len(path) == 0 { return ty, true } switch ty.Kind() { case reflect.Slice, reflect.Array, reflect.Map: if hasIndex(path[0]) { return lookupType(ty.Elem(), path[1:]...) } // Aggregate. return lookupType(ty.Elem(), path...) case reflect.Ptr: return lookupType(ty.Elem(), path...) case reflect.Interface: // We can't know from here without a value. Let's just return this type. return ty, true case reflect.Struct: if f, ok := ty.FieldByName(path[0]); ok { return lookupType(f.Type, path[1:]...) } if f, ok := FieldByTagName(ty, path[0]); ok { return lookupType(f.Type, path[1:]...) } } return nil, false }
lookup/lookup.go
0.786008
0.558568
lookup.go
starcoder
package draw import ( "image" ) // Op represents a Porter-Duff compositing operator. type Op int const ( /* Porter-Duff compositing operators */ Clear Op = 0 SinD Op = 8 DinS Op = 4 SoutD Op = 2 DoutS Op = 1 S = SinD | SoutD SoverD = SinD | SoutD | DoutS SatopD = SinD | DoutS SxorD = SoutD | DoutS D = DinS | DoutS DoverS = DinS | DoutS | SoutD DatopS = DinS | SoutD DxorS = DoutS | SoutD /* == SxorD */ Ncomp = 12 ) func setdrawop(d *Display, op Op) { if op != SoverD { a := d.bufimage(2) a[0] = 'O' a[1] = byte(op) } } func draw(dst *Image, r image.Rectangle, src *Image, p0 image.Point, mask *Image, p1 image.Point, op Op) { setdrawop(dst.Display, op) a := dst.Display.bufimage(1 + 4 + 4 + 4 + 4*4 + 2*4 + 2*4) if src == nil { src = dst.Display.Black } if mask == nil { mask = dst.Display.Opaque } a[0] = 'd' bplong(a[1:], dst.id) bplong(a[5:], src.id) bplong(a[9:], mask.id) bplong(a[13:], uint32(r.Min.X)) bplong(a[17:], uint32(r.Min.Y)) bplong(a[21:], uint32(r.Max.X)) bplong(a[25:], uint32(r.Max.Y)) bplong(a[29:], uint32(p0.X)) bplong(a[33:], uint32(p0.Y)) bplong(a[37:], uint32(p1.X)) bplong(a[41:], uint32(p1.Y)) } func (dst *Image) draw(r image.Rectangle, src, mask *Image, p1 image.Point) { draw(dst, r, src, p1, mask, p1, SoverD) } // Draw copies the source image with upper left corner p1 to the destination // rectangle r, through the specified mask using operation SoverD. The // coordinates are aligned so p1 in src and mask both correspond to r.min in // the destination. func (dst *Image) Draw(r image.Rectangle, src, mask *Image, p1 image.Point) { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() draw(dst, r, src, p1, mask, p1, SoverD) } // DrawOp copies the source image with upper left corner p1 to the destination // rectangle r, through the specified mask using the specified operation. The // coordinates are aligned so p1 in src and mask both correspond to r.min in // the destination. func (dst *Image) DrawOp(r image.Rectangle, src, mask *Image, p1 image.Point, op Op) { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() draw(dst, r, src, p1, mask, p1, op) } // GenDraw copies the source image with upper left corner p1 to the destination // rectangle r, through the specified mask using operation SoverD. The // coordinates are aligned so p1 in src and p0 in mask both correspond to r.min in // the destination. func (dst *Image) GenDraw(r image.Rectangle, src *Image, p0 image.Point, mask *Image, p1 image.Point) { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() draw(dst, r, src, p0, mask, p1, SoverD) } // GenDrawOp copies the source image with upper left corner p1 to the destination // rectangle r, through the specified mask using the specified operation. The // coordinates are aligned so p1 in src and p0 in mask both correspond to r.min in // the destination. func GenDrawOp(dst *Image, r image.Rectangle, src *Image, p0 image.Point, mask *Image, p1 image.Point, op Op) { dst.Display.mu.Lock() defer dst.Display.mu.Unlock() draw(dst, r, src, p0, mask, p1, op) }
_vendor/src/code.google.com/p/goplan9/draw/draw.go
0.725649
0.505676
draw.go
starcoder
package hplot import ( "image/color" "math" "gonum.org/v1/plot" "gonum.org/v1/plot/plotter" "gonum.org/v1/plot/vg" "gonum.org/v1/plot/vg/draw" ) // S2D plots a set of 2-dim points with error bars. type S2D struct { Data plotter.XYer // GlyphStyle is the style of the glyphs drawn // at each point. draw.GlyphStyle // LineStyle is the style of the line drawn // connecting each point. // Use zero width to disable. LineStyle draw.LineStyle // XErrs is the x error bars plotter. XErrs *plotter.XErrorBars // YErrs is the y error bars plotter. YErrs *plotter.YErrorBars // Band displays a colored band between the y-min and y-max error bars. Band *Band // Steps controls the style of the connecting // line (NoSteps, HiSteps, etc...) Steps StepsKind } // withXErrBars enables the X error bars func (pts *S2D) withXErrBars() error { xerr, ok := pts.Data.(plotter.XErrorer) if !ok { return nil } type xerrT struct { plotter.XYer plotter.XErrorer } xplt, err := plotter.NewXErrorBars(xerrT{pts.Data, xerr}) if err != nil { return err } pts.XErrs = xplt return nil } // withYErrBars enables the Y error bars func (pts *S2D) withYErrBars() error { yerr, ok := pts.Data.(plotter.YErrorer) if !ok { return nil } type yerrT struct { plotter.XYer plotter.YErrorer } yplt, err := plotter.NewYErrorBars(yerrT{pts.Data, yerr}) if err != nil { return err } pts.YErrs = yplt return nil } // withBand enables the band between ymin-ymax error bars. func (pts *S2D) withBand() error { yerr, ok := pts.Data.(plotter.YErrorer) if !ok { return nil } var ( top plotter.XYs bot plotter.XYs ) switch pts.Steps { case NoSteps: top = make(plotter.XYs, pts.Data.Len()) bot = make(plotter.XYs, pts.Data.Len()) for i := range top { x, y := pts.Data.XY(i) ymin, ymax := yerr.YError(i) top[i].X = x top[i].Y = y + math.Abs(ymax) bot[i].X = x bot[i].Y = y - math.Abs(ymin) } case HiSteps: top = make(plotter.XYs, 2*pts.Data.Len()) bot = make(plotter.XYs, 2*pts.Data.Len()) xerr := pts.Data.(plotter.XErrorer) for i := range top { idata := i / 2 x, y := pts.Data.XY(idata) xmin, xmax := xerr.XError(idata) ymin, ymax := yerr.YError(idata) switch { case i%2 != 0: top[i].X = x + math.Abs(xmax) top[i].Y = y + math.Abs(ymax) bot[i].X = x + math.Abs(xmax) bot[i].Y = y - math.Abs(ymin) default: top[i].X = x - math.Abs(xmin) top[i].Y = y + math.Abs(ymax) bot[i].X = x - math.Abs(xmin) bot[i].Y = y - math.Abs(ymin) } } } pts.Band = NewBand(color.Gray{200}, top, bot) return nil } // NewS2D creates a 2-dim scatter plot from a XYer. func NewS2D(data plotter.XYer, opts ...Options) *S2D { s := &S2D{ Data: data, GlyphStyle: plotter.DefaultGlyphStyle, } s.GlyphStyle.Shape = draw.CrossGlyph{} cfg := newConfig(opts) s.Steps = cfg.steps if cfg.bars.xerrs { _ = s.withXErrBars() } if cfg.bars.yerrs { _ = s.withYErrBars() } if cfg.band { _ = s.withBand() } if cfg.glyph != (draw.GlyphStyle{}) { s.GlyphStyle = cfg.glyph } return s } // Plot draws the Scatter, implementing the plot.Plotter // interface. func (pts *S2D) Plot(c draw.Canvas, plt *plot.Plot) { trX, trY := plt.Transforms(&c) if pts.Band != nil { pts.Band.Plot(c, plt) } for i := 0; i < pts.Data.Len(); i++ { x, y := pts.Data.XY(i) c.DrawGlyph(pts.GlyphStyle, vg.Point{X: trX(x), Y: trY(y)}) } if pts.LineStyle.Width > 0 { data, err := plotter.CopyXYs(pts.Data) if err != nil { panic(err) } if pts.Steps == HiSteps { xerr := pts.Data.(plotter.XErrorer) dsteps := make(plotter.XYs, 0, 2*len(data)) for i, d := range data { xmin, xmax := xerr.XError(i) dsteps = append(dsteps, plotter.XY{X: d.X - xmin, Y: d.Y}) dsteps = append(dsteps, plotter.XY{X: d.X + xmax, Y: d.Y}) } data = dsteps } line := plotter.Line{ XYs: data, LineStyle: pts.LineStyle, } line.Plot(c, plt) } if pts.XErrs != nil { pts.XErrs.LineStyle.Color = pts.GlyphStyle.Color pts.XErrs.Plot(c, plt) } if pts.YErrs != nil { pts.YErrs.LineStyle.Color = pts.GlyphStyle.Color pts.YErrs.Plot(c, plt) } } // DataRange returns the minimum and maximum // x and y values, implementing the plot.DataRanger // interface. func (pts *S2D) DataRange() (xmin, xmax, ymin, ymax float64) { if dr, ok := pts.Data.(plot.DataRanger); ok { xmin, xmax, ymin, ymax = dr.DataRange() } else { xmin, xmax, ymin, ymax = plotter.XYRange(pts.Data) } if pts.XErrs != nil { xmin1, xmax1, ymin1, ymax1 := pts.XErrs.DataRange() xmin = math.Min(xmin1, xmin) xmax = math.Max(xmax1, xmax) ymin = math.Min(ymin1, ymin) ymax = math.Max(ymax1, ymax) } if pts.YErrs != nil { xmin1, xmax1, ymin1, ymax1 := pts.YErrs.DataRange() xmin = math.Min(xmin1, xmin) xmax = math.Max(xmax1, xmax) ymin = math.Min(ymin1, ymin) ymax = math.Max(ymax1, ymax) } return xmin, xmax, ymin, ymax } // GlyphBoxes returns a slice of plot.GlyphBoxes, // implementing the plot.GlyphBoxer interface. func (pts *S2D) GlyphBoxes(plt *plot.Plot) []plot.GlyphBox { bs := make([]plot.GlyphBox, pts.Data.Len()) for i := 0; i < pts.Data.Len(); i++ { x, y := pts.Data.XY(i) bs[i].X = plt.X.Norm(x) bs[i].Y = plt.Y.Norm(y) bs[i].Rectangle = pts.GlyphStyle.Rectangle() } if pts.XErrs != nil { bs = append(bs, pts.XErrs.GlyphBoxes(plt)...) } if pts.YErrs != nil { bs = append(bs, pts.YErrs.GlyphBoxes(plt)...) } return bs } // Thumbnail the thumbnail for the Scatter, // implementing the plot.Thumbnailer interface. func (pts *S2D) Thumbnail(c *draw.Canvas) { ymin := c.Min.Y ymax := c.Max.Y xmin := c.Min.X xmax := c.Max.X if pts.Band != nil { box := []vg.Point{ {X: xmin, Y: ymin}, {X: xmax, Y: ymin}, {X: xmax, Y: ymax}, {X: xmin, Y: ymax}, {X: xmin, Y: ymin}, } c.FillPolygon(pts.Band.FillColor, c.ClipPolygonXY(box)) } if pts.LineStyle.Width != 0 { ymid := c.Center().Y line := []vg.Point{{X: xmin, Y: ymid}, {X: xmax, Y: ymid}} c.StrokeLines(pts.LineStyle, c.ClipLinesX(line)...) } if pts.GlyphStyle != (draw.GlyphStyle{}) { c.DrawGlyph(pts.GlyphStyle, c.Center()) if pts.YErrs != nil { var ( yerrs = pts.YErrs vsize = 0.5 * ((ymax - ymin) * 0.95) x = c.Center().X ylo = c.Center().Y - vsize yup = c.Center().Y + vsize xylo = vg.Point{X: x, Y: ylo} xyup = vg.Point{X: x, Y: yup} line = []vg.Point{xylo, xyup} bar = c.ClipLinesY(line) ) c.StrokeLines(yerrs.LineStyle, bar...) for _, pt := range []vg.Point{xylo, xyup} { if c.Contains(pt) { c.StrokeLine2(yerrs.LineStyle, pt.X-yerrs.CapWidth/2, pt.Y, pt.X+yerrs.CapWidth/2, pt.Y, ) } } } } }
hplot/s2d.go
0.735926
0.501099
s2d.go
starcoder
package main import ( "math/rand" ) func Smoke(x, y, power float64) { for i := 0; i < 50; i++ { // smoke color := rand.Float32() * 0xFFFF particles.NewParticle(particle{ r: color, g: color, b: color, a: color, size: float64(1 + rand.Intn(2)), Phys: Phys{ x: x, y: y, vy: power/2 - rand.Float64()*power, vx: power/2 - rand.Float64()*power, fx: power/2 - rand.Float64()*power, fy: power/2 - rand.Float64()*power, life: rand.Float64() * 3, mass: -0.2, restitution: 0, active: true, }, }) } } func Explode(x, y, power float64) { world.Explode(int(x), int(y), int(power)) for i := 0; i < int(power)*50; i++ { // smoke color := rand.Float32() * 0xFFFF particles.NewParticle(particle{ r: color, g: color, b: color, a: color, size: float64(1 + rand.Intn(2)), Phys: Phys{ x: x, y: y, vy: power/6 - rand.Float64()*power/3, vx: power/6 - rand.Float64()*power/3, fx: power/6 - rand.Float64()*power/3, fy: power/6 - rand.Float64()*power/3, life: rand.Float64() * 2, mass: -0.1, restitution: 0, active: true, }, }) // Fire cr := float32(rand.Intn(0xFFFFFF)) cg := float32(rand.Intn(0x33555)) cb := float32(0) ca := float32(0xFFF + rand.Intn(0xFFFFFF)) // Some random exploding parts. life := rand.Float64() expHit := 0 if power > 3 { if rand.Intn(100) > 97 { life += 2 expHit = 2 + rand.Intn(3) } } particles.NewParticle(particle{ r: cr * 2, g: cg, b: cb, a: ca, size: float64(1 + rand.Intn(3)), Phys: Phys{ explodeOnHit: expHit, x: x, y: y, vy: power/4 - rand.Float64()*power/2, vx: power/4 - rand.Float64()*power/2, fx: power/4 - rand.Float64()*power/2, fy: power/4 - rand.Float64()*power/2, life: life, mass: 1, restitution: -0.1, active: true, }, }) } } func Star() { particles.NewParticle(particle{ r: 0xFFFFFF, g: 0xFFFFFF, b: 0xFFFFFF, a: 0xFFFF, z: 0, size: rand.Float64() * 5, Phys: Phys{ x: screenWidth * rand.Float64(), y: screenHeight - rand.Float64()*screenHeight/3, vy: 0, vx: rand.Float64() * 10, fx: rand.Float64() * 10, fy: 0, life: 3 + rand.Float64()*2, mass: 0, restitution: 0, active: true, }, }) }
effects.go
0.505371
0.411584
effects.go
starcoder
package day08 import ( "fmt" "math" mapset "github.com/deckarep/golang-set" ) type Entry struct { Patterns []string OutputDigits []string } func (e *Entry) Solve() (int, error) { var digits [10]mapset.Set fiveDigitPatterns, sixDigitPatterns := make([]string, 0, 3), make([]string, 0, 3) for _, p := range e.Patterns { switch len(p) { case 2: // 1 is the only digit using two segments digits[1] = patternToSet(p) case 3: // 7 is the only digit using three segments digits[7] = patternToSet(p) case 4: // 4 is the only digit using four segments digits[4] = patternToSet(p) case 5: fiveDigitPatterns = append(fiveDigitPatterns, p) case 6: sixDigitPatterns = append(sixDigitPatterns, p) case 7: // 8 is the only digit using seven segments digits[8] = patternToSet(p) } } // 9 is the only six-segment superset of 4. Find it and remove it from // sixDigitPatterns var j int for _, p := range sixDigitPatterns { candidate := patternToSet(p) if candidate.IsSuperset(digits[4]) { digits[9] = candidate } else { sixDigitPatterns[j] = p j++ } } sixDigitPatterns = sixDigitPatterns[:j] // Now that 9 has been identified, 0 is the only remaining six-segment // superset of 1. Once we've identified 0, the other must be 6 p0, p1 := patternToSet(sixDigitPatterns[0]), patternToSet(sixDigitPatterns[1]) if p0.IsSuperset(digits[1]) { digits[0] = p0 digits[6] = p1 } else { digits[0] = p1 digits[6] = p0 } for _, p := range fiveDigitPatterns { digit := patternToSet(p) if digit.IsSuperset(digits[1]) { // 3 is the only five-segment superset of 1 (and 7, in fact - either // would work) digits[3] = digit } else if digit.IsSubset(digits[6]) { // 5 is the only five-segment subset of 6 digits[5] = digit } else { // 2 is neither 3 nor 5 digits[2] = digit } } var n int digit: for i, d := range e.OutputDigits { ourDigit := patternToSet(d) for candidateDigit, candidateDigitSet := range digits { if ourDigit.Equal(candidateDigitSet) { n += candidateDigit * int(math.Pow10(len(e.OutputDigits)-(i+1))) continue digit } } return 0, fmt.Errorf("day08: failed to map %s to a digit", d) } return n, nil } func patternToSet(pattern string) mapset.Set { set := mapset.NewSet() for _, c := range pattern { set.Add(c) } return set }
day08/entry.go
0.582966
0.549822
entry.go
starcoder
package arbor import ( "encoding/json" "fmt" ) const ( // WelcomeType should be used as the `Type` field of a WELCOME ProtocolMessage WelcomeType = 0 // QueryType should be used as the `Type` field of a QUERY ProtocolMessage QueryType = 1 // NewMessageType should be used as the `Type` field of a NEW_MESSAGE ProtocolMessage NewMessageType = 2 // NewType is the `Type` of a NEW Message NewType = 2 // MetaType is the `Type` of a META Message MetaType = 3 ) // Message is a protocol-layer message in Arbor type Message ProtocolMessage // ProtocolMessage represents a message in the Arbor chat protocol. This may or // may not contain a chat message sent between users. type ProtocolMessage struct { // Root is only used in WELCOME messages and identifies the root of this server's message tree Root string // Recent is only used in WELCOME messages and provides a list of recently-sent message ids Recent []string // The type of the message, should be one of the constants defined in this // package. Type uint8 // Major is only used in WELCOME messages and identifies the major version number of the protocol version in use Major uint8 // Minor is only used in WELCOME messages and identifies the minor version number of the protocol version in use Minor uint8 // Message is the actual chat message content, if any. This is currently only // used in NEW_MESSAGE messages *ChatMessage // Meta is the `Meta` field in META type arbor messages. Meta map[string]string } // Equals returns true if other is equivalent to the message (has the same data or is the same message) func (m *ProtocolMessage) Equals(other *ProtocolMessage) bool { if (m == nil) != (other == nil) { // one is nil and the other is not return false } if m == other { // either both nil or pointers to the same address return true } if m.Type != other.Type || m.Root != other.Root || m.Major != other.Major || m.Minor != other.Minor { return false } if !m.ChatMessage.Equals(other.ChatMessage) { return false } if !sameSlice(m.Recent, other.Recent) { return false } if !sameMap(m.Meta, other.Meta) { return false } return true } // Source: https://stackoverflow.com/a/15312097 func sameSlice(a, b []string) bool { if (a == nil) != (b == nil) { return false } if len(a) != len(b) { return false } for i, v := range a { if v != b[i] { return false } } return true } func sameMap(a, b map[string]string) bool { if (a == nil) != (b == nil) { return false } if len(a) != len(b) { return false } for key, val := range a { if val != b[key] { return false } } return true } // MarshalJSON transforms a ProtocolMessage into JSON func (m *ProtocolMessage) MarshalJSON() ([]byte, error) { switch m.Type { case WelcomeType: return json.Marshal(struct { Root string Recent []string Type uint8 Major uint8 Minor uint8 }{Type: m.Type, Root: m.Root, Recent: m.Recent, Major: m.Major, Minor: m.Minor}) case QueryType: return json.Marshal(struct { UUID string Type uint8 }{UUID: m.UUID, Type: m.Type}) case NewMessageType: return json.Marshal(struct { *ChatMessage Type uint8 }{ChatMessage: m.ChatMessage, Type: m.Type}) case MetaType: return json.Marshal(struct { Meta map[string]string Type uint8 }{Type: m.Type, Meta: m.Meta}) default: return nil, fmt.Errorf("Unknown message type, could not marshal") } } // String returns a JSON representation of the message as a string. func (m *ProtocolMessage) String() string { data, _ := json.Marshal(m) // nolint: gosec dataString := string(data) return dataString } // IsValid returns whether the message has the minimum correct fields for its message // type. func (m *ProtocolMessage) IsValid() bool { switch m.Type { case WelcomeType: return m.IsValidWelcome() case QueryType: return m.IsValidQuery() case NewMessageType: return m.IsValidNew() case MetaType: return m.IsValidMeta() default: return false } } // IsValidWelcome checks that the message is a valid Welcome message. func (m *ProtocolMessage) IsValidWelcome() bool { switch { case m.Type != WelcomeType: fallthrough case m.Major == 0 && m.Minor == 0: fallthrough case m.Recent == nil: fallthrough case m.Meta != nil && len(m.Meta) != 0: fallthrough case m.Root == "": return false } return true } // IsValidNew checks that the message is a valid New message. func (m *ProtocolMessage) IsValidNew() bool { switch { case m.Type != NewMessageType: fallthrough case m.ChatMessage == nil: fallthrough case m.Username == "": fallthrough case m.Content == "": fallthrough case m.Meta != nil && len(m.Meta) != 0: fallthrough case m.Timestamp == 0: return false } return true } // IsValidQuery checks that the message is a valid Query message. func (m *ProtocolMessage) IsValidQuery() bool { switch { case m.Type != QueryType: fallthrough case m.ChatMessage == nil: fallthrough case m.Meta != nil && len(m.Meta) != 0: fallthrough case m.UUID == "": return false } return true } // IsValidMeta returns whether the message is valid as a META-type protocol message. func (m *ProtocolMessage) IsValidMeta() bool { switch { case m.Type != MetaType: fallthrough case m.Meta == nil: fallthrough case m.ChatMessage != nil: fallthrough case m.Major != 0 || m.Minor != 0: fallthrough case m.Root != "": fallthrough case m.Recent != nil: return false } return true }
protocol_message.go
0.567218
0.428174
protocol_message.go
starcoder
package pgsql import ( "database/sql" "database/sql/driver" ) // TSVectorArrayFromStringSliceSlice returns a driver.Valuer that produces a PostgreSQL tsvector[] from the given Go [][]string. func TSVectorArrayFromStringSliceSlice(val [][]string) driver.Valuer { return tsVectorArrayFromStringSliceSlice{val: val} } // TSVectorArrayToStringSliceSlice returns an sql.Scanner that converts a PostgreSQL tsvector[] into a Go [][]string and sets it to val. func TSVectorArrayToStringSliceSlice(val *[][]string) sql.Scanner { return tsVectorArrayToStringSliceSlice{val: val} } // TSVectorArrayFromByteSliceSliceSlice returns a driver.Valuer that produces a PostgreSQL tsvector[] from the given Go [][][]byte. func TSVectorArrayFromByteSliceSliceSlice(val [][][]byte) driver.Valuer { return tsVectorArrayFromByteSliceSliceSlice{val: val} } // TSVectorArrayToByteSliceSliceSlice returns an sql.Scanner that converts a PostgreSQL tsvector[] into a Go [][][]byte and sets it to val. func TSVectorArrayToByteSliceSliceSlice(val *[][][]byte) sql.Scanner { return tsVectorArrayToByteSliceSliceSlice{val: val} } type tsVectorArrayFromStringSliceSlice struct { val [][]string } func (v tsVectorArrayFromStringSliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } size := (2 + (len(v.val) - 1)) // curly braces + number of commas for i := 0; i < len(v.val); i++ { if v.val[i] == nil { size += 4 // len(`NULL`) } else if len(v.val[i]) == 0 { size += 2 // len(`""`) } else { size += (2 + (len(v.val[i]) - 1)) // double quotes + number of spaces for j := 0; j < len(v.val[i]); j++ { size += len(v.val[i][j]) } } } out := make([]byte, size) out[0] = '{' var pos int for i := 0; i < len(v.val); i++ { if v.val[i] == nil { out[pos+1] = 'N' out[pos+2] = 'U' out[pos+3] = 'L' out[pos+4] = 'L' out[pos+5] = ',' pos += 5 continue } if len(v.val[i]) == 0 { out[pos+1] = '"' out[pos+2] = '"' out[pos+3] = ',' pos += 3 continue } pos += 1 out[pos] = '"' for j, num := 0, len(v.val[i]); j < num; j++ { pos += 1 length := len(v.val[i][j]) copy(out[pos:pos+length], v.val[i][j]) pos += length out[pos] = ' ' } out[pos] = '"' pos += 1 out[pos] = ',' } out[pos] = '}' return out, nil } type tsVectorArrayToStringSliceSlice struct { val *[][]string } func (v tsVectorArrayToStringSliceSlice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { *v.val = nil return nil } elems := pgParseVectorArray(data) stringss := make([][]string, len(elems)) for i := 0; i < len(elems); i++ { if elems[i] == nil { continue } if len(elems[i]) == 1 && len(elems[i][0]) == 0 { stringss[i] = []string{} continue } strings := make([]string, len(elems[i])) for j := 0; j < len(elems[i]); j++ { strings[j] = string(elems[i][j]) } stringss[i] = strings } *v.val = stringss return nil } type tsVectorArrayFromByteSliceSliceSlice struct { val [][][]byte } func (v tsVectorArrayFromByteSliceSliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } size := (2 + (len(v.val) - 1)) // curly braces + number of commas for i := 0; i < len(v.val); i++ { if v.val[i] == nil { size += 4 // len(`NULL`) } else if len(v.val[i]) == 0 { size += 2 // len(`""`) } else { size += (2 + (len(v.val[i]) - 1)) // double quotes + number of spaces for j := 0; j < len(v.val[i]); j++ { size += len(v.val[i][j]) } } } out := make([]byte, size) out[0] = '{' var pos int for i := 0; i < len(v.val); i++ { if v.val[i] == nil { out[pos+1] = 'N' out[pos+2] = 'U' out[pos+3] = 'L' out[pos+4] = 'L' out[pos+5] = ',' pos += 5 continue } if len(v.val[i]) == 0 { out[pos+1] = '"' out[pos+2] = '"' out[pos+3] = ',' pos += 3 continue } pos += 1 out[pos] = '"' for j, num := 0, len(v.val[i]); j < num; j++ { pos += 1 length := len(v.val[i][j]) copy(out[pos:pos+length], v.val[i][j]) pos += length out[pos] = ' ' } out[pos] = '"' pos += 1 out[pos] = ',' } out[pos] = '}' return out, nil } type tsVectorArrayToByteSliceSliceSlice struct { val *[][][]byte } func (v tsVectorArrayToByteSliceSliceSlice) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { *v.val = nil return nil } elems := pgParseVectorArray(data) bytesss := make([][][]byte, len(elems)) for i := 0; i < len(elems); i++ { if elems[i] == nil { continue } if len(elems[i]) == 1 && len(elems[i][0]) == 0 { bytesss[i] = [][]byte{} continue } bytess := make([][]byte, len(elems[i])) for j := 0; j < len(elems[i]); j++ { bytess[j] = make([]byte, len(elems[i][j])) copy(bytess[j], elems[i][j]) } bytesss[i] = bytess } *v.val = bytesss return nil }
pgsql/tsvectorarr.go
0.596081
0.643238
tsvectorarr.go
starcoder
package block import ( "github.com/df-mc/dragonfly/dragonfly/world" ) // Crop is an interface for all crops that are grown on farmland. A crop has a random chance to grow during random ticks. type Crop interface { // GrowthStage returns the crop's current stage of growth. The max value is 7. GrowthStage() int // SameCrop checks if two crops are of the same type. SameCrop(c Crop) bool } // crop is a base for crop plants. type crop struct { noNBT transparent empty // Growth is the current stage of growth. The max value is 7. Growth int } // NeighbourUpdateTick ... func (c crop) NeighbourUpdateTick(pos, _ world.BlockPos, w *world.World) { if _, ok := w.Block(pos.Side(world.FaceDown)).(Farmland); !ok { w.BreakBlockWithoutParticles(pos) } } // HasLiquidDrops ... func (c crop) HasLiquidDrops() bool { return true } // GrowthStage returns the current stage of growth. func (c crop) GrowthStage() int { return c.Growth } // CalculateGrowthChance calculates the chance the crop will grow during a random tick. func (c crop) CalculateGrowthChance(pos world.BlockPos, w *world.World) float64 { points := 0.0 block := w.Block(pos) under := pos.Side(world.FaceDown) for x := -1; x <= 1; x++ { for z := -1; z <= 1; z++ { block := w.Block(under.Add(world.BlockPos{x, 0, z})) if farmland, ok := block.(Farmland); ok { farmlandPoints := 0.0 if farmland.Hydration > 0 { farmlandPoints = 4 } else { farmlandPoints = 2 } if x != 0 || z != 0 { farmlandPoints = (farmlandPoints - 1) / 4 } points += farmlandPoints } } } north := pos.Side(world.FaceNorth) south := pos.Side(world.FaceSouth) northSouth := sameCrop(block, w.Block(north)) || sameCrop(block, w.Block(south)) westEast := sameCrop(block, w.Block(pos.Side(world.FaceWest))) || sameCrop(block, w.Block(pos.Side(world.FaceEast))) if northSouth && westEast { points /= 2 } else { diagonal := sameCrop(block, w.Block(north.Side(world.FaceWest))) || sameCrop(block, w.Block(north.Side(world.FaceEast))) || sameCrop(block, w.Block(south.Side(world.FaceWest))) || sameCrop(block, w.Block(south.Side(world.FaceEast))) if diagonal { points /= 2 } } chance := 1 / (25/points + 1) return chance } // sameCrop checks if both blocks are crops and that they are the same type. func sameCrop(blockA, blockB world.Block) bool { if a, ok := blockA.(Crop); ok { if b, ok := blockB.(Crop); ok { return a.SameCrop(b) } } return false } // min returns the smaller of the two integers passed. func min(a, b int) int { if a < b { return a } return b }
dragonfly/block/crop.go
0.786131
0.504944
crop.go
starcoder
package main import ( "math" ) type SunEventInfo struct { Hour, Minute int TimeZone string } func calculateDayOfYear(month int, day int, year int) int { var one = math.Floor((float64(275) * float64(month) / float64(9.0))) var two = math.Floor((float64(month) + float64(9)) / float64(12.0)) var three = (1 + math.Floor((float64(year)-float64(4)*math.Floor(float64(year)/float64(4))+float64(2))/float64(3))) return int(one) - int((two * three)) + day - 30 } func LongitudeHourToTime(day float64, lngHour float64, sunset bool) float64 { if sunset { return day + ((float64(18) - lngHour) / float64(24)) } return day + ((6 - lngHour) / 24) } func MeanAnomaly(time float64) float64 { return (.9856 * time) - 3.289 } func SunLongitude(meanAnomaly float64) float64 { var lng = meanAnomaly + (1.916 * math.Sin(meanAnomaly*math.Pi/180)) + (.02*math.Sin(2*meanAnomaly*math.Pi/180) + 282.634) if lng > 360 { return lng - 360 } if lng < 0 { return lng + 360 } return lng } func CalcLeftQuad(trueLong float64) float64 { var ninety float64 = 90.0 return math.Floor(trueLong/ninety) * ninety } func CalcRightQuad(RA float64) float64 { var ninety float64 = 90.0 return math.Floor(RA/ninety) * ninety } func RA_ToQuad(RA float64, trueLong float64) float64 { return RA + (CalcLeftQuad(trueLong) - CalcRightQuad(RA)) } func RightAscenion(trueLong float64) float64 { var sunTan float64 = math.Tan(trueLong * math.Pi / 180) var innerTan = .91764 * sunTan var RA float64 = math.Atan(innerTan) * (180 / math.Pi) RA = RA_ToQuad(RA, trueLong) / 15.0 if RA > 360 { RA -= 360 } else if RA < 0 { RA += 360 } return RA } func sinDec(trueLong float64) float64 { return .39782 * math.Sin(trueLong*math.Pi/180) } func cosDec(trueLong float64) float64 { SinDec := sinDec(trueLong) arcSin := math.Asin(SinDec) * 180 / math.Pi return math.Cos(arcSin * math.Pi / 180) } func LocalHourAngle(zenith, latitude, longitude, trueLong float64) float64 { sinLat := sinDec(trueLong) * math.Sin(latitude*math.Pi/180) numerator := zenith - sinLat denominator := cosDec(longitude) * math.Cos(latitude*math.Pi/180) angle := numerator / denominator return angle } func CalculateSunHour(localHour float64, sunset bool) float64 { var hour float64 if sunset { hour = math.Acos(localHour) * 180 / math.Pi } else { hour = 360 - math.Acos(localHour)*180/math.Pi } hour /= 15 return hour } func floatTimeToSplit(time float64) (int, int) { var hours int = int(time) var minFrac float64 = time - float64(hours) var minutes int = int(60 * minFrac) return hours, minutes } func CalculateSunTime(month, day, year int, zenith, lat, lng float64, sunset bool) SunEventInfo { dayOfYear := calculateDayOfYear(month, day, year) lngHour := lng / 15 time := LongitudeHourToTime(float64(dayOfYear), lngHour, sunset) anomaly := MeanAnomaly(time) trueLongitude := SunLongitude(anomaly) RA := RightAscenion(trueLongitude) localHour := LocalHourAngle(zenith, lat, lng, trueLongitude) var hour float64 = CalculateSunHour(localHour, sunset) localEventTime := (hour + RA) - (.06571 * time) - 6.62 UTC := localEventTime - lngHour if UTC < 0 { UTC += 24 } else if UTC > 24 { UTC -= 24 } hours, minutes := floatTimeToSplit(UTC) return SunEventInfo{Hour: hours, Minute: minutes, TimeZone: "UTC"} }
suncalculator.go
0.720368
0.460592
suncalculator.go
starcoder
package service import "github.com/GoogleCloudPlatform/compute-image-tools/proto/go/pb" type literalLoggable struct { strings map[string]string int64s map[string][]int64 bools map[string]bool traceLogs []string inspectionResults *pb.InspectionResults } func (w literalLoggable) GetInspectionResults() *pb.InspectionResults { return w.inspectionResults } func (w literalLoggable) GetValue(key string) string { return w.strings[key] } func (w literalLoggable) GetValueAsBool(key string) bool { return w.bools[key] } func (w literalLoggable) GetValueAsInt64Slice(key string) []int64 { return w.int64s[key] } func (w literalLoggable) ReadSerialPortLogs() []string { return w.traceLogs } // SingleImageImportLoggableBuilder initializes and builds a Loggable with the metadata // fields that are relevant when importing a single image. type SingleImageImportLoggableBuilder struct { literalLoggable } // NewSingleImageImportLoggableBuilder creates and initializes a SingleImageImportLoggableBuilder. func NewSingleImageImportLoggableBuilder() *SingleImageImportLoggableBuilder { return &SingleImageImportLoggableBuilder{literalLoggable{ strings: map[string]string{}, int64s: map[string][]int64{}, bools: map[string]bool{}, }} } // SetInspectionResults sets inspection results. func (b *SingleImageImportLoggableBuilder) SetInspectionResults(inspectionResults *pb.InspectionResults) *SingleImageImportLoggableBuilder { b.inspectionResults = inspectionResults return b } // SetUEFIMetrics sets UEFI related metrics. func (b *SingleImageImportLoggableBuilder) SetUEFIMetrics(isUEFICompatibleImageBool bool, isUEFIDetectedBool bool, biosBootableBool bool, rootFSString string) *SingleImageImportLoggableBuilder { b.bools[isUEFICompatibleImage] = isUEFICompatibleImageBool b.bools[isUEFIDetected] = isUEFIDetectedBool b.bools[uefiBootable] = isUEFIDetectedBool b.bools[biosBootable] = biosBootableBool b.strings[rootFS] = rootFSString return b } // SetDiskAttributes sets disk related attributes. func (b *SingleImageImportLoggableBuilder) SetDiskAttributes(fileFormat string, sourceSize int64, targetSize int64) *SingleImageImportLoggableBuilder { b.strings[importFileFormat] = fileFormat b.int64s[sourceSizeGb] = []int64{sourceSize} b.int64s[targetSizeGb] = []int64{targetSize} return b } // SetInflationAttributes sets inflation related attributes. func (b *SingleImageImportLoggableBuilder) SetInflationAttributes(matchResult string, inflationTypeStr string, inflationTimeInt64 int64, shadowInflationTimeInt64 int64) *SingleImageImportLoggableBuilder { b.strings[inflationType] = inflationTypeStr b.strings[shadowDiskMatchResult] = matchResult b.int64s[inflationTime] = []int64{inflationTimeInt64} b.int64s[shadowInflationTime] = []int64{shadowInflationTimeInt64} return b } // AppendTraceLogs sets trace logs during the import. func (b *SingleImageImportLoggableBuilder) AppendTraceLogs(traceLogs []string) *SingleImageImportLoggableBuilder { if b.traceLogs != nil { b.traceLogs = append(b.traceLogs, traceLogs...) } else { b.traceLogs = traceLogs } return b } // Build builds the actual Loggable object. func (b *SingleImageImportLoggableBuilder) Build() Loggable { return b.literalLoggable }
cli_tools/common/utils/logging/service/literal_loggable.go
0.658857
0.440108
literal_loggable.go
starcoder
package internal import ( "fmt" ) var ( squareDigitToLetterLat map[int]string squareLetterToDigitLat map[string]float64 squareDigitToLetterLon map[int]string squareLetterToDigitLon map[string]float64 squareDegLatitudes = [...]float64{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, } squareDegLongitudes = [...]float64{ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, } ) func init() { squareDigitToLetterLat = map[int]string{ 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", } squareLetterToDigitLat = map[string]float64{ "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, } squareDigitToLetterLon = map[int]string{ 0: "0", 1: "0", 2: "1", 3: "1", 4: "2", 5: "2", 6: "3", 7: "3", 8: "4", 9: "4", 10: "5", 11: "5", 12: "6", 13: "6", 14: "7", 15: "7", 16: "8", 17: "8", 18: "9", 19: "9", } squareLetterToDigitLon = map[string]float64{ "0": 0, "1": 2, "2": 4, "3": 6, "4": 8, "5": 10, "6": 12, "7": 14, "8": 16, "9": 18, } } type Square struct { // characters {0,1,...9} Decoded as // longitude {0,2...,18} [degree] // latitude {0,1...,9) [degree] Decoded LatLonDeg //characters Decoded as longitude and latitude Encoded LatLonChar //latitude and longitude Encoded as characters } func (a Square) String() string { s := "" if a.Decoded.String() != "" { s = fmt.Sprintf("Decoded:%s", a.Decoded.String()) } if a.Encoded.String() != "" { if s == "" { s = fmt.Sprintf("Encoded:%s", a.Encoded.String()) } else { s += fmt.Sprintf(" Encoded:%s", a.Encoded.String()) } } return s } func SquareEncode(lld LatLonDeg) (Field, Square) { s := Square{} f := FieldEncode(lld) iLat, iLon := 0, 0 fLat := lld.Lat - f.Decoded.Lat fLon := lld.Lon - f.Decoded.Lon for _, v := range squareDegLongitudes { if fLon >= v && fLon < v+2 { iLon = int(v) break } } for _, v := range squareDegLatitudes { if fLat >= v && fLat < v+1 { iLat = int(v) break } } s.Encoded.setLatChar(squareDigitToLetterLat[iLat]) s.Encoded.setLonChar(squareDigitToLetterLon[iLon]) s.Decoded.Lat = float64(iLat) s.Decoded.Lon = float64(iLon) return f, s } func SquareDecode(llc LatLonChar) Square { s := Square{} s.Decoded.Lat = squareLetterToDigitLat[llc.GetLatChar()] s.Decoded.Lon = squareLetterToDigitLon[llc.GetLonChar()] s.Encoded = llc return s }
geo/internal/square.go
0.568176
0.487368
square.go
starcoder
package infobip import ( "encoding/json" ) // TfaApplicationConfiguration struct for TfaApplicationConfiguration type TfaApplicationConfiguration struct { // Tells if multiple PIN verifications are allowed. AllowMultiplePinVerifications *bool `json:"allowMultiplePinVerifications,omitempty"` // Number of possible PIN attempts. PinAttempts *int32 `json:"pinAttempts,omitempty"` // PIN time to live. Should be in format of `{timeLength}{timeUnit}`. Here `timeLength` is an optional positive integer with a default value of 1 and `timeUnit` is one of: `ms`, `s`, `m`, `h` or `d` representing milliseconds, seconds, minutes, hours and days respectively. Must not be larger that one year, although much lower values are recommended. PinTimeToLive *string `json:"pinTimeToLive,omitempty"` // Overall number of requests in time interval for generating a PIN and sending an SMS using single application. Should be in format of `{attempts}/{timeLength}{timeUnit}`. Here `attempts` is a mandatory positive integer and `timeLength` is an optional positive integer with a default value of 1. `timeUnit` is one of: `ms`, `s`, `m`, `h` or `d` representing milliseconds, seconds, minutes, hours and days respectively. Time component must not be larger that one year, although much lower values are recommended. SendPinPerApplicationLimit *string `json:"sendPinPerApplicationLimit,omitempty"` // Number of requests in time interval for generating a PIN and sending an SMS to one phone number (MSISDN). Should be in format of `{attempts}/{timeLength}{timeUnit}`. Here `attempts` is a mandatory positive integer and `timeLength` is an optional positive integer with a default value of 1. `timeUnit` is one of: `ms`, `s`, `m`, `h` or `d` representing milliseconds, seconds, minutes, hours and days respectively. Time component must not be larger that one year, although much lower values are recommended. SendPinPerPhoneNumberLimit *string `json:"sendPinPerPhoneNumberLimit,omitempty"` // Number of PIN verification requests in time interval from one phone number (MSISDN). Should be in format of `{attempts}/{timeLength}{timeUnit}`. Here `attempts` is a mandatory positive integer and `timeLength` is an optional positive integer with a default value of 1. `timeUnit` is one of: `ms`, `s`, `m`, `h` or `d` representing milliseconds, seconds, minutes, hours and days respectively. Time component must not be larger that one day, although much lower values are recommended. VerifyPinLimit *string `json:"verifyPinLimit,omitempty"` } // NewTfaApplicationConfiguration instantiates a new TfaApplicationConfiguration 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 NewTfaApplicationConfiguration() *TfaApplicationConfiguration { this := TfaApplicationConfiguration{} var allowMultiplePinVerifications bool = true this.AllowMultiplePinVerifications = &allowMultiplePinVerifications var pinAttempts int32 = 10 this.PinAttempts = &pinAttempts var pinTimeToLive string = "15m" this.PinTimeToLive = &pinTimeToLive var sendPinPerApplicationLimit string = "10000/1d" this.SendPinPerApplicationLimit = &sendPinPerApplicationLimit var sendPinPerPhoneNumberLimit string = "3/1d" this.SendPinPerPhoneNumberLimit = &sendPinPerPhoneNumberLimit var verifyPinLimit string = "1/3s" this.VerifyPinLimit = &verifyPinLimit return &this } // NewTfaApplicationConfigurationWithDefaults instantiates a new TfaApplicationConfiguration 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 NewTfaApplicationConfigurationWithDefaults() *TfaApplicationConfiguration { this := TfaApplicationConfiguration{} var allowMultiplePinVerifications bool = true this.AllowMultiplePinVerifications = &allowMultiplePinVerifications var pinAttempts int32 = 10 this.PinAttempts = &pinAttempts var pinTimeToLive string = "15m" this.PinTimeToLive = &pinTimeToLive var sendPinPerApplicationLimit string = "10000/1d" this.SendPinPerApplicationLimit = &sendPinPerApplicationLimit var sendPinPerPhoneNumberLimit string = "3/1d" this.SendPinPerPhoneNumberLimit = &sendPinPerPhoneNumberLimit var verifyPinLimit string = "1/3s" this.VerifyPinLimit = &verifyPinLimit return &this } // GetAllowMultiplePinVerifications returns the AllowMultiplePinVerifications field value if set, zero value otherwise. func (o *TfaApplicationConfiguration) GetAllowMultiplePinVerifications() bool { if o == nil || o.AllowMultiplePinVerifications == nil { var ret bool return ret } return *o.AllowMultiplePinVerifications } // GetAllowMultiplePinVerificationsOk returns a tuple with the AllowMultiplePinVerifications field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TfaApplicationConfiguration) GetAllowMultiplePinVerificationsOk() (*bool, bool) { if o == nil || o.AllowMultiplePinVerifications == nil { return nil, false } return o.AllowMultiplePinVerifications, true } // HasAllowMultiplePinVerifications returns a boolean if a field has been set. func (o *TfaApplicationConfiguration) HasAllowMultiplePinVerifications() bool { if o != nil && o.AllowMultiplePinVerifications != nil { return true } return false } // SetAllowMultiplePinVerifications gets a reference to the given bool and assigns it to the AllowMultiplePinVerifications field. func (o *TfaApplicationConfiguration) SetAllowMultiplePinVerifications(v bool) { o.AllowMultiplePinVerifications = &v } // GetPinAttempts returns the PinAttempts field value if set, zero value otherwise. func (o *TfaApplicationConfiguration) GetPinAttempts() int32 { if o == nil || o.PinAttempts == nil { var ret int32 return ret } return *o.PinAttempts } // GetPinAttemptsOk returns a tuple with the PinAttempts field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TfaApplicationConfiguration) GetPinAttemptsOk() (*int32, bool) { if o == nil || o.PinAttempts == nil { return nil, false } return o.PinAttempts, true } // HasPinAttempts returns a boolean if a field has been set. func (o *TfaApplicationConfiguration) HasPinAttempts() bool { if o != nil && o.PinAttempts != nil { return true } return false } // SetPinAttempts gets a reference to the given int32 and assigns it to the PinAttempts field. func (o *TfaApplicationConfiguration) SetPinAttempts(v int32) { o.PinAttempts = &v } // GetPinTimeToLive returns the PinTimeToLive field value if set, zero value otherwise. func (o *TfaApplicationConfiguration) GetPinTimeToLive() string { if o == nil || o.PinTimeToLive == nil { var ret string return ret } return *o.PinTimeToLive } // GetPinTimeToLiveOk returns a tuple with the PinTimeToLive field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TfaApplicationConfiguration) GetPinTimeToLiveOk() (*string, bool) { if o == nil || o.PinTimeToLive == nil { return nil, false } return o.PinTimeToLive, true } // HasPinTimeToLive returns a boolean if a field has been set. func (o *TfaApplicationConfiguration) HasPinTimeToLive() bool { if o != nil && o.PinTimeToLive != nil { return true } return false } // SetPinTimeToLive gets a reference to the given string and assigns it to the PinTimeToLive field. func (o *TfaApplicationConfiguration) SetPinTimeToLive(v string) { o.PinTimeToLive = &v } // GetSendPinPerApplicationLimit returns the SendPinPerApplicationLimit field value if set, zero value otherwise. func (o *TfaApplicationConfiguration) GetSendPinPerApplicationLimit() string { if o == nil || o.SendPinPerApplicationLimit == nil { var ret string return ret } return *o.SendPinPerApplicationLimit } // GetSendPinPerApplicationLimitOk returns a tuple with the SendPinPerApplicationLimit field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TfaApplicationConfiguration) GetSendPinPerApplicationLimitOk() (*string, bool) { if o == nil || o.SendPinPerApplicationLimit == nil { return nil, false } return o.SendPinPerApplicationLimit, true } // HasSendPinPerApplicationLimit returns a boolean if a field has been set. func (o *TfaApplicationConfiguration) HasSendPinPerApplicationLimit() bool { if o != nil && o.SendPinPerApplicationLimit != nil { return true } return false } // SetSendPinPerApplicationLimit gets a reference to the given string and assigns it to the SendPinPerApplicationLimit field. func (o *TfaApplicationConfiguration) SetSendPinPerApplicationLimit(v string) { o.SendPinPerApplicationLimit = &v } // GetSendPinPerPhoneNumberLimit returns the SendPinPerPhoneNumberLimit field value if set, zero value otherwise. func (o *TfaApplicationConfiguration) GetSendPinPerPhoneNumberLimit() string { if o == nil || o.SendPinPerPhoneNumberLimit == nil { var ret string return ret } return *o.SendPinPerPhoneNumberLimit } // GetSendPinPerPhoneNumberLimitOk returns a tuple with the SendPinPerPhoneNumberLimit field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TfaApplicationConfiguration) GetSendPinPerPhoneNumberLimitOk() (*string, bool) { if o == nil || o.SendPinPerPhoneNumberLimit == nil { return nil, false } return o.SendPinPerPhoneNumberLimit, true } // HasSendPinPerPhoneNumberLimit returns a boolean if a field has been set. func (o *TfaApplicationConfiguration) HasSendPinPerPhoneNumberLimit() bool { if o != nil && o.SendPinPerPhoneNumberLimit != nil { return true } return false } // SetSendPinPerPhoneNumberLimit gets a reference to the given string and assigns it to the SendPinPerPhoneNumberLimit field. func (o *TfaApplicationConfiguration) SetSendPinPerPhoneNumberLimit(v string) { o.SendPinPerPhoneNumberLimit = &v } // GetVerifyPinLimit returns the VerifyPinLimit field value if set, zero value otherwise. func (o *TfaApplicationConfiguration) GetVerifyPinLimit() string { if o == nil || o.VerifyPinLimit == nil { var ret string return ret } return *o.VerifyPinLimit } // GetVerifyPinLimitOk returns a tuple with the VerifyPinLimit field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *TfaApplicationConfiguration) GetVerifyPinLimitOk() (*string, bool) { if o == nil || o.VerifyPinLimit == nil { return nil, false } return o.VerifyPinLimit, true } // HasVerifyPinLimit returns a boolean if a field has been set. func (o *TfaApplicationConfiguration) HasVerifyPinLimit() bool { if o != nil && o.VerifyPinLimit != nil { return true } return false } // SetVerifyPinLimit gets a reference to the given string and assigns it to the VerifyPinLimit field. func (o *TfaApplicationConfiguration) SetVerifyPinLimit(v string) { o.VerifyPinLimit = &v } func (o TfaApplicationConfiguration) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.AllowMultiplePinVerifications != nil { toSerialize["allowMultiplePinVerifications"] = o.AllowMultiplePinVerifications } if o.PinAttempts != nil { toSerialize["pinAttempts"] = o.PinAttempts } if o.PinTimeToLive != nil { toSerialize["pinTimeToLive"] = o.PinTimeToLive } if o.SendPinPerApplicationLimit != nil { toSerialize["sendPinPerApplicationLimit"] = o.SendPinPerApplicationLimit } if o.SendPinPerPhoneNumberLimit != nil { toSerialize["sendPinPerPhoneNumberLimit"] = o.SendPinPerPhoneNumberLimit } if o.VerifyPinLimit != nil { toSerialize["verifyPinLimit"] = o.VerifyPinLimit } return json.Marshal(toSerialize) } type NullableTfaApplicationConfiguration struct { value *TfaApplicationConfiguration isSet bool } func (v NullableTfaApplicationConfiguration) Get() *TfaApplicationConfiguration { return v.value } func (v *NullableTfaApplicationConfiguration) Set(val *TfaApplicationConfiguration) { v.value = val v.isSet = true } func (v NullableTfaApplicationConfiguration) IsSet() bool { return v.isSet } func (v *NullableTfaApplicationConfiguration) Unset() { v.value = nil v.isSet = false } func NewNullableTfaApplicationConfiguration(val *TfaApplicationConfiguration) *NullableTfaApplicationConfiguration { return &NullableTfaApplicationConfiguration{value: val, isSet: true} } func (v NullableTfaApplicationConfiguration) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableTfaApplicationConfiguration) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
v2/model_tfa_application_configuration.go
0.841207
0.470858
model_tfa_application_configuration.go
starcoder
package steps import ( "bufio" "bytes" "math" "github.com/antongulenko/go-onlinestats" "github.com/bitflow-stream/go-bitflow/bitflow" "gonum.org/v1/gonum/mat" ) func ValuesToVector(input []bitflow.Value) []float64 { values := make([]float64, len(input)) for i, val := range input { values[i] = float64(val) } return values } func SampleToVector(sample *bitflow.Sample) []float64 { return ValuesToVector(sample.Values) } func FillSample(s *bitflow.Sample, values []float64) { s.Resize(len(values)) for i, val := range values { s.Values[i] = bitflow.Value(val) } } func AppendToSample(s *bitflow.Sample, values []float64) { oldValues := s.Values l := len(s.Values) if !s.Resize(l + len(values)) { copy(s.Values, oldValues) } for i, val := range values { s.Values[l+i] = bitflow.Value(val) } } func IsValidNumber(val float64) bool { return !math.IsNaN(val) && !math.IsInf(val, 0) } func FillSampleFromMatrix(s *bitflow.Sample, row int, mat *mat.Dense) { FillSample(s, mat.RawRowView(row)) } func FillSamplesFromMatrix(s []*bitflow.Sample, mat *mat.Dense) { for i, sample := range s { FillSampleFromMatrix(sample, i, mat) } } const _nul = rune(0) func SplitShellCommand(s string) []string { scanner := bufio.NewScanner(bytes.NewBuffer([]byte(s))) scanner.Split(bufio.ScanRunes) var res []string var buf bytes.Buffer quote := _nul for scanner.Scan() { r := rune(scanner.Text()[0]) flush := false switch quote { case _nul: switch r { case ' ', '\t', '\r', '\n': flush = true case '"', '\'': quote = r flush = true } case '"', '\'': if r == quote { flush = true quote = _nul } } if flush { if buf.Len() > 0 { res = append(res, buf.String()) buf.Reset() } } else { buf.WriteRune(r) } } // Un-closed quotes are ignored if buf.Len() > 0 { res = append(res, buf.String()) } return res } type FeatureStats struct { onlinestats.Running Min float64 Max float64 } func NewFeatureStats() *FeatureStats { result := new(FeatureStats) result.Reset() return result } func (stats *FeatureStats) Reset() { stats.Running = onlinestats.Running{} stats.Min = math.MaxFloat64 stats.Max = -math.MaxFloat64 } func (stats *FeatureStats) Push(values ...float64) { for _, value := range values { stats.Running.Push(value) stats.Min = math.Min(stats.Min, value) stats.Max = math.Max(stats.Max, value) } } func (stats *FeatureStats) ScaleMinMax(val float64, outputMin, outputMax float64) float64 { return ScaleMinMax(val, stats.Min, stats.Max, outputMin, outputMax) } func (stats *FeatureStats) ScaleStddev(val float64) float64 { return ScaleStddev(val, stats.Mean(), stats.Stddev(), stats.Min, stats.Max) } func GetMinMax(header *bitflow.Header, samples []*bitflow.Sample) ([]float64, []float64) { min := make([]float64, len(header.Fields)) max := make([]float64, len(header.Fields)) for num := range header.Fields { min[num] = math.MaxFloat64 max[num] = -math.MaxFloat64 } for _, sample := range samples { for i, val := range sample.Values { min[i] = math.Min(min[i], float64(val)) max[i] = math.Max(max[i], float64(val)) } } return min, max } func GetStats(header *bitflow.Header, samples []*bitflow.Sample) []FeatureStats { res := make([]FeatureStats, len(header.Fields)) for i := range res { res[i].Reset() } for _, sample := range samples { for i, val := range sample.Values { res[i].Push(float64(val)) } } return res } func ScaleStddev(val float64, mean, stddev, min, max float64) float64 { res := (val - mean) / stddev if !IsValidNumber(res) { // Special case for zero standard deviation: fallback to min-max scaling res = ScaleMinMax(float64(val), min, max, -1, 1) } return res } func ScaleMinMax(val, min, max, outputMin, outputMax float64) float64 { res := (val - min) / (max - min) if IsValidNumber(res) { // res is now in 0..1, transpose it within the range outputMin..outputMax res = res*(outputMax-outputMin) + outputMin } else { res = (outputMax + outputMin) / 2 // min == max -> pick the middle } return res }
steps/helpers.go
0.606498
0.50769
helpers.go
starcoder
package compare import "github.com/benpate/derp" // Interface tries its best to muscle value2 and value2 into compatable types so that they can be compared. // If value1 is LESS THAN value2, it returns -1, nil // If value1 is EQUAL TO value2, it returns 0, nil // If value1 is GREATER THAN value2, it returns 1, nil // If the two values are not compatable, then it returns 0, [DERP] with an explanation of the error. // Currently, this function ONLLY compares identical numeric or string types. In the future, it *may* // be expanded to perform simple type converstions between similar types. func Interface(value1 interface{}, value2 interface{}) (int, error) { switch v1 := value1.(type) { case int: switch v2 := value2.(type) { case int: return Int64(int64(v1), int64(v2)), nil case int8: return Int64(int64(v1), int64(v2)), nil case int16: return Int64(int64(v1), int64(v2)), nil case int32: return Int64(int64(v1), int64(v2)), nil case int64: return Int64(int64(v1), int64(v2)), nil case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case int8: switch v2 := value2.(type) { case int: return Int64(int64(v1), int64(v2)), nil case int8: return Int64(int64(v1), int64(v2)), nil case int16: return Int64(int64(v1), int64(v2)), nil case int32: return Int64(int64(v1), int64(v2)), nil case int64: return Int64(int64(v1), int64(v2)), nil case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case int16: switch v2 := value2.(type) { case int: return Int64(int64(v1), int64(v2)), nil case int8: return Int64(int64(v1), int64(v2)), nil case int16: return Int64(int64(v1), int64(v2)), nil case int32: return Int64(int64(v1), int64(v2)), nil case int64: return Int64(int64(v1), int64(v2)), nil case uint: return UInt64(uint64(v1), uint64(v2)), nil case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case int32: switch v2 := value2.(type) { case int: return Int64(int64(v1), int64(v2)), nil case int8: return Int64(int64(v1), int64(v2)), nil case int16: return Int64(int64(v1), int64(v2)), nil case int32: return Int64(int64(v1), int64(v2)), nil case int64: return Int64(int64(v1), int64(v2)), nil case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case int64: switch v2 := value2.(type) { case int: return Int64(int64(v1), int64(v2)), nil case int8: return Int64(int64(v1), int64(v2)), nil case int16: return Int64(int64(v1), int64(v2)), nil case int32: return Int64(int64(v1), int64(v2)), nil case int64: return Int64(int64(v1), int64(v2)), nil case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case uint: switch v2 := value2.(type) { case uint: return UInt64(uint64(v1), uint64(v2)), nil case uint8: return UInt64(uint64(v1), uint64(v2)), nil case uint16: return UInt64(uint64(v1), uint64(v2)), nil case uint32: return UInt64(uint64(v1), uint64(v2)), nil case uint64: return UInt64(uint64(v1), v2), nil // TODO: range checking? case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case uint8: switch v2 := value2.(type) { case uint: return UInt64(uint64(v1), uint64(v2)), nil case uint8: return UInt64(uint64(v1), uint64(v2)), nil case uint16: return UInt64(uint64(v1), uint64(v2)), nil case uint32: return UInt64(uint64(v1), uint64(v2)), nil case uint64: return UInt64(uint64(v1), v2), nil // TODO: range checking? case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case uint16: switch v2 := value2.(type) { case uint: return UInt64(uint64(v1), uint64(v2)), nil case uint8: return UInt64(uint64(v1), uint64(v2)), nil case uint16: return UInt64(uint64(v1), uint64(v2)), nil case uint32: return UInt64(uint64(v1), uint64(v2)), nil case uint64: return UInt64(uint64(v1), v2), nil // TODO: range checking? case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case uint32: switch v2 := value2.(type) { case uint: return UInt64(uint64(v1), uint64(v2)), nil case uint8: return UInt64(uint64(v1), uint64(v2)), nil case uint16: return UInt64(uint64(v1), uint64(v2)), nil case uint32: return UInt64(uint64(v1), uint64(v2)), nil case uint64: return UInt64(uint64(v1), v2), nil // TODO: range checking? case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case uint64: switch v2 := value2.(type) { case uint: return UInt64(uint64(v1), uint64(v2)), nil case uint8: return UInt64(uint64(v1), uint64(v2)), nil case uint16: return UInt64(uint64(v1), uint64(v2)), nil case uint32: return UInt64(uint64(v1), uint64(v2)), nil case uint64: return UInt64(uint64(v1), v2), nil // TODO: range checking? case float32: return Float32(float32(v1), v2), nil case float64: return Float64(float64(v1), v2), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case float32: switch v2 := value2.(type) { case int: return Float64(float64(v1), float64(v2)), nil case int8: return Float64(float64(v1), float64(v2)), nil case int16: return Float64(float64(v1), float64(v2)), nil case int32: return Float64(float64(v1), float64(v2)), nil case int64: return Float64(float64(v1), float64(v2)), nil case uint: return Float64(float64(v1), float64(v2)), nil case uint8: return Float64(float64(v1), float64(v2)), nil case uint16: return Float64(float64(v1), float64(v2)), nil case uint32: return Float64(float64(v1), float64(v2)), nil case uint64: return Float64(float64(v1), float64(v2)), nil case float32: return Float64(float64(v1), float64(v2)), nil case float64: return Float64(float64(v1), float64(v2)), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case float64: switch v2 := value2.(type) { case int: return Float64(float64(v1), float64(v2)), nil case int8: return Float64(float64(v1), float64(v2)), nil case int16: return Float64(float64(v1), float64(v2)), nil case int32: return Float64(float64(v1), float64(v2)), nil case int64: return Float64(float64(v1), float64(v2)), nil case uint: return Float64(float64(v1), float64(v2)), nil case uint8: return Float64(float64(v1), float64(v2)), nil case uint16: return Float64(float64(v1), float64(v2)), nil case uint32: return Float64(float64(v1), float64(v2)), nil case uint64: return Float64(float64(v1), float64(v2)), nil case float32: return Float64(float64(v1), float64(v2)), nil case float64: return Float64(float64(v1), float64(v2)), nil default: return 0, derp.New(500, "compare.Interface", "Incompatible data type", value1, value2) } case string: if v2, ok := value2.(string); ok { return String(v1, v2), nil } case Stringer: if v2, ok := value2.(Stringer); ok { return String(v1.String(), v2.String()), nil } } return 0, derp.New(500, "compare.Interface", "Incompatible Types", value1, value2) } // Stringer is an interface for types that can be converted to String type Stringer interface { String() string }
interface.go
0.593609
0.499817
interface.go
starcoder
package chart import ( "fmt" "github.com/wcharczuk/go-chart/seq" ) // BollingerBandsSeries draws bollinger bands for an inner series. // Bollinger bands are defined by two lines, one at SMA+k*stddev, one at SMA-k*stdev. type BollingerBandsSeries struct { Name string Style Style YAxis YAxisType Period int K float64 InnerSeries ValuesProvider valueBuffer *seq.Buffer } // GetName returns the name of the time series. func (bbs BollingerBandsSeries) GetName() string { return bbs.Name } // GetStyle returns the line style. func (bbs BollingerBandsSeries) GetStyle() Style { return bbs.Style } // GetYAxis returns which YAxis the series draws on. func (bbs BollingerBandsSeries) GetYAxis() YAxisType { return bbs.YAxis } // GetPeriod returns the window size. func (bbs BollingerBandsSeries) GetPeriod() int { if bbs.Period == 0 { return DefaultSimpleMovingAveragePeriod } return bbs.Period } // GetK returns the K value, or the number of standard deviations above and below // to band the simple moving average with. // Typical K value is 2.0. func (bbs BollingerBandsSeries) GetK(defaults ...float64) float64 { if bbs.K == 0 { if len(defaults) > 0 { return defaults[0] } return 2.0 } return bbs.K } // Len returns the number of elements in the series. func (bbs BollingerBandsSeries) Len() int { return bbs.InnerSeries.Len() } // GetBoundedValues gets the bounded value for the series. func (bbs *BollingerBandsSeries) GetBoundedValues(index int) (x, y1, y2 float64) { if bbs.InnerSeries == nil { return } if bbs.valueBuffer == nil || index == 0 { bbs.valueBuffer = seq.NewBufferWithCapacity(bbs.GetPeriod()) } if bbs.valueBuffer.Len() >= bbs.GetPeriod() { bbs.valueBuffer.Dequeue() } px, py := bbs.InnerSeries.GetValues(index) bbs.valueBuffer.Enqueue(py) x = px ay := seq.New(bbs.valueBuffer).Average() std := seq.New(bbs.valueBuffer).StdDev() y1 = ay + (bbs.GetK() * std) y2 = ay - (bbs.GetK() * std) return } // GetBoundedLastValues returns the last bounded value for the series. func (bbs *BollingerBandsSeries) GetBoundedLastValues() (x, y1, y2 float64) { if bbs.InnerSeries == nil { return } period := bbs.GetPeriod() seriesLength := bbs.InnerSeries.Len() startAt := seriesLength - period if startAt < 0 { startAt = 0 } vb := seq.NewBufferWithCapacity(period) for index := startAt; index < seriesLength; index++ { xn, yn := bbs.InnerSeries.GetValues(index) vb.Enqueue(yn) x = xn } ay := seq.Seq{Provider: vb}.Average() std := seq.Seq{Provider: vb}.StdDev() y1 = ay + (bbs.GetK() * std) y2 = ay - (bbs.GetK() * std) return } // Render renders the series. func (bbs *BollingerBandsSeries) Render(r Renderer, canvasBox Box, xrange, yrange Range, defaults Style) { s := bbs.Style.InheritFrom(defaults.InheritFrom(Style{ StrokeWidth: 1.0, StrokeColor: DefaultAxisColor.WithAlpha(64), FillColor: DefaultAxisColor.WithAlpha(32), })) Draw.BoundedSeries(r, canvasBox, xrange, yrange, s, bbs, bbs.GetPeriod()) } // Validate validates the series. func (bbs BollingerBandsSeries) Validate() error { if bbs.InnerSeries == nil { return fmt.Errorf("bollinger bands series requires InnerSeries to be set") } return nil }
vendor/github.com/wcharczuk/go-chart/bollinger_band_series.go
0.847242
0.574454
bollinger_band_series.go
starcoder
package dbf import ( "math" "github.com/cpmech/gosl/chk" ) // CutSin implements a sine function such as: // if find["cps"]: # means cut_positive is True // if y < 0: y(t) = a * sin(b*t) + c // else: y(t) = 0 // else: # means cut_positive is False so cut negative values // if y > 0: y(t) = a * sin(b*t) + c // else: y(t) = 0 // Input: // b/pi -- is a flag that says that b is in fact b divided by π // thus, the code will multiply b by π internally type CutSin struct { // parameters A float64 B float64 C float64 // derived bDivPi bool cutPositive bool } // set allocators database func init() { allocators["cut-sin"] = func() T { return new(CutSin) } } // Init initialises the function func (o *CutSin) Init(prms Params) { e := prms.Connect(&o.A, "a", "cut-sin function") e += prms.Connect(&o.C, "c", "cut-sin function") p := prms.Find("b/pi") if p == nil { e += prms.Connect(&o.B, "b", "cut-sin function") } else { e += prms.Connect(&o.B, "b/pi", "cut-sin function") o.bDivPi = true } p = prms.Find("cps") if p == nil { o.cutPositive = false } else { o.cutPositive = true } if e != "" { chk.Panic("%v\n", e) } } // F returns y = F(t, x) func (o CutSin) F(t float64, x []float64) float64 { b := o.B if o.bDivPi { b = o.B * math.Pi } if o.cutPositive { if o.A*math.Sin(b*t)+o.C <= 0.0 { return o.A*math.Sin(b*t) + o.C } return 0.0 } if o.A*math.Sin(b*t)+o.C >= 0.0 { return o.A*math.Sin(b*t) + o.C } return 0.0 } // G returns ∂y/∂t_cteX = G(t, x) func (o CutSin) G(t float64, x []float64) float64 { b := o.B if o.bDivPi { b = o.B * math.Pi } if o.cutPositive { if o.A*math.Sin(b*t)+o.C <= 0.0 { return o.A * b * math.Cos(b*t) } return 0.0 } if o.A*math.Sin(b*t)+o.C >= 0.0 { return o.A * b * math.Cos(b*t) } return 0.0 } // H returns ∂²y/∂t²_cteX = H(t, x) func (o CutSin) H(t float64, x []float64) float64 { b := o.B if o.bDivPi { b = o.B * math.Pi } if o.cutPositive { if o.A*math.Sin(b*t)+o.C <= 0.0 { return -o.A * b * b * math.Sin(b*t) } return 0.0 } if o.A*math.Sin(b*t)+o.C >= 0.0 { return -o.A * b * b * math.Sin(b*t) } return 0.0 } // Grad returns ∇F = ∂y/∂x = Grad(t, x) func (o CutSin) Grad(v []float64, t float64, x []float64) { setvzero(v) return }
fun/dbf/f_cutsin.go
0.52975
0.400603
f_cutsin.go
starcoder
package goment // StartOf mutates the original Goment by setting it to the start of a unit of time. func (g *Goment) StartOf(units string) *Goment { switch units { case "y", "year", "years": g.startOfYear() case "Q", "quarter", "quarters": g.startOfQuarter() case "M", "month", "months": g.startOfMonth() case "w", "week", "weeks": g.startOfWeek() case "W", "isoWeek", "isoWeeks": g.startOfISOWeek() case "d", "day", "days", "date": g.startOfDay() case "h", "hour", "hours": g.startOfHour() case "m", "minute", "minutes": g.startOfMinute() case "s", "second", "seconds": g.startOfSecond() } return g } func (g *Goment) startOfYear() *Goment { return g.SetMonth(1).startOfMonth() } func (g *Goment) startOfQuarter() *Goment { firstMonthOfQuarter := (g.Quarter() * 3) - 2 return g.SetMonth(firstMonthOfQuarter).startOfMonth() } func (g *Goment) startOfMonth() *Goment { return g.SetDate(1).startOfDay() } func (g *Goment) startOfWeek() *Goment { return g.SetWeekday(0).startOfDay() } func (g *Goment) startOfISOWeek() *Goment { return g.SetDate(g.Date()-(g.ISOWeekday()-1)).StartOf("day") } func (g *Goment) startOfDay() *Goment { return g.SetHour(0).startOfHour() } func (g *Goment) startOfHour() *Goment { return g.SetMinute(0).startOfMinute() } func (g *Goment) startOfMinute() *Goment { return g.SetSecond(0).startOfSecond() } func (g *Goment) startOfSecond() *Goment { return g.SetNanosecond(0) } // EndOf mutates the original Goment by setting it to the end of a unit of time. func (g *Goment) EndOf(units string) *Goment { switch units { case "y", "year", "years": g.endOfYear() case "Q", "quarter", "quarters": g.endOfQuarter() case "M", "month", "months": g.endOfMonth() case "w", "week", "weeks": g.endOfWeek() case "W", "isoWeek", "isoWeeks": g.endOfISOWeek() case "d", "day", "days", "date": g.endOfDay() case "h", "hour", "hours": g.endOfHour() case "m", "minute", "minutes": g.endOfMinute() case "s", "second", "seconds": g.endOfSecond() } return g } func (g *Goment) endOfYear() *Goment { return g.SetMonth(12).endOfMonth() } func (g *Goment) endOfQuarter() *Goment { lastMonthOfQuarter := g.Quarter() * 3 return g.SetMonth(lastMonthOfQuarter).endOfMonth() } func (g *Goment) endOfMonth() *Goment { return g.SetDate(g.DaysInMonth()).endOfDay() } func (g *Goment) endOfWeek() *Goment { return g.SetWeekday(6).startOfDay() } func (g *Goment) endOfISOWeek() *Goment { return g.SetISOWeekday(6).startOfDay() } func (g *Goment) endOfDay() *Goment { return g.SetHour(23).endOfHour() } func (g *Goment) endOfHour() *Goment { return g.SetMinute(59).endOfMinute() } func (g *Goment) endOfMinute() *Goment { return g.SetSecond(59).endOfSecond() } func (g *Goment) endOfSecond() *Goment { return g.SetNanosecond(999999999) }
start_end_of.go
0.70619
0.663683
start_end_of.go
starcoder
package optimize import ( "math" "github.com/gonum/floats" ) // LinesearchMethod represents an abstract optimization method in which a // function is optimized through successive line search optimizations. type LinesearchMethod struct { // NextDirectioner specifies the search direction of each linesearch. NextDirectioner NextDirectioner // Linesearcher performs a linesearch along the search direction. Linesearcher Linesearcher x []float64 // Starting point for the current iteration. dir []float64 // Search direction for the current iteration. first bool // Indicator of the first iteration. nextMajor bool // Indicates that MajorIteration must be commanded at the next call to Iterate. eval Operation // Indicator of valid fields in Location. lastStep float64 // Step taken from x in the previous call to Iterate. lastOp Operation // Operation returned from the previous call to Iterate. } func (ls *LinesearchMethod) Init(loc *Location) (Operation, error) { if loc.Gradient == nil { panic("linesearch: gradient is nil") } dim := len(loc.X) ls.x = resize(ls.x, dim) ls.dir = resize(ls.dir, dim) ls.first = true ls.nextMajor = false // Indicate that all fields of loc are valid. ls.eval = FuncEvaluation | GradEvaluation if loc.Hessian != nil { ls.eval |= HessEvaluation } ls.lastStep = math.NaN() ls.lastOp = NoOperation return ls.initNextLinesearch(loc) } func (ls *LinesearchMethod) Iterate(loc *Location) (Operation, error) { switch ls.lastOp { case NoOperation: // TODO(vladimir-ch): Either Init has not been called, or the caller is // trying to resume the optimization run after Iterate previously // returned with an error. Decide what is the proper thing to do. See also #125. case MajorIteration: // The previous updated location did not converge the full // optimization. Initialize a new Linesearch. return ls.initNextLinesearch(loc) default: // Update the indicator of valid fields of loc. ls.eval |= ls.lastOp if ls.nextMajor { ls.nextMajor = false // Linesearcher previously finished, and the invalid fields of loc // have now been validated. Announce MajorIteration. ls.lastOp = MajorIteration return ls.lastOp, nil } } // Continue the linesearch. f := math.NaN() if ls.eval&FuncEvaluation != 0 { f = loc.F } projGrad := math.NaN() if ls.eval&GradEvaluation != 0 { projGrad = floats.Dot(loc.Gradient, ls.dir) } op, step, err := ls.Linesearcher.Iterate(f, projGrad) if err != nil { return ls.error(err) } switch op { case MajorIteration: // Linesearch has been finished. ls.lastOp = complementEval(loc, ls.eval) if ls.lastOp == NoOperation { // loc is complete, MajorIteration can be declared directly. ls.lastOp = MajorIteration } else { // Declare MajorIteration on the next call to Iterate. ls.nextMajor = true } case FuncEvaluation, GradEvaluation, FuncEvaluation | GradEvaluation: if step != ls.lastStep { // We are moving to a new location, and not, say, evaluating extra // information at the current location. // Compute the next evaluation point and store it in loc.X. floats.AddScaledTo(loc.X, ls.x, step, ls.dir) if floats.Equal(ls.x, loc.X) { // Step size has become so small that the next evaluation point is // indistinguishable from the starting point for the current // iteration due to rounding errors. return ls.error(ErrNoProgress) } ls.lastStep = step ls.eval = NoOperation // Indicate all invalid fields of loc. } ls.lastOp = op default: panic("linesearch: Linesearcher returned invalid operation") } return ls.lastOp, nil } func (ls *LinesearchMethod) error(err error) (Operation, error) { ls.lastOp = NoOperation return ls.lastOp, err } // initNextLinesearch initializes the next linesearch using the previous // complete location stored in loc. It fills loc.X and returns an evaluation // to be performed at loc.X. func (ls *LinesearchMethod) initNextLinesearch(loc *Location) (Operation, error) { copy(ls.x, loc.X) var step float64 if ls.first { ls.first = false step = ls.NextDirectioner.InitDirection(loc, ls.dir) } else { step = ls.NextDirectioner.NextDirection(loc, ls.dir) } projGrad := floats.Dot(loc.Gradient, ls.dir) if projGrad >= 0 { return ls.error(ErrNonDescentDirection) } op := ls.Linesearcher.Init(loc.F, projGrad, step) switch op { case FuncEvaluation, GradEvaluation, FuncEvaluation | GradEvaluation: default: panic("linesearch: Linesearcher returned invalid operation") } floats.AddScaledTo(loc.X, ls.x, step, ls.dir) if floats.Equal(ls.x, loc.X) { // Step size is so small that the next evaluation point is // indistinguishable from the starting point for the current iteration // due to rounding errors. return ls.error(ErrNoProgress) } ls.lastStep = step ls.eval = NoOperation // Invalidate all fields of loc. ls.lastOp = op return ls.lastOp, nil } // ArmijoConditionMet returns true if the Armijo condition (aka sufficient // decrease) has been met. Under normal conditions, the following should be // true, though this is not enforced: // - initGrad < 0 // - step > 0 // - 0 < decrease < 1 func ArmijoConditionMet(currObj, initObj, initGrad, step, decrease float64) bool { return currObj <= initObj+decrease*step*initGrad } // StrongWolfeConditionsMet returns true if the strong Wolfe conditions have been met. // The strong Wolfe conditions ensure sufficient decrease in the function // value, and sufficient decrease in the magnitude of the projected gradient. // Under normal conditions, the following should be true, though this is not // enforced: // - initGrad < 0 // - step > 0 // - 0 <= decrease < curvature < 1 func StrongWolfeConditionsMet(currObj, currGrad, initObj, initGrad, step, decrease, curvature float64) bool { if currObj > initObj+decrease*step*initGrad { return false } return math.Abs(currGrad) < curvature*math.Abs(initGrad) } // WeakWolfeConditionsMet returns true if the weak Wolfe conditions have been met. // The weak Wolfe conditions ensure sufficient decrease in the function value, // and sufficient decrease in the value of the projected gradient. Under normal // conditions, the following should be true, though this is not enforced: // - initGrad < 0 // - step > 0 // - 0 <= decrease < curvature< 1 func WeakWolfeConditionsMet(currObj, currGrad, initObj, initGrad, step, decrease, curvature float64) bool { if currObj > initObj+decrease*step*initGrad { return false } return currGrad >= curvature*initGrad }
vendor/github.com/gonum/optimize/linesearch.go
0.688678
0.40645
linesearch.go
starcoder
package dsp // region Complex Fir Filter type FirFilter struct { taps []float32 sampleHistory []complex64 tapsLen int decimation int } func MakeFirFilter(taps []float32) *FirFilter { return &FirFilter{ taps: taps, sampleHistory: make([]complex64, len(taps)), tapsLen: len(taps), decimation: 1, } } func MakeDecimationFirFilter(decimation int, taps []float32) *FirFilter { return &FirFilter{ taps: taps, sampleHistory: make([]complex64, len(taps)), tapsLen: len(taps), decimation: decimation, } } func (f *FirFilter) Filter(data []complex64, length int) { var samples = append(f.sampleHistory, data...) for i := 0; i < length; i++ { DotProduct(&data[i], samples[i:i+f.tapsLen], f.taps) } f.sampleHistory = data[len(data)-f.tapsLen:] } func (f *FirFilter) FilterOut(data []complex64) []complex64 { var samples = append(f.sampleHistory, data...) var output = make([]complex64, len(data)) var length = len(samples) - f.tapsLen for i := 0; i < length; i++ { output[i] = DotProductResult(samples[i:], f.taps) } f.sampleHistory = samples[length:] return output } func (f *FirFilter) FilterBuffer(input, output []complex64) int { var samples = append(f.sampleHistory, input...) var length = len(samples) - f.tapsLen if len(output) < length { panic("There is not enough space in output buffer") } for i := 0; i < length; i++ { output[i] = DotProductResult(samples[i:], f.taps) } f.sampleHistory = samples[length:] return length } func (f *FirFilter) FilterSingle(data []complex64) complex64 { return DotProductResult(data, f.taps) } func (f *FirFilter) FilterDecimate(data []complex64, decimate int, length int) { var samples = append(f.sampleHistory, data...) var j = 0 for i := 0; i < length; i++ { DotProduct(&data[i], samples[j:], f.taps) j += decimate } f.sampleHistory = data[len(data)-f.tapsLen:] } func (f *FirFilter) FilterDecimateBuffer(input, output []complex64, decimate int) int { var samples = append(f.sampleHistory, input...) var length = len(input) / decimate if len(output) < length { panic("There is not enough space in output buffer") } for i := 0; i < length; i++ { var srcIdx = decimate * i output[i] = DotProductResult(samples[srcIdx:], f.taps) } f.sampleHistory = samples[len(samples)-f.tapsLen:] return length } func (f *FirFilter) FilterDecimateOut(data []complex64, decimate int) []complex64 { var samples = append(f.sampleHistory, data...) var length = len(data) / decimate var output = make([]complex64, length) for i := 0; i < length; i++ { var srcIdx = decimate * i var sl = samples[srcIdx:] if len(sl) < len(f.taps) { break } output[i] = DotProductResult(sl, f.taps) } f.sampleHistory = samples[len(samples)-f.tapsLen:] return output } func (f *FirFilter) SetTaps(taps []float32) { f.taps = taps } func (f *FirFilter) Work(data []complex64) []complex64 { if f.decimation > 1 { return f.FilterDecimateOut(data, f.decimation) } return f.FilterOut(data) } func (f *FirFilter) WorkBuffer(input, output []complex64) int { if f.decimation > 1 { return f.FilterDecimateBuffer(input, output, f.decimation) } return f.FilterBuffer(input, output) } func (f *FirFilter) PredictOutputSize(inputLength int) int { return inputLength / f.decimation } // endregion // region Float Fir Filter type FloatFirFilter struct { taps []float32 sampleHistory []float32 tapsLen int decimation int } func MakeFloatFirFilter(taps []float32) *FloatFirFilter { return &FloatFirFilter{ taps: taps, sampleHistory: make([]float32, len(taps)), tapsLen: len(taps), } } func MakeDecimationFloatFirFilter(decimation int, taps []float32) *FloatFirFilter { return &FloatFirFilter{ taps: taps, sampleHistory: make([]float32, len(taps)), tapsLen: len(taps), decimation: decimation, } } func (f *FloatFirFilter) Filter(data []float32, length int) { var samples = append(f.sampleHistory, data...) for i := 0; i < length; i++ { DotProductFloat(&data[i], samples[i:], f.taps) } f.sampleHistory = data[len(data)-f.tapsLen:] } func (f *FloatFirFilter) FilterBuffer(input, output []float32) int { var samples = append(f.sampleHistory, input...) var length = len(samples) - f.tapsLen if len(output) < length { panic("There is not enough space in output buffer") } for i := 0; i < length; i++ { output[i] = DotProductFloatResult(samples[i:], f.taps) } f.sampleHistory = samples[length:] return length } func (f *FloatFirFilter) FilterSingle(data []float32) float32 { return DotProductFloatResult(data, f.taps) } func (f *FloatFirFilter) FilterDecimate(data []float32, decimate int, length int) { var samples = append(f.sampleHistory, data...) var j = 0 for i := 0; i < length; i++ { DotProductFloat(&data[i], samples[j:], f.taps) j += decimate if j >= len(samples) { break } } f.sampleHistory = data[len(data)-f.tapsLen:] } func (f *FloatFirFilter) FilterDecimateOut(data []float32, decimate int) []float32 { var samples = append(f.sampleHistory, data...) var length = len(data) / decimate var output = make([]float32, length) for i := 0; i < length; i++ { var srcIdx = decimate * i output[i] = DotProductFloatResult(samples[srcIdx:], f.taps) } f.sampleHistory = samples[len(samples)-f.tapsLen:] return output } func (f *FloatFirFilter) FilterDecimateBuffer(input, output []float32, decimate int) int { var samples = append(f.sampleHistory, input...) var length = len(input) / decimate if len(output) < length { panic("There is not enough space in output buffer") } for i := 0; i < length; i++ { var srcIdx = decimate * i output[i] = DotProductFloatResult(samples[srcIdx:], f.taps) } f.sampleHistory = samples[len(samples)-f.tapsLen:] return length } func (f *FloatFirFilter) FilterOut(data []float32) []float32 { var samples = append(f.sampleHistory, data...) var length = len(data) var output = make([]float32, length) for i := 0; i < length; i++ { output[i] = DotProductFloatResult(samples[i:], f.taps) } f.sampleHistory = samples[len(samples)-f.tapsLen:] return output } func (f *FloatFirFilter) Work(data []float32) []float32 { return f.FilterOut(data) } func (f *FloatFirFilter) WorkBuffer(input, output []float32) int { return f.FilterBuffer(input, output) } func (f *FloatFirFilter) SetTaps(taps []float32) { f.taps = taps } func (f *FloatFirFilter) PredictOutputSize(inputLength int) int { return inputLength / f.decimation } // endregion
dsp/fir.go
0.557123
0.4206
fir.go
starcoder
package schema // SiteSchemaJSON is the content of the file "site.schema.json". const SiteSchemaJSON = `{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "site.schema.json#", "title": "Site configuration", "description": "Configuration for a Sourcegraph site.", "allowComments": true, "type": "object", "additionalProperties": false, "properties": { "dontIncludeSymbolResultsByDefault": { "description": "Set to ` + "`" + `true` + "`" + ` to not include symbol results if no ` + "`" + `type:` + "`" + ` filter was given", "type": "boolean", "group": "Search" }, "disableBuiltInSearches": { "description": "Whether built-in searches should be hidden on the Searches page.", "type": "boolean", "group": "Search" }, "search.index.enabled": { "description": "Whether indexed search is enabled. If unset Sourcegraph detects the environment to decide if indexed search is enabled. Indexed search is RAM heavy, and is disabled by default in the single docker image. All other environments will have it enabled by default. The size of all your repository working copies is the amount of additional RAM required.", "type": "boolean", "!go": { "pointer": true }, "group": "Search" }, "search.largeFiles": { "description": "A list of file glob patterns where matching files will be indexed and searched regardless of their size. The glob pattern syntax can be found here: https://golang.org/pkg/path/filepath/#Match.", "type": "array", "items": { "type": "string" }, "group": "Search", "examples": [["go.sum", "package-lock.json", "*.thrift"]] }, "experimentalFeatures": { "description": "Experimental features to enable or disable. Features that are now enabled by default are marked as deprecated.", "type": "object", "additionalProperties": false, "properties": { "discussions": { "description": "Enables the code discussions experiment.", "type": "string", "enum": ["enabled", "disabled"], "default": "disabled" }, "statusIndicator": { "description": "Enables the external service status indicator in the navigation bar.", "type": "string", "enum": ["enabled", "disabled"], "default": "disabled" } }, "group": "Experimental", "hide": true }, "corsOrigin": { "description": "Only required when using the Phabricator integration for Sourcegraph (https://docs.sourcegraph.com/integration/phabricator). This value is the space-separated list of allowed origins for cross-origin HTTP requests to Sourcegraph. Usually it contains the base URL for your Phabricator instance.\n\nPreviously, this value was also used for the GitHub, GitLab, etc., integrations. It is no longer necessary for those. You may remove this setting if you are not using the Phabricator integration. eg \"https://my-phabricator.example.com\"", "type": "string", "examples": ["https://my-phabricator.example.com"], "group": "Security" }, "disableAutoGitUpdates": { "description": "Disable periodically fetching git contents for existing repositories.", "type": "boolean", "default": false, "group": "External services" }, "disablePublicRepoRedirects": { "description": "Disable redirects to sourcegraph.com when visiting public repositories that can't exist on this server.", "type": "boolean", "group": "External services" }, "git.cloneURLToRepositoryName": { "description": "JSON array of configuration that maps from Git clone URL to repository name. Sourcegraph automatically resolves remote clone URLs to their proper code host. However, there may be non-remote clone URLs (e.g., in submodule declarations) that Sourcegraph cannot automatically map to a code host. In this case, use this field to specify the mapping. The mappings are tried in the order they are specified and take precedence over automatic mappings.", "type": "array", "items": { "title": "CloneURLToRepositoryName", "description": "Describes a mapping from clone URL to repository name. The ` + "`" + `from` + "`" + ` field contains a regular expression with named capturing groups. The ` + "`" + `to` + "`" + ` field contains a template string that references capturing group names. For instance, if ` + "`" + `from` + "`" + ` is \"^../(?P<name>\\w+)$\" and ` + "`" + `to` + "`" + ` is \"github.com/user/{name}\", the clone URL \"../myRepository\" would be mapped to the repository name \"github.com/user/myRepository\".", "type": "object", "additionalProperties": false, "required": ["from", "to"], "properties": { "from": { "description": "A regular expression that matches a set of clone URLs. The regular expression should use the Go regular expression syntax (https://golang.org/pkg/regexp/) and contain at least one named capturing group. The regular expression matches partially by default, so use \"^...$\" if whole-string matching is desired.", "type": "string" }, "to": { "description": "The repository name output pattern. This should use ` + "`" + `{matchGroup}` + "`" + ` syntax to reference the capturing groups from the ` + "`" + `from` + "`" + ` field.", "type": "string" } } }, "group": "External services" }, "githubClientID": { "description": "Client ID for GitHub.", "type": "string", "group": "Internal", "hide": true }, "githubClientSecret": { "description": "Client secret for GitHub.", "type": "string", "group": "Internal", "hide": true }, "gitMaxConcurrentClones": { "description": "Maximum number of git clone processes that will be run concurrently to update repositories.", "type": "integer", "default": 5, "group": "External services" }, "repoListUpdateInterval": { "description": "Interval (in minutes) for checking code hosts (such as GitHub, Gitolite, etc.) for new repositories.", "type": "integer", "default": 1, "group": "External services" }, "maxReposToSearch": { "description": "The maximum number of repositories to search across. The user is prompted to narrow their query if exceeded. Any value less than or equal to zero means unlimited.", "type": "integer", "default": -1, "group": "Search" }, "parentSourcegraph": { "description": "URL to fetch unreachable repository details from. Defaults to \"https://sourcegraph.com\"", "type": "object", "additionalProperties": false, "properties": { "url": { "type": "string", "default": "https://sourcegraph.com" } }, "group": "External services" }, "auth.accessTokens": { "description": "Settings for access tokens, which enable external tools to access the Sourcegraph API with the privileges of the user.", "type": "object", "additionalProperties": false, "properties": { "allow": { "description": "Allow or restrict the use of access tokens. The default is \"all-users-create\", which enables all users to create access tokens. Use \"none\" to disable access tokens entirely. Use \"site-admin-create\" to restrict creation of new tokens to admin users (existing tokens will still work until revoked).", "type": "string", "enum": ["all-users-create", "site-admin-create", "none"], "default": "all-users-create" } }, "default": { "allow": "all-users-create" }, "examples": [ { "allow": "site-admin-create" }, { "allow": "none" } ], "group": "Security" }, "branding": { "description": "Customize Sourcegraph homepage logo and search icon.\n\nOnly available in Sourcegraph Enterprise.", "type": "object", "additionalProperties": false, "properties": { "light": { "$ref": "#/definitions/BrandAssets" }, "dark": { "$ref": "#/definitions/BrandAssets" }, "favicon": { "description": "The URL of the favicon to be used for your instance. We recommend using the following file format: ICO", "type": "string", "format": "uri" }, "disableSymbolSpin": { "description": "Prevents the icon in the top-left corner of the screen from spinning on hover.", "type": "boolean", "default": false } }, "examples": [ { "favicon": "https://example.com/favicon.ico", "light": { "logo": "https://example.com/logo_light.png", "symbol": "https://example.com/search_symbol_light_24x24.png" }, "dark": { "logo": "https://example.com/logo_dark.png", "symbol": "https://example.com/search_symbol_dark_24x24.png" }, "disableSymbolSpin": true } ] }, "email.smtp": { "title": "SMTPServerConfig", "description": "The SMTP server used to send transactional emails (such as email verifications, reset-password emails, and notifications).", "type": "object", "additionalProperties": false, "required": ["host", "port", "authentication"], "properties": { "host": { "description": "The SMTP server host.", "type": "string" }, "port": { "description": "The SMTP server port.", "type": "integer" }, "username": { "description": "The username to use when communicating with the SMTP server.", "type": "string" }, "password": { "description": "The username to use when communicating with the SMTP server.", "type": "string" }, "authentication": { "description": "The type of authentication to use for the SMTP server.", "type": "string", "enum": ["none", "PLAIN", "CRAM-MD5"] }, "domain": { "description": "The HELO domain to provide to the SMTP server (if needed).", "type": "string" } }, "default": null, "examples": [ { "host": "smtp.example.com", "port": 465, "username": "alice", "password": "<PASSWORD>", "authentication": "PLAIN" } ], "group": "Email" }, "email.imap": { "title": "IMAPServerConfig", "description": "Optional. The IMAP server used to retrieve emails (such as code discussion reply emails).", "type": "object", "additionalProperties": false, "required": ["host", "port"], "properties": { "host": { "description": "The IMAP server host.", "type": "string" }, "port": { "description": "The IMAP server port.", "type": "integer" }, "username": { "description": "The username to use when communicating with the IMAP server.", "type": "string" }, "password": { "description": "The username to use when communicating with the IMAP server.", "type": "string" } }, "default": null, "examples": [ { "host": "imap.example.com", "port": 993, "username": "alice", "password": "<PASSWORD>" } ], "group": "Email", "hide": true }, "email.address": { "description": "The \"from\" address for emails sent by this server.", "type": "string", "format": "email", "group": "Email", "default": "<EMAIL>" }, "extensions": { "description": "Configures Sourcegraph extensions.", "type": "object", "properties": { "disabled": { "description": "Disable all usage of extensions.", "type": "boolean", "default": false, "!go": { "pointer": true } }, "remoteRegistry": { "description": "The remote extension registry URL, or ` + "`" + `false` + "`" + ` to not use a remote extension registry. If not set, the default remote extension registry URL is used.", "oneOf": [{ "type": "string", "format": "uri" }, { "type": "boolean", "const": false }] }, "allowRemoteExtensions": { "description": "Allow only the explicitly listed remote extensions (by extension ID, such as \"alice/myextension\") from the remote registry. If not set, all remote extensions may be used from the remote registry. To completely disable the remote registry, set ` + "`" + `remoteRegistry` + "`" + ` to ` + "`" + `false` + "`" + `.\n\nOnly available in Sourcegraph Enterprise.", "type": "array", "items": { "type": "string" } } }, "default": { "remoteRegistry": "https://sourcegraph.com/.api/registry" }, "examples": [ { "remoteRegistry": "https://sourcegraph.com/.api/registry", "allowRemoteExtensions": ["sourcegraph/java"] } ], "group": "Extensions" }, "discussions": { "description": "Configures Sourcegraph code discussions.", "type": "object", "properties": { "abuseProtection": { "description": "Enable abuse protection features (for public instances like Sourcegraph.com, not recommended for private instances).", "type": "boolean", "default": false }, "abuseEmails": { "description": "Email addresses to notify of e.g. new user reports about abusive comments. Otherwise emails will not be sent.", "type": "array", "items": { "type": "string" }, "default": [] } }, "group": "Experimental", "hide": true } }, "definitions": { "BrandAssets": { "type": "object", "properties": { "logo": { "description": "The URL to the image used on the homepage. This will replace the Sourcegraph logo on the homepage. Maximum width: 320px. We recommend using the following file formats: SVG, PNG", "type": "string", "format": "uri" }, "symbol": { "description": "The URL to the symbol used as the search icon. Recommended size: 24x24px. We recommend using the following file formats: SVG, PNG, ICO", "type": "string", "format": "uri" } } } } } `
schema/site_stringdata.go
0.843122
0.463687
site_stringdata.go
starcoder
package core type Distance struct { root *Cell cellDists map[*Cell]int maximum int // cache farthest *Cell // cache } func NewDistance(root *Cell) Distance { return Distance{root: root, cellDists: map[*Cell]int{ root: 0, }} } func (d Distance) distanceTo(cell *Cell) (int, bool) { v, ok := d.cellDists[cell] return v, ok } func (d *Distance) setDistanceTo(cell *Cell, v int) { d.cellDists[cell] = v } func (d *Distance) cells() (result []*Cell) { result = make([]*Cell, len(d.cellDists)) i := 0 for k := range d.cellDists { result[i] = k i++ } return } func (c *Cell) Distances() *Distance { d := NewDistance(c) frontier := []*Cell{c} for len(frontier) > 0 { newFrontier := []*Cell{} for _, cell := range frontier { for _, linked := range cell.linkedCells() { if _, found := d.distanceTo(linked); found { continue } v, _ := d.distanceTo(cell) d.setDistanceTo(linked, v+1) newFrontier = append(newFrontier, linked) } } frontier = newFrontier } return &d } func (d Distance) PathToCell(goal *Cell) *Distance { current := goal breadcrumbs := NewDistance(d.root) v, _ := d.distanceTo(current) breadcrumbs.setDistanceTo(current, v) for current != d.root { for _, neighbor := range current.linkedCells() { vn, _ := d.distanceTo(neighbor) vc, _ := d.distanceTo(current) if vn < vc { breadcrumbs.setDistanceTo(neighbor, vn) current = neighbor break } } } return &breadcrumbs } func (d *Distance) Max() (*Cell, int) { if d.farthest == nil { d.maximum = 0 d.farthest = d.root for cell, distance := range d.cellDists { if distance > d.maximum { d.farthest = cell d.maximum = distance } } } return d.farthest, d.maximum } func (g Grid) LongestPath() *Distance { start := g.CellAt(0, 0) distances := start.Distances() newStart, _ := distances.Max() newDistances := newStart.Distances() goal, _ := newDistances.Max() return newDistances.PathToCell(goal) }
core/distance.go
0.78968
0.516474
distance.go
starcoder
package container import ( "fmt" "reflect" "strings" ) // LabelledTuple is a labelled tuple containing a list of fields and a label set. // Fields can be any data type and is used to store data. // TupleLabels is a label set that is associated to the tuple itself. type LabelledTuple Tuple // NewLabelledTuple creates a labelled tuple according to the labels and values present in the fields. // NewLabelledTuple searches the first field for labels. func NewLabelledTuple(fields ...interface{}) (lt LabelledTuple) { if len(fields) == 0 { lt = LabelledTuple(NewTuple(Labels{})) } else { var lbls Labels if len(fields) == 0 { lbls = Labels{} } else { lbls = fields[0].(Labels) lblsc := make(Labels) for _, v := range lbls.Labelling() { lbl := lbls.Retrieve(v) lblsc.Add(NewLabel(lbl.ID())) } lbls = lblsc } if len(fields) < 1 { lt = LabelledTuple(NewTuple(lbls)) } else { fields[0] = lbls lt = LabelledTuple(NewTuple(fields...)) } } return lt } // Length returns the amount of fields of the tuple. func (lt *LabelledTuple) Length() (sz int) { sz = -1 if lt != nil { sz = len((*lt).Flds) - 1 } return } // Fields returns the fields of the tuple. func (lt *LabelledTuple) Fields() (flds []interface{}) { if lt != nil { if lt.Length() >= 2 { flds = (*lt).Flds[1:] } } return flds } // GetFieldAt returns the i'th field of the tuple. func (lt *LabelledTuple) GetFieldAt(i int) (fld interface{}) { if lt != nil && i >= 0 && i < lt.Length() { fld = (*lt).Flds[i+1] } return } // SetFieldAt sets the i'th field of the tuple to the value of val. func (lt *LabelledTuple) SetFieldAt(i int, val interface{}) (b bool) { if lt != nil && i >= 0 && i < lt.Length() { (*lt).Flds[i+1] = val b = true } return b } // Apply iterates through the labelled tuple t and applies the function fun to each field. // Apply returns true function fun could be applied to all the fields, and false otherwise. func (lt *LabelledTuple) Apply(fun func(field interface{}) interface{}) (b bool) { b = false if lt != nil { b = true for i := 0; i < lt.Length(); i++ { lt.SetFieldAt(i, fun(lt.GetFieldAt(i))) } } return b } // Labels returns the label set belonging to the labelled tuple. func (lt *LabelledTuple) Labels() (ls Labels) { return (*lt).Flds[0].(Labels) } // Tuple returns a tuple without the label. func (lt *LabelledTuple) Tuple() (t Tuple) { t = NewTuple((*lt).Flds[1:]...) return t } // MatchLabels matches a labelled tuples t labels against labels ls. func (lt *LabelledTuple) MatchLabels(ls Labels) (mls *Labels, b bool) { b = lt != nil if b { ltls := lt.Labels() mls, b = ltls.Intersect(&ls) } return mls, b } // MatchTemplate pattern matches labelled tuple t against the template tp. // MatchTemplate discriminates between encapsulated formal fields and actual fields. // MatchTemplate returns true if the template matches the labelled tuple and false otherwise. func (lt *LabelledTuple) MatchTemplate(tp Template) (b bool) { b = lt != nil && lt.Length() == (&tp).Length() if b { t := lt.Tuple() b = (&t).Match(tp) } return b } // ParenthesisType returns a pair of strings that encapsulates labelled tuple t. // ParenthesisType is used in the String() method. func (lt LabelledTuple) ParenthesisType() (string, string) { return "(", ")" } // Delimiter returns the delimiter used to seperate a labelled tuple t's fields. // Delimiter is used in the String() method. func (lt LabelledTuple) Delimiter() string { return ", " } // String returns a print friendly representation of the tuple. func (lt LabelledTuple) String() (s string) { ld, rd := lt.ParenthesisType() delim := lt.Delimiter() strs := make([]string, lt.Length()) for i := range strs { field := lt.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" } } s = fmt.Sprintf("%s%s%s%s%s", ld, lt.Labels(), " : ", strings.Join(strs, delim), rd) return s }
container/labelled_tuple.go
0.688154
0.507629
labelled_tuple.go
starcoder
package dmc import ( "strconv" "github.com/lucasb-eyer/go-colorful" ) func (d *DmcColors) LabToDmc(l float64, a float64, b float64) (string, string) { var previousDistance float64 var dmc string var floss string // ic is Color struct holding the Lab values passed in to LabToDmc ic := colorful.Lab(l, a, b) // Search for hex in d.HexMap to check for exact matches. If it exists, loop through // d.ColorBank for the color name and floss number hex := ic.Hex() if val, ok := d.HexMap[hex]; ok { for _, c := range d.ColorBank { if c.ColorName == val { return c.ColorName, c.Floss } } // Otherwise, use the hex value to create a new colorful.Color // and search through the d.ColorBank for the closest match (in L*a*b colorspace) } else { for i, c := range d.ColorBank { red, _ := strconv.Atoi(c.R) green, _ := strconv.Atoi(c.G) blue, _ := strconv.Atoi(c.B) // tempc is a temporary colorful.Color struct holding the rgb values of // each color in the the colorBank so they can be converted to lab colorspace // values and tested for distance between colors tempc := colorful.Color{R: float64(red), G: float64(green), B: float64(blue)} l, a, b := tempc.Lab() // tc is colorful.Color struct holding the Lab values of each color in the // color bank to test how close it is to ic tc := colorful.Lab(l, a, b) if i == 0 { previousDistance = ic.DistanceLuv(tc) dmc = c.ColorName floss = c.Floss continue } curDis := ic.DistanceLuv(tc) if curDis == 0 { dmc = c.ColorName floss = c.Floss break } if curDis < previousDistance { previousDistance = ic.DistanceLuv(tc) dmc = c.ColorName floss = c.Floss } } } return dmc, floss } // Convenience functions for convertion LAB colors to other color spaces func (d *DmcColors) LabToRgb(l float64, a float64, b float64) (float64, float64, float64) { c := colorful.Lab(l, a, b) _r := c.R _g := c.G _b := c.B return _r, _g, _b } func (d *DmcColors) LabToHex(l float64, a float64, b float64) string { c := colorful.Lab(l, a, b) return c.Hex() } func (d *DmcColors) LabToHsv(l float64, a float64, b float64) (float64, float64, float64) { c := colorful.Lab(l, a, b) return c.Hsv() }
lab.go
0.735926
0.538134
lab.go
starcoder
package complex import "math" type Complex struct { Re float64 `json:"re"` Im float64 `json:"im"` } func (a Complex) Add(b Complex) (c Complex) { c.Re = a.Re + b.Re c.Im = a.Im + b.Im return } func (a Complex) Sub(b Complex) (c Complex) { c.Re = a.Re - b.Re c.Im = a.Im - b.Im return } func (a Complex) Mul(b Complex) (c Complex) { c.Re = a.Re*b.Re - a.Im*b.Im c.Im = a.Im*b.Re + a.Re*b.Im return } func (a Complex) Div(b Complex) (c Complex) { norm := b.Norm() c.Re = (a.Re*b.Re + a.Im*b.Im) / norm c.Im = (a.Im*b.Re - a.Re*b.Im) / norm return } func (a Complex) AddScalar(scalar float64) (c Complex) { c.Re = a.Re + scalar c.Im = a.Im return } func (a Complex) SubScalar(scalar float64) (c Complex) { c.Re = a.Re - scalar c.Im = a.Im return } func (a Complex) MulScalar(scalar float64) (c Complex) { c.Re = a.Re * scalar c.Im = a.Im * scalar return } func (a Complex) DivScalar(scalar float64) (c Complex) { c.Re = a.Re / scalar c.Im = a.Im / scalar return } func (a Complex) Conjugate() (b Complex) { b.Re = a.Re b.Im = -a.Im return } func (a Complex) Norm() float64 { return (a.Re * a.Re) + (a.Im * a.Im) } // Simple Magnitude func (a Complex) _magnitude() float64 { return math.Sqrt(a.Norm()) } // Better Magnitude func (z Complex) Magnitude() float64 { var ( a = math.Abs(z.Re) b = math.Abs(z.Im) ) if a == 0 { return b } if b == 0 { return a } var m float64 if a >= b { m = b / a m = a * math.Sqrt(1+m*m) } else { m = a / b m = b * math.Sqrt(1+m*m) } return m } func (a Complex) Argument() float64 { return math.Atan2(a.Im, a.Re) } // b = 1 / a func (a Complex) Invert() (b Complex) { norm := a.Norm() return Complex{ Re: a.Re / norm, Im: -a.Im / norm, } } func (a Complex) Polar() Polar { return Polar{ Radius: a.Magnitude(), Angle: a.Argument(), } } func (a Complex) Power(p float64) Complex { return Polar{ Radius: math.Exp(p * 0.5 * math.Log(a.Norm())), Angle: a.Argument() * p, }.Complex() } // Trigonometric form type Polar struct { Radius float64 Angle float64 } func (p Polar) Complex() Complex { sin, cos := math.Sincos(p.Angle) return Complex{ Re: p.Radius * cos, Im: p.Radius * sin, } }
complex/complex.go
0.932661
0.489931
complex.go
starcoder
package ciede2000 import ( "math" "github.com/zarken-go/colorspace" ) const ( pow25To7 = 6103515625.0 // math.Pow(25, 7) ) func deg2Rad(deg float64) float64 { return deg * (math.Pi / 180.0) } func DeltaE(Lab1, Lab2 colorspace.Lab) float64 { c1 := math.Sqrt(math.Pow(Lab1.A, 2) + math.Pow(Lab1.B, 2)) c2 := math.Sqrt(math.Pow(Lab2.A, 2) + math.Pow(Lab2.B, 2)) barC := (c1 + c2) / 2 G := .5 * (1 - math.Sqrt(math.Pow(barC, 7)/(math.Pow(barC, 7)+pow25To7))) a1p := (1.0 + G) * Lab1.A a2p := (1.0 + G) * Lab2.A deg180InRad := math.Pi deg360InRad := 2 * math.Pi CPrime1 := math.Sqrt(math.Pow(a1p, 2) + math.Pow(Lab1.B, 2)) CPrime2 := math.Sqrt(math.Pow(a2p, 2) + math.Pow(Lab2.B, 2)) var h1p, h2p float64 if !(a1p == 0 && Lab1.B == 0) { h1p = math.Atan2(Lab1.B, a1p) if h1p < 0 { h1p += deg360InRad } } if !(a2p == 0 && Lab2.B == 0) { h2p = math.Atan2(Lab2.B, a2p) if h2p < 0 { h2p += deg360InRad } } LpDelta := Lab2.L - Lab1.L CpDelta := CPrime2 - CPrime1 var deltahPrime float64 if CPrime1*CPrime2 == 0 { deltahPrime = 0 } else { deltahPrime = h2p - h1p if deltahPrime < -deg180InRad { deltahPrime += deg360InRad } else if deltahPrime > deg180InRad { deltahPrime -= deg360InRad } } HpDelta := 2 * math.Sqrt(CPrime1*CPrime2) * math.Sin(deltahPrime/2) barLPrime := (Lab1.L + Lab2.L) / 2.0 barCPrime := (CPrime1 + CPrime2) / 2.0 var barhPrime float64 hPrimeSum := h1p + h2p if CPrime1*CPrime2 == 0.0 { barhPrime = hPrimeSum } else { if math.Abs(h1p-h2p) <= deg180InRad { barhPrime = hPrimeSum / 2.0 } else { if hPrimeSum < deg360InRad { barhPrime = (hPrimeSum + deg360InRad) / 2.0 } else { barhPrime = (hPrimeSum - deg360InRad) / 2.0 } } } T := 1.0 - (0.17 * math.Cos(barhPrime-deg2Rad(30))) + (0.24 * math.Cos(2.0*barhPrime)) + (0.32 * math.Cos(3.0*barhPrime+deg2Rad(6))) - (0.20 * math.Cos(4.0*barhPrime-deg2Rad(63))) deltaTheta := deg2Rad(30) * math.Exp(-math.Pow((barhPrime-deg2Rad(275))/deg2Rad(25), 2.0)) Rc := 2.0 * math.Sqrt(math.Pow(barCPrime, 7.0)/(math.Pow(barCPrime, 7.0)+pow25To7)) Sl := 1.0 + ((0.015 * math.Pow(barLPrime-50, 2.0)) / math.Sqrt(20.0+math.Pow(barLPrime-50, 2.0))) Sc := 1.0 + 0.045*barCPrime Sh := 1.0 + 0.015*barCPrime*T Rt := -math.Sin(2.0*deltaTheta) * Rc return math.Sqrt( math.Pow(LpDelta/Sl, 2) + math.Pow(CpDelta/Sc, 2) + math.Pow(HpDelta/Sh, 2) + (Rt * (CpDelta / Sc) * (HpDelta / Sh))) }
ciede2000/delta.go
0.616128
0.538316
delta.go
starcoder
package paralleltest import ( "go/ast" "strings" "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" ) const Doc = `check that tests use t.Parallel() method It also checks that the t.Parallel is used if multiple tests cases are run as part of single test. As part of ensuring parallel tests works as expected it checks for reinitialising of the range value over the test cases.(https://tinyurl.com/y6555cy6)` func NewAnalyzer() *analysis.Analyzer { return &analysis.Analyzer{ Name: "paralleltest", Doc: Doc, Run: run, Requires: []*analysis.Analyzer{inspect.Analyzer}, } } func run(pass *analysis.Pass) (interface{}, error) { inspector := inspector.New(pass.Files) nodeFilter := []ast.Node{ (*ast.FuncDecl)(nil), } inspector.Preorder(nodeFilter, func(node ast.Node) { funcDecl := node.(*ast.FuncDecl) var funcHasParallelMethod, rangeStatementOverTestCasesExists, rangeStatementHasParallelMethod, testLoopVariableReinitialised bool var testRunLoopIdentifier string var numberOfTestRun int var positionOfTestRunNode []ast.Node var rangeNode ast.Node // Check runs for test functions only if !isTestFunction(funcDecl) { return } for _, l := range funcDecl.Body.List { switch v := l.(type) { case *ast.ExprStmt: ast.Inspect(v, func(n ast.Node) bool { // Check if the test method is calling t.parallel if !funcHasParallelMethod { funcHasParallelMethod = methodParallelIsCalledInTestFunction(n) } // Check if the t.Run within the test function is calling t.parallel if methodRunIsCalledInTestFunction(n) { hasParallel := false numberOfTestRun++ ast.Inspect(v, func(p ast.Node) bool { if !hasParallel { hasParallel = methodParallelIsCalledInTestFunction(p) } return true }) if !hasParallel { positionOfTestRunNode = append(positionOfTestRunNode, n) } } return true }) // Check if the range over testcases is calling t.parallel case *ast.RangeStmt: rangeNode = v ast.Inspect(v, func(n ast.Node) bool { // nolint: gocritic switch r := n.(type) { case *ast.ExprStmt: if methodRunIsCalledInRangeStatement(r.X) { rangeStatementOverTestCasesExists = true testRunLoopIdentifier = methodRunFirstArgumentObjectName(r.X) if !rangeStatementHasParallelMethod { rangeStatementHasParallelMethod = methodParallelIsCalledInMethodRun(r.X) } } } return true }) // Check for the range loop value identifier re assignment // More info here https://gist.github.com/kunwardeep/80c2e9f3d3256c894898bae82d9f75d0 if rangeStatementOverTestCasesExists { var rangeValueIdentifier string if i, ok := v.Value.(*ast.Ident); ok { rangeValueIdentifier = i.Name } testLoopVariableReinitialised = testCaseLoopVariableReinitialised(v.Body.List, rangeValueIdentifier, testRunLoopIdentifier) } } } if !funcHasParallelMethod { pass.Reportf(node.Pos(), "Function %s missing the call to method parallel\n", funcDecl.Name.Name) } if rangeStatementOverTestCasesExists && rangeNode != nil { if !rangeStatementHasParallelMethod { pass.Reportf(rangeNode.Pos(), "Range statement for test %s missing the call to method parallel in test Run\n", funcDecl.Name.Name) } else { if testRunLoopIdentifier == "" { pass.Reportf(rangeNode.Pos(), "Range statement for test %s does not use range value in test Run\n", funcDecl.Name.Name) } else if !testLoopVariableReinitialised { pass.Reportf(rangeNode.Pos(), "Range statement for test %s does not reinitialise the variable %s\n", funcDecl.Name.Name, testRunLoopIdentifier) } } } // Check if the t.Run is more than one as there is no point making one test parallel if numberOfTestRun > 1 && len(positionOfTestRunNode) > 0 { for _, n := range positionOfTestRunNode { pass.Reportf(n.Pos(), "Function %s has missing the call to method parallel in the test run\n", funcDecl.Name.Name) } } }) return nil, nil } func testCaseLoopVariableReinitialised(statements []ast.Stmt, rangeValueIdentifier string, testRunLoopIdentifier string) bool { if len(statements) > 1 { for _, s := range statements { leftIdentifier, rightIdentifier := getLeftAndRightIdentifier(s) if leftIdentifier == testRunLoopIdentifier && rightIdentifier == rangeValueIdentifier { return true } } } return false } // Return the left hand side and the right hand side identifiers name func getLeftAndRightIdentifier(s ast.Stmt) (string, string) { var leftIdentifier, rightIdentifier string // nolint: gocritic switch v := s.(type) { case *ast.AssignStmt: if len(v.Rhs) == 1 { if i, ok := v.Rhs[0].(*ast.Ident); ok { rightIdentifier = i.Name } } if len(v.Lhs) == 1 { if i, ok := v.Lhs[0].(*ast.Ident); ok { leftIdentifier = i.Name } } } return leftIdentifier, rightIdentifier } func methodParallelIsCalledInMethodRun(node ast.Node) bool { var methodParallelCalled bool // nolint: gocritic switch callExp := node.(type) { case *ast.CallExpr: for _, arg := range callExp.Args { if !methodParallelCalled { ast.Inspect(arg, func(n ast.Node) bool { if !methodParallelCalled { methodParallelCalled = methodParallelIsCalledInRunMethod(n) return true } return false }) } } } return methodParallelCalled } func methodParallelIsCalledInRunMethod(node ast.Node) bool { return exprCallHasMethod(node, "Parallel") } func methodParallelIsCalledInTestFunction(node ast.Node) bool { return exprCallHasMethod(node, "Parallel") } func methodRunIsCalledInRangeStatement(node ast.Node) bool { return exprCallHasMethod(node, "Run") } func methodRunIsCalledInTestFunction(node ast.Node) bool { return exprCallHasMethod(node, "Run") } func exprCallHasMethod(node ast.Node, methodName string) bool { // nolint: gocritic switch n := node.(type) { case *ast.CallExpr: if fun, ok := n.Fun.(*ast.SelectorExpr); ok { return fun.Sel.Name == methodName } } return false } // Gets the object name `tc` from method t.Run(tc.Foo, func(t *testing.T) func methodRunFirstArgumentObjectName(node ast.Node) string { // nolint: gocritic switch n := node.(type) { case *ast.CallExpr: for _, arg := range n.Args { if s, ok := arg.(*ast.SelectorExpr); ok { if i, ok := s.X.(*ast.Ident); ok { return i.Name } } } } return "" } // Checks if the function has the param type *testing.T) func isTestFunction(funcDecl *ast.FuncDecl) bool { testMethodPackageType := "testing" testMethodStruct := "T" testPrefix := "Test" if !strings.HasPrefix(funcDecl.Name.Name, testPrefix) { return false } if funcDecl.Type.Params != nil && len(funcDecl.Type.Params.List) != 1 { return false } param := funcDecl.Type.Params.List[0] if starExp, ok := param.Type.(*ast.StarExpr); ok { if selectExpr, ok := starExp.X.(*ast.SelectorExpr); ok { if selectExpr.Sel.Name == testMethodStruct { if s, ok := selectExpr.X.(*ast.Ident); ok { return s.Name == testMethodPackageType } } } } return false }
vendor/github.com/kunwardeep/paralleltest/pkg/paralleltest/paralleltest.go
0.622115
0.494019
paralleltest.go
starcoder
package multipivotquicksort import ( "fmt" "sort" "sync" ) /*MultiPivot uses a variant of the QuickSort with multiple pivots, splitting the arrays in multiple segments (pivots+1). It consumes more space (memory), is not yet optimized to work with only 1 slice, it copies the data in each step. singleThread should be used for small data sets, benchmark with your own data sets to see which is best. pivotCount 1 has the same effect as the regular quickSort, with larger data sets (millions) more then 7 pivots can improve the algorithm. .*/ func MultiPivot(list []int, pivotCount uint8, singleThread bool) (result []int, err error) { defer func() { r := recover() if r != nil { err = fmt.Errorf("%v %v", r, list) } }() n := len(list) if n <= 1 { result = list return } if pivotCount <= 1 { pivotCount = 1 } if n <= 20 || n/int(pivotCount) < 10 { sort.Ints(list) result = list return } pivots := list[:pivotCount] sort.Ints(pivots) list = list[pivotCount:] segments := make([][]int, pivotCount+1) for _, el := range list { for pindex, pvalue := range pivots { if el < pvalue { segments[pindex] = append(segments[pindex], el) goto found } } //the element is >= last pivot, so it goes to the last bucket/segment segments[pivotCount] = append(segments[pivotCount], el) found: } //apply the same alg to each segment/bucket sortedSegments := make([][]int, len(segments)) if singleThread { for sindex, segment := range segments { sortedSegments[sindex], err = MultiPivot(segment, pivotCount, singleThread) if err != nil { return } } } else { var wg sync.WaitGroup wg.Add(len(segments)) //goroutines share memory, has a race problem //but each one has its own index for sindex, segment := range segments { go func(sindex int, segment []int) { sortedSegments[sindex], err = MultiPivot(segment, pivotCount, singleThread) wg.Done() }(sindex, segment) } wg.Wait() } //glue the segments in the result result = make([]int, n) //preallocate i := 0 for sindex, sortedSegment := range sortedSegments { i += copy(result[i:], sortedSegment) if sindex < len(pivots) { result[i] = pivots[sindex] i++ } } return }
sort/multipivotquicksort/sort.go
0.558809
0.427695
sort.go
starcoder
package entity import ( "fmt" ) // JourneyPlace represents one URL in visitor history // Some nodes are not directly logged to the access logs due to caching layers. // In that case, we will replicate missing information based on referer URL and access log records type JourneyPlace struct { ID string WasLogged bool Data *AccessLogRecord } // Print a dubug information about journey nodes func (n *JourneyPlace) Print() string { return fmt.Sprintf("%v", n.Data.URI) } // Journey represents visitor access history and consists of URLs they visited // Infrastructure can include caching layers which prevents some records to be processed and logged by server engine. // Our goal is to reproduce visitor journey as long as possible based on referer URLs type Journey struct { ID string IP string Places []*JourneyPlace Roads map[JourneyPlace][]*JourneyPlace } // AddPlace adds a journey Places to the journey func (jg *Journey) AddPlace(n *JourneyPlace) *JourneyPlace { jg.Places = append(jg.Places, n) return n } // GetLastPlace func (jg *Journey) GetLastPlace() *JourneyPlace { if len(jg.Places) == 0 { return nil } return jg.Places[len(jg.Places)-1] } // AddRoad adds an road between journey Places func (jg *Journey) AddRoad(n1, n2 *JourneyPlace) { if jg.Roads == nil { jg.Roads = make(map[JourneyPlace][]*JourneyPlace) } jg.Roads[*n1] = append(jg.Roads[*n1], n2) } // Print a debug info about journey graph structure func (jg *Journey) Print() { s := "" for i := 0; i < len(jg.Places); i++ { s += jg.Places[i].Print() + " -> " near := jg.Roads[*jg.Places[i]] for j := 0; j < len(near); j++ { s += near[j].Print() + " " } s += "\n" } fmt.Println(s) } // FindPlace finds a place in journey by place URI func (jg *Journey) FindPlace(uri string) *JourneyPlace { for i := 0; i < len(jg.Places); i++ { place := jg.Places[i] if place.Data.URI == uri { return place } } return nil } // FindPlace finds a place in journey by place URI func (jg *Journey) FindLastPlace(uri string) *JourneyPlace { for i := len(jg.Places) - 1; i >= 0; i-- { place := jg.Places[i] if place.Data.URI == uri { return place } } return nil }
internal/domain/entity/journey.go
0.671471
0.462048
journey.go
starcoder
package tfengine // Schema is the Terraform engine input schema. // TODO(https://github.com/golang/go/issues/35950): Move this to its own file. const Schema = ` title = "Terraform Engine Config Schema" additionalProperties = false properties = { version = { description = <<EOF Optional constraint on the binary version required for this config. See [syntax](https://www.terraform.io/docs/configuration/version-constraints.html). EOF type = "string" } data = { description = <<EOF Global set of key-value pairs to pass to all templates. It will be merged with data set in the templates. EOF type = "object" } template = { description = <<EOF Templates the engine will parse and fill in with values from data. Templates use the [Go templating engine](https://golang.org/pkg/text/template/). Template maintainers can use several [helper template funcs](../../template/funcmap.go). EOF type = "array" items = { type = "object" additionalProperties = false properties = { name = { description = "Name of the template." type = "string" } recipe_path = { description = "Path to a recipe YAML config. Mutually exclusive with 'component_path'." type = "string" } output_path = { description = <<EOF Relative path for this template to write its contents. This value will be joined with the value passed in by the flag at --output_path. EOF type = "string" } data = { description = "Key value pairs passed to this template." type = "object" } # ---------------------------------------------------------------------- # NOTE: The fields below should typically be set by recipe maintainers and not end users. # ---------------------------------------------------------------------- component_path = { description = "Path to a component directory. Mutually exclusive with 'recipe_path'." type = "string" } flatten = { description = <<EOF Keys to flatten within an object or list of objects. Any resulting key value pairs will be merged into data. This is not recursive. Example: A foundation recipe may expect audit information to be in a field 'AUDIT'. Thus a user will likely write 'AUDIT: { PROJECT_ID: "foo"}' in their config. However, the audit template itself will look for the field 'PROJECT_ID'. Thus, the audit template should flatten the 'AUDIT' key. EOF type = "array" items = { type = "object" required = ["key"] properties = { key = { description = "Name of key in data to flatten." type = "string" } index = { description = "If set, assume value is a list and the index is being flattened." type = "integer" } } } } passthrough = { description = <<EOF Keys to pass directly to a child template data. This is not recursive. Example: The deployment recipe expects "terraform_addons" to be passed to it directly, so the project recipe uses this key to do so. EOF type = "array" items = { type = "string" } } } } } schema = { description = "Schema the data for this template must adhere to. Typically only set in recipes." type = "object" } } `
internal/tfengine/schema.go
0.558327
0.456228
schema.go
starcoder
package behaviours import ( "fmt" "github.com/MaximeWeyl/goTestifyRecursive/formatting" "github.com/stretchr/testify/assert" "reflect" ) //ExpectedStruct Assert/Require a struct. The values are the behaviours we expect for each element type ExpectedStruct map[string]interface{} //CheckField Assert that a value struct matches the expected slice func (e ExpectedStruct) CheckField(t assert.TestingT, actualValueInterface interface{}, parentFieldName string) bool { actualType := reflect.TypeOf(actualValueInterface) actualValue := reflect.ValueOf(actualValueInterface) // This utility is for testing structs ! if actualType.Kind() != reflect.Struct { return assert.Fail(t, "Non struct", "Tried to check an expected struct against a non struct object, consider fixing your test for field {%s}", parentFieldName) } var success = true // We browse all expected fields and test if they correspond to the actual struct or not for fieldKey, expectedFieldInterface := range e { _, structFieldFound := actualType.FieldByName(fieldKey) fieldName := formatting.FormatFieldName(parentFieldName, fieldKey) if !structFieldFound { success = assert.Fail(t, "Field not found", "Expected field not found : {%s}", fieldName, ) && success continue } actualFieldValue := actualValue.FieldByName(fieldKey) actualFieldInterface := actualFieldValue.Interface() switch castedExpectedField := expectedFieldInterface.(type) { case FieldBehaviour: success = castedExpectedField.CheckField( t, actualFieldInterface, fieldName, ) && success default: success = assert.Equalf( t, expectedFieldInterface, actualFieldInterface, "Check of Equality for field {%s}", fieldName, ) && success } } // If some fields were not reviewed, we fail and tell what fields were missing allFieldsReviewed := len(e) == actualType.NumField() if !allFieldsReviewed { missingFields := make([]string, 0) for i := 0; i < actualType.NumField(); i++ { name := actualType.Field(i).Name _, found := e[name] if !found { missingFields = append(missingFields, name) } } precision := "" if parentFieldName != "" { precision = fmt.Sprintf("of field {%s} ", parentFieldName) } if len(missingFields) != 0 { missingFieldsString := "" for i, s := range missingFields { if i != 0 { missingFieldsString += ", " } missingFieldsString += fmt.Sprintf("{%s}", s) } success = assert.Fail( t, "Fields are missing", "Some fields %sare missing : %s", precision, missingFieldsString, ) && success } } return success }
behaviours/expectedStruct.go
0.650689
0.459319
expectedStruct.go
starcoder
package nmea /** $WIMWV NMEA 0183 standard Wind Speed and Angle, in relation to the vessel’s bow/centerline. Syntax $WIMWV,<1>,<2>,<3>,<4>,<5>*hh<CR><LF> Fields <1> Wind angle, 0.0 to 359.9 degrees, in relation to the vessel’s bow/centerline, to the nearest 0.1 degree. If the data for this field is not valid, the field will be blank. <2> Reference: R = Relative (apparent wind, as felt when standing on the moving ship) T = Theoretical (calculated actual wind, as though the vessel were stationary) <3> Wind speed, to the nearest tenth of a unit. If the data for this field is not valid, the field will be blank. <4> Wind speed units: K = km/hr M = m/s N = knots S = statute miles/hr (Most WeatherStations will commonly use "N" (knots)) <5> Status: A = data valid; V = data invalid */ const ( // TypeMWV type for MWV sentences TypeMWV = "MWV" // RelativeMWV for Valid Relative angle data RelativeMWV = "R" // TheoreticalMWV for valid Theoretical angle data TheoreticalMWV = "T" // UnitKMHMWV unit for Kilometer per hour (KM/H) UnitKMHMWV = "K" // KM/H // UnitMSMWV unit for Meters per second (M/S) UnitMSMWV = "M" // M/S // UnitKnotsMWV unit for knots UnitKnotsMWV = "N" // knots // UnitSMilesHMWV unit for Miles per hour (M/H) UnitSMilesHMWV = "S" // ValidMWV data is valid ValidMWV = "A" // InvalidMWV data is invalid InvalidMWV = "V" ) // MWV is the Wind Speed and Angle, in relation to the vessel’s bow/centerline. type MWV struct { BaseSentence WindAngle float64 Reference string WindSpeed float64 WindSpeedUnit string StatusValid bool } func newMWV(s BaseSentence) (MWV, error) { p := NewParser(s) p.AssertType(TypeMWV) return MWV{ BaseSentence: s, WindAngle: p.Float64(0, "wind angle"), Reference: p.EnumString(1, "reference", RelativeMWV, TheoreticalMWV), WindSpeed: p.Float64(2, "wind speed"), WindSpeedUnit: p.EnumString(3, "wind speed unit", UnitKMHMWV, UnitMSMWV, UnitKnotsMWV, UnitSMilesHMWV), StatusValid: p.EnumString(4, "status", ValidMWV, InvalidMWV) == ValidMWV, }, p.Err() }
mwv.go
0.649579
0.55923
mwv.go
starcoder
package model /* ModelType defines a type for use by models. */ type ModelType int const ( // ModelTypeList causes the model to behave as a list (keys are unsigned, // contiguous integers beginning at 0). ModelTypeList ModelType = iota // ModelTypeHash causes the model to behave as a hash (keys are strings, // order is static). ModelTypeHash ) /* Model is a list or a map of Values. This interface defines data storage and access methods for data models in order to provide a consistent interface for communicating messages between instances. This allows several abstractions on and recursions into multidimensional untyped data structures. */ type Model interface { // Delete removes a value from this model. Delete(key interface{}) error // Filter filters elements of the data using a callback function and // returns the result. Filter(callback func(Value) Model) Model // Get returns the specified data value in this model. Get(key interface{}) (Value, error) // GetID returns returns this model's id. GetID() interface{} // GetType returns the model type. GetType() ModelType // Has tests to see of a specified data element exists in this model. Has(key interface{}) bool // Lock marks this model as read-only. There is no Unlock. Lock() // Map applies a callback to all elements in this model and returns the // result. Map(callback func(Value) Model) Model // Merge merges data from any Model into this Model. Merge(Model) error // Push a value to the end of the internal data store. Push(value interface{}) error // Reduce iteratively reduces the data set to a single value using a // callback function and returns the result. Reduce(callback func(Value) bool) Value // Set stores a value in the internal data store. All values must be // identified by key. Set(key interface{}, value interface{}) error // SetData replaces the current data stored in the model with the // provided data. SetData(data interface{}) error // SetID sets this Model's identifier property. SetID(id interface{}) // SetType sets the model type. If any data is stored in this model, // this property becomes read-only. SetType(typ ModelType) error }
model/model.go
0.606032
0.470676
model.go
starcoder
// Package advsearch searches elements in sorted slices or user defined collections of any kind // Because of the generic interfaces, advsearch can also be used to define possible insertion // positions in a data structure or a position in a data structure based on other criteria // based on the user's implementation of the Match() function. package advsearch import ( "errors" "math" ) const ( eps float64 = 0.0000001 ) // Searchable is the interface to implement to be able to use BinarySearch // on your data structure. // The package requires that elements can be enumerated with an integer based index. type Searchable interface { // True, if the value of e is smaller than the element at index i Smaller(e interface{}, i int) bool // Length of the data structure (element count) Len() int // Defines if we have a match based on the index i. // Most likely when e and value at i are equal. // You may also look at the elements before or after i to // determine a match (i.e. to find a possible insertion position). Match(e interface{}, i int) bool } // SearchableInterpolation is the interface to implement to be able to use // Interpolation Search and Quadratic Binary Search on your data structure. type SearchableInterpolation interface { // We need all defined methods from Searchable Searchable // Method to get a value that can be used to interpolate the approximate // position in your data structure. Integers or other numbers can just // be casted to float64. This will not affect your search negatively. // This is needed for interpolation search and quadratic binary search. GetValue(i int) float64 // Additionally, we don't know, what elements are in the data structure. // So we need the additional conversion function to work with e. ExtractValue(e interface{}) float64 } func findLeftInterval(s SearchableInterpolation, e interface{}, stepSize, start int) int { thisStep := start - stepSize for s.ExtractValue(e) < s.GetValue(thisStep) && thisStep > 0 { thisStep -= stepSize } if thisStep < 0 { return 0 } return thisStep } func findRightInterval(s SearchableInterpolation, e interface{}, stepSize, start int) int { thisStep := start + stepSize for thisStep < s.Len() && s.ExtractValue(e) > s.GetValue(thisStep) { thisStep += stepSize } if thisStep >= s.Len() { return s.Len() - 1 } return thisStep } func quadSearch(s SearchableInterpolation, e interface{}, l, r int) (int, error) { // Check against possible division by zero later. if s.Match(e, l) { return l, nil } if r < l || math.Abs(s.GetValue(l)-s.GetValue(r)) <= eps { return -1, errors.New("No index could be found for the given element.") } percentage := (s.ExtractValue(e) - s.GetValue(l)) / (s.GetValue(r) - s.GetValue(l)) // When the element we are looking for is outside the given range if percentage > 1.0 || percentage < 0.0 { return -1, errors.New("The element seems to be outside the given range.") } index := int(percentage*float64(r-l) + float64(l)) if s.Match(e, index) { return index, nil } if s.Smaller(e, index) { return quadSearch(s, e, findLeftInterval(s, e, int(math.Sqrt(float64(index-1-l))), index-1), index-1) } return quadSearch(s, e, index+1, findRightInterval(s, e, int(math.Sqrt(float64(r-(index+1)))), index+1)) } // QuadraticBinarySearch searches a match of the element e in the sorted data structure s. // It will return the index/position in s based on your implementation of s.Match(). // Assuming that all methods of the interface Searchable and SearchableInterpolation run in O(1), // QuadraticBinarySearch will have a time complexity of θ(sqrt(n)) worst case and θ(log(log(n))) average case. // Pre-condition: s must be sorted! func QuadraticBinarySearch(s SearchableInterpolation, e interface{}) (int, error) { return quadSearch(s, e, 0, s.Len()-1) } func intSearch(s SearchableInterpolation, e interface{}, l, r int) (int, error) { // Check against possible division by zero later. if s.Match(e, l) { return l, nil } if r < l || math.Abs(s.GetValue(l)-s.GetValue(r)) <= eps { return -1, errors.New("No index could be found for the given element.") } percentage := (s.ExtractValue(e) - s.GetValue(l)) / (s.GetValue(r) - s.GetValue(l)) // When the element we are looking for is outside the given range if percentage > 1.0 || percentage < 0.0 { return -1, errors.New("The element seems to be outside the given range.") } index := int(percentage*float64(r-l) + float64(l)) if s.Match(e, index) { return index, nil } if s.Smaller(e, index) { return intSearch(s, e, l, index-1) } return intSearch(s, e, index+1, r) } // InterpolationSearch searches a match of the element e in the sorted data structure s. // It will return the index/position in s based on your implementation of s.Match(). // Assuming that all methods of the interface Searchable and SearchableInterpolation run in O(1), // InterpolationSearch will have a time complexity of θ(n) worst case and θ(log(log(n))) average case. // Pre-condition: s must be sorted! func InterpolationSearch(s SearchableInterpolation, e interface{}) (int, error) { return intSearch(s, e, 0, s.Len()-1) } func binSearch(s Searchable, e interface{}, l, r int) (int, error) { if r < l { return -1, errors.New("No index could be found for the given element in the data structure") } index := (r + l) / 2 if s.Match(e, index) { return index, nil } if s.Smaller(e, index) { return binSearch(s, e, l, index-1) } return binSearch(s, e, index+1, r) } // BinarySearch searches a match of the element e in the sorted data structure s. // It will return the index/position in s based on your implementation of s.Match(). // Assuming that all methods of the interface Searchable run in O(1), BinarySearch // will have a guaranteed time complexity of θ(log(n)) worst and average case. // Pre-condition: s must be sorted! func BinarySearch(s Searchable, e interface{}) (int, error) { return binSearch(s, e, 0, s.Len()-1) }
advsearch.go
0.83104
0.633779
advsearch.go
starcoder
package cmd import ( "fmt" "github.com/spf13/cobra" ) const usage = `The following instructions are supported: Directives: ".begin" ".end" ".org" Memory: "ld" "st" Arithmetic: "add", "addcc" "sub", "subcc" Logic: "and", "andcc" "or", "orcc" "orn", "orncc" "xor", "xorcc" "sll", "sra" Control: "be" "bne" "bneg" "bpos" "ba" Subroutine: "call" "jmpl" "ld": Load a register from main memory. The memory address must be aligned on a word boundary. Example usages: ld [x], %r1. Meaning: Copy the contents of memory location x into register %r1. "st": Store a register into main memory. The memory address must be aligned on a word boundary. Example usages: st %r1, [x]. Meaning: Store the contents of %r1 into the memory location x. "add", "addcc": Adds the source operands into the destination register using two's complement arithmetic. "addcc" sets the condition codes according to the result. Example usage: add %r1, %r2, %r4. Meaning: %r4 = %r1 + %r2 Example usage: addcc %r1, 2, %r2. Meaning: %r2 = %r2 + 2 "sub", "subcc": Perform integer subtraction on the source operands and put result into the destination register using two's complement arithmetic. "subcc" sets the condition codes according to the result. Example usage: sub %r1, %r2, %r4. Meaning: %r4 = %r1 - %r2 Example usage: subcc %r1, 2, %r2. Meaning: %r2 = %r2 - 2 "and", "andcc": Bitwise AND the source operands into the destination register. "andcc" sets the N and Z condition codes according to the result. Example usage: and %r1, %r2, %r4. Meaning: %r4 = %r1 AND %r2 Example usage: andcc %r1, 2, %r4. Meaning: %r4 = %r1 AND 2 "or", "orcc": Bitwise OR the source operands into the destination register. "orcc" sets the N and Z condition codes according to the result. Example usage: or %r1, %r2, %r4. Meaning: %r4 = %r1 AND %r2 Example usage: orcc %r1, 1, %r2. Meaning: %r2 = %r1 OR 1 "orn", "orncc": Bitwise NOR the source operands into the destination register. "orncc" will set the N and Z condition codes according to the result. Example usage: orncc %r1, %r0, %r1. Meaning: Complement %r1. "xor", "xorcc": Bitwise XOR (exclusive OR) the source operands into the destination register. "xorcc" will set the N and Z condition codes according to the result. Example usage: xorcc %r1, %r0, %r1. Meaning: %r1 = %r1 XOR %r0. "sll": Shifts a register to the left by 0-31 bits. The vacant bit positions in the right side of the shifted register are filled with 0's. Example usage: sll %r1, 3, %r4. Meaning: Shift %r1 left by 3 bits and store in %r4. Example usage: sll %r1, %r4, %r5. Meaning: Shift %r1 left by the value stored in %r4 and store in %r5. "sra": Shifts a register to the right by 0-31 bits. The sign bit is replicated as the value is shifted right. Example usage: sra %r1, 3, %r4. Meaning: Shift %r1 right by 3 bits and store in %r4. Example usage: sra %r1, %r4, %r5. Meaning: Shift %r1 right by the value stored in %r4 and store in %r5. "be": Branch on equal to zero. If the z condition code is 1, then branch to the address represented by the label which is the instruction operand. Example usage: be label. Meaning: Branch to label if Z is 1. "bne": Branch on not equal. Branch if not equal to zero to the address represented by the label which is the instruction operand. Example usage: bne label. Meaning: Branch to label if not equal to zero. "bneg": Branch on negative. If the n condition code is 1, then branch to the address represented by the label which is the instruction operand. Example usage: bneg label. Meaning: Branch to label if N is 1. "bne": Branch on not equal. Branch if not equal to zero to the address represented by the label which is the instruction operand. Example usage: bne label. Meaning: Branch to label if not equal to zero. "bpos": Branch on positive. If the condition codes signal a positive result, branch to the address represented by the label which is the instruction operand. Example usage: bpos label. Meaning: Branch if positive. "ba": Branch always. Always branch to the address represented by the label which is the instruction operand. Example usage: ba label. Meaning: Always branch to label. "call": Call a subroutine and store the address of the current instruction in %r15. The instruction operand is the address of the subroutine and is stored as a 30 bit displacement in the call instruction format. Example usage: call sub_r. Meaning: Call the subroutine located at sub_r. "jmpl": Unconditional, register indirect control transfer. Jump to a new address and store the address of the current instruction in the destination register. Example usage: jmpl %r15 + 4, %r2. Meaning: Set the program counter to the contents of %r15 + 4. The current address is stored into %r2. The following pseudo-operations are supported: .begin, .end: Start and stop assembly, respectively. .org: Change location counter to the address specified. Example usage: .org 0x800. The next instruction will be assembled at location 0x800 (2048). NOTE: A pseudo-operation should NOT be followed by a colon because it is not a program label. Comments begin with the "!" symbol and continue to the end of line. Example usage: ba exit ! Go to program exit ` // usageCmd represents the usage command var usageCmd = &cobra.Command{ Use: "usage", Short: "Show advanced usage information and supported instructions", Long: `Show detailed information about the ARC assembly language and supported ARC instructions.`, Run: func(cmd *cobra.Command, args []string) { fmt.Print(usage) }, } func init() { RootCmd.AddCommand(usageCmd) }
cmd/arc/cmd/usage.go
0.745861
0.563498
usage.go
starcoder
package feature import ( "github.com/shuLhan/numerus" "github.com/shuLhan/tekstus" "github.com/shuLhan/wvcgen/revision" "math" ) /* KullbackLeiblerDivergence comput and return the divergence of two string based on their character probabability. */ func KullbackLeiblerDivergence(a, b string) (divergence float64) { aCharsd, aValuesd := tekstus.CountAlnumDistribution(a) bCharsd, bValuesd := tekstus.CountAlnumDistribution(b) sumValuesA := numerus.IntsSum(aValuesd) sumValuesB := numerus.IntsSum(bValuesd) charsDiff := tekstus.RunesDiff(aCharsd, bCharsd) aMin, _, _ := numerus.IntsFindMin(aValuesd) bMin, _, _ := numerus.IntsFindMin(bValuesd) min := aMin if bMin < aMin { min = bMin } epsilon := float64(min) * 0.001 gamma := 1.0 - (float64(len(charsDiff)) * epsilon) // Check if sum of a up to 1. var sum float64 for _, v := range aValuesd { sum += float64(v) / float64(sumValuesA) } sumDiff := 1 - math.Abs(sum) if sumDiff > 0.000009 { return 0 } sum = 0 for _, v := range bValuesd { sum += float64(v) / float64(sumValuesB) } sumDiff = 1 - math.Abs(sum) if sumDiff > 0.000009 { return 0 } for x, v := range aCharsd { probA := float64(aValuesd[x]) / float64(sumValuesA) probB := epsilon contain, atIdx := tekstus.RunesContain(bCharsd, v) if contain { probB = gamma * (float64(bValuesd[atIdx]) / float64(sumValuesB)) } divergence += (probA - probB) * math.Log(probA/probB) } return divergence } /* ComputeImpact return percentage of words in new revision compared to old revision, using count_of_words_in_new / (count_of_words_in_old + count_of_words_in_new) if no words are found in old and new revision, return 0. */ func ComputeImpact(oldrevid, newrevid string, wordlist []string) float64 { oldtext, _ := revision.GetContentClean(oldrevid) newtext, _ := revision.GetContentClean(newrevid) oldCnt := tekstus.StringCountTokens(oldtext, wordlist, false) newCnt := tekstus.StringCountTokens(newtext, wordlist, false) total := float64(oldCnt + newCnt) if total == 0 { return 0 } return float64(newCnt) / total }
feature/algorithm.go
0.655887
0.412826
algorithm.go
starcoder
package query import ( "fmt" "strconv" "strings" ) // Querier provides the interface to query using a given command and provide // the resultant string. The command string should include the appropriate // terminator for the instrument. type Querier interface { Query(cmd string) (value string, err error) } // Bool queries a Querier with the given command and returns a bool. func Bool(q Querier, cmd string) (bool, error) { s, err := q.Query(cmd) if err != nil { return false, err } switch s { case "OFF", "0": return false, nil case "ON", "1": return true, nil default: return false, fmt.Errorf("could not determine boolean status from %s", s) } } // Boolf queries the Querier according to a format specifier and returns a // bool. func Boolf(q Querier, format string, a ...interface{}) (bool, error) { return Bool(q, fmt.Sprintf(format, a...)) } // Float64 queries the Querier with the given command and returns a float64. func Float64(q Querier, cmd string) (float64, error) { s, err := q.Query(cmd) if err != nil { return 0.0, err } return strconv.ParseFloat(strings.TrimSpace(s), 64) } // Float64f queries the querier according to a format specifier and returns a // float. func Float64f(q Querier, format string, a ...interface{}) (float64, error) { return Float64(q, fmt.Sprintf(format, a...)) } // Int queries the querier with the given command and returns an int. func Int(q Querier, cmd string) (int, error) { s, err := q.Query(cmd) if err != nil { return 0, err } i, err := strconv.ParseInt(strings.TrimSpace(s), 10, 32) return int(i), err } // Intf queries the querier according to a format specifier and returns a // int. func Intf(q Querier, format string, a ...interface{}) (int, error) { return Int(q, fmt.Sprintf(format, a...)) } // String queries the querier with the given command and returns a string. func String(q Querier, cmd string) (string, error) { return q.Query(cmd) } // Stringf queries the querier according to a format specifier and returns a // string. func Stringf(q Querier, format string, a ...interface{}) (string, error) { return String(q, fmt.Sprintf(format, a...)) }
query.go
0.744471
0.411643
query.go
starcoder
package ansi8 import ( "fmt" "github.com/shyang107/pencil" ) // Print formats using the default formats for its operands and writes to // standard output. Spaces are added between operands when neither is a // string. It returns the number of bytes written and any write error // encountered. This is the standard fmt.Print() method wrapped with the given // color. func (c *Color) Print(a ...interface{}) (n int, err error) { c.Set() defer c.unset() return fmt.Fprint(pencil.Output, a...) } // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. // This is the standard fmt.Printf() method wrapped with the given color. func (c *Color) Printf(format string, a ...interface{}) (n int, err error) { c.Set() defer c.unset() return fmt.Fprintf(pencil.Output, format, a...) } // Println formats using the default formats for its operands and writes to // standard output. Spaces are always added between operands and a newline is // appended. It returns the number of bytes written and any write error // encountered. This is the standard fmt.Print() method wrapped with the given // color. func (c *Color) Println(a ...interface{}) (n int, err error) { c.Set() defer c.unset() return fmt.Fprintln(pencil.Output, a...) } // PrintFunc returns a new function that prints the passed arguments as // colorized with color.Print(). func (c *Color) PrintFunc() func(a ...interface{}) { return func(a ...interface{}) { c.Print(a...) } } // PrintfFunc returns a new function that prints the passed arguments as // colorized with color.Printf(). func (c *Color) PrintfFunc() func(format string, a ...interface{}) { return func(format string, a ...interface{}) { c.Printf(format, a...) } } // PrintlnFunc returns a new function that prints the passed arguments as // colorized with color.Println(). func (c *Color) PrintlnFunc() func(a ...interface{}) { return func(a ...interface{}) { c.Println(a...) } }
ansi8/print.go
0.763748
0.405478
print.go
starcoder
package tournify import ( "errors" "fmt" "sort" ) // TeamStatsInterface is used to show team statistics. Currently this is specifically made for // group tournaments where there is a need to rank teams. type TeamStatsInterface interface { GetGroup() GroupInterface GetTeam() TeamInterface GetPlayed() int GetWins() int GetLosses() int GetTies() int GetPointsFor() float64 GetPointsAgainst() float64 GetDiff() float64 GetPoints() int AddPoints(points int) Print() string } // TeamStats is a default struct used as an example of how structs can be implemented for tournify type TeamStats struct { Tournament TournamentInterface Group GroupInterface Team TeamInterface Played int Wins int Losses int Ties int PointsFor float64 PointsAgainst float64 Points int } // GetGroup returns the Group that the statistics were generated for, stats are directly related to a team and the group they are in. func (t *TeamStats) GetGroup() GroupInterface { return t.Group } // GetTeam returns the Team that the statistics were generated for, stats are directly related to a team and the group they are in. func (t *TeamStats) GetTeam() TeamInterface { return t.Team } // GetPlayed returns the number of games played func (t *TeamStats) GetPlayed() int { return t.Played } // GetWins returns the number of won games func (t *TeamStats) GetWins() int { return t.Wins } // GetLosses returns the number of lost games func (t *TeamStats) GetLosses() int { return t.Losses } // GetTies returns the number of games resulting in a tied game func (t *TeamStats) GetTies() int { return t.Ties } // GetPointsFor returns the number of goals or points that this team has made func (t *TeamStats) GetPointsFor() float64 { return t.PointsFor } // GetPointsAgainst returns the number of goals or points that other teams have made against this team func (t *TeamStats) GetPointsAgainst() float64 { return t.PointsAgainst } // GetDiff returns the difference of PointsFor and PointsAgainst func (t *TeamStats) GetDiff() float64 { return t.PointsFor - t.PointsAgainst } // GetPoints returns the number of points the team has based on wins, losses or ties func (t *TeamStats) GetPoints() int { return t.Points } // AddPoints adds the specified number of points to Points func (t *TeamStats) AddPoints(points int) { t.Points += points } // Print prints the stats as a single string func (t *TeamStats) Print() string { return fmt.Sprintf("%d\t%d\t%d\t%d\t%d\t%d\t%.0f/%.0f\t%.0f\t%d", t.GetGroup().GetID(), t.GetTeam().GetID(), t.GetPlayed(), t.GetWins(), t.GetTies(), t.GetLosses(), t.GetPointsFor(), t.GetPointsAgainst(), t.GetDiff(), t.GetPoints()) } // PrintGroupTournamentStats takes an array of team stats and returns them as a single string with a new line for each team func PrintGroupTournamentStats(teamStats []TeamStatsInterface) string { res := "Group\tTeam\tPlayed\tWins\tTies\tLosses\t+/-\tDiff\tPoints\n" for _, ts := range teamStats { res += ts.Print() res += "\n" } return res } // GetGroupTournamentStats takes 4 inputs. The first input is the tournament itself. // The other three input defines how many points a team should get for a win, loss or tie. The standard is 3, 0, 1 but // it can vary depending on the tournament. func GetGroupTournamentStats(t TournamentInterface, winPoints int, lossPoints int, tiePoints int) ([]TeamStatsInterface, error) { if t.GetType() != int(TournamentTypeGroup) { return nil, errors.New("can not get stats for tournament type which is not TournamentTypeGroup") } var stats []TeamStatsInterface for _, group := range t.GetGroups() { groupStats := GetGroupStats(group, winPoints, lossPoints, tiePoints) stats = append(stats, groupStats...) } return stats, nil } // GetGroupStats returns the current stats for all the teams in a single group func GetGroupStats(group GroupInterface, winPoints int, lossPoints int, tiePoints int) []TeamStatsInterface { var groupStats []TeamStatsInterface teamStats := map[int]*TeamStats{} for _, team := range *group.GetTeams() { teamStats[team.GetID()] = &TeamStats{ Group: group, Team: team, } } for _, game := range *group.GetGames() { if _, ok := teamStats[game.GetHomeTeam().GetID()]; !ok { teamStats[game.GetHomeTeam().GetID()] = &TeamStats{ Group: group, Team: game.GetHomeTeam(), } } // Calculate stats for the home team in every game teamStats[game.GetHomeTeam().GetID()].PointsFor += game.GetHomeScore().GetPoints() teamStats[game.GetHomeTeam().GetID()].PointsAgainst += game.GetAwayScore().GetPoints() if game.GetHomeScore().GetPoints() > game.GetAwayScore().GetPoints() { teamStats[game.GetHomeTeam().GetID()].Wins++ } else if game.GetHomeScore().GetPoints() == game.GetAwayScore().GetPoints() { teamStats[game.GetHomeTeam().GetID()].Ties++ } else { teamStats[game.GetHomeTeam().GetID()].Losses++ } teamStats[game.GetHomeTeam().GetID()].Played++ // Calculate stats for the away team in every game if _, ok := teamStats[game.GetAwayTeam().GetID()]; !ok { teamStats[game.GetAwayTeam().GetID()] = &TeamStats{ Group: group, Team: game.GetAwayTeam(), } } teamStats[game.GetAwayTeam().GetID()].PointsFor += game.GetAwayScore().GetPoints() teamStats[game.GetAwayTeam().GetID()].PointsAgainst += game.GetHomeScore().GetPoints() if game.GetHomeScore().GetPoints() < game.GetAwayScore().GetPoints() { teamStats[game.GetAwayTeam().GetID()].Wins++ } else if game.GetHomeScore().GetPoints() == game.GetAwayScore().GetPoints() { teamStats[game.GetAwayTeam().GetID()].Ties++ } else { teamStats[game.GetAwayTeam().GetID()].Losses++ } teamStats[game.GetAwayTeam().GetID()].Played++ } for _, t := range teamStats { t.Points = t.Wins * winPoints t.Points += t.Losses * lossPoints t.Points += t.Ties * tiePoints groupStats = append(groupStats, t) } groupStats = SortTournamentStats(groupStats) return groupStats } // SortTournamentStats sorts the statistics by points, diff and finally scored goals against other teams func SortTournamentStats(stats []TeamStatsInterface) []TeamStatsInterface { sort.Slice(stats, func(i, j int) bool { if stats[i].GetPoints() > stats[j].GetPoints() { return true } else if stats[i].GetPoints() < stats[j].GetPoints() { return false } else { if stats[i].GetDiff() > stats[j].GetDiff() { return true } else if stats[i].GetDiff() < stats[j].GetDiff() { return false } else { if stats[i].GetPointsFor() > stats[j].GetPointsFor() { return true } else if stats[i].GetPointsFor() < stats[j].GetPointsFor() { return false } } } return true }) return stats }
teamstats.go
0.616012
0.451508
teamstats.go
starcoder
package tree /* This package support the generation of an "at glance" view of a Cluster API cluster designed to help the user in quickly understanding if there are problems and where. The "at glance" view is based on the idea that we should avoid to overload the user with information, but instead surface problems, if any; in practice: - The view assumes we are processing objects conforming with https://github.com/kubernetes-sigs/cluster-api/blob/master/docs/proposals/20200506-conditions.md. As a consequence each object should have a Ready condition summarizing the object state. - The view organizes objects in a hierarchical tree, however it is not required that the tree reflects the ownerReference tree so it is possible to skip objects not relevant for triaging the cluster status e.g. secrets or templates. - It is possible to add "meta names" to object, thus making hierarchical tree more consistent for the users, e.g. use MachineInfrastructure instead of using all the different infrastructure machine kinds (AWSMachine, VSphereMachine etc.). - It is possible to add "virtual nodes", thus allowing to make the hierarchical tree more meaningful for the users, e.g. adding a Workers object to group all the MachineDeployments. - It is possible to "group" siblings objects by ready condition e.g. group all the machines with Ready=true in a single node instead of listing each one of them. - Given that the ready condition of the child object bubbles up to the parents, it is possible to avoid the "echo" (reporting the same condition at the parent/child) e.g. if a machine's Ready condition is already surface an error from the infrastructure machine, let's avoid to show the InfrastructureMachine given that representing its state is redundant in this case. - In order to avoid long list of objects (think e.g. a cluster with 50 worker machines), sibling objects with the same value for the ready condition can be grouped together into a virtual node, e.g. 10 Machines ready The ObjectTree object defined implements all the above behaviors of the "at glance" visualization, by generating a tree of Kubernetes objects; each object gets a set of annotation, reflecting its own visualization specific attributes, e.g is virtual node, is group node, meta name etc. The Discovery object uses the ObjectTree to build the "at glance" view of a Cluster API. */
cmd/clusterctl/client/tree/doc.go
0.857589
0.774413
doc.go
starcoder
package transform type WHT16 struct { fScale uint iScale uint data []int } // For perfect reconstruction, forward results are scaled by 8 unless the // parameter is set to false (in which case rounding may roduce errors) func NewWHT16(scale bool) (*WHT16, error) { this := new(WHT16) this.data = make([]int, 256) if scale == true { this.fScale = 0 this.iScale = 8 } else { this.fScale = 4 this.iScale = 4 } return this, nil } // For perfect reconstruction, forward results are scaled by 16 unless // parameter is set to false (in which case rounding may introduce errors) func (this *WHT16) Forward(src, dst []int) (uint, uint, error) { return this.compute(src, dst, this.fScale) } func (this *WHT16) compute(input, output []int, shift uint) (uint, uint, error) { dataptr := 0 buffer := this.data // alias // Pass 1: process rows. for i := 0; i < 256; i += 16 { // Aliasing for speed x0 := input[i] x1 := input[i+1] x2 := input[i+2] x3 := input[i+3] x4 := input[i+4] x5 := input[i+5] x6 := input[i+6] x7 := input[i+7] x8 := input[i+8] x9 := input[i+9] x10 := input[i+10] x11 := input[i+11] x12 := input[i+12] x13 := input[i+13] x14 := input[i+14] x15 := input[i+15] a0 := x0 + x1 a1 := x2 + x3 a2 := x4 + x5 a3 := x6 + x7 a4 := x8 + x9 a5 := x10 + x11 a6 := x12 + x13 a7 := x14 + x15 a8 := x0 - x1 a9 := x2 - x3 a10 := x4 - x5 a11 := x6 - x7 a12 := x8 - x9 a13 := x10 - x11 a14 := x12 - x13 a15 := x14 - x15 b0 := a0 + a1 b1 := a2 + a3 b2 := a4 + a5 b3 := a6 + a7 b4 := a8 + a9 b5 := a10 + a11 b6 := a12 + a13 b7 := a14 + a15 b8 := a0 - a1 b9 := a2 - a3 b10 := a4 - a5 b11 := a6 - a7 b12 := a8 - a9 b13 := a10 - a11 b14 := a12 - a13 b15 := a14 - a15 a0 = b0 + b1 a1 = b2 + b3 a2 = b4 + b5 a3 = b6 + b7 a4 = b8 + b9 a5 = b10 + b11 a6 = b12 + b13 a7 = b14 + b15 a8 = b0 - b1 a9 = b2 - b3 a10 = b4 - b5 a11 = b6 - b7 a12 = b8 - b9 a13 = b10 - b11 a14 = b12 - b13 a15 = b14 - b15 buffer[dataptr] = a0 + a1 buffer[dataptr+1] = a2 + a3 buffer[dataptr+2] = a4 + a5 buffer[dataptr+3] = a6 + a7 buffer[dataptr+4] = a8 + a9 buffer[dataptr+5] = a10 + a11 buffer[dataptr+6] = a12 + a13 buffer[dataptr+7] = a14 + a15 buffer[dataptr+8] = a0 - a1 buffer[dataptr+9] = a2 - a3 buffer[dataptr+10] = a4 - a5 buffer[dataptr+11] = a6 - a7 buffer[dataptr+12] = a8 - a9 buffer[dataptr+13] = a10 - a11 buffer[dataptr+14] = a12 - a13 buffer[dataptr+15] = a14 - a15 dataptr += 16 } dataptr = 0 adjust := (1 << shift) >> 1 // Pass 2: process columns. for i := 0; i < 16; i++ { // Aliasing for speed x0 := buffer[dataptr] x1 := buffer[dataptr+16] x2 := buffer[dataptr+32] x3 := buffer[dataptr+48] x4 := buffer[dataptr+64] x5 := buffer[dataptr+80] x6 := buffer[dataptr+96] x7 := buffer[dataptr+112] x8 := buffer[dataptr+128] x9 := buffer[dataptr+144] x10 := buffer[dataptr+160] x11 := buffer[dataptr+176] x12 := buffer[dataptr+192] x13 := buffer[dataptr+208] x14 := buffer[dataptr+224] x15 := buffer[dataptr+240] a0 := x0 + x1 a1 := x2 + x3 a2 := x4 + x5 a3 := x6 + x7 a4 := x8 + x9 a5 := x10 + x11 a6 := x12 + x13 a7 := x14 + x15 a8 := x0 - x1 a9 := x2 - x3 a10 := x4 - x5 a11 := x6 - x7 a12 := x8 - x9 a13 := x10 - x11 a14 := x12 - x13 a15 := x14 - x15 b0 := a0 + a1 b1 := a2 + a3 b2 := a4 + a5 b3 := a6 + a7 b4 := a8 + a9 b5 := a10 + a11 b6 := a12 + a13 b7 := a14 + a15 b8 := a0 - a1 b9 := a2 - a3 b10 := a4 - a5 b11 := a6 - a7 b12 := a8 - a9 b13 := a10 - a11 b14 := a12 - a13 b15 := a14 - a15 a0 = b0 + b1 a1 = b2 + b3 a2 = b4 + b5 a3 = b6 + b7 a4 = b8 + b9 a5 = b10 + b11 a6 = b12 + b13 a7 = b14 + b15 a8 = b0 - b1 a9 = b2 - b3 a10 = b4 - b5 a11 = b6 - b7 a12 = b8 - b9 a13 = b10 - b11 a14 = b12 - b13 a15 = b14 - b15 output[i] = (a0 + a1 + adjust) >> shift output[i+16] = (a2 + a3 + adjust) >> shift output[i+32] = (a4 + a5 + adjust) >> shift output[i+48] = (a6 + a7 + adjust) >> shift output[i+64] = (a8 + a9 + adjust) >> shift output[i+80] = (a10 + a11 + adjust) >> shift output[i+96] = (a12 + a13 + adjust) >> shift output[i+112] = (a14 + a15 + adjust) >> shift output[i+128] = (a0 - a1 + adjust) >> shift output[i+144] = (a2 - a3 + adjust) >> shift output[i+160] = (a4 - a5 + adjust) >> shift output[i+176] = (a6 - a7 + adjust) >> shift output[i+192] = (a8 - a9 + adjust) >> shift output[i+208] = (a10 - a11 + adjust) >> shift output[i+224] = (a12 - a13 + adjust) >> shift output[i+240] = (a14 - a15 + adjust) >> shift dataptr++ } return 256, 256, nil } // The transform is symmetric (except, potentially, for scaling) func (this *WHT16) Inverse(src, dst []int) (uint, uint, error) { return this.compute(src, dst, this.iScale) }
go/src/kanzi/transform/WHT16.go
0.552781
0.42483
WHT16.go
starcoder
package tracker import "github.com/vsariola/sointu" type SongRow struct { Pattern int Row int } type SongPoint struct { Track int SongRow } type SongRect struct { Corner1 SongPoint Corner2 SongPoint } func (r SongRow) AddRows(rows int) SongRow { return SongRow{Row: r.Row + rows, Pattern: r.Pattern} } func (r SongRow) AddPatterns(patterns int) SongRow { return SongRow{Row: r.Row, Pattern: r.Pattern + patterns} } func (r SongRow) Wrap(score sointu.Score) SongRow { totalRow := r.Pattern*score.RowsPerPattern + r.Row r.Row = mod(totalRow, score.RowsPerPattern) r.Pattern = mod((totalRow-r.Row)/score.RowsPerPattern, score.Length) return r } func (r SongRow) Clamp(score sointu.Score) SongRow { totalRow := r.Pattern*score.RowsPerPattern + r.Row if totalRow < 0 { totalRow = 0 } if totalRow >= score.LengthInRows() { totalRow = score.LengthInRows() - 1 } r.Row = totalRow % score.RowsPerPattern r.Pattern = ((totalRow - r.Row) / score.RowsPerPattern) % score.Length return r } func (r SongPoint) AddRows(rows int) SongPoint { return SongPoint{Track: r.Track, SongRow: r.SongRow.AddRows(rows)} } func (r SongPoint) AddPatterns(patterns int) SongPoint { return SongPoint{Track: r.Track, SongRow: r.SongRow.AddPatterns(patterns)} } func (p SongPoint) Wrap(score sointu.Score) SongPoint { p.Track = mod(p.Track, len(score.Tracks)) p.SongRow = p.SongRow.Wrap(score) return p } func (p SongPoint) Clamp(score sointu.Score) SongPoint { if p.Track < 0 { p.Track = 0 } else if l := len(score.Tracks); p.Track >= l { p.Track = l - 1 } p.SongRow = p.SongRow.Clamp(score) return p } func (r *SongRect) Contains(p SongPoint) bool { track1, track2 := r.Corner1.Track, r.Corner2.Track if track2 < track1 { track1, track2 = track2, track1 } if p.Track < track1 || p.Track > track2 { return false } pattern1, row1, pattern2, row2 := r.Corner1.Pattern, r.Corner1.Row, r.Corner2.Pattern, r.Corner2.Row if pattern2 < pattern1 || (pattern1 == pattern2 && row2 < row1) { pattern1, row1, pattern2, row2 = pattern2, row2, pattern1, row1 } if p.Pattern < pattern1 || p.Pattern > pattern2 { return false } if p.Pattern == pattern1 && p.Row < row1 { return false } if p.Pattern == pattern2 && p.Row > row2 { return false } return true } func mod(a, b int) int { if a < 0 { return b - 1 - mod(-a-1, b) } return a % b }
tracker/songpoint.go
0.698638
0.472136
songpoint.go
starcoder
// Package pipeline provides the ability to construct and run a pipeline. package pipeline import ( "container/list" "fmt" "github.com/abitofhelp/minipipeline/stage" ) // The type Pipeline implements the IPipeline interface and to make it possible // to easily construct and rearrange a pipeline using a fluent interface. Basically, // it is going to be a bi-directional linked list. type Pipeline struct { // Field stages is a list of the stages from the fluent interface. // The list is in the order that will be used for the pipeline. stages list.List } // Function FirstStage locates the first stage in the pipeline. // Returns the (stage instance, nil) on success; Otherwise, (nil, error). func (p Pipeline) FirstStage() (first *stage.Stage, err error) { e := p.stages.Front() // Convert the list's node's value to IStage. step, ok := e.Value.(*stage.Stage) if !ok { return nil, fmt.Errorf("failed to convert a list node value to type step.IStage: %v", e.Value) } return step, nil } // Function LastStage locates the last stage in the pipeline. // Returns the (stage instance, nil) on success; Otherwise, (nil, error). func (p Pipeline) LastStage() (last *stage.Stage, err error) { e := p.stages.Back() // Convert the list's node's value to IStage. step, ok := e.Value.(*stage.Stage) if !ok { return nil, fmt.Errorf("failed to convert a list node value to type step.IStage: %v", e.Value) } return step, nil } // Function FindStage will locate a stage of interest in the pipeline. // Parameter stageOfInterest is the kind of stage to seek in the pipeline. // Returns (stage instance, nil) on success, otherwise (nil, error) func (p Pipeline) FindStage(stageOfInterest stage.Stages) (found *stage.Stage, err error) { // Traverse the stages in the pipeline to find the one that has been requested. for e := p.stages.Front(); e != nil; e = e.Next() { // Convert the list's node's value to IStage. step, ok := e.Value.(*stage.Stage) if !ok { return nil, fmt.Errorf("failed to convert a list node value to type step.IStage: %v", e.Value) } if step.Stage() == stageOfInterest { return step, nil } } return nil, fmt.Errorf("failed to find a stage %s in the pipeline", stageOfInterest.String()) } // Function New creates a new instance of a pipeline. func New() (*Pipeline, error) { // Use the Builder to create the pipeline using a fluent interface. // The order of the stages is the same as in the pipeline. // Build will take care of setting up the channels between the stages. pb := &Builder{} pipeline, err := pb. Intake(). Analysis(). Transformation(). Validation(). Delivery(). Build() return pipeline, err }
pipeline/pipeline.go
0.832781
0.434101
pipeline.go
starcoder
package algorithms import ( "github.com/dploop/golib/stl/iterators" "github.com/dploop/golib/stl/types" ) func AllOf(first, last iterators.InputIterator, pred types.UnaryPredicate) bool { for !first.Equal(last) { if !pred(first.Read()) { return false } first = first.Next().(iterators.InputIterator) } return true } func AnyOf(first, last iterators.InputIterator, pred types.UnaryPredicate) bool { for !first.Equal(last) { if pred(first.Read()) { return true } first = first.Next().(iterators.InputIterator) } return false } func NoneOf(first, last iterators.InputIterator, pred types.UnaryPredicate) bool { for !first.Equal(last) { if pred(first.Read()) { return false } first = first.Next().(iterators.InputIterator) } return true } func ForEach(first, last iterators.InputIterator, fn types.UnaryPredicate) { for !first.Equal(last) { fn(first.Read()) first = first.Next().(iterators.InputIterator) } } func Find(first, last iterators.InputIterator, val types.Data) iterators.InputIterator { for !first.Equal(last) { if first.Read() == val { return first } first = first.Next().(iterators.InputIterator) } return last } func FindIf(first, last iterators.InputIterator, pred types.UnaryPredicate) iterators.InputIterator { for !first.Equal(last) { if pred(first.Read()) { return first } first = first.Next().(iterators.InputIterator) } return last } func FindIfNot(first, last iterators.InputIterator, pred types.UnaryPredicate) iterators.InputIterator { for !first.Equal(last) { if !pred(first.Read()) { return first } first = first.Next().(iterators.InputIterator) } return last } func Count(first, last iterators.InputIterator, val types.Data) (count types.Size) { for !first.Equal(last) { if first.Read() == val { count++ } first = first.Next().(iterators.InputIterator) } return count } func CountIf(first, last iterators.InputIterator, pred types.UnaryPredicate) (count types.Size) { for !first.Equal(last) { if pred(first.Read()) { count++ } first = first.Next().(iterators.InputIterator) } return count }
stl/algorithms/non_modifying_sequence.go
0.721056
0.543833
non_modifying_sequence.go
starcoder
package platformsnotificationevents import ( "encoding/json" ) // Amount struct for Amount type Amount struct { // The three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes). Currency string `json:"currency"` // The amount of the transaction, in [minor units](https://docs.adyen.com/development-resources/currency-codes). Value int64 `json:"value"` } // NewAmount instantiates a new Amount 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 NewAmount(currency string, value int64, ) *Amount { this := Amount{} this.Currency = currency this.Value = value return &this } // NewAmountWithDefaults instantiates a new Amount 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 NewAmountWithDefaults() *Amount { this := Amount{} return &this } // GetCurrency returns the Currency field value func (o *Amount) GetCurrency() string { if o == nil { var ret string return ret } return o.Currency } // GetCurrencyOk returns a tuple with the Currency field value // and a boolean to check if the value has been set. func (o *Amount) GetCurrencyOk() (*string, bool) { if o == nil { return nil, false } return &o.Currency, true } // SetCurrency sets field value func (o *Amount) SetCurrency(v string) { o.Currency = v } // GetValue returns the Value field value func (o *Amount) GetValue() int64 { if o == nil { var ret int64 return ret } return o.Value } // GetValueOk returns a tuple with the Value field value // and a boolean to check if the value has been set. func (o *Amount) GetValueOk() (*int64, bool) { if o == nil { return nil, false } return &o.Value, true } // SetValue sets field value func (o *Amount) SetValue(v int64) { o.Value = v } func (o Amount) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["currency"] = o.Currency } if true { toSerialize["value"] = o.Value } return json.Marshal(toSerialize) } type NullableAmount struct { value *Amount isSet bool } func (v NullableAmount) Get() *Amount { return v.value } func (v *NullableAmount) Set(val *Amount) { v.value = val v.isSet = true } func (v NullableAmount) IsSet() bool { return v.isSet } func (v *NullableAmount) Unset() { v.value = nil v.isSet = false } func NewNullableAmount(val *Amount) *NullableAmount { return &NullableAmount{value: val, isSet: true} } func (v NullableAmount) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAmount) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
src/platformsnotificationevents/model_amount.go
0.808974
0.450359
model_amount.go
starcoder
package protobufquery import ( "bytes" "google.golang.org/protobuf/reflect/protoreflect" ) // A NodeType is the type of a Node. type NodeType uint const ( // DocumentNode is a document object that, as the root of the document tree, // provides access to the entire XML document. DocumentNode NodeType = iota // ElementNode is an element. ElementNode // TextNode is the text content of a node. TextNode ) // A Node consists of a NodeType and some Data (tag name for // element nodes, content for text) and are part of a tree of Nodes. type Node struct { Parent, PrevSibling, NextSibling, FirstChild, LastChild *Node Type NodeType Name string Data *protoreflect.Value level int } // ChildNodes gets all child nodes of the node. func (n *Node) ChildNodes() []*Node { var a []*Node for nn := n.FirstChild; nn != nil; nn = nn.NextSibling { a = append(a, nn) } return a } // InnerText gets the value of the node and all its child nodes. func (n *Node) InnerText() string { var output func(*bytes.Buffer, *Node) output = func(buf *bytes.Buffer, n *Node) { if n.Type == TextNode { buf.WriteString(n.Data.String()) return } for child := n.FirstChild; child != nil; child = child.NextSibling { output(buf, child) } } var buf bytes.Buffer output(&buf, n) return buf.String() } func outputXML(buf *bytes.Buffer, n *Node) { if n.Type == TextNode { buf.WriteString(n.Data.String()) return } name := "element" if n.Name != "" { name = n.Name } buf.WriteString("<" + name + ">") for child := n.FirstChild; child != nil; child = child.NextSibling { outputXML(buf, child) } buf.WriteString("</" + name + ">") } // OutputXML prints the XML string. func (n *Node) OutputXML() string { var buf bytes.Buffer buf.WriteString(`<?xml version="1.0"?>`) for n := n.FirstChild; n != nil; n = n.NextSibling { outputXML(&buf, n) } return buf.String() } // SelectElement finds the first of child elements with the // specified name. func (n *Node) SelectElement(name string) *Node { for nn := n.FirstChild; nn != nil; nn = nn.NextSibling { if nn.Name == name { return nn } } return nil } // Value return the value of the node itself or its 'TextElement' children. // If `nil`, the value is either really `nil` or there is no matching child. func (n *Node) Value() interface{} { if n.Type == TextNode { if n.Data == nil { return nil } return n.Data.Interface() } result := make([]interface{}, 0) for child := n.FirstChild; child != nil; child = child.NextSibling { if child.Type != TextNode || child.Data == nil { continue } result = append(result, child.Data.Interface()) } if len(result) == 0 { return nil } else if len(result) == 1 { return result[0] } return result } // Parse ProtocolBuffer message. func Parse(msg protoreflect.Message) (*Node, error) { doc := &Node{Type: DocumentNode} visit(doc, msg, 1) return doc, nil } func visit(parent *Node, msg protoreflect.Message, level int) { msg.Range(func(f protoreflect.FieldDescriptor, v protoreflect.Value) bool { traverse(parent, f, v, level) return true }) } func traverse(parent *Node, field protoreflect.FieldDescriptor, value protoreflect.Value, level int) { node := &Node{Type: ElementNode, Name: string(field.Name()), level: level} nodeChildren := 0 if field.IsList() { l := value.List() for i := 0; i < l.Len(); i++ { subNode := handleValue(field.Kind(), l.Get(i), level+1) if subNode.Type == ElementNode { // Add element nodes directly to the parent subNode.Name = node.Name addNode(parent, subNode) } else { // Add basic nodes to the local collection node elementNode := &Node{Type: ElementNode, level: level + 1} subNode.level += 2 addNode(elementNode, subNode) addNode(node, elementNode) nodeChildren++ } } } else { subNode := handleValue(field.Kind(), value, level+1) if subNode.Type == ElementNode { // Add element nodes directly to the parent subNode.Name = node.Name addNode(parent, subNode) } else { // Add basic nodes to the local collection node addNode(node, subNode) nodeChildren++ } } // Only add the node if it has children if nodeChildren > 0 { addNode(parent, node) } } func handleValue(kind protoreflect.Kind, value protoreflect.Value, level int) *Node { var node *Node switch kind { case protoreflect.MessageKind: node = &Node{Type: ElementNode, level: level} visit(node, value.Message(), level+1) default: node = &Node{Type: TextNode, Data: &value, level: level} } return node } func addNode(top, n *Node) { if n.level == top.level { top.NextSibling = n n.PrevSibling = top n.Parent = top.Parent if top.Parent != nil { top.Parent.LastChild = n } } else if n.level > top.level { n.Parent = top if top.FirstChild == nil { top.FirstChild = n top.LastChild = n } else { t := top.LastChild t.NextSibling = n n.PrevSibling = t top.LastChild = n } } }
node.go
0.666931
0.411406
node.go
starcoder
package godash import ( "errors" "reflect" ) // Without removes values from a slice and returns the new slice. // It accepts a slice of any type as the first parameter, followed by a list of parameter values to remove from the slice. // The additional values must be of the same type as the provided slice. // If using a basic type, such as string or int, it is recommended to use the more specific functions, such as WithoutString or WithoutInt. // Otherwise, if using this function directly, the returned result will need to have a type assertion applied. func Without(slice interface{}, values ...interface{}) (interface{}, error) { sliceVal := reflect.ValueOf(slice) if sliceVal.Type().Kind() != reflect.Slice { return nil, errors.New("godash: invalid parameter type. Without func expects parameter 1 to be a slice") } for _, v := range values { if sliceVal.Type().Elem() != reflect.TypeOf(v) { return nil, errors.New("godash: invalid parameter type. Without func expects additional parameters to match the type of the provided slice") } } dest := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(slice).Elem()), 0, sliceVal.Len()) for i := 0; i < sliceVal.Len(); i++ { remove := false for _, v := range values { if reflect.DeepEqual(sliceVal.Index(i).Interface(), v) { remove = true break } } if !remove { dest = reflect.Append(dest, sliceVal.Index(i)) } } return dest.Interface(), nil } // WithoutString removes string values from a string slice func WithoutString(slice []string, values ...interface{}) ([]string, error) { result, err := Without(slice, values...) if err != nil { return nil, err } return result.([]string), nil } // WithoutInt removes int values from an int slice func WithoutInt(slice []int, values ...interface{}) ([]int, error) { result, err := Without(slice, values...) if err != nil { return nil, err } return result.([]int), nil } // WithoutInt8 removes int8 values from an int8 slice func WithoutInt8(slice []int8, values ...interface{}) ([]int8, error) { result, err := Without(slice, values...) if err != nil { return nil, err } return result.([]int8), nil } // WithoutFloat32 removes float32 values from a float32 slice func WithoutFloat32(slice []float32, values ...interface{}) ([]float32, error) { result, err := Without(slice, values...) if err != nil { return nil, err } return result.([]float32), nil } // WithoutBy removes values from a slice based on output from a provided validator function and returns the new slice. // The supplied function must accept an interface{} parameter and return bool. // Values for which the validator function returns true will be removed from the slice. func WithoutBy(slice interface{}, fn validator) (interface{}, error) { sliceVal := reflect.ValueOf(slice) if sliceVal.Type().Kind() != reflect.Slice { return nil, errors.New("godash: invalid parameter type. WithoutBy func expects parameter 1 to be a slice") } dest := reflect.MakeSlice(reflect.SliceOf(reflect.TypeOf(slice).Elem()), 0, sliceVal.Len()) for i := 0; i < sliceVal.Len(); i++ { v := sliceVal.Index(i).Interface() if remove := fn(v); !remove { dest = reflect.Append(dest, sliceVal.Index(i)) } } return dest.Interface(), nil }
without.go
0.824002
0.528777
without.go
starcoder
package leetcode /** * @title 设计链表 * * 设计链表的实现。您可以选择使用单链表或双链表。 * 单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。 * 如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。 * * 在链表类中实现这些功能: * get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。 * addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。 * addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。 * addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。 * deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。 * * 示例: * MyLinkedList linkedList = new MyLinkedList(); * linkedList.addAtHead(1); * linkedList.addAtTail(3); * linkedList.addAtIndex(1,2); //链表变为1-> 2-> 3 * linkedList.get(1); //返回2 * linkedList.deleteAtIndex(1); //现在链表是1-> 3 * linkedList.get(1); //返回3 * * 提示: * 所有值都在 [1, 1000] 之内。 * 操作次数将在 [1, 1000] 之内。 * 请不要使用内置的 LinkedList 库。 * * @see https://leetcode-cn.com/problems/design-linked-list/description/ * @difficulty Easy */ type MyLinkedList struct { Val int Next *MyLinkedList } /** Initialize your data structure here. */ func Constructor707() MyLinkedList { //head return MyLinkedList{-1, nil} } /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ func (this *MyLinkedList) Get(index int) int { p := this.Next i := 0 for p != nil { if i == index { return p.Val } p = p.Next i++ } return -1 } /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ func (this *MyLinkedList) AddAtHead(val int) { p := &MyLinkedList{val, this.Next} this.Next = p } /** Append a node of value val to the last element of the linked list. */ func (this *MyLinkedList) AddAtTail(val int) { p := this for p.Next != nil { p = p.Next } p.Next = &MyLinkedList{val, nil} } /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ func (this *MyLinkedList) AddAtIndex(index int, val int) { p := this i := 0 for p != nil { if i == index { q := p.Next p.Next = &MyLinkedList{val, q} break } p = p.Next i++ } } /** Delete the index-th node in the linked list, if the index is valid. */ func (this *MyLinkedList) DeleteAtIndex(index int) { p := this i := 0 for p != nil { if i == index && p.Next != nil { p.Next = p.Next.Next } p = p.Next i++ } } /** * Your MyLinkedList object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Get(index); * obj.AddAtHead(val); * obj.AddAtTail(val); * obj.AddAtIndex(index,val); * obj.DeleteAtIndex(index); */
src/0707.design-linked-list.go
0.580709
0.442817
0707.design-linked-list.go
starcoder
package evaluate import ( "fmt" "github.com/haunt98/evaluator/expression" "github.com/haunt98/evaluator/token" ) func (v *visitor) visitOr(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } leftLit, ok := left.(*expression.BoolLiteral) if !ok { return nil, fmt.Errorf("expect bool literal got %s", left) } // true or any -> true if leftLit.Value { return leftLit, nil } right, err := v.Visit(expr.Right) if err != nil { return nil, err } rightLit, ok := right.(*expression.BoolLiteral) if !ok { return nil, fmt.Errorf("expect bool literal got %s", right) } return rightLit, nil } func (v *visitor) visitAnd(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } leftLit, ok := left.(*expression.BoolLiteral) if !ok { return nil, fmt.Errorf("expect bool literal got %s", left) } // false and any -> false if !leftLit.Value { return leftLit, nil } right, err := v.Visit(expr.Right) if err != nil { return nil, err } rightLit, ok := right.(*expression.BoolLiteral) if !ok { return nil, fmt.Errorf("expect bool literal got %s", right) } return rightLit, nil } func (v *visitor) visitEqual(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } right, err := v.Visit(expr.Right) if err != nil { return nil, err } // TODO: handle more types switch l := left.(type) { case *expression.BoolLiteral: switch r := right.(type) { case *expression.BoolLiteral: return expression.NewBoolLiteral(l.Value == r.Value), nil default: return nil, fmt.Errorf("expect bool literal got %T", r) } case *expression.IntLiteral: switch r := right.(type) { case *expression.IntLiteral: return expression.NewBoolLiteral(l.Value == r.Value), nil default: return nil, fmt.Errorf("expect int literal got %T", r) } case *expression.StringLiteral: switch r := right.(type) { case *expression.StringLiteral: return expression.NewBoolLiteral(l.Value == r.Value), nil default: return nil, fmt.Errorf("expect string literal got %T", r) } default: return nil, fmt.Errorf("not implement visit equal %T", l) } } func (v *visitor) visitNotEqual(expr *expression.BinaryExpression) (expression.Expression, error) { equalExpr, err := v.visitEqual(expr) if err != nil { return nil, err } equalLit, ok := equalExpr.(*expression.BoolLiteral) if !ok { return nil, fmt.Errorf("export bool literal got %s", equalExpr) } return expression.NewBoolLiteral(!equalLit.Value), nil } func (v *visitor) visitLess(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } leftLit, ok := left.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", left) } right, err := v.Visit(expr.Right) if err != nil { return nil, err } rightLit, ok := right.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", right) } return expression.NewBoolLiteral(leftLit.Value < rightLit.Value), nil } func (v *visitor) visitLessOrEqual(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } leftLit, ok := left.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", left) } right, err := v.Visit(expr.Right) if err != nil { return nil, err } rightLit, ok := right.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", right) } return expression.NewBoolLiteral(leftLit.Value <= rightLit.Value), nil } func (v *visitor) visitGreater(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } leftLit, ok := left.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", left) } right, err := v.Visit(expr.Right) if err != nil { return nil, err } rightLit, ok := right.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", right) } return expression.NewBoolLiteral(leftLit.Value > rightLit.Value), nil } func (v *visitor) visitGreaterOrEqual(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } leftLit, ok := left.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", left) } right, err := v.Visit(expr.Right) if err != nil { return nil, err } rightLit, ok := right.(*expression.IntLiteral) if !ok { return nil, fmt.Errorf("expect int literal got %s", right) } return expression.NewBoolLiteral(leftLit.Value >= rightLit.Value), nil } func (v *visitor) visitIn(expr *expression.BinaryExpression) (expression.Expression, error) { left, err := v.Visit(expr.Left) if err != nil { return nil, err } right, err := v.Visit(expr.Right) if err != nil { return nil, err } rightArr, ok := right.(*expression.ArrayExpression) if !ok { return nil, fmt.Errorf("expect array expression got %s", right) } // compare left to all children of right for _, child := range rightArr.Children { equalExpr, err := v.visitEqual(expression.NewBinaryExpression(token.Equal, left, child)) if err != nil { continue } equalLit, ok := equalExpr.(*expression.BoolLiteral) if !ok { continue } if equalLit.Value { return expression.NewBoolLiteral(true), nil } } return expression.NewBoolLiteral(false), nil } func (v *visitor) visitNotIn(expr *expression.BinaryExpression) (expression.Expression, error) { equalExpr, err := v.visitIn(expr) if err != nil { return nil, err } equalLit, ok := equalExpr.(*expression.BoolLiteral) if !ok { return nil, fmt.Errorf("expect bool literal got %s", equalLit) } return expression.NewBoolLiteral(!equalLit.Value), nil }
evaluate/binary.go
0.622689
0.47025
binary.go
starcoder
package hilbert import ( "sort" "github.com/Workiva/go-datastructures/rtree" ) type hilbert int64 type hilberts []hilbert func getParent(parent *node, key hilbert, r1 rtree.Rectangle) *node { var n *node for parent != nil && !parent.isLeaf { n = parent.searchNode(key) parent = n } if parent != nil && r1 != nil { // must be leaf and we need exact match // we are safe to travel to the right i := parent.search(key) for parent.keys.byPosition(i) == key { if equal(parent.nodes.list[i], r1) { break } i++ if i == parent.keys.len() { if parent.right == nil { // we are far to the right break } if parent.right.keys.byPosition(0) != key { break } parent = parent.right i = 0 } } } return parent } type nodes struct { list rtree.Rectangles } func (ns *nodes) push(n rtree.Rectangle) { ns.list = append(ns.list, n) } func (ns *nodes) splitAt(i, capacity uint64) (*nodes, *nodes) { i++ right := make(rtree.Rectangles, uint64(len(ns.list))-i, capacity) copy(right, ns.list[i:]) for j := i; j < uint64(len(ns.list)); j++ { ns.list[j] = nil } ns.list = ns.list[:i] return ns, &nodes{list: right} } func (ns *nodes) byPosition(pos uint64) *node { if pos >= uint64(len(ns.list)) { return nil } return ns.list[pos].(*node) } func (ns *nodes) insertAt(i uint64, n rtree.Rectangle) { ns.list = append(ns.list, nil) copy(ns.list[i+1:], ns.list[i:]) ns.list[i] = n } func (ns *nodes) replaceAt(i uint64, n rtree.Rectangle) { ns.list[i] = n } func (ns *nodes) len() uint64 { return uint64(len(ns.list)) } func (ns *nodes) deleteAt(i uint64) { copy(ns.list[i:], ns.list[i+1:]) ns.list = ns.list[:len(ns.list)-1] } func newNodes(size uint64) *nodes { return &nodes{ list: make(rtree.Rectangles, 0, size), } } type keys struct { list hilberts } func (ks *keys) splitAt(i, capacity uint64) (*keys, *keys) { i++ right := make(hilberts, uint64(len(ks.list))-i, capacity) copy(right, ks.list[i:]) ks.list = ks.list[:i] return ks, &keys{list: right} } func (ks *keys) len() uint64 { return uint64(len(ks.list)) } func (ks *keys) byPosition(i uint64) hilbert { if i >= uint64(len(ks.list)) { return -1 } return ks.list[i] } func (ks *keys) deleteAt(i uint64) { copy(ks.list[i:], ks.list[i+1:]) ks.list = ks.list[:len(ks.list)-1] } func (ks *keys) delete(k hil<PASSWORD>) hilbert { i := ks.search(k) if i >= uint64(len(ks.list)) { return -1 } if ks.list[i] != k { return -1 } old := ks.list[i] ks.deleteAt(i) return old } func (ks *keys) search(key h<PASSWORD>) uint64 { i := sort.Search(len(ks.list), func(i int) bool { return ks.list[i] >= key }) return uint64(i) } func (ks *keys) insert(key hil<PASSWORD>) (hilbert, uint64) { i := ks.search(key) if i == uint64(len(ks.list)) { ks.list = append(ks.list, key) return -1, i } var old hilbert if ks.list[i] == key { old = ks.list[i] ks.list[i] = key } else { ks.insertAt(i, key) } return old, i } func (ks *keys) last() hilbert { return ks.list[len(ks.list)-1] } func (ks *keys) insertAt(i uint64, k hilbert) { ks.list = append(ks.list, -1) copy(ks.list[i+1:], ks.list[i:]) ks.list[i] = k } func (ks *keys) withPosition(k hilbert) (hilbert, uint64) { i := ks.search(k) if i == uint64(len(ks.list)) { return -1, i } if ks.list[i] == k { return ks.list[i], i } return -1, i } func newKeys(size uint64) *keys { return &keys{ list: make(hilberts, 0, size), } } type node struct { keys *keys nodes *nodes isLeaf bool parent, right *node mbr *rectangle maxHilbert hilbert } func (n *node) insert(kb *keyBundle) rtree.Rectangle { i := n.keys.search(kb.key) if n.isLeaf { // we can have multiple keys with the same hilbert number for i < n.keys.len() && n.keys.list[i] == kb.key { if equal(n.nodes.list[i], kb.left) { old := n.nodes.list[i] n.nodes.list[i] = kb.left return old } i++ } } if i == n.keys.len() { n.maxHilbert = kb.key } n.keys.insertAt(i, kb.key) if n.isLeaf { n.nodes.insertAt(i, kb.left) } else { if n.nodes.len() == 0 { n.nodes.push(kb.left) n.nodes.push(kb.right) } else { n.nodes.replaceAt(i, kb.left) n.nodes.insertAt(i+1, kb.right) } n.mbr.adjust(kb.left) n.mbr.adjust(kb.right) if kb.right.(*node).maxHilbert > n.maxHilbert { n.maxHilbert = kb.right.(*node).maxHilbert } } return nil } func (n *node) delete(kb *keyBundle) rtree.Rectangle { i := n.keys.search(kb.key) if n.keys.byPosition(i) != kb.key { // hilbert value not found return nil } if !equal(n.nodes.list[i], kb.left) { return nil } old := n.nodes.list[i] n.keys.deleteAt(i) n.nodes.deleteAt(i) return old } func (n *node) LowerLeft() (int32, int32) { return n.mbr.xlow, n.mbr.ylow } func (n *node) UpperRight() (int32, int32) { return n.mbr.xhigh, n.mbr.yhigh } func (n *node) needsSplit(ary uint64) bool { return n.keys.len() >= ary } func (n *node) splitLeaf(i, capacity uint64) (hilbert, *node, *node) { key := n.keys.byPosition(i) _, rightKeys := n.keys.splitAt(i, capacity) _, rightNodes := n.nodes.splitAt(i, capacity) nn := &node{ keys: rightKeys, nodes: rightNodes, isLeaf: true, right: n.right, parent: n.parent, } n.right = nn nn.mbr = newRectangleFromRects(rightNodes.list) n.mbr = newRectangleFromRects(n.nodes.list) nn.maxHilbert = rightKeys.last() n.maxHilbert = n.keys.last() return key, n, nn } func (n *node) splitInternal(i, capacity uint64) (hilbert, *node, *node) { key := n.keys.byPosition(i) n.keys.delete(key) _, rightKeys := n.keys.splitAt(i-1, capacity) _, rightNodes := n.nodes.splitAt(i, capacity) nn := newNode(false, rightKeys, rightNodes) for _, n := range rightNodes.list { n.(*node).parent = nn } nn.mbr = newRectangleFromRects(rightNodes.list) n.mbr = newRectangleFromRects(n.nodes.list) nn.maxHilbert = nn.keys.last() n.maxHilbert = n.keys.last() return key, n, nn } func (n *node) split(i, capacity uint64) (hilbert, *node, *node) { if n.isLeaf { return n.splitLeaf(i, capacity) } return n.splitInternal(i, capacity) } func (n *node) search(key hilbert) uint64 { return n.keys.search(key) } func (n *node) searchNode(key hilbert) *node { i := n.search(key) return n.nodes.byPosition(uint64(i)) } func (n *node) searchRects(r *rectangle) rtree.Rectangles { rects := make(rtree.Rectangles, 0, n.nodes.len()) for _, child := range n.nodes.list { if intersect(r, child) { rects = append(rects, child) } } return rects } func (n *node) key() hilbert { return n.keys.last() } func newNode(isLeaf bool, keys *keys, ns *nodes) *node { return &node{ isLeaf: isLeaf, keys: keys, nodes: ns, } }
vendor/src/github.com/Workiva/go-datastructures/rtree/hilbert/node.go
0.550849
0.420302
node.go
starcoder
package binp import "errors" // Parser type. Don't touch the internals. type Parser struct { r []byte off int } // Create a new parser with the given buffer. Panics on error. func NewParser(b []byte) *Parser { return &Parser{b, 0} } // Parse a byte from the buffer. func (p *Parser) Byte(d *byte) *Parser { if p == nil || len(p.r) < p.off+1 { return nil } *d = p.r[p.off] p.off++ return p } // Parse a byte from the buffer, synonym for .Byte. func (p *Parser) B8(d *byte) *Parser { if p == nil || len(p.r) < p.off+1 { return nil } *d = p.r[p.off] p.off++ return p } // Parse a byte from the buffer, synonym for .Byte. func (p *Parser) N8(d *byte) *Parser { if p == nil || len(p.r) < p.off+1 { return nil } *d = p.r[p.off] p.off++ return p } // Parse n bytes from the buffer and copy to a []byte pointer that is allocated. func (p *Parser) NBytes(n int, d *[]byte) *Parser { if p == nil || n > len(p.r[p.off:]) { return nil } *d = make([]byte, n) copy(*d, p.r[p.off:]) p.off += n return p } // Parse n bytes from the buffer and copy to the supplied []byte. func (p *Parser) NBytesCopy(n int, d []byte) *Parser { if p == nil || n > len(p.r[p.off:]) { return nil } copy(d, p.r[p.off:p.off+n]) p.off += n return p } // Parse n bytes from the buffer to a []byte pointer that refers to the parser internal buffer. func (p *Parser) NBytesPeek(n int, d *[]byte) *Parser { if p == nil || n > len(p.r[p.off:]) { return nil } *d = p.r[p.off : p.off+n] p.off += n return p } // Ensure the input is aligned possibly skipping bytes. func (p *Parser) Align(n int) *Parser { if p == nil { return nil } r := p.off % n if r != 0 { p.off += n - r } return p } // Skip bytes. func (p *Parser) Skip(n int) *Parser { p.off += n return p } // Parse a null terminated string. func (p *Parser) String0(d *string) *Parser { if p == nil { return nil } for i, ch := range p.r[p.off:] { if ch == 0 { p.NString(i, d) p.off++ return p } } panic("String0: null byte not found") } // Check that we are at the end of input. func (p *Parser) End() error { if p == nil || p.off != len(p.r) { return eparse } return nil } var eparse = errors.New("binparser invalid input") // Check that we are at the end of input. func (p *Parser) AtEnd() bool { return p.off == len(p.r) } // Peek the rest of input as raw bytes. func (p *Parser) PeekRest(d *[]byte) *Parser { *d = p.r[p.off:] return p }
binparser_common.go
0.68679
0.520009
binparser_common.go
starcoder
package integration import ( "image/color" ) // ColourFromARGB creates a colour from the separate A/R/G/B quantities. func ColourFromARGB(a uint8, r uint8, g uint8, b uint8) uint32 { return (uint32(a) << 24) | (uint32(r) << 16) | (uint32(g) << 8) | (uint32(b) << 0) } // ColourToARGB splits a colour apart. func ColourToARGB(col uint32) (a uint8, r uint8, g uint8, b uint8) { a = uint8((col & 0xFF000000) >> 24) r = uint8((col & 0xFF0000) >> 16) g = uint8((col & 0xFF00) >> 8) b = uint8((col & 0xFF) >> 0) return a, r, g, b } // ColourComponentClamp clamps an integer into the 0..255 range (acting as a safe converter from int32 to uint8) func ColourComponentClamp(i int32) uint8 { if i < 0 { return 0 } else if i > 255 { return 255 } return uint8(i) } // ColourMix linearly interpolates between two colours in the standard space (no "linear light" business) func ColourMix(cola uint32, colb uint32, amount float64) uint32 { invAmount := 1 - amount aA, aR, aG, aB := ColourToARGB(cola) bA, bR, bG, bB := ColourToARGB(colb) cA := ColourComponentClamp(int32((float64(aA) * invAmount) + (float64(bA) * amount))) cR := ColourComponentClamp(int32((float64(aR) * invAmount) + (float64(bR) * amount))) cG := ColourComponentClamp(int32((float64(aG) * invAmount) + (float64(bG) * amount))) cB := ColourComponentClamp(int32((float64(aB) * invAmount) + (float64(bB) * amount))) return ColourFromARGB(cA, cR, cG, cB) } // ColourTransform transforms colours. It's useful when doing image transforms from alphaless images to alpha/etc. type ColourTransform func(c uint32) uint32 // ColourTransform2 combines two colours to make a third. type ColourTransform2 func(a uint32, b uint32) uint32 // ColourTransformBlueToStencil uses the blue channel as an alpha stencil and gives the image a white background. func ColourTransformBlueToStencil(c uint32) uint32 { return ((c & 0xFF) << 24) | 0xFFFFFF } // ColourTransformInvert inverts the colour channels. func ColourTransformInvert(c uint32) uint32 { a, r, g, b := ColourToARGB(c) return ColourFromARGB(a, 255 - r, 255 - g, 255 - b) } // ColourTransform2Blend implements standard blending. func ColourTransform2Blend(dest uint32, source uint32) uint32 { dA := dest >> 24 sA := source >> 24 resColour := ColourMix(source, dest, float64(dA) / 255) & 0xFFFFFF resAlpha := ColourComponentClamp(int32(sA + dA)) return resColour | uint32(resAlpha) << 24 } // ConvertGoImageColourToUint32 converts a Go colour into an ARGB colour uint32 as losslessly as possible. func ConvertGoImageColourToUint32(col color.Color) uint32 { // Colour type appears to be per-pixel. Great. More problems. switch colConv := col.(type) { case color.NRGBA: return ColourFromARGB(colConv.A, colConv.R, colConv.G, colConv.B) case color.RGBA: // This is still premultiplied and thus NOT GOOD, but let's roll with it a := colConv.A r := colConv.R g := colConv.G b := colConv.B if (a != 0) && (a != 255) { // Alpha not 0 (would /0) or a NOP a16 := uint16(a) r = uint8((uint16(colConv.R) * 255) / a16) g = uint8((uint16(colConv.G) * 255) / a16) b = uint8((uint16(colConv.B) * 255) / a16) } return ColourFromARGB(a, r, g, b) } // Give up and work backwards from premultiplied (NOT GOOD!!!) r, g, b, a := col.RGBA() if (a != 0) && (a != 0xFFFF) { // Scaling, also implicitly does the 8-bit conversion r *= 255 g *= 255 b *= 255 r /= a g /= a b /= a } else { // Convert to 8-bit r >>= 8 g >>= 8 b >>= 8 } // Convert alpha to 8-bit a >>= 8 return ColourFromARGB(uint8(a), uint8(r), uint8(g), uint8(b)) } // ConvertUint32ToGoImageColour converts a uint32 colour to a colour.NRGBA (which is essentially in the same format) func ConvertUint32ToGoImageColour(col uint32) color.NRGBA { a, r, g, b := ColourToARGB(col) return color.NRGBA{ A: a, R: r, G: g, B: b, } }
frenyard/integration/imagingColours.go
0.830078
0.531209
imagingColours.go
starcoder
package infoblox import ( "github.com/CARFAX/skyinfoblox/api/common/v261/model" "github.com/carfax/terraform-provider-infoblox/infoblox/util" "github.com/hashicorp/terraform/helper/schema" ) func resourceNetwork() *schema.Resource { return &schema.Resource{ Create: resourceNetworkCreate, Read: resourceNetworkRead, Update: resourceNetworkUpdate, Delete: DeleteResource, Schema: map[string]*schema.Schema{ "network": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "The network address in IPv4 Address/CIDR format.", }, "network_view": { Type: schema.TypeString, Optional: true, Computed: true, Description: "The name of the network view in which this network resides.", }, "comment": { Type: schema.TypeString, Optional: true, Description: "Comment for the network, maximum 256 characters.", ValidateFunc: util.ValidateMaxLength(256), }, "authority": { Type: schema.TypeBool, Optional: true, Description: "Authority for the DHCP network. Associated with the field use_authority", }, "use_authority": { Type: schema.TypeBool, Optional: true, }, "auto_create_reversezone": { Type: schema.TypeBool, Optional: true, Description: "This flag controls whether reverse zones are automatically created when the network is added. Cannot be updated, nor is readable", }, "disable": { Type: schema.TypeBool, Optional: true, Description: "Determines whether a network is disabled or not. When this is set to False, the network is enabled.", }, "enable_ddns": { Type: schema.TypeBool, Optional: true, Description: "The dynamic DNS updates flag of a DHCP network object. If set to True, the DHCP server sends DDNS updates to DNS servers in the same Grid, and to external DNS servers.", }, "use_enable_ddns": { Type: schema.TypeBool, Optional: true, }, "high_water_mark": { Type: schema.TypeInt, Optional: true, Computed: true, ValidateFunc: util.ValidateUnsignedInteger, Description: "The percentage of DHCP network usage threshold above which network usage is not expected and may warrant your attention. When the high watermark is reached, the Infoblox appliance generates a syslog message and sends a warning (if enabled). A number that specifies the percentage of allocated addresses. The range is from 1 to 100.", }, "high_water_mark_reset": { Type: schema.TypeInt, Optional: true, Computed: true, ValidateFunc: util.ValidateUnsignedInteger, Description: "The percentage of DHCP network usage below which the corresponding SNMP trap is reset. A number that specifies the percentage of allocated addresses. The range is from 1 to 100. The high watermark reset value must be lower than the high watermark value.", }, "low_water_mark": { Type: schema.TypeInt, Optional: true, Computed: true, ValidateFunc: util.ValidateUnsignedInteger, Description: "The percentage of DHCP network usage below which the Infoblox appliance generates a syslog message and sends a warning (if enabled). A number that specifies the percentage of allocated addresses. The range is from 1 to 100.", }, "low_water_mark_reset": { Type: schema.TypeInt, Optional: true, Computed: true, ValidateFunc: util.ValidateUnsignedInteger, Description: "The percentage of DHCP network usage threshold below which network usage is not expected and may warrant your attention. When the low watermark is crossed, the Infoblox appliance generates a syslog message and sends a warning (if enabled). A number that specifies the percentage of allocated addresses. The range is from 1 to 100. The low watermark reset value must be higher than the low watermark value.", }, "enable_dhcp_thresholds": { Type: schema.TypeBool, Optional: true, Description: "Determines if DHCP thresholds are enabled for the network.", }, "use_enable_dhcp_thresholds": { Type: schema.TypeBool, Optional: true, }, "enable_discovery": { Type: schema.TypeBool, Optional: true, Description: "Determines whether a discovery is enabled or not for this network. When this is set to False, the network discovery is disabled.", }, "use_enable_discovery": { Type: schema.TypeBool, Optional: true, }, "discovery_member": { Type: schema.TypeString, Optional: true, Description: "The member that will run discovery for this network.", }, "ipv4addr": { Type: schema.TypeString, Optional: true, Computed: true, Description: "The IPv4 Address of the network.", }, "lease_scavenge_time": { Type: schema.TypeInt, Optional: true, Computed: true, Description: "An integer that specifies the period of time (in seconds) that frees and backs up leases remained in the database before they are automatically deleted. To disable lease scavenging, set the parameter to -1. The minimum positive value must be greater than 86400 seconds (1 day).", }, "members": { Type: schema.TypeList, Description: "DHCP Member which is going to serve this network.", Optional: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "ipv4addr": { Type: schema.TypeString, Description: "IPv4 address of the member pair", Optional: true, }, "ipv6addr": { Type: schema.TypeString, Description: "IPv6 address of the member pair", Optional: true, }, "name": { Type: schema.TypeString, Description: "FQDN of the member pair", Optional: true, }, }, }, }, "netmask": { Type: schema.TypeInt, Optional: true, Computed: true, Description: "Number of bits in the network mask example: 8,16,24 etc ", }, "network_container": { Type: schema.TypeString, Optional: true, Computed: true, Description: "The network container to which this network belongs (if any). Cannot be updated nor written", }, "extattrs": { Type: schema.TypeMap, Optional: true, Description: "Map of attributes to be sent as extra attributes.", }, "options": &schema.Schema{ Type: schema.TypeSet, Optional: true, Computed: true, Description: "DHCP Related] Options such as DNS servers, gateway, ntp, etc", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Description: "DHCP Option Name", Optional: true, }, "num": { Type: schema.TypeInt, Description: "DHCO Option number", Optional: true, ValidateFunc: util.ValidateUnsignedInteger, }, "use_option": { Type: schema.TypeBool, Description: "Use the option or not", Optional: true, }, "value": { Type: schema.TypeString, Description: "Value of the option. For an option this value is required", Optional: true, }, "vendor_class": { Type: schema.TypeString, Description: "Vendor Class", Default: "DHCP", Optional: true, }, }, }, }, "use_options": { Type: schema.TypeBool, Optional: true, }, "recycle_leases": { Type: schema.TypeBool, Optional: true, Default: true, Description: "If the field is set to True, the leases are kept in the Recycle Bin until one week after expiration. Otherwise, the leases are permanently deleted.", }, "use_recycle_leases": { Type: schema.TypeBool, Optional: true, Default: true, }, "restart_if_needed": { Type: schema.TypeBool, Optional: true, Description: "Restarts the member service. Not readable", }, "update_dns_on_lease_renewal": { Type: schema.TypeBool, Optional: true, Description: "This field controls whether the DHCP server updates DNS when a DHCP lease is renewed.", }, }, } } func resourceNetworkCreate(d *schema.ResourceData, m interface{}) error { return CreateResource(model.NetworkObj, resourceNetwork(), d, m) } func resourceNetworkRead(d *schema.ResourceData, m interface{}) error { return ReadResource(resourceNetwork(), d, m) } func resourceNetworkUpdate(d *schema.ResourceData, m interface{}) error { return UpdateResource(resourceNetwork(), d, m) }
infoblox/resource_network.go
0.5
0.463019
resource_network.go
starcoder
package kata import "strings" // All commands are implemented as functions on the machine structure type command = func(work *machine) // Dataset of the running Custom Paintfuck machine // The code string is stored as array of command functions type machine struct { grid [][]bool gridXN int // width of the grid gridYN int // height of the grid gridPointerX int // index (x and y) of current cell in the grid gridPointerY int program []command commandPointer int // index of next command to execute commandCounter int // number of exceuted commands } // Command No operation func commandNop(work *machine) { work.commandPointer++ // nop's are not counted, commandCount is unchanged } // Command n - Move data pointer north (up) func commandMoveNorth(work *machine) { work.gridPointerY = (work.gridPointerY - 1 + work.gridYN) % work.gridYN work.commandPointer++ work.commandCounter++ } // Command s - Move data pointer south (down) func commandMoveSouth(work *machine) { work.gridPointerY = (work.gridPointerY + 1) % work.gridYN work.commandPointer++ work.commandCounter++ } // Command e - Move data pointer east (right) func commandMoveEast(work *machine) { work.gridPointerX = (work.gridPointerX + 1) % work.gridXN work.commandPointer++ work.commandCounter++ } // Command w - Move data pointer west (left) func commandMoveWest(work *machine) { work.gridPointerX = (work.gridPointerX - 1 + work.gridXN) % work.gridXN work.commandPointer++ work.commandCounter++ } // Command * - Flip the bit at the current cell func commandFlip(work *machine) { work.grid[work.gridPointerY][work.gridPointerX] = !work.grid[work.gridPointerY][work.gridPointerX] work.commandPointer++ work.commandCounter++ } // Generate command [ - Jump past matching ] if value at current cell is 0 func generateJumpPast(targetCommandPointer int) command { return func(work *machine) { if !work.grid[work.gridPointerY][work.gridPointerX] { work.commandPointer = targetCommandPointer } else { work.commandPointer++ } work.commandCounter++ } } // Generate command ] - Jump back to matching [ (if value at current cell is nonzero) func generateJumpBack(targetCommandPointer int) command { return func(work *machine) { if work.grid[work.gridPointerY][work.gridPointerX] { work.commandPointer = targetCommandPointer } else { work.commandPointer++ } // back jumps are not counted, commandCount is unchanged } } // Make grid filled with 0 func makeGrid(width, height int) [][]bool { grid := make([][]bool, height) for indexY := 0; indexY < height; indexY++ { grid[indexY] = make([]bool, width) } return grid } // Translate internal grid to string func translateGridToString(grid [][]bool) string { var accu strings.Builder for indexY := 0; indexY < len(grid); indexY++ { if indexY > 0 { accu.WriteString("\r\n") } row := grid[indexY] for indexX := 0; indexX < len(row); indexX++ { if row[indexX] { accu.WriteRune('1') } else { accu.WriteRune('0') } } } return accu.String() } // Translate code string func translateCode(code string) []command { program := make([]command, 0, len(code)) jumpStack := make([]int, 0) for _, c := range code { switch c { case 'n': program = append(program, commandMoveNorth) case 's': program = append(program, commandMoveSouth) case 'e': program = append(program, commandMoveEast) case 'w': program = append(program, commandMoveWest) case '*': program = append(program, commandFlip) case '[': jumpStack = append(jumpStack, len(program)) program = append(program, commandNop) case ']': i := len(jumpStack) - 1 jumpStart := jumpStack[i] program[jumpStart] = generateJumpPast(len(program)) program = append(program, generateJumpBack(jumpStart)) jumpStack = jumpStack[:i] } } return program } // run the program func run(work *machine, iterations int) { nc := len(work.program) for work.commandCounter < iterations && work.commandPointer < nc { work.program[work.commandPointer](work) } } func Interpreter(code string, iterations, width, height int) string { work := machine{ grid: makeGrid(width, height), gridXN: width, gridYN: height, gridPointerX: 0, gridPointerY: 0, program: translateCode(code), commandPointer: 0, commandCounter: 0} run(&work, iterations) return translateGridToString(work.grid) }
4_kyu/Esolang_Interpreters_3_Custom_Paintfk_Interpreter.go
0.593374
0.415847
Esolang_Interpreters_3_Custom_Paintfk_Interpreter.go
starcoder
package astcopy import ( "go/ast" ) // CopyNodeMap hold mapping copied node to original node. type CopyNodeMap map[ast.Node]ast.Node // Node returns x node deep copy. // Copy of nil argument is nil. func Node(x ast.Node, nMap CopyNodeMap) ast.Node { return copyNode(x, nMap) } // NodeList returns xs node slice deep copy. // Copy of nil argument is nil. func NodeList(xs []ast.Node, nMap CopyNodeMap) []ast.Node { if xs == nil { return nil } cp := make([]ast.Node, len(xs)) for i := range xs { cp[i] = copyNode(xs[i], nMap) } return cp } // Expr returns x expression deep copy. // Copy of nil argument is nil. func Expr(x ast.Expr, nMap CopyNodeMap) ast.Expr { return copyExpr(x, nMap) } // ExprList returns xs expression slice deep copy. // Copy of nil argument is nil. func ExprList(xs []ast.Expr, nMap CopyNodeMap) []ast.Expr { if xs == nil { return nil } cp := make([]ast.Expr, len(xs)) for i := range xs { cp[i] = copyExpr(xs[i], nMap) } return cp } // Stmt returns x statement deep copy. // Copy of nil argument is nil. func Stmt(x ast.Stmt, nMap CopyNodeMap) ast.Stmt { return copyStmt(x, nMap) } // StmtList returns xs statement slice deep copy. // Copy of nil argument is nil. func StmtList(xs []ast.Stmt, nMap CopyNodeMap) []ast.Stmt { if xs == nil { return nil } cp := make([]ast.Stmt, len(xs)) for i := range xs { cp[i] = copyStmt(xs[i], nMap) } return cp } // Decl returns x declaration deep copy. // Copy of nil argument is nil. func Decl(x ast.Decl, nMap CopyNodeMap) ast.Decl { return copyDecl(x, nMap) } // DeclList returns xs declaration slice deep copy. // Copy of nil argument is nil. func DeclList(xs []ast.Decl, nMap CopyNodeMap) []ast.Decl { if xs == nil { return nil } cp := make([]ast.Decl, len(xs)) for i := range xs { cp[i] = copyDecl(xs[i], nMap) } return cp } // BadExpr returns x deep copy. // Copy of nil argument is nil. func BadExpr(x *ast.BadExpr, nMap CopyNodeMap) *ast.BadExpr { if x == nil { return nil } cp := *x if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // Ident returns x deep copy. // Copy of nil argument is nil. func Ident(x *ast.Ident, nMap CopyNodeMap) *ast.Ident { if x == nil { return nil } cp := *x if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // IdentList returns xs identifier slice deep copy. // Copy of nil argument is nil. func IdentList(xs []*ast.Ident, nMap CopyNodeMap) []*ast.Ident { if xs == nil { return nil } cp := make([]*ast.Ident, len(xs)) for i := range xs { cp[i] = Ident(xs[i], nMap) } return cp } // Ellipsis returns x deep copy. // Copy of nil argument is nil. func Ellipsis(x *ast.Ellipsis, nMap CopyNodeMap) *ast.Ellipsis { if x == nil { return nil } cp := *x cp.Elt = copyExpr(x.Elt, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // BasicLit returns x deep copy. // Copy of nil argument is nil. func BasicLit(x *ast.BasicLit, nMap CopyNodeMap) *ast.BasicLit { if x == nil { return nil } cp := *x if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // FuncLit returns x deep copy. // Copy of nil argument is nil. func FuncLit(x *ast.FuncLit, nMap CopyNodeMap) *ast.FuncLit { if x == nil { return nil } cp := *x cp.Type = FuncType(x.Type, nMap) cp.Body = BlockStmt(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // CompositeLit returns x deep copy. // Copy of nil argument is nil. func CompositeLit(x *ast.CompositeLit, nMap CopyNodeMap) *ast.CompositeLit { if x == nil { return nil } cp := *x cp.Type = copyExpr(x.Type, nMap) cp.Elts = ExprList(x.Elts, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ParenExpr returns x deep copy. // Copy of nil argument is nil. func ParenExpr(x *ast.ParenExpr, nMap CopyNodeMap) *ast.ParenExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // SelectorExpr returns x deep copy. // Copy of nil argument is nil. func SelectorExpr(x *ast.SelectorExpr, nMap CopyNodeMap) *ast.SelectorExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) cp.Sel = Ident(x.Sel, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // IndexExpr returns x deep copy. // Copy of nil argument is nil. func IndexExpr(x *ast.IndexExpr, nMap CopyNodeMap) *ast.IndexExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) cp.Index = copyExpr(x.Index, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // SliceExpr returns x deep copy. // Copy of nil argument is nil. func SliceExpr(x *ast.SliceExpr, nMap CopyNodeMap) *ast.SliceExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) cp.Low = copyExpr(x.Low, nMap) cp.High = copyExpr(x.High, nMap) cp.Max = copyExpr(x.Max, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // TypeAssertExpr returns x deep copy. // Copy of nil argument is nil. func TypeAssertExpr(x *ast.TypeAssertExpr, nMap CopyNodeMap) *ast.TypeAssertExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) cp.Type = copyExpr(x.Type, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // CallExpr returns x deep copy. // Copy of nil argument is nil. func CallExpr(x *ast.CallExpr, nMap CopyNodeMap) *ast.CallExpr { if x == nil { return nil } cp := *x cp.Fun = copyExpr(x.Fun, nMap) cp.Args = ExprList(x.Args, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // StarExpr returns x deep copy. // Copy of nil argument is nil. func StarExpr(x *ast.StarExpr, nMap CopyNodeMap) *ast.StarExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // UnaryExpr returns x deep copy. // Copy of nil argument is nil. func UnaryExpr(x *ast.UnaryExpr, nMap CopyNodeMap) *ast.UnaryExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // BinaryExpr returns x deep copy. // Copy of nil argument is nil. func BinaryExpr(x *ast.BinaryExpr, nMap CopyNodeMap) *ast.BinaryExpr { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) cp.Y = copyExpr(x.Y, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // KeyValueExpr returns x deep copy. // Copy of nil argument is nil. func KeyValueExpr(x *ast.KeyValueExpr, nMap CopyNodeMap) *ast.KeyValueExpr { if x == nil { return nil } cp := *x cp.Key = copyExpr(x.Key, nMap) cp.Value = copyExpr(x.Value, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ArrayType returns x deep copy. // Copy of nil argument is nil. func ArrayType(x *ast.ArrayType, nMap CopyNodeMap) *ast.ArrayType { if x == nil { return nil } cp := *x cp.Len = copyExpr(x.Len, nMap) cp.Elt = copyExpr(x.Elt, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // StructType returns x deep copy. // Copy of nil argument is nil. func StructType(x *ast.StructType, nMap CopyNodeMap) *ast.StructType { if x == nil { return nil } cp := *x cp.Fields = FieldList(x.Fields, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // Field returns x deep copy. // Copy of nil argument is nil. func Field(x *ast.Field, nMap CopyNodeMap) *ast.Field { if x == nil { return nil } cp := *x cp.Names = IdentList(x.Names, nMap) cp.Type = copyExpr(x.Type, nMap) cp.Tag = BasicLit(x.Tag, nMap) cp.Doc = CommentGroup(x.Doc, nMap) cp.Comment = CommentGroup(x.Comment, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // FieldList returns x deep copy. // Copy of nil argument is nil. func FieldList(x *ast.FieldList, nMap CopyNodeMap) *ast.FieldList { if x == nil { return nil } cp := *x if x.List != nil { cp.List = make([]*ast.Field, len(x.List)) for i := range x.List { cp.List[i] = Field(x.List[i], nMap) } } if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // FuncType returns x deep copy. // Copy of nil argument is nil. func FuncType(x *ast.FuncType, nMap CopyNodeMap) *ast.FuncType { if x == nil { return nil } cp := *x cp.Params = FieldList(x.Params, nMap) cp.Results = FieldList(x.Results, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // InterfaceType returns x deep copy. // Copy of nil argument is nil. func InterfaceType(x *ast.InterfaceType, nMap CopyNodeMap) *ast.InterfaceType { if x == nil { return nil } cp := *x cp.Methods = FieldList(x.Methods, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // MapType returns x deep copy. // Copy of nil argument is nil. func MapType(x *ast.MapType, nMap CopyNodeMap) *ast.MapType { if x == nil { return nil } cp := *x cp.Key = copyExpr(x.Key, nMap) cp.Value = copyExpr(x.Value, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ChanType returns x deep copy. // Copy of nil argument is nil. func ChanType(x *ast.ChanType, nMap CopyNodeMap) *ast.ChanType { if x == nil { return nil } cp := *x cp.Value = copyExpr(x.Value, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // BlockStmt returns x deep copy. // Copy of nil argument is nil. func BlockStmt(x *ast.BlockStmt, nMap CopyNodeMap) *ast.BlockStmt { if x == nil { return nil } cp := *x cp.List = StmtList(x.List, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ImportSpec returns x deep copy. // Copy of nil argument is nil. func ImportSpec(x *ast.ImportSpec, nMap CopyNodeMap) *ast.ImportSpec { if x == nil { return nil } cp := *x cp.Name = Ident(x.Name, nMap) cp.Path = BasicLit(x.Path, nMap) cp.Doc = CommentGroup(x.Doc, nMap) cp.Comment = CommentGroup(x.Comment, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ValueSpec returns x deep copy. // Copy of nil argument is nil. func ValueSpec(x *ast.ValueSpec, nMap CopyNodeMap) *ast.ValueSpec { if x == nil { return nil } cp := *x cp.Names = IdentList(x.Names, nMap) cp.Values = ExprList(x.Values, nMap) cp.Type = copyExpr(x.Type, nMap) cp.Doc = CommentGroup(x.Doc, nMap) cp.Comment = CommentGroup(x.Comment, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // TypeSpec returns x deep copy. // Copy of nil argument is nil. func TypeSpec(x *ast.TypeSpec, nMap CopyNodeMap) *ast.TypeSpec { if x == nil { return nil } cp := *x cp.Name = Ident(x.Name, nMap) cp.Type = copyExpr(x.Type, nMap) cp.Doc = CommentGroup(x.Doc, nMap) cp.Comment = CommentGroup(x.Comment, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // Spec returns x deep copy. // Copy of nil argument is nil. func Spec(x ast.Spec, nMap CopyNodeMap) ast.Spec { if x == nil { return nil } switch x := x.(type) { case *ast.ImportSpec: return ImportSpec(x, nMap) case *ast.ValueSpec: return ValueSpec(x, nMap) case *ast.TypeSpec: return TypeSpec(x, nMap) default: panic("unhandled spec") } } // SpecList returns xs spec slice deep copy. // Copy of nil argument is nil. func SpecList(xs []ast.Spec, nMap CopyNodeMap) []ast.Spec { if xs == nil { return nil } cp := make([]ast.Spec, len(xs)) for i := range xs { cp[i] = Spec(xs[i], nMap) } return cp } // BadStmt returns x deep copy. // Copy of nil argument is nil. func BadStmt(x *ast.BadStmt, nMap CopyNodeMap) *ast.BadStmt { if x == nil { return nil } cp := *x if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // DeclStmt returns x deep copy. // Copy of nil argument is nil. func DeclStmt(x *ast.DeclStmt, nMap CopyNodeMap) *ast.DeclStmt { if x == nil { return nil } cp := *x cp.Decl = copyDecl(x.Decl, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // EmptyStmt returns x deep copy. // Copy of nil argument is nil. func EmptyStmt(x *ast.EmptyStmt, nMap CopyNodeMap) *ast.EmptyStmt { if x == nil { return nil } cp := *x if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // LabeledStmt returns x deep copy. // Copy of nil argument is nil. func LabeledStmt(x *ast.LabeledStmt, nMap CopyNodeMap) *ast.LabeledStmt { if x == nil { return nil } cp := *x cp.Label = Ident(x.Label, nMap) cp.Stmt = copyStmt(x.Stmt, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ExprStmt returns x deep copy. // Copy of nil argument is nil. func ExprStmt(x *ast.ExprStmt, nMap CopyNodeMap) *ast.ExprStmt { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // SendStmt returns x deep copy. // Copy of nil argument is nil. func SendStmt(x *ast.SendStmt, nMap CopyNodeMap) *ast.SendStmt { if x == nil { return nil } cp := *x cp.Chan = copyExpr(x.Chan, nMap) cp.Value = copyExpr(x.Value, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // IncDecStmt returns x deep copy. // Copy of nil argument is nil. func IncDecStmt(x *ast.IncDecStmt, nMap CopyNodeMap) *ast.IncDecStmt { if x == nil { return nil } cp := *x cp.X = copyExpr(x.X, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // AssignStmt returns x deep copy. // Copy of nil argument is nil. func AssignStmt(x *ast.AssignStmt, nMap CopyNodeMap) *ast.AssignStmt { if x == nil { return nil } cp := *x cp.Lhs = ExprList(x.Lhs, nMap) cp.Rhs = ExprList(x.Rhs, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // GoStmt returns x deep copy. // Copy of nil argument is nil. func GoStmt(x *ast.GoStmt, nMap CopyNodeMap) *ast.GoStmt { if x == nil { return nil } cp := *x cp.Call = CallExpr(x.Call, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // DeferStmt returns x deep copy. // Copy of nil argument is nil. func DeferStmt(x *ast.DeferStmt, nMap CopyNodeMap) *ast.DeferStmt { if x == nil { return nil } cp := *x cp.Call = CallExpr(x.Call, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ReturnStmt returns x deep copy. // Copy of nil argument is nil. func ReturnStmt(x *ast.ReturnStmt, nMap CopyNodeMap) *ast.ReturnStmt { if x == nil { return nil } cp := *x cp.Results = ExprList(x.Results, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // BranchStmt returns x deep copy. // Copy of nil argument is nil. func BranchStmt(x *ast.BranchStmt, nMap CopyNodeMap) *ast.BranchStmt { if x == nil { return nil } cp := *x cp.Label = Ident(x.Label, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // IfStmt returns x deep copy. // Copy of nil argument is nil. func IfStmt(x *ast.IfStmt, nMap CopyNodeMap) *ast.IfStmt { if x == nil { return nil } cp := *x cp.Init = copyStmt(x.Init, nMap) cp.Cond = copyExpr(x.Cond, nMap) cp.Body = BlockStmt(x.Body, nMap) cp.Else = copyStmt(x.Else, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // CaseClause returns x deep copy. // Copy of nil argument is nil. func CaseClause(x *ast.CaseClause, nMap CopyNodeMap) *ast.CaseClause { if x == nil { return nil } cp := *x cp.List = ExprList(x.List, nMap) cp.Body = StmtList(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // SwitchStmt returns x deep copy. // Copy of nil argument is nil. func SwitchStmt(x *ast.SwitchStmt, nMap CopyNodeMap) *ast.SwitchStmt { if x == nil { return nil } cp := *x cp.Init = copyStmt(x.Init, nMap) cp.Tag = copyExpr(x.Tag, nMap) cp.Body = BlockStmt(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // TypeSwitchStmt returns x deep copy. // Copy of nil argument is nil. func TypeSwitchStmt(x *ast.TypeSwitchStmt, nMap CopyNodeMap) *ast.TypeSwitchStmt { if x == nil { return nil } cp := *x cp.Init = copyStmt(x.Init, nMap) cp.Assign = copyStmt(x.Assign, nMap) cp.Body = BlockStmt(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // CommClause returns x deep copy. // Copy of nil argument is nil. func CommClause(x *ast.CommClause, nMap CopyNodeMap) *ast.CommClause { if x == nil { return nil } cp := *x cp.Comm = copyStmt(x.Comm, nMap) cp.Body = StmtList(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // SelectStmt returns x deep copy. // Copy of nil argument is nil. func SelectStmt(x *ast.SelectStmt, nMap CopyNodeMap) *ast.SelectStmt { if x == nil { return nil } cp := *x cp.Body = BlockStmt(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // ForStmt returns x deep copy. // Copy of nil argument is nil. func ForStmt(x *ast.ForStmt, nMap CopyNodeMap) *ast.ForStmt { if x == nil { return nil } cp := *x cp.Init = copyStmt(x.Init, nMap) cp.Cond = copyExpr(x.Cond, nMap) cp.Post = copyStmt(x.Post, nMap) cp.Body = BlockStmt(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // RangeStmt returns x deep copy. // Copy of nil argument is nil. func RangeStmt(x *ast.RangeStmt, nMap CopyNodeMap) *ast.RangeStmt { if x == nil { return nil } cp := *x cp.Key = copyExpr(x.Key, nMap) cp.Value = copyExpr(x.Value, nMap) cp.X = copyExpr(x.X, nMap) cp.Body = BlockStmt(x.Body, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // Comment returns x deep copy. // Copy of nil argument is nil. func Comment(x *ast.Comment, nMap CopyNodeMap) *ast.Comment { if x == nil { return nil } cp := *x if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // CommentGroup returns x deep copy. // Copy of nil argument is nil. func CommentGroup(x *ast.CommentGroup, nMap CopyNodeMap) *ast.CommentGroup { if x == nil { return nil } cp := *x if x.List != nil { cp.List = make([]*ast.Comment, len(x.List)) for i := range x.List { cp.List[i] = Comment(x.List[i], nMap) } } if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // File returns x deep copy. // Copy of nil argument is nil. func File(x *ast.File, nMap CopyNodeMap) *ast.File { if x == nil { return nil } cp := *x cp.Doc = CommentGroup(x.Doc, nMap) cp.Name = Ident(x.Name, nMap) cp.Decls = DeclList(x.Decls, nMap) cp.Imports = make([]*ast.ImportSpec, len(x.Imports)) for i := range x.Imports { cp.Imports[i] = ImportSpec(x.Imports[i], nMap) } cp.Unresolved = IdentList(x.Unresolved, nMap) cp.Comments = make([]*ast.CommentGroup, len(x.Comments)) for i := range x.Comments { cp.Comments[i] = CommentGroup(x.Comments[i], nMap) } if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // Package returns x deep copy. // Copy of nil argument is nil. func Package(x *ast.Package, nMap CopyNodeMap) *ast.Package { if x == nil { return nil } cp := *x cp.Files = make(map[string]*ast.File) for filename, f := range x.Files { cp.Files[filename] = f } if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // BadDecl returns x deep copy. // Copy of nil argument is nil. func BadDecl(x *ast.BadDecl, nMap CopyNodeMap) *ast.BadDecl { if x == nil { return nil } cp := *x if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // GenDecl returns x deep copy. // Copy of nil argument is nil. func GenDecl(x *ast.GenDecl, nMap CopyNodeMap) *ast.GenDecl { if x == nil { return nil } cp := *x cp.Specs = SpecList(x.Specs, nMap) cp.Doc = CommentGroup(x.Doc, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } // FuncDecl returns x deep copy. // Copy of nil argument is nil. func FuncDecl(x *ast.FuncDecl, nMap CopyNodeMap) *ast.FuncDecl { if x == nil { return nil } cp := *x cp.Recv = FieldList(x.Recv, nMap) cp.Name = Ident(x.Name, nMap) cp.Type = FuncType(x.Type, nMap) cp.Body = BlockStmt(x.Body, nMap) cp.Doc = CommentGroup(x.Doc, nMap) if nMap != nil { base := nMap[x] if base == nil { base = x } nMap[&cp] = base } return &cp } func copyNode(x ast.Node, nMap CopyNodeMap) ast.Node { switch x := x.(type) { case ast.Expr: return copyExpr(x, nMap) case ast.Stmt: return copyStmt(x, nMap) case ast.Decl: return copyDecl(x, nMap) case ast.Spec: return Spec(x, nMap) case *ast.FieldList: return FieldList(x, nMap) case *ast.Comment: return Comment(x, nMap) case *ast.CommentGroup: return CommentGroup(x, nMap) case *ast.File: return File(x, nMap) case *ast.Package: return Package(x, nMap) default: panic("unhandled node") } } func copyExpr(x ast.Expr, nMap CopyNodeMap) ast.Expr { if x == nil { return nil } switch x := x.(type) { case *ast.BadExpr: return BadExpr(x, nMap) case *ast.Ident: return Ident(x, nMap) case *ast.Ellipsis: return Ellipsis(x, nMap) case *ast.BasicLit: return BasicLit(x, nMap) case *ast.FuncLit: return FuncLit(x, nMap) case *ast.CompositeLit: return CompositeLit(x, nMap) case *ast.ParenExpr: return ParenExpr(x, nMap) case *ast.SelectorExpr: return SelectorExpr(x, nMap) case *ast.IndexExpr: return IndexExpr(x, nMap) case *ast.SliceExpr: return SliceExpr(x, nMap) case *ast.TypeAssertExpr: return TypeAssertExpr(x, nMap) case *ast.CallExpr: return CallExpr(x, nMap) case *ast.StarExpr: return StarExpr(x, nMap) case *ast.UnaryExpr: return UnaryExpr(x, nMap) case *ast.BinaryExpr: return BinaryExpr(x, nMap) case *ast.KeyValueExpr: return KeyValueExpr(x, nMap) case *ast.ArrayType: return ArrayType(x, nMap) case *ast.StructType: return StructType(x, nMap) case *ast.FuncType: return FuncType(x, nMap) case *ast.InterfaceType: return InterfaceType(x, nMap) case *ast.MapType: return MapType(x, nMap) case *ast.ChanType: return ChanType(x, nMap) default: panic("unhandled expr") } } func copyStmt(x ast.Stmt, nMap CopyNodeMap) ast.Stmt { if x == nil { return nil } switch x := x.(type) { case *ast.BadStmt: return BadStmt(x, nMap) case *ast.DeclStmt: return DeclStmt(x, nMap) case *ast.EmptyStmt: return EmptyStmt(x, nMap) case *ast.LabeledStmt: return LabeledStmt(x, nMap) case *ast.ExprStmt: return ExprStmt(x, nMap) case *ast.SendStmt: return SendStmt(x, nMap) case *ast.IncDecStmt: return IncDecStmt(x, nMap) case *ast.AssignStmt: return AssignStmt(x, nMap) case *ast.GoStmt: return GoStmt(x, nMap) case *ast.DeferStmt: return DeferStmt(x, nMap) case *ast.ReturnStmt: return ReturnStmt(x, nMap) case *ast.BranchStmt: return BranchStmt(x, nMap) case *ast.BlockStmt: return BlockStmt(x, nMap) case *ast.IfStmt: return IfStmt(x, nMap) case *ast.CaseClause: return CaseClause(x, nMap) case *ast.SwitchStmt: return SwitchStmt(x, nMap) case *ast.TypeSwitchStmt: return TypeSwitchStmt(x, nMap) case *ast.CommClause: return CommClause(x, nMap) case *ast.SelectStmt: return SelectStmt(x, nMap) case *ast.ForStmt: return ForStmt(x, nMap) case *ast.RangeStmt: return RangeStmt(x, nMap) default: panic("unhandled stmt") } } func copyDecl(x ast.Decl, nMap CopyNodeMap) ast.Decl { if x == nil { return nil } switch x := x.(type) { case *ast.BadDecl: return BadDecl(x, nMap) case *ast.GenDecl: return GenDecl(x, nMap) case *ast.FuncDecl: return FuncDecl(x, nMap) default: panic("unhandled decl") } }
astcopy.go
0.694613
0.477676
astcopy.go
starcoder
package yangtree // yangtree consists of the data node. type DataNode interface { IsDataNode() IsNil() bool // IsNil() is used to check the data node is null. IsBranchNode() bool // IsBranchNode() returns true if the data node is a DataBranch (a container or a list node). IsLeafNode() bool // IsLeafNode() returns true if the data node is a DataLeaf (a leaf or a multiple leaf-list node) or DataLeafList (a single leaf-list node). IsDuplicatableNode() bool // IsDuplicatable() returns true if multiple nodes having the same ID can exist in the tree. IsListableNode() bool // IsListable() returns true if the nodes that has the same schema are listed in the tree. IsStateNode() bool // IsStateNode() returns true if the node is a config=false node. HasStateNode() bool // HasStateNode() returns true if the node has a config=false child node. HasMultipleValues() bool // HasMultipleValues() returns true if the node has a set of values (= *DataLeafList). IsLeaf() bool // IsLeaf() returns true if the data node is an yang leaf. IsLeafList() bool // IsLeafList() returns true if the data node is an yang leaf-list. IsList() bool // IsList() returns true if the data node is an yang list. IsContainer() bool // IsContainer returns true if the data node is an yang container node. Name() string // Name() returns the name of the data node. QName(rfc7951 bool) (string, bool) // QName() returns the namespace-qualified name e.g. module-name:node-name or module-prefix:node-name. ID() string // ID() returns the data node ID (NODE[KEY=VALUE]). The ID is an XPath element combined with XPath predicates to identify the node instance. Schema() *SchemaNode // Schema() returns the schema of the data node. Parent() DataNode // Parent() returns the parent if it is present. Children() []DataNode // Children() returns all child nodes. Insert(child DataNode, i InsertOption) (DataNode, error) // Insert() inserts a new child node. It replaces and returns the old one. Delete(child DataNode) error // Delete() deletes the child node if it is present. Replace(src DataNode) error // Replace() replaces itself to the src node. Merge(src DataNode) error // Merge() merges the src node including all children to the current data node. Remove() error // Remove() removes itself. // GetOrNew() gets or creates a node having the id (NODE_NAME or NODE_NAME[KEY=VALUE]) and returns // the found or created node with the boolean value that // indicates the returned node is created. GetOrNew(id string, i InsertOption) (DataNode, bool, error) Create(id string, value ...string) (DataNode, error) // Create() creates a child using the node id (NODE_NAME or NODE_NAME[KEY=VALUE]). Update(id string, value ...string) (DataNode, error) // Update() updates a child that has the node id (NODE_NAME or NODE_NAME[KEY=VALUE]) using the input values. CreateByMap(pmap map[string]interface{}) error // CreateByMap() updates the data node using pmap (path predicate map) and string values. UpdateByMap(pmap map[string]interface{}) error // UpdateByMap() updates the data node using pmap (path predicate map) and string values. Exist(id string) bool // Exist() is used to check a data node is present. Get(id string) DataNode // Get() is used to get the first child has the id. GetValue(id string) interface{} // GetValue() is used to get the value of the child that has the id. GetValueString(id string) string // GetValueString() is used to get the value, converted to string, of the child that has the id. GetAll(id string) []DataNode // GetAll() is used to get all children that have the id. Lookup(idPrefix string) []DataNode // Lookup() is used to get all children on which their keys start with the prefix string of the node id. Len() int // Len() returns the number of children or the number of values. Index(id string) int // Index() finds all children by the node id and returns the position. Child(index int) DataNode // Child() gets the child of the index. String() string // String() returns a string to identify the node. Path() string // Path() returns the path from the root to the current data node. PathTo(descendant DataNode) string // PathTo() returns a relative path to a descendant node. SetValue(value ...interface{}) error // SetValue() writes the values to the data node. SetValueSafe(value ...interface{}) error // SetValueSafe() writes the values to the data node. It will recover the value if failed. UnsetValue(value ...interface{}) error // UnsetValue() clear the value of the data node to the default. SetValueString(value ...string) error // SetValueString() writes the values to the data node. The value must be string. SetValueStringSafe(value ...string) error // SetValueStringSafe() writes the values to the data node. It will recover the value if failed. UnsetValueString(value ...string) error // UnsetValueString() clear the value of the data node to the default. HasValueString(value string) bool // HasValueString() returns true if the data node value has the value. Value() interface{} // Value() returns the raw data of the data node. Values() []interface{} // Values() returns its values using []interface{} slice ValueString() string // ValueString() returns the string value of the data node. SetMetadata(name string, value ...interface{}) error // SetMetadata() sets a metadata. SetMetadataString(name string, value ...string) error // SetMetadataString() sets a metadata using string values. UnsetMetadata(name string) error // UnsetMetadata() remove a metadata. // Metadata(name string) interface{} // Metadatas(name string) []interface{} Metadata() map[string]DataNode } // yangtree Option type Option interface { IsOption() } // SetValueString(node, editopt, valuestring ...) // SetValue(node, editopt, value ...) // New YANGTreeOption // YANGTreeOption is used to store yangtree options. type YANGTreeOption struct { // If SingleLeafList is enabled, leaf-list data represents to a single leaf-list node that contains several values. // If disabled, leaf-list data represents to multiple leaf-list nodes that contains each single value. SingleLeafList bool LeafListValueAsKey bool // leaf-list value can be represented to the xpath if it is set to true. CreatedWithDefault bool // DataNode (data node) is created with the default value of the schema if set. YANGLibrary2016 bool // Load ietf-yang-library@2016-06-21 YANGLibrary2019 bool // Load ietf-yang-library@2019-01-04 SchemaSetName string // The name of the schema set // DefaultValueString [json, yaml, xml] } func (yangtreeOption YANGTreeOption) IsOption() {} // Metadata option is used to print out the metadata of the tree. type Metadata struct{} func (metadata Metadata) IsOption() {} // RepresentItself option is used to print out a top node itself to a json or yaml document. // enumSchema := RootSchema.FindSchema("/sample/container-val/enum-val") // datanode, _ := NewWithValue(enumSchema, "enum1") // if j, _ := MarshalJSON(datanode); len(j) > 0 { // fmt.Println(string(j)) // // "enum1" // } // if j, _ := MarshalJSON(datanode, RepresentItself{}); len(j) > 0 { // fmt.Println(string(j)) // // {"enum-val":"enum1"} // } type RepresentItself struct{} func (f RepresentItself) IsOption() {}
interface.go
0.608594
0.677654
interface.go
starcoder
// Package image provides functions to operate on container images efficiently. package image import ( "fmt" "log" "sort" "github.com/google/go-containerregistry/pkg/v1/google" ) // List represents the container images of the application we check. // It provides conveniences to access/operate images by the image tag. type List struct { // TagToDigest is a map from a tag name to the digest of the image tagged. TagToDigest map[string]string // name is the name of the image list. name string // byCreated is a list of 'google.ManifestInfo' ordered by the created time. // Note: we cannot use updated time to order because tagging/untagging // changes the updated time. byCreated []*google.ManifestInfo // tagToIndex is a map from a tag to the index of the ManifestInfo in the // list of 'byCreated'. It helps us to find the neighbour manifests quickly // by tag name. tagToIndex map[string]int } // NewList creates a new List instance. func NewList(name string, manifests map[string]google.ManifestInfo) *List { q := make([]*google.ManifestInfo, 0, len(manifests)) for digest := range manifests { m := manifests[digest] // It makes no sense to us if a manifest has no tags. So filter them // out. if len(m.Tags) == 0 { continue } q = append(q, &m) } // Using heap sort may be better since we usually only need to check the top // N images. But because we don't have too much data (e.g. ~1K images for // drone), using basic sort method is easier to understand. sort.Slice(q, func(i, j int) bool { return q[i].Created.After(q[j].Created) }) // Construct the tag to index map. ti := map[string]int{} for i, mi := range q { for _, t := range mi.Tags { ti[t] = i } } // Construct the tag to digest map. td := map[string]string{} for digest, m := range manifests { for _, t := range m.Tags { td[t] = digest } } return &List{ TagToDigest: td, name: name, byCreated: q, tagToIndex: ti, } } func (i *List) String() string { return i.name } // Manifest gets the manifest info of a given tag name. func (i *List) Manifest(tagName string) (*google.ManifestInfo, bool) { idx, ok := i.tagToIndex[tagName] if !ok { return nil, false } return i.byCreated[idx], true } // NewestTag returns a tag of the newest/latest image. // It doesn't matter to return which tag when the image has multiple tags since // any of them can identify the image. func (i *List) NewestTag() (string, bool) { if len(i.byCreated) == 0 { return "", false } for _, t := range i.byCreated { // All manifests without tags have been filtered out. return t.Tags[0], true } return "", false } // TraverseToNewer traverses the image list to the newer direction. func (i *List) TraverseToNewer(startingTag string, f func(*google.ManifestInfo) (bool, error)) (bool, error) { nextNewer := func(idx int) (*google.ManifestInfo, bool) { if idx == 0 { return nil, false // No more newer image. } return i.byCreated[idx-1], true } ok, err := i.traverse(startingTag, nextNewer, f) if err != nil { return false, fmt.Errorf("traverse to newer: %s", err) } return ok, nil } // TraverseToOlder traverses the image list to the older direction. func (i *List) TraverseToOlder(startingTag string, f func(*google.ManifestInfo) (bool, error)) (bool, error) { nextOlder := func(idx int) (*google.ManifestInfo, bool) { if idx == len(i.byCreated)-1 { return nil, false // No more older image. } return i.byCreated[idx+1], true } ok, err := i.traverse(startingTag, nextOlder, f) if err != nil { return false, fmt.Errorf("traverse to older: %s", err) } return ok, nil } // traverse traverses the image list from the image identified by 'tag'. // The callback function will be called for all the images (the starting image // included) and it uses the boolean return value to indicate whether stop // (true) or not (false). func (i *List) traverse(startingTag string, next func(int) (*google.ManifestInfo, bool), f func(*google.ManifestInfo) (bool, error)) (bool, error) { m, ok := i.Manifest(startingTag) if !ok { return false, fmt.Errorf("traverse %q: starting tag %q not found", i, startingTag) } for { stop, err := f(m) if err != nil { return false, fmt.Errorf("traverse %q: %s", i, err) } if stop { return true, nil } // All manifests without tags have been filtered out. t := m.Tags[0] idx, ok := i.tagToIndex[t] if !ok { return false, fmt.Errorf("traverse %q: data inconsistency: %q not found", i, t) } m, ok = next(idx) if !ok { return false, nil // No more image available. } } } // NewerThan indicates whether the image identified by tagName1 is newer (in // term of building time) than the one identified by tagName2. func (i *List) NewerThan(tagName1, tagName2 string) (bool, error) { idx1, ok1 := i.tagToIndex[tagName1] if !ok1 { return false, fmt.Errorf("cannot find tag %q in images of %q", tagName1, i) } idx2, ok2 := i.tagToIndex[tagName2] if !ok2 { return false, fmt.Errorf("cannot find tag %q in images of %q", tagName2, i) } return idx1 < idx2, nil } // PutTag puts 'tag' to the images identified by 'target'. // The function is not transaction safe so the caller MUST ensure 'target' is // existing in the image list. // It's OK that 'tag' is non-existing. In this case, it's equivalent to add a // new tag to the 'target'. func (i *List) PutTag(tag, target string) error { // Moving a tag equivalent to delete tag and then add the tag. if err := i.DeleteTag(tag); err != nil { return fmt.Errorf("put tag: %s", err) } if err := i.addTag(tag, target); err != nil { return fmt.Errorf("put tag: %s", err) } return nil } // addTag adds a new tag to the image identified by the 'target' tag. func (i *List) addTag(tag, target string) error { idx, ok := i.tagToIndex[target] if !ok { return fmt.Errorf("add tag to images %q: cannot find target tag %q", i, target) } // We have ensured all manifests has at least one tag. i.TagToDigest[tag] = i.TagToDigest[i.byCreated[idx].Tags[0]] i.byCreated[idx].Tags = append(i.byCreated[idx].Tags, tag) i.tagToIndex[tag] = idx return nil } // DeleteTag deletes a tag from a manifest of the images. // We cannot delete the only tag of a manifest. // We don't return errors when try to delete a non-existing tag. func (i *List) DeleteTag(tag string) error { idx, ok := i.tagToIndex[tag] if !ok { log.Printf("%q: Skip deleting non-existing tag %q", i, tag) return nil } tags := i.byCreated[idx].Tags tagCount := len(tags) if tagCount <= 1 { return fmt.Errorf("delete tag of images %q: it is the only tag %q", i, tag) } i.byCreated[idx].Tags = removeFrom(tag, tags) delete(i.tagToIndex, tag) delete(i.TagToDigest, tag) return nil } // removeFrom removes a string from a string slice. func removeFrom(s string, slice []string) []string { for i, e := range slice { if e == s { slice[i] = slice[len(slice)-1] return slice[:len(slice)-1] } } return slice }
go/src/infra/cros/cmd/k8s-management/tag-manager/internal/image/list.go
0.737914
0.426083
list.go
starcoder
package main import ( "fmt" "math/rand" "time" ) func main() { fmt.Println("Let's simulate an election!") // Seed the PRNG rand.Seed(time.Now().UnixNano()) numTrials := 10000 marginOfError := 0.10 fileName := "debates.txt" // Read in the 2 files we are interested in electoralVotes := ReadElectoralVotes("electoralVotes.txt") polls := ReadPollingData(fileName) probability1, probability2, probabilityTie := SimulateMultipleElections(polls, electoralVotes, numTrials, marginOfError) fmt.Println("Estimated probability of ") fmt.Println(" Candidate1 win:", probability1) fmt.Println(" Candidate2 win:", probability2) fmt.Println(" Tie: ", probabilityTie) } // SimulateMultipleElections runs our simulation // Takes pooling data as a map of state names to %support as a float. (for // candidate 1 - candidate 2 is just 100% - the %support for candidate 1), along with a map // of state names to electoral college votes, a number of trials, and a marigin of error in the // polls // It returns the probabilities of candidate1, candidatew winning or a tie func SimulateMultipleElections( polls map[string]float64, electoralVotes map[string]uint, numTrials int, marginOfError float64) (float64, float64, float64) { winCount1 := 0 winCount2 := 0 tieCount := 0 // simulate an election numtrials times and update the counts each time for i := 0; i < numTrials; i++ { votes1, votes2 := SimulateOneElection(polls, electoralVotes, marginOfError) if votes1 > votes2 { winCount1++ } else if votes1 < votes2 { winCount2++ } else { tieCount++ } } probability1 := float64(winCount1) / float64(numTrials) probability2 := float64(winCount2) / float64(numTrials) probabilityTie := float64(tieCount) / float64(numTrials) return probability1, probability2, probabilityTie } // SimulateOneElection runs a single election and returns the votes for each candidate func SimulateOneElection(polls map[string]float64, electoralVotes map[string]uint, marginOfError float64) (uint, uint) { var collegeVotes1 uint = 0 var collegeVotes2 uint = 0 // range over all the states, and simulate the elction in each state for state := range polls { poll := polls[state] // The polling value in the state for candidate1 numVotes := electoralVotes[state] // adjust the polling value for randomness based on margin of error adjustedPoll := AddNoise(poll, marginOfError) // Check on who won the state based on the adjustedPoll if adjustedPoll >= .5 { // candidate1 wins collegeVotes1 += numVotes } else { // candidate2 wins collegeVotes2 += numVotes } } return collegeVotes1, collegeVotes2 } // AddNoise takes the polling value for candidate1, the polls margin of error, and returns an // adjusted polling value after adding random noise func AddNoise(poll float64, marginOfError float64) float64 { x := rand.NormFloat64() //random number from standard normal distribution x = x / 2 // x has a 95% chance of being between -1 and 1 x = x * marginOfError // x has a 95% chance of being between -marginOfError and marginOfError return x + poll }
election/main.go
0.683102
0.457561
main.go
starcoder
package gl import ( "unsafe" "github.com/go-gl/gl/v3.2-core/gl" ) func Init() error { return gl.Init() } func NeedVao() bool { return true } func GetError() uint32 { return gl.GetError() } func Viewport(x, y, width, height int32) { gl.Viewport(x, y, width, height) } func ClearColor(r, g, b, a float32) { gl.ClearColor(r, g, b, a) } func Clear(flags uint32) { gl.Clear(flags) } func Disable(flag uint32) { gl.Disable(flag) } func Enable(flag uint32) { gl.Enable(flag) } func Scissor(x, y, w, h int32) { gl.Scissor(x, y, w, h) } func DepthMask(flag bool) { gl.DepthMask(flag) } func ColorMask(r, g, b, a bool) { gl.ColorMask(r, g, b, a) } func BlendFunc(src, dst uint32) { gl.BlendFunc(src, dst) } func DepthFunc(fn uint32) { gl.DepthFunc(fn) } // vao func GenVertexArrays(n int32, arrays *uint32) { gl.GenVertexArrays(n, arrays) } func BindVertexArray(array uint32) { gl.BindVertexArray(array) } func DeleteVertexArrays(n int32, array *uint32) { gl.DeleteVertexArrays(n, array) } // program & shader func CreateProgram() uint32 { return gl.CreateProgram() } func AttachShader(program, shader uint32) { gl.AttachShader(program, shader) } func LinkProgram(program uint32) { gl.LinkProgram(program) } func UseProgram(id uint32) { gl.UseProgram(id) } func GetProgramiv(program uint32, pname uint32, params *int32) { gl.GetProgramiv(program, pname, params) } // TODO 原来的实现中 buf = loglength + 1 的,需要测试这种情况... func GetProgramInfoLog(program uint32) string { var logLength int32 GetProgramiv(program, INFO_LOG_LENGTH, &logLength) if logLength == 0 { return "" } buf := make([]uint8, logLength) gl.GetProgramInfoLog(program, logLength, nil, &buf[0]) return string(buf) } func CreateShader(xtype uint32) uint32 { return gl.CreateShader(xtype) } func ShaderSource(shader uint32, src string) { cstr, free := gl.Strs(src) gl.ShaderSource(shader, 1, cstr, nil) free() } func CompileShader(shader uint32) { gl.CompileShader(shader) } func GetShaderiv(shader uint32, pname uint32, params *int32) { gl.GetShaderiv(shader, pname, params) } func GetShaderInfoLog(shader uint32) string { var logLength int32 gl.GetShaderiv(shader, gl.INFO_LOG_LENGTH, &logLength) buf := make([]uint8, logLength) gl.GetShaderInfoLog(shader, logLength, nil, &buf[0]) return string(buf) } func DeleteShader(shader uint32) { gl.DeleteShader(shader) } // buffers & draw func GenBuffers(n int32, buffers *uint32) { gl.GenBuffers(n, buffers) } func BufferData(target uint32, size int, data unsafe.Pointer, usage uint32) { gl.BufferData(target, size, data, usage) } func BufferSubData(target uint32, offset, size int, data unsafe.Pointer) { gl.BufferSubData(target, offset, size, data) } func BindBuffer(target uint32, buffer uint32) { gl.BindBuffer(target, buffer) } func DeleteBuffers(n int32, buffers *uint32) { gl.DeleteBuffers(n, buffers) } func DrawElements(mode uint32, count int32, typ uint32, offset int) { gl.DrawElements(mode, count, typ, gl.PtrOffset(offset)) } func DrawArrays(mode uint32, first, count int32) { gl.DrawArrays(mode, first, count) } // uniform func GetUniformLocation(program uint32, name string) int32 { return gl.GetUniformLocation(program, gl.Str(name)) } func Uniform1i(loc, v int32) { gl.Uniform1i(loc, v) } func Uniform1iv(loc, num int32, v *int32) { gl.Uniform1iv(loc, num, v) } func Uniform1f(location int32, v0 float32) { gl.Uniform1f(location, v0) } func Uniform2f(location int32, v0, v1 float32) { gl.Uniform2f(location, v0, v1) } func Uniform3f(location int32, v0, v1, v2 float32) { gl.Uniform3f(location, v0, v1, v2) } func Uniform4f(location int32, v0, v1, v2, v3 float32) { gl.Uniform4f(location, v0, v1, v2, v3) } func Uniform1fv(loc, num int32, v *float32) { gl.Uniform1fv(loc, num, v) } func Uniform4fv(loc, num int32, v *float32) { gl.Uniform4fv(loc, num, v) } func UniformMatrix3fv(loc, num int32, t bool, v *float32) { gl.UniformMatrix3fv(loc, num, t, v) } func UniformMatrix4fv(loc, num int32, t bool, v *float32) { gl.UniformMatrix4fv(loc, num, t, v) } // attribute func EnableVertexAttribArray(index uint32) { gl.EnableVertexAttribArray(index) } func VertexAttribPointer(index uint32, size int32, xtype uint32, normalized bool, stride int32, offset int) { gl.VertexAttribPointer(index, size, xtype, normalized, stride, gl.PtrOffset(offset)) } func DisableVertexAttribArray(index uint32) { gl.DisableVertexAttribArray(index) } func GetAttribLocation(program uint32, name string) int32 { return gl.GetAttribLocation(program, gl.Str(name)) } func BindFragDataLocation(program uint32, color uint32, name string) { gl.BindFragDataLocation(program, color, gl.Str(name)) } // texture func ActiveTexture(texture uint32) { gl.ActiveTexture(texture) } func BindTexture(target uint32, texture uint32) { gl.BindTexture(target, texture) } func TexSubImage2D(target uint32, level int32, xOffset, yOffset, width, height int32, format, xtype uint32, pixels unsafe.Pointer) { gl.TexSubImage2D(target, level, xOffset, yOffset, width, height, format, xtype, pixels) } func TexImage2D(target uint32, level int32, internalFormat int32, width, height, border int32, format, xtype uint32, pixels unsafe.Pointer) { gl.TexImage2D(target, level, internalFormat, width, height, border, format, xtype, pixels) } func DeleteTextures(n int32, textures *uint32) { gl.DeleteTextures(n, textures) } func GenTextures(n int32, textures *uint32) { gl.GenTextures(n, textures) } func TexParameteri(texture uint32, pname uint32, params int32) { gl.TexParameteri(texture, pname, params) }
hid/gl/gl_gl3.go
0.625667
0.430447
gl_gl3.go
starcoder
package mod256 import ( . "math/bits" ) // z = 1/x mod m if it exists, otherwise 0 // Returns true if the inverse exists // Inv computes the (multiplicative) inverse of a residue, if it exists. func (z *Residue) Inv() bool { var ( b, c, // Borrow & carry a4, a3, a2, a1, a0, b4, b3, b2, b1, b0, c4, c3, c2, c1, c0, d4, d3, d2, d1, d0 uint64 ) x := z.r y := z.m.m u3, u2, u1, u0 := x[3], x[2], x[1], x[0] v3, v2, v1, v0 := y[3], y[2], y[1], y[0] if (u3 | u2 | u1 | u0) == 0 || // u == 0 (v3 | v2 | v1 | v0) == 0 || // v == 0 (u0 | v0) & 1 == 0 { // 2|gcd(u,v) // there is no inverse z.r[3], z.r[2], z.r[1], z.r[0] = 0, 0, 0, 0 return false } a4, a3, a2, a1, a0 = 0, 0, 0, 0, 1 b4, b3, b2, b1, b0 = 0, 0, 0, 0, 0 c4, c3, c2, c1, c0 = 0, 0, 0, 0, 0 d4, d3, d2, d1, d0 = 0, 0, 0, 0, 1 done := false for !done { for u0 & 1 == 0 { u0 = (u0 >> 1) | (u1 << 63) u1 = (u1 >> 1) | (u2 << 63) u2 = (u2 >> 1) | (u3 << 63) u3 = (u3 >> 1) if (a0 | b0) & 1 == 1 { a0, c = Add64(a0, y[0], 0) a1, c = Add64(a1, y[1], c) a2, c = Add64(a2, y[2], c) a3, c = Add64(a3, y[3], c) a4, _ = Add64(a4, 0, c) b0, b = Sub64(b0, x[0], 0) b1, b = Sub64(b1, x[1], b) b2, b = Sub64(b2, x[2], b) b3, b = Sub64(b3, x[3], b) b4, _ = Sub64(b4, 0, b) } a0 = (a0 >> 1) | (a1 << 63) a1 = (a1 >> 1) | (a2 << 63) a2 = (a2 >> 1) | (a3 << 63) a3 = (a3 >> 1) | (a4 << 63) a4 = uint64(int64(a4) >> 1) b0 = (b0 >> 1) | (b1 << 63) b1 = (b1 >> 1) | (b2 << 63) b2 = (b2 >> 1) | (b3 << 63) b3 = (b3 >> 1) | (b4 << 63) b4 = uint64(int64(b4) >> 1) } for v0 & 1 == 0 { v0 = (v0 >> 1) | (v1 << 63) v1 = (v1 >> 1) | (v2 << 63) v2 = (v2 >> 1) | (v3 << 63) v3 = (v3 >> 1) if (c0 | d0) & 1 == 1 { c0, c = Add64(c0, y[0], 0) c1, c = Add64(c1, y[1], c) c2, c = Add64(c2, y[2], c) c3, c = Add64(c3, y[3], c) c4, _ = Add64(c4, 0, c) d0, b = Sub64(d0, x[0], 0) d1, b = Sub64(d1, x[1], b) d2, b = Sub64(d2, x[2], b) d3, b = Sub64(d3, x[3], b) d4, _ = Sub64(d4, 0, b) } c0 = (c0 >> 1) | (c1 << 63) c1 = (c1 >> 1) | (c2 << 63) c2 = (c2 >> 1) | (c3 << 63) c3 = (c3 >> 1) | (c4 << 63) c4 = uint64(int64(c4) >> 1) d0 = (d0 >> 1) | (d1 << 63) d1 = (d1 >> 1) | (d2 << 63) d2 = (d2 >> 1) | (d3 << 63) d3 = (d3 >> 1) | (d4 << 63) d4 = uint64(int64(d4) >> 1) } t0, b := Sub64(u0, v0, 0) t1, b := Sub64(u1, v1, b) t2, b := Sub64(u2, v2, b) t3, b := Sub64(u3, v3, b) if b == 0 { // u >= v u3, u2, u1, u0 = t3, t2, t1, t0 a0, b = Sub64(a0, c0, 0) a1, b = Sub64(a1, c1, b) a2, b = Sub64(a2, c2, b) a3, b = Sub64(a3, c3, b) a4, _ = Sub64(a4, c4, b) b0, b = Sub64(b0, d0, 0) b1, b = Sub64(b1, d1, b) b2, b = Sub64(b2, d2, b) b3, b = Sub64(b3, d3, b) b4, _ = Sub64(b4, d4, b) } else { // v > u v0, b = Sub64(v0, u0, 0) v1, b = Sub64(v1, u1, b) v2, b = Sub64(v2, u2, b) v3, _ = Sub64(v3, u3, b) c0, b = Sub64(c0, a0, 0) c1, b = Sub64(c1, a1, b) c2, b = Sub64(c2, a2, b) c3, b = Sub64(c3, a3, b) c4, _ = Sub64(c4, a4, b) d0, b = Sub64(d0, b0, 0) d1, b = Sub64(d1, b1, b) d2, b = Sub64(d2, b2, b) d3, b = Sub64(d3, b3, b) d4, _ = Sub64(d4, b4, b) } if (u3 | u2 | u1 | u0) == 0 { done = true } } if (v3 | v2 | v1 | (v0 - 1)) != 0 { // gcd(z,m) != 1 z.r[3], z.r[2], z.r[1], z.r[0] = 0, 0, 0, 0 return false } // Add or subtract modulus to find 256-bit inverse (<= 2 iterations expected) for (c4 >> 63) != 0 { c0, c = Add64(c0, y[0], 0) c1, c = Add64(c1, y[1], c) c2, c = Add64(c2, y[2], c) c3, c = Add64(c3, y[3], c) c4, _ = Add64(c4, 0, c) } for c4 != 0 { c0, b = Sub64(c0, y[0], 0) c1, b = Sub64(c1, y[1], b) c2, b = Sub64(c2, y[2], b) c3, b = Sub64(c3, y[3], b) c4, _ = Sub64(c4, 0, b) } z.r[3], z.r[2], z.r[1], z.r[0] = c3, c2, c1, c0 return true }
inv.go
0.536313
0.518059
inv.go
starcoder
package render import ( "errors" "fmt" "strange-secrets.com/mantra/algebra" "strange-secrets.com/mantra/render/sampling" "strange-secrets.com/mantra/scene" "strange-secrets.com/mantra/scene/shading" "time" ) const ( TestImageWidth = 1024 * 2 // 640 TestImageHeight = 1024 // 480 ) type Renderer struct { Images map[string] Target Time algebra.MnFloat } func NewRenderer() *Renderer { return &Renderer{ Images: make(map[string] Target), } } // Creates a new image within the renderer which may be used as a target for a render operation. func (r *Renderer) CreateRenderTarget(name string, width int, height int) (Target, error) { if _, ok := r.Images[name]; ok { return nil, fmt.Errorf("cannot create render target \"%s\", name already in use", name) } renderTarget, err := NewGammaTarget(name, width, height) if err != nil { return nil, err } r.Images[name] = renderTarget return renderTarget, nil } func (r *Renderer) Render(imageName string, cameraName string, world *scene.Scene) error { cameraNode := world.GetNode(cameraName) if cameraNode == nil { return fmt.Errorf("cannot find camera \"%s\" for rendering", cameraName) } if target, ok := r.Images[imageName]; ok { return r.renderImage(cameraNode, target, world) } return fmt.Errorf("cannot render image \"%s\", image could not be found", imageName) } func (r *Renderer) renderImage(cameraNode *scene.Node, target Target, world *scene.Scene) error { if cameraNode == nil { return errors.New("cannot render image without camera node") } if target == nil { return errors.New("cannot render nil image") } start := time.Now() // We intend to use multi-threading for these blocks of pixels block := Block{ X: 0, Y: 0, Width: TestImageWidth, Height: TestImageHeight, } r.renderBlock(block, cameraNode, target, world) fmt.Println(fmt.Sprintf("render completed %dms", time.Since(start).Milliseconds())) return nil } func (r *Renderer) renderImageAsync(cameraNode *scene.Node, target Target, world *scene.Scene) error { if cameraNode == nil { return errors.New("cannot render image without camera node") } if target == nil { return errors.New("cannot render nil image") } lbc := NewLinearBlockChannel(target, 16, 16) start := time.Now() for loop := 0; loop < 4; loop++ { go r.processBlocks(lbc, cameraNode, target, world) } fmt.Println(fmt.Sprintf("render completed %dms", time.Since(start).Milliseconds())) return nil } func (r *Renderer) processBlocks(bc BlockChannel, cameraNode *scene.Node, target Target, world *scene.Scene) { for block := bc.NextBlock(); block.Width != 0; block = bc.NextBlock() { r.renderBlock(block, cameraNode, target, world) } } func (r *Renderer) renderBlock(block Block, cameraNode *scene.Node, target Target, world *scene.Scene) { //sampler := sampling.NewPixelSampler() sampler := sampling.NewRandomSampler(8) for y := 0; y < block.Height; y++ { for x := 0; x < block.Width; x++ { sampler.Reset(x + block.X, y + block.Y) target.Set(x + block.X, y + block.Y, r.renderPixel(sampler.Reset(x + block.X, y + block.Y), cameraNode, world)) } } } func (r *Renderer) renderPixel(pixel algebra.Vector2, sampler sampling.Sampler2D, cameraNode *scene.Node, world *scene.Scene) algebra.Vector3 { halfWidth := float64(TestImageWidth) / 2.0 halfHeight := float64(TestImageHeight) / 2.0 renderInfo := shading.RenderInfo{ Pixel: algebra.ZeroVector2, Width: TestImageWidth, Height: TestImageHeight, Aspect: float64(TestImageWidth) / float64(TestImageHeight), } result := algebra.ZeroVector3 valid := true // Here we should split the pixel up into multiple rays for anti-aliasing for renderInfo.Pixel, valid = sampler.Next(pixel); valid { renderInfo.Pixel.X = (renderInfo.Pixel.X - halfWidth) / halfWidth renderInfo.Pixel.Y = -(renderInfo.Pixel.Y - halfHeight) / halfHeight direction := cameraNode.CastRay(renderInfo.Pixel.X, renderInfo.Pixel.Y, renderInfo.Aspect) traceInfo := scene.NewTraceInfo(renderInfo, cameraNode.Location, direction) // TODO: Perhaps ShadeRay should return a color? result = result.Add(world.ShadeRay(traceInfo)) } return result.DivideScalar(algebra.MnFloat(sampler.Length())) }
render/renderer.go
0.724578
0.402803
renderer.go
starcoder
package dh import ( crand "crypto/rand" "crypto/sha1" "math/big" mrand "math/rand" "time" ) // cryptoRandomBigInt returns a random big int. // It returns nil if failed to get random bytes from crypto/rand. func cryptoRandomBigInt(nb int) *big.Int { b := make([]byte, nb) _, err := crand.Read(b) if err != nil { return nil } r := new(big.Int) r.SetBytes(b) return r } // GeneratePQ implements [2.2.1.1. Generation of p, q] in page 8 func GeneratePQ(m, L int) (p, q *big.Int) { // step 1: Set m' = m/160 mp := m/160 + 1 // step 2: Set L' = L/160 Lp := L/160 + 1 // step 3: Set N' = L/1024 Np := L/1024 + 1 var SEED *big.Int for { // step 4: Select an arbitrary bit string SEED such that the length of SEED >= m SEED = cryptoRandomBigInt(m / 8) if SEED == nil { continue } // step 5: Set U = 0 U := big.NewInt(0) // step 6: For i = 0 to m' - 1 // U = U + (SHA1[SEED + i] XOR SHA1[SEED + m' + 1]) * 2^(160*i) for i := 0; i < mp; i++ { Up := new(big.Int) xorPart1 := new(big.Int) t := new(big.Int) t.Add(SEED, big.NewInt(int64(i))) // SEED + i sha := sha1.Sum(t.Bytes()) xorPart1.SetBytes(sha[:]) // SHA1[SEED + i] -> xorPart1 xorPart2 := new(big.Int) t.Add(t, big.NewInt(int64(mp))) // SEED + i + m' sha = sha1.Sum(t.Bytes()) xorPart2.SetBytes(sha[:]) // SHA1[SEED + m' + i] -> xorPart2 Up.Xor(xorPart1, xorPart2) // XOR v := new(big.Int) v.Mul(big.NewInt(160), big.NewInt(int64(i))) v.Exp(big.NewInt(2), v, nil) // 2^(160*i) Up.Mul(Up, v) U.Add(U, Up) // U = U + ... } // step 5: Form q from U mod (2^m), and setting MSB and LSB to 1 t := big.NewInt(2) t.Exp(t, big.NewInt(160), nil) U.Mod(U, t) q = new(big.Int) q.Set(U) q.SetBit(q, 0, 1) q.SetBit(q, m-1, 1) // step 6: test whether q is prime if q.ProbablyPrime(100) { // step 7: If q is not prime then go to step 4 break } } // step 8: Let counter = 0 counter := 0 for { // step 9: Set R = seed + 2*m' + (L' * counter) R := new(big.Int) R.Set(SEED) t := new(big.Int) t.Mul(big.NewInt(2), big.NewInt(int64(mp))) R.Add(R, t) t.Mul(big.NewInt(int64(Lp)), big.NewInt(int64(counter))) R.Add(R, t) // step 10: Set V = 0 V := big.NewInt(0) // step 12: For i = 0 to L'-1 do V = V + SHA1(R + i) * 2^(160*i) for i := 0; i < Lp; i++ { sha := new(big.Int) sha.Add(R, big.NewInt(int64(i))) shaBytes := sha1.Sum(sha.Bytes()) sha.SetBytes(shaBytes[:]) second := new(big.Int) second.Mul(big.NewInt(160), big.NewInt(int64(i))) second.Exp(big.NewInt(2), second, nil) sha.Mul(sha, second) V.Add(V, sha) } // step 13: W = V mod 2^L W := new(big.Int) t.Exp(big.NewInt(2), big.NewInt(int64(L)), nil) W.Mod(V, t) // step 14: X = W OR 2^(L-1) X := new(big.Int) X.SetBit(W, L-1, 1) // step 15: Set p = X - (X mod (2*q)) + 1 p = new(big.Int) p.Set(X) t.Mul(big.NewInt(2), q) X.Mod(X, t) p.Sub(p, X) p.Add(p, big.NewInt(1)) // step 16: If p > 2^(L-1), test whether p is prime t.Exp(big.NewInt(2), big.NewInt(int64(L-1)), nil) if p.Cmp(t) == 1 { if p.ProbablyPrime(100) { // step 17: If p is prime, output p, q, seed, counter and stop break } } // step 18: Set counter = counter + 1 counter++ // step 19: If counter < (4096 * N) then go to 8 if counter >= 4096*Np { // !! where is N? !! return nil, nil } } return } // GenerateG implements [2.2.1.2. Generation of g] in page 9 func GenerateG(p, q *big.Int) (g *big.Int) { r := mrand.New(mrand.NewSource(time.Now().UnixNano())) g = new(big.Int) for { j := new(big.Int) j.Sub(p, big.NewInt(1)) j.Div(j, q) h := new(big.Int) h.Rand(r, p) if h.Cmp(big.NewInt(0)) == 0 { continue } g.Exp(h, j, p) if g.Cmp(big.NewInt(1)) != 0 { break } } return }
dh.go
0.512205
0.406037
dh.go
starcoder
package funl // OperatorInfo contains information about one operator type OperatorInfo struct{} // NewOperatorDocs returns documentation for operators func NewOperatorDocs() map[string]string { return map[string]string{ "and": ` Operator: and Performs logical and -operation for arguments. All arguments are assumed to be boolean expressions. Number of arguments need to be at least 1. Return value is boolean type: - true: if all arguments are true - false: otherwise Usage: and(<boolean-expr> <boolean-expr> <boolean-expr> ...) Note. and -operator stops evaluating any more input arguments after any input expression evaluates to false. `, "or": ` Operator: or Performs logical or -operation for arguments. All arguments are assumed to be boolean expressions. Number of arguments need to be at least 1. Return value is boolean type: - true: if any of arguments is true - false: otherwise Usage: or(<boolean-expr> <boolean-expr> <boolean-expr> ...) Note. or -operator stops evaluating any more input arguments after any input expression evaluates to true. `, "call": ` Operator: call Calls function or procedure given as 1st argument. Arguments of function/procedure call are following arguments. Number of arguments needs to be at least 1 (func/proc to be called). Arguments are evaluated before calling the function/procedure. Function/procedure can be also external procedure or function. Return value is return value of function/procedure. Usage: call(<func/proc> <arg-1> <arg-2> ...) `, "not": ` Operator: not Performs logical not -operation for argument. Argument is assumed to be boolean expression. Number of arguments need to be 1. Return value is boolean type: - true: if argument is false - false: if argument is true Usage: not(<boolean-expr>) `, "eq": ` Operator: eq Evaluates two arguments and compares resulting values. Number of arguments need to be 2. Return value is boolean type: - true: if values are equal - false: if values differ Usage: eq(<expr-1> <expr-2>) Note. not all types are comparable (function/procedure values) `, "if": ` Operator: if Evaluates 1st argument and based on value evaluates eiher 2nd or 3rd argument. It's assumed that 1st argument evalutes to boolean value: - true: 2nd argument is evaluated and returned as value - false: 3rd argument is evaluated and returned as value Number of arguments need to be 3. Return value is evaluated value of either 2nd or 3rd argument expression. Usage: if(<condition-expression> <expr-1> <expr-2>) `, "plus": ` Operator: plus Performs either arithmetic sum operation or string concatenation depending on input argument types. All arguments need to be of same type. Input arguments can be of type: - int: evaluates to arithmetic sum - float: evaluates to arithmetic sum - string: concatenation of argument strings Number of arguments need to be at least 2. Return value is of type int/float/string depending on type of input arguments. Usage: plus(<expr-1> <expr-2> <expr-3> ...) `, "minus": ` Operator: minus Performs arithmetic subtraction operation for two input arguments so that 2nd argument is subtracted from 1st one. Both arguments need to be of same type. Input arguments can be of type: - int - float Number of arguments need to be 2. Return value is result of subtraction of type int/float depending on type of input arguments. Usage: minus(<expr-1> <expr-2>) `, "mul": ` Operator: mul Performs arithmetic multiplication operation. Input arguments can be of type: - int - float Number of arguments need to be at least 2. Return value is multiplication result of input arguments. If any of arguments is of type float then result value type is float. Usage: mul(<expr-1> <expr-2> <expr-3> ...) `, "div": ` Operator: div Performs arithmetic division operation for two input arguments so that 1st argument is dividend and 2nd argument is divisor. Both arguments need to be of same type. Input arguments can be of type: - int - float If both arguments are of type int then result is of type int, otherwise result is of type float. In case of division of two int's result is quotient of division operation. Number of arguments need to be 2. Return value is result of division of type int/float depending on type of input arguments. Note. If divisor is zero (int or float) runtime error is generated. Usage: div(<expr-1> <expr-2>) `, "mod": ` Operator: mod Performs modulo operation for two input arguments, result is remainder of division operation where 1st argument is dividend and 2nd argument is divisor. Input arguments need to be of type int. Number of arguments need to be 2. Return value is remainder value of division of input arguments. Note. If divisor is zero (int or float) runtime error is generated. Usage: mod(<expr-1> <expr-2>) `, "list": ` Operator: list Creates list value. Arguments can be of any type. Arguments are evaluated to values which are put to list. Order of items in list is order of arguments. Number of arguments is not restricted (if none, empty list is created). Return value is list value. Usage: list(<expr-1> <expr-2> <expr-2> ...) `, "empty": ` Operator: empty Returns true if list/map is empty, false otherwise. Number of arguments need to be 1. Argument is assumed to be either list or map. Return value is boolean value. Usage: empty(<expr>) `, "head": ` Operator: head Returns 1st item from list which is given as argument. Number of arguments need to be 1. Argument is assumed to be list. Return value may be any type of value. Note. if list is empty runtime error is generated. Usage: head(<list-expr>) `, "last": ` Operator: last Returns last item from list which is given as argument. Number of arguments need to be 1. Argument is assumed to be list. Return value may be any type of value. Note. if list is empty runtime error is generated. Usage: last(<list-expr>) `, "rest": ` Operator: rest Returns rest of the list given as argument, excluding 1st item (head) of list. Number of arguments need to be 1. Argument is assumed to be list. Return value is list. Note. if list is empty runtime error is generated. Usage: rest(<list-expr>) `, "append": ` Operator: append Appends value(s) to the end of the list. Number of arguments need to be at least 1. First argument is assumed to be list. Following arguments are added to the end of list in that same order (2nd argument, 3rd argument etc.) Return value is list (with appended values). Note. if there's just one argument (list) then equal list is returned. Usage: append(<list-expr> <expr> <expr> ...) `, "add": ` Operator: add Adds value(s) in the front of the list. Number of arguments need to be at least 1. First argument is assumed to be list. Following arguments are added to the end of list in that same order (2nd argument, 3rd argument etc.) Return value is list (with added values). Note. if there's just one argument (list) then equal list is returned. Usage: add(<list-expr> <expr> <expr> ...) `, "len": ` Operator: len Returns length of list/map/string. Number of arguments need to be 1. Argument is assumed to be list, map or string. Length is evaluated as follows: - list: number of items in list - map: number of key-value pairs in map - string: number of characters in string Return value is type of int (length of argument value). Usage: len(<expr>) `, "type": ` Operator: type Returns type of value evaluated from argument expression. Number of arguments need to be 1. Return value is type of string, returning following values depending on argument value type: - int: 'int' - float: 'float' - bool: 'bool' - string: 'string' - function: 'function' (also for procedure) - list: 'list' - channel: 'channel' - map: 'map' - opaque value: 'opaque:' + opaque type specific name (string) - external procedure/function: 'ext-proc' Note. Runtime error is generated in case type -operator is called for opaque value in function call. (could otherwise cause impure side-effects in theory) Usage: type(<expr>) `, "in": ` Operator: in Returns true if 2nd argument is included in list, map or string given as 1st argument. Inclusion means: - for list: value equals to some value in list - for map: value equals to some key value of map - for string: (string) value is substring of string Number of arguments need to be 2. Return value is boolean value: - true: if 2nd argument is included in value of 1st argument - false: if 2nd argument is not included in value of 1st argument Note. In case 1st argument is type of string then it's assumed that 2nd argument is also type of string (otherwise runtime error is generated) Usage: in(<list/map/string-expr> <expr>) `, "ind": ` Operator: ind Returns value in list/string (given as 1st argument) located in location defined by index value given as 2nd argument (int). This means that if 1st argument is: - list: returns item in list in location defined by index - string: returns character (string) located in location defined by index Number of arguments need to be 2. Return value is: - in case of list: value of item in given location -> any type - in case of string: string (one character) Note. If index defined by 2nd argument points outside the limits of list/string then runtime error is generated Usage: ind(<list/string-expr> <index-expr>) `, "find": ` Operator: find Returns list of index values (int) which point the locations of values (defined by 2nd argument) in list/string (1st argument). Finds equal values in list and returns indexes to those in list. Finds substring locations in string and and returns indexes to those in list. Number of arguments need to be 2. Return value is list, contains index values (of type int). Note. if value is not found in list/string then empty list is returned Usage: find(<list/string-expr> <index-expr>) `, "slice": ` Operator: slice Returns "slice" (sub-list/sub-string) of list/string (1st argument) defined by 2nd argument, and optionally by 3rd argument. 2nd argument defines starting index from where rest of items in list or characters in string are included. 3rd argument is optional and defines end location until which items/characers are included. Number of arguments need to be 2 or 3. 1st argument is assumed to be list or string. 2nd and 3rd argument are assumed to be type of int. Examples: slice('12345' 3) -> '45' slice('12345' 2) -> '345' slice('12345' 5) -> Runtime error: slice: Index out of range (2nd: 5) slice('12345678' 3 4) -> '45' slice('12345' 3 3) -> '4' slice('12345' 3 2) -> Runtime error: slice: 3rd index (2) should not be less than 2nd one (3) slice(list(1 2 3 4 5) 2 3) -> list(3, 4) Note. It's assumed that 2nd argument is equal or less than 3rd argument (otherwise runtime error is generated) Note. If 2nd argument is out of range of list/string then runtime error is generated Usage: slice(<list/string-expr> <begin-index-expr>) slice(<list/string-expr> <begin-index-expr> <end-index-expr>) `, "rrest": ` Operator: rrest Returns list which is equal to list given as argument but last item not included. Number of arguments need to be 1. Argument is assumed to be list. Examples: rrest(list(1 2 3 4)) -> list(1, 2, 3) rrest(list(1)) -> list() rrest(list()) -> Runtime error: Attempt to access empty list in rrest operator Note. If list given as argument is empty runtime error is generated Usage: rrest(<list-expr>) `, "reverse": ` Operator: reverse Returns list given as argument in reverse order. Number of arguments need to be 1. Argument is assumed to be list. Examples: reverse(list(1 2 3 4)) -> list(4, 3, 2, 1) reverse(list(1)) -> list(1) reverse(list()) -> list() Usage: reverse(<list-expr>) `, "extend": ` Operator: extend Returns list containing items which are items of lists which are given as arguments. Number of arguments can be anything from zero to upwards. Arguments are assumed to be list types. Examples: extend(list(1 2) list(3 4) list(5 6)) -> list(1, 2, 3, 4, 5, 6) extend(list(1 2) list() list(5 6)) -> list(1, 2, 5, 6) extend(list(1 2)) -> list(1, 2) extend(list()) -> list() extend() -> list() Usage: extend(<list-expr> <list-expr> ...) `, "split": ` Operator: split Returns list of substrings that result from splitting string given as 1st argument by string given as 2nd argument. If there's just one argument then splitting is made by one or more consecutive whitespace characters. Number of arguments can be 1 or 2. Arguments are assumed to be string types. Examples: split('abcd,abcd,abcd' ',') -> list('abcd', 'abcd', 'abcd') split('first and second and third' 'and') -> list('first ', ' second ', ' third') split('first and second and third' ' and ') -> list('first', 'second', 'third') split('some text') -> list('some', 'text') split('sometext') -> list('sometext') split('some text' '') -> list('s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't') Note. splitting with empty string ('') results list containing all characters of 1st argument as strings Usage: split(<string-expr> <string-expr>) split(<string-expr>) `, "gt": ` Operator: gt Returns true if 1st argument is greater than 2nd argument (in arithmetic sense), false otherwise. Number of arguments is assumed to be 2. Arguments are assumed to be int or float type. Usage: gt(<expr> <expr>) `, "lt": ` Operator: lt Returns true if 1st argument is less than 2nd argument (in arithmetic sense), false otherwise. Number of arguments is assumed to be 2. Arguments are assumed to be int or float type. Usage: lt(<expr> <expr>) `, "le": ` Operator: le Returns true if 1st argument is less than or equal to 2nd argument (in arithmetic sense), false otherwise. Number of arguments is assumed to be 2. Arguments are assumed to be int or float type. Usage: le(<expr> <expr>) `, "ge": ` Operator: ge Returns true if 1st argument is greater than or equal to 2nd argument (in arithmetic sense), false otherwise. Number of arguments is assumed to be 2. Arguments are assumed to be int or float type. Usage: ge(<expr> <expr>) `, "str": ` Operator: str Return string representation of argument. Number of arguments is assumed to be 1. Argument can be of any type, return value is string. Usage: str(<expr>) `, "conv": ` Operator: conv Converts 1st argument to type defined by 2nd argument (string), if possible. Number of arguments is assumed to be 2. First argument can be of any type, 2nd argument is assumed to string having one of follwong values: - 'string' : converts 1st argument to string - 'list' : converts string to list containing all string characters as items - 'float' : converts int value to float value - 'int' : converts float value to int or string value to int Return value is converted value. Examples: conv(100 'string') -> '100' conv(list(1 2 3) 'string') -> 'list(1, 2, 3)' conv('abcd' 'list') -> list('a', 'b', 'c', 'd') conv(100 'float') -> 100 (float) conv(10.5 'int') -> 10 conv('100' 'int') -> 100 conv('abc' 'int') -> 'Not able to convert to int' Note. If conversion cannot be done Runtime error is generated, exception is failing conversion from string to int: string 'Not able to convert to int' is returned Usage: conv(<expr> <expr>) `, "case": ` Operator: case Evaluates 1st argument and compares it to first matching value and returns corresponding value in case of match. Last argument can be used for returning default value in case no match was found. Number of arguments is assumed to be at least 2. Arguments that are compared can be of any comparable type. (int/bool/string/float/list/map, opaque type if compared in function call) Other arguments can be of any type. Last argument (default value) is optional, if it's not given and there is no match then Runtime error is generated. Usage: case( <expr> <compare-expr-1> <value-1> <compare-expr-2> <value-2> ... <default-value> ) case( <expr> <compare-expr-1> <value-1> <compare-expr-2> <value-2> ... ) `, "name": ` Operator: name Return string representation of symbol given as argument. Number of arguments is assumed to be 1. Argument is assumed to be symbol (not value nor operator call). Return value is string. Example: name(some-symbol) -> 'some-symbol' Note. argument is not evaluated Usage: name(<symbol>) `, "error": ` Operator: error Generates runtime error. Prints string representation of possible arguments. Number of arguments can be anything from 0 upwards. Arguments can be of any type, string representation is printed. There is no return value as execution is not continued. Example: error() -> Runtime error: error('...some error...') -> Runtime error: ...some error... error('...some error...' list(1 2 3)) -> Runtime error: ...some error...list(1, 2, 3) error('...some error...' list(1 2 3):) -> Runtime error: ...some error...123 Usage: error() error(<expr>) error(<expr> <expr> <expr> ...) `, "print": ` Operator: print Concatenates string representations of arguments and prints that to screen/stdout. Number of arguments can be anything from 0 upwards. Arguments can be of any type, string representation is concatenated and printed. Return value is always true (boolean). Note. As print is meant to be used for debugging purposes (stdio having better procedures for printing to console) it's allowed in functions only if printing in functions -mode is enabled. That's because pure functions should not have I/O side-effects. This mode is controlled by -noprint option. (default mode is that printing is allowed in functions) If printing is not allowed in functions and that is done then runtime error is generated. Usage: print(<expr> <expr> <expr> ...) `, "spawn": ` Operator: spawn Starts fiber (lightweight unit of execution thread) for each argument to evaluate that argument. Number of arguments can be anything from 0 upwards. Arguments can be of any type. Return value is always true (boolean). Note. spawn is not allowed to be called from function (only from procedure). Usage: spawn(<expr> <expr> <expr> ...) `, "chan": ` Operator: chan Creates channel value. If no arguments are given then channel is unbuffered (meaning send waits until there's someone receiving on channel). If argument is given it's assumed to be int -value which defines buffer size for channel (in which case channel is buffered one, meaning that send may not block until there's reader). Return value is channel value. Usage: chan() chan(<int: buffer-size>) `, "send": ` Operator: send Evaluates and sends value (given as 2nd argument) to channel (given as 1st argument). By default blocks execution until receiving fiber reads channel, however it can be defined with optional 3rd argument that execution does not block to writing to channel (so that if channel is full current fiber does not block to wait other fibers to read from it) Requires 2 or 3 arguments. Optional 3rd argument is map (options map) which can have following name-values: - 'wait' : bool value: - true -> block to wait if channel is full - false -> returns if channel is full (no waiting) Default is true (blocks to writing to channel) Return value is true if value was written to channel, false if value was not written to channel. Note. send is not allowed to be called from function (only from procedure). Example: ch = chan(100) was-added = send(ch 'some value') was-added = send(ch 'some value' map('wait' false)) Usage: send(<channel-expr> <expr>) send(<channel-expr> <expr> <options-map>) `, "recwith": ` Operator: recwith Receives value from channel (given as 1st argument). Requires 2 argument, 1st argument is assumed to be channel. Second argument is map (options map) which can have following name-values: - 'wait' : bool value: - true -> block to wait if channel is empty - false -> returns if channel is empty (no waiting) Default is true (blocks to receiving from channel) - 'limit-sec' : int-value, number of seconds to wait in channel (returns after time limit if no items received from channel) - 'limit-nanosec' : int-value, number of nanoseconds to wait in channel (returns after time limit if no items received from channel) Default is that there is no time limit (waits forever). Return value is list of two items. List returned has following items: 1) First item (bool) is true if value was received from channel. If no value was received then it's false. 2) Second item is value received from channel ('' if value not received) Note. recwith is not allowed to be called from function (only from procedure). Example: ch = chan() value-received, value = recwith(ch map('wait' false)): Usage: recwith(<channel-expr> <options-map>) `, "recv": ` Operator: recv Receives value from channel (given as argument). Blocks until there's value available in channel. Requires 1 argument, argument is assumed to be channel. Return value is value received from channel. Note. recv is not allowed to be called from function (only from procedure). Usage: recv(<channel-expr>) `, "symval": ` Operator: symval Symval returns value represented by symbol name given as string argument. Requires 1 argument, argument is assumed to be string type. Return value is value represented by symbol in scope. Note. if symbol is not found from current scope then runtime error is generated. Note. symval is not allowed to be called from function (only procedure allowed), otherwise runtime error is generated. Example: call(proc() some-sym = 10 symval('some-sym') end) -> 10 call(proc() some-sym = 10 symval('rubbish') end) -> Runtime error: symval: symbol not found (rubbish) call(func() some-sym = 10 symval('some-sym') end) -> Runtime error: symval not allowed in function Usage: symval(<string-expr>) `, "try": ` Operator: try Catches runtime error if such happens during evaluation of 1st argument. If no runtime error happens then try returns evaluated value of 1st argument. If runtime error happens then runtime error text is returned (as string value) unless 2nd argument is given in which case 2nd argument is evaluated and value of that is returned. Requires 1 or 2 arguments, arguments can be of any type. Return value is value of 1st argument evaluated, or in runtime error case 2nd argument if such exists, otherwise runtime error text as string. Note. try is not allowed to be called from function (only procedure allowed), otherwise runtime error is generated. Usage: try(<expr>) try(<expr> <expr>) `, "select": ` Operator: select Receives input value from any of several channels and calls channel specific handler function/procedure. Channels and handler functions/procedures can be given as separate arguments or as two lists containing channels and handlers. Return value of handler is returned as value from select. Can have two kind of arguments: 1) channel and handler (proc) pairs: as channel N:th argument and corresponding handler N+1:th argument 2) two lists: as 1st list containing all channels and 2nd list containing all handlers so that channel and related handler are in same index in lists Number of arguments must not be zero and must be even number. Return value is value returned from handler. Handler takes one argument which is value received from channel. Note. select is not allowed to be called from function (only procedure allowed), otherwise runtime error is generated. Usage: select( <channel-expr> <handler-expr> <channel-expr> <handler-expr> <channel-expr> <handler-expr> ... ) select(<list-of-channels-expr> <list-of-handlers-expr>) `, "eval": ` Operator: eval Evaluates expression given as string argument and returns resulted value of evaluation. Requires 1 argument, argument is assumed to be string. Return value result of evaluated expression represented as argument. Example: eval('plus(1 2 3)') -> 6 eval(sprintf('plus(%d %d %d)' list(1 2 3):)) -> 6 Usage: eval(<string-expression>) `, "while": ` Operator: while Similar to call -operator but can be used for "tail call optimization". if condition (1st argument) is true while reconstructs current call frame by re-evaluating all current frame call arguments with ones following 1st argument (2nd, 3rd etc.), as many as current frame has call arguments. Also all let -definitions are re-evaluated in innermost frame. Last argument is returned when condition becomes false. Use cases: - recursive call with tail call optimization (not consuming call stack) - in procedure to implement some I/O event loop kind of handling (or channel reading) Requires at least 2 arguments. Note. while -operator can only be used in function/procedure body, not in let -definitions, nor as function/procedure calls as arguments. Usage: while(<condition-expr> <arg-1> <arg-2> ... <result-expr>) `, "float": ` Operator: float Constructs float value. Converts int value given as argument to corresponding float value (if float value is given then same is returned). Requires 1 argument. Return value type is float. Usage: float(<expr>) `, "map": ` Operator: map Creates (persistent) map. Arguments are interpreted so that n:th (0, 2, 4, ...) argument is key and following argument is corresponding value (n+1:th: 1, 3, 5, ...). If no arguments are given then empty map is created. Map item values can be of any type but map keys can be only: - int - string - float - list - boolean If same key is given twice then runtime error is generated. There must be even number of arguments otherwise runtime error is generated (or no arguments). Return value is map value that was created. Example: map() -> map() map(1 2 3 4) -> map(1 : 2, 3 : 4) map(1 2 3) -> Runtime error: map: uneven amount of arguments (3) Usage: map(<key> <value> <key> <value> ...) `, "put": ` Operator: put Puts key-value pair to map. First argument is map, 2nd argument is key and 3rd argument is value. Map item value can be of any type but map key can be only: - int - string - float - list - boolean If key is already in map then runtime error is generated. There must be 3 arguments. Return value is map value with added key-value pair. Usage: put(<map> <key> <value>) `, "get": ` Operator: get Gets value for given key from map. If key is not found runtime error is generated. First argument is map, 2nd argument is key. There must be 2 arguments. Return value is value corresponding to key. Example: get(map(1 2 3 4) 1) -> 2 get(map(1 2 3 4) 10) -> Runtime error: get: key not found (10) Usage: get(<map> <key>) `, "getl": ` Operator: getl Gets value for given key from map. Returns result as list of two items where 1st item (boolean) is true if key was found in map, otherwise false. Second item in list is corresponding value if key was found, otherwise value is false. First argument is map, 2nd argument is key. There must be 2 arguments. Return value is list of 2 items: - First item true if key found, false otherwise - Second item value corresponding to key if key was found, otherwise false value Example: getl(map(1 2 3 4) 1) -> list(true, 2) getl(map(1 2 3 4) 10) -> list(false, false) is-key-found value = getl(map(1 2 3 4) 1): Usage: getl(<map> <key>) `, "keys": ` Operator: keys Returns all keys of map (given as argument) as list. There's not any particular order guaranteed in list. There must be one argument which is map. Return value is list (conatins all keys of map). Example: keys(map(1 2 3 4)) -> list(1, 3) keys(map()) -> list() Usage: keys(<map>) `, "vals": ` Operator: vals Returns all values of map (given as argument) as list. There's not any particular order guaranteed in list. There must be one argument which is map. Return value is list (conatins all values of map). Example: vals(map(1 2 3 4)) -> list(2, 4) vals(map()) -> list() Usage: vals(<map>) `, "keyvals": ` Operator: keyvals Returns all key-value pairs of map (given as argument) as lists. There's not any particular order guaranteed in list. Each key-value pair is represented as its own list (of 12 items): - 1st item is key - 2nd item is value There must be one argument which is map. Return value is list containing lists representing key-value pairs. Example: keyvals(map(1 2 3 4)) -> list(list(1, 2), list(3, 4)) keyvals(map()) -> list() Usage: keyvals(<map>) `, "let": ` Operator: let Let-definition by using operator let. First argument is symbol for which value is assigned from evaluating expression given as 2nd argument. Symbol value is assgined to in current scope. x = 100 is identical to: _ = let(x 100) Can be used in REPL (option -repl) to set some let-definitions. There must be 2 arguments: 1st argument needs to be symbol and 2nd argument is any expression. Return value is evaluation result (value) from 2nd argument (same value which is assigned to symbol). Example: keyvals(map(1 2 3 4)) -> list(list(1, 2), list(3, 4)) keyvals(map()) -> list() Usage: let(<symbol> <expr>) `, "imp": ` Operator: imp Imports module by using operator imp. First argument is symbol which is name of module. Module is returned as map in which: - keys are names of functions/procedures/other values (as string) - corresponding values are function/procedure/other values import stdfiles is equivalent to: my-file-mod = imp(stdfiles) usage is via map: call(get(my-file-mod 'cwd')) same as -> call(stdfiles.cwd) There must be 1 argument which is symbol representing module name to be imported. Return value is map containing symbol names (strings) as keys and corresponding values. Note. if module of given symbol is not found then runtime error is generated. Example: imp(stdlog) -> map('get-logger' : ext-proc, 'get-default-logger' : ext-proc) imp(not-to-found) -> Runtime error: Module not found: not-to-found Usage: imp(<symbol>) `, "del": ` Operator: del Returns map value based on map given as 1st argument from which key-value pair defined by key given as 2nd argument is removed. If key does not exist is map given as 1st argument then runtime error is generated. There must be 2 arguments: 1st argument is source map and 2nd argument defines key for which key-value pair is to be removed. Example: del(map(1 2 3 4) 3) -> map(1 : 2) del(map(1 2 3 4) 9) -> Runtime error: del: key not found Usage: del(<map> <key>) `, "dell": ` Operator: dell Similar to del-operator that produces map (based on map given as 1st argument) from which key-value pair defined by key given as 2nd argument Returns list (of two items): - first item (boolean): true if key was found, false otherwise - second item (map): 1. if 1st item is true, then map without given key-value pair 2. if 1st item is false, original map (1st argument) (no runtime error is generated when key is not found) There must be 2 arguments: 1st argument is source map and 2nd argument defines key for which key-value pair is to be removed. Example: dell(map(1 2 3 4) 3) -> list(true, map(1 : 2)) dell(map(1 2 3 4) 9) -> list(false, map(1 : 2, 3 : 4)) found newmap = dell(map(1 2 3 4) 3): Usage: dell(<map> <key>) `, "sprintf": ` Operator: sprintf Formats according to a format specifier and returns the resulting string. First argument is format string and following arguments are operands for formation. There must be at least 1 argument. First argument is format string (type of string) and following ones operands. Return value is string (formatted). Example: sprintf('%d : %v : %s : %f : %v' 10 true 'some text' 0.5 list(1 2 3)) -> '10 : true : some text : 0.500000 : list(1, 2, 3)' Usage: sprintf(<format-string> <expr> <expr> ...) `, "argslist": ` Operator: argslist Returns list of arguments given to current (innermost) function/procedure call context. Requires no arguments. Return value is list type. List contains all argument values in same order as given in function/procedure call. Example: call(func() argslist() end 1 2 3) -> list(1, 2, 3) call(func(p1 p2 p3) argslist() end 1 2 3) -> list(1, 2, 3) call(func(p1 _ p3) argslist() end 1 2 3) -> list(1, 2, 3) call(func(_ _ _) argslist() end 1 2 3) -> list(1, 2, 3) Usage: argslist() `, "cond": ` Operator: cond Multiway conditional expression (multiway if). Arguments are interpreted so that there's multiple conditional pairs and last argument defines value in case no other pair matches. First condition expression that returns true causes corresponding expression to be evaluated and returned from cond -operator. cond( <1st condition (boolean expression)> <1st expression: evaluated if 1st condition is true> <2nd condition (boolean expression)> <2nd expression: evaluated if 2nd condition is true> <3rd condition (boolean expression)> <3rd expression: evaluated if 3rd condition is true> ... <default expression: evaluated if no other condition is true> ) Requires at least 3 arguments. Assumes that there's always (2 * n) + 1 arguments as there needs to be 1...n condition-expression pairs and one default expression. Return value is value corresponding to matching condition or default. Example: cond(eq(1 1) 10 eq(3 4) 20 'default') -> 10 cond(eq(1 2) 10 eq(3 3) 20 'default') -> 20 cond(eq(1 2) 10 eq(3 4) 20 'default') -> 'default' Usage: cond( <condition (bool)> <expr> <condition (bool)> <expr> <condition (bool)> <expr> ... <default/else-expr> ) `, "help": ` Operator: help Returns documentation about certain language topic as string or in some cases list of strings. See more information by help(). Assumes no arguments or one argument. Argument type is assumed to be string (defining topic). Return type can be: - string - list (of strings) Usage: help() help(<topic-as-string>) `, } } // Operators contains operator information (operator name as key) type Operators map[string]OperatorInfo // NewDefaultOperators returns default set of operators func NewDefaultOperators() Operators { return Operators{ "and": OperatorInfo{}, "or": OperatorInfo{}, "call": OperatorInfo{}, "not": OperatorInfo{}, "eq": OperatorInfo{}, "if": OperatorInfo{}, "plus": OperatorInfo{}, "minus": OperatorInfo{}, "mul": OperatorInfo{}, "div": OperatorInfo{}, "mod": OperatorInfo{}, "list": OperatorInfo{}, "empty": OperatorInfo{}, "head": OperatorInfo{}, "last": OperatorInfo{}, "rest": OperatorInfo{}, "append": OperatorInfo{}, "add": OperatorInfo{}, "len": OperatorInfo{}, "type": OperatorInfo{}, "in": OperatorInfo{}, "ind": OperatorInfo{}, "find": OperatorInfo{}, "slice": OperatorInfo{}, "rrest": OperatorInfo{}, "reverse": OperatorInfo{}, "extend": OperatorInfo{}, "split": OperatorInfo{}, "gt": OperatorInfo{}, "lt": OperatorInfo{}, "le": OperatorInfo{}, "ge": OperatorInfo{}, "str": OperatorInfo{}, "conv": OperatorInfo{}, "case": OperatorInfo{}, "name": OperatorInfo{}, "error": OperatorInfo{}, "print": OperatorInfo{}, "spawn": OperatorInfo{}, "chan": OperatorInfo{}, "send": OperatorInfo{}, "recv": OperatorInfo{}, "symval": OperatorInfo{}, "try": OperatorInfo{}, "select": OperatorInfo{}, "eval": OperatorInfo{}, "while": OperatorInfo{}, "float": OperatorInfo{}, "map": OperatorInfo{}, "put": OperatorInfo{}, "get": OperatorInfo{}, "getl": OperatorInfo{}, "keys": OperatorInfo{}, "vals": OperatorInfo{}, "keyvals": OperatorInfo{}, "let": OperatorInfo{}, "imp": OperatorInfo{}, "del": OperatorInfo{}, "dell": OperatorInfo{}, "sprintf": OperatorInfo{}, "argslist": OperatorInfo{}, "cond": OperatorInfo{}, "help": OperatorInfo{}, "recwith": OperatorInfo{}, } } func (ops Operators) isOperator(operatorName string) bool { _, found := ops[operatorName] return found }
funl/operators.go
0.863823
0.587056
operators.go
starcoder
package problem0641 // MyCircularDeque 结构体 type MyCircularDeque struct { f, r *node len, cap int } type node struct { value int pre, next *node } // Constructor initialize your data structure here. Set the size of the deque to be k. func Constructor(k int) MyCircularDeque { return MyCircularDeque{ cap: k, } } // InsertFront adds an item at the front of Deque. Return true if the operation is successful. func (d *MyCircularDeque) InsertFront(value int) bool { if d.len == d.cap { return false } n := &node{ value: value, } if d.len == 0 { d.f = n d.r = n } else { n.next = d.f d.f.pre = n d.f = n } d.len++ return true } // InsertLast adds an item at the rear of Deque. Return true if the operation is successful. func (d *MyCircularDeque) InsertLast(value int) bool { if d.len == d.cap { return false } n := &node{ value: value, } if d.len == 0 { d.f = n d.r = n } else { n.pre = d.r d.r.next = n d.r = n } d.len++ return true } // DeleteFront deletes an item from the front of Deque. Return true if the operation is successful. func (d *MyCircularDeque) DeleteFront() bool { if d.len == 0 { return false } if d.len == 1 { d.f, d.r = nil, nil } else { d.f = d.f.next d.f.pre = nil } d.len-- return true } // DeleteLast deletes an item from the rear of Deque. Return true if the operation is successful. func (d *MyCircularDeque) DeleteLast() bool { if d.len == 0 { return false } if d.len == 1 { d.f, d.r = nil, nil } else { d.r = d.r.pre d.r.next = nil } d.len-- return true } // GetFront get the front item from the deque. func (d *MyCircularDeque) GetFront() int { if d.len == 0 { return -1 } return d.f.value } // GetRear get the last item from the deque. func (d *MyCircularDeque) GetRear() int { if d.len == 0 { return -1 } return d.r.value } // IsEmpty checks whether the circular deque is empty or not. func (d *MyCircularDeque) IsEmpty() bool { return d.len == 0 } // IsFull checks whether the circular deque is full or not. func (d *MyCircularDeque) IsFull() bool { return d.len == d.cap } /** * Your MyCircularDeque object will be instantiated and called as such: * obj := Constructor(k); * param_1 := obj.InsertFront(value); * param_2 := obj.InsertLast(value); * param_3 := obj.DeleteFront(); * param_4 := obj.DeleteLast(); * param_5 := obj.GetFront(); * param_6 := obj.GetRear(); * param_7 := obj.IsEmpty(); * param_8 := obj.IsFull(); */
Algorithms/0641.design-circular-deque/design-circular-deque.go
0.556641
0.537527
design-circular-deque.go
starcoder
package naro import ( "context" "sync" "time" "github.com/jonboulle/clockwork" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) // AnomalyDetector is a type that can be trained to detect issues // within new NodeTimePeriodSummaries. type AnomalyDetector interface { String() string Train(summaries []*NodeTimePeriodSummary) error IsAnomalous(ns *NodeTimePeriodSummary) (bool, string, error) } // AnomalyDetectorFactory is a function that can create new // AnomalyDetectors. type AnomalyDetectorFactory func() (AnomalyDetector, error) // AnomalyHandler is a type that can respond to anomalies. This is // where node repairs are wired in. type AnomalyHandler interface { HandleAnomaly(context.Context, *NodeTimePeriodSummary, string) error } // DetectorController runs a set of AnomalyDetectors periodically, // informing handlers of when an anomaly is detected. type DetectorController struct { stopChan chan struct{} wg *sync.WaitGroup factories []AnomalyDetectorFactory trainingTimePeriod time.Duration detectionTimePeriod time.Duration runInterval time.Duration store Store clock clockwork.Clock handlers []AnomalyHandler } // NewDetectorController returns a new DetectorController. func NewDetectorController(trainingTimePeriod, detectionTimePeriod, runInterval time.Duration, factories []AnomalyDetectorFactory, store Store, clock clockwork.Clock, handlers []AnomalyHandler) *DetectorController { return &DetectorController{ stopChan: make(chan struct{}), wg: &sync.WaitGroup{}, factories: factories, trainingTimePeriod: trainingTimePeriod, detectionTimePeriod: detectionTimePeriod, runInterval: runInterval, store: store, clock: clock, handlers: handlers, } } func (d *DetectorController) getDetectors() ([]AnomalyDetector, error) { var detectors []AnomalyDetector for _, factory := range d.factories { detector, err := factory() if err != nil { return nil, errors.Wrapf(err, "error creating AnomalyDetector with factory") } detectors = append(detectors, detector) } currentTime := d.clock.Now() trainingStart := currentTime.Add(-d.trainingTimePeriod) summaries, err := d.store.GetNodeTimePeriodSummaries(trainingStart, currentTime) if err != nil { return nil, errors.Wrapf(err, "error fetching NodeTimePeriodSummaries for training") } for _, detector := range detectors { logrus.Debugf("DetectorController: training %s with %d summaries", detector, len(summaries)) if err := detector.Train(summaries); err != nil { return nil, errors.Wrapf(err, "error training detector") } } return detectors, nil } // Start begins starts the controller's run loop. func (d *DetectorController) Start() { d.wg.Add(1) go func() { defer d.wg.Done() for { select { case <-d.stopChan: return case <-d.clock.After(d.runInterval): } logrus.Debugf("DetectorController: starting run loop") if err := d.run(); err != nil { logrus.WithError(err).Errorf("error running DetectorController") } } }() } // Stop stops the detector's run loop. func (d *DetectorController) Stop() { close(d.stopChan) d.wg.Wait() } // run performs anomaly detection, informing handlers of any // anomalies. The set of detectors is trained prior to running any // detection algorithms. func (d *DetectorController) run() error { detectors, err := d.getDetectors() if err != nil { return errors.Wrapf(err, "error creating detectors") } currentTime := d.clock.Now() detectionStart := currentTime.Add(-d.detectionTimePeriod) summaries, err := d.store.GetNodeTimePeriodSummaries(detectionStart, currentTime) if err != nil { return errors.Wrapf(err, "error fetching NodeTimePeriodSummaries for detection") } for _, detector := range detectors { for _, nodeSummary := range summaries { logrus.Debugf("DetectorController: attempting to detect anomaly in %s with %s", nodeSummary.Node, detector) nodeSummary.RemoveOlderRepairedEvents() isAnomalous, meta, err := detector.IsAnomalous(nodeSummary) if err != nil { logrus.WithError(err).Errorf("error detecting anomaly in NodeTimePeriodSummary") continue } if isAnomalous { logrus.Infof("DetectorController: detected anomaly in %s with %s: %s", nodeSummary.Node, detector, meta) for _, handler := range d.handlers { if err := handler.HandleAnomaly(context.Background(), nodeSummary, meta); err != nil { logrus.WithError(err). Errorf("error handling anomalous NodeTimePeriodSummary") continue } } } } } return nil }
pkg/naro/anomaly_detection.go
0.662251
0.407274
anomaly_detection.go
starcoder