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 types // LanguageType provides a structure for storing inflections rules of a language. type LanguageType struct { Short string // The short hand form represention the language, ex. `en` (English). Pluralizations RulesType // Rules for pluralizing standard words. Singularizations RulesType // Rules for singularizing standard words. Irregulars IrregularsType // Slice containing irregular words that do not follow standard rules. Uncountables UncountablesType // Words that are uncountable, having the same form for both singular and plural. } func convert(str, form string, language *LanguageType, rules RulesType) string { if language.Uncountables.Contains(str) { return str } else if irregular, ok := language.Irregulars.IsIrregular(str); ok { if form == "singular" { return irregular.Singular } return irregular.Plural } else { for _, rule := range rules { if rule.Regexp.MatchString(str) { return rule.Regexp.ReplaceAllString(str, rule.Replacer) } } } return str } // Pluralize converts the given string to the languages plural form. func (self *LanguageType) Pluralize(str string) string { return convert(str, "plural", self, self.Pluralizations) } // Singularize converts the given string to the languages singular form. func (self *LanguageType) Singularize(str string) string { return convert(str, "singular", self, self.Singularizations) } // Plural defines a pluralization rule for a language. func (self *LanguageType) Plural(matcher, replacer string) *LanguageType { self.Pluralizations = append(self.Pluralizations, Rule(matcher, replacer)) return self } // Plural defines a singularization rule for a language. func (self *LanguageType) Singular(matcher, replacer string) *LanguageType { self.Singularizations = append(self.Singularizations, Rule(matcher, replacer)) return self } // Plural defines an irregular word for a langauge. func (self *LanguageType) Irregular(singular, plural string) *LanguageType { self.Irregulars = append(self.Irregulars, Irregular(singular, plural)) return self } // Plural defines an uncountable word for a langauge. func (self *LanguageType) Uncountable(uncountable string) *LanguageType { self.Uncountables = append(self.Uncountables, uncountable) return self } // Language if a factory method to a new LanguageType. func Language(short string) (language *LanguageType) { language = new(LanguageType) language.Pluralizations = make(RulesType, 0) language.Singularizations = make(RulesType, 0) language.Irregulars = make(IrregularsType, 0) language.Uncountables = make(UncountablesType, 0) return }
go/src/github.com/chuckpreslar/inflect/types/language.go
0.835282
0.596639
language.go
starcoder
package lmath import ( "fmt" "math" ) const ( mat4Dim = 4 ) var ( Mat4Identity = Mat4{[16]float64{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}} ) type Mat4 struct { mat [16]float64 } // New Mat4 with the given values. // Row-Order. func NewMat4( m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 float64) *Mat4 { // 0 1 2 3 // 4 5 6 7 // 8 9 10 11 // 12 13 14 15 out := Mat4{} out.mat[0] = m11 out.mat[1] = m12 out.mat[2] = m13 out.mat[3] = m14 out.mat[4] = m21 out.mat[5] = m22 out.mat[6] = m23 out.mat[7] = m24 out.mat[8] = m31 out.mat[9] = m32 out.mat[10] = m33 out.mat[11] = m34 out.mat[12] = m41 out.mat[13] = m42 out.mat[14] = m43 out.mat[15] = m44 return &out } // Load the matrix with 16 floats. // Specified in Row-Major order. func (this *Mat4) Load(m [16]float64) *Mat4 { this.mat = m return this } // Load the matrix with 16 floats. // Specified in Row-Major order. func (this *Mat4) Load32(m [16]float32) *Mat4 { for k, v := range m { this.mat[k] = float64(v) } return this } // Retrieve a 16 float array of all the values of the matrix. // Returned in Row-Major order. func (this Mat4) Dump() (m [16]float64) { m = this.mat return } // Retrieve a 16 float array of all the values of the matrix. // Returned in Col-Major order. func (this Mat4) DumpOpenGL() (m [16]float64) { m[0], m[1], m[2], m[3] = this.Col(0) m[4], m[5], m[6], m[7] = this.Col(1) m[8], m[9], m[10], m[11] = this.Col(2) m[12], m[13], m[14], m[15] = this.Col(3) return } // Retrieve a 16 float array of all the values of the matrix. // Returned in Col-Major order. func (this Mat4) DumpOpenGLf32() (m [16]float32) { m[0] = float32(this.mat[0]) m[1] = float32(this.mat[4]) m[2] = float32(this.mat[8]) m[3] = float32(this.mat[12]) m[4] = float32(this.mat[1]) m[5] = float32(this.mat[5]) m[6] = float32(this.mat[9]) m[7] = float32(this.mat[13]) m[8] = float32(this.mat[2]) m[9] = float32(this.mat[6]) m[10] = float32(this.mat[10]) m[11] = float32(this.mat[14]) m[12] = float32(this.mat[3]) m[13] = float32(this.mat[7]) m[14] = float32(this.mat[11]) m[15] = float32(this.mat[15]) return } // Return a copy of this matrix. // Carbon-copy of all elements func (this Mat4) Copy() Mat4 { return this } // Compare this matrix to the other. // Return true if all elements between them are the same. // Equality is measured using an epsilon (< 0.0000001). func (this Mat4) Eq(other Mat4) bool { for k, _ := range this.mat { if closeEq(this.mat[k], other.mat[k], epsilon) == false { return false } } return true } // Retrieve the element at row and column. // 0 indexed. // Does not do any bounds checking. func (this Mat4) Get(row, col int) float64 { return this.mat[row*mat4Dim+col] } // Set the value at the specified column and row. // 0 indexed. // Does not do any bounds checking. func (this *Mat4) Set(row, col int, value float64) *Mat4 { this.mat[row*mat4Dim+col] = value return this } // Retrieve the element at the given index assuming a linear array. // (i.e matrix[0], matrix[5]). // 0 indexed. func (this Mat4) At(index int) float64 { return this.mat[index] } // Set the element of the matrix specified at the index to the given value. // 0 indexed. // Return a pointer to the 'this' func (this *Mat4) SetAt(index int, value float64) *Mat4 { this.mat[index] = value return this } // Set the specified row of the matrix to the given x,y,z,w values. // 0 indexed. // Does not do bounds checking of the row. func (this *Mat4) SetRow(row int, x, y, z, w float64) *Mat4 { this.mat[row*mat4Dim] = x this.mat[row*mat4Dim+1] = y this.mat[row*mat4Dim+2] = z this.mat[row*mat4Dim+3] = w return this } // Set the specified column of the matrix to the given x,y,z,w values. // 0 indexed. // Does not do bounds checking on the col. func (this *Mat4) SetCol(col int, x, y, z, w float64) *Mat4 { this.mat[mat4Dim*0+col] = x this.mat[mat4Dim*1+col] = y this.mat[mat4Dim*2+col] = z this.mat[mat4Dim*3+col] = w return this } // Retrieve the x,y,z,w elements from the specified row. // 0 indexed. // Does not bounds check the row. func (this Mat4) Row(row int) (x, y, z, w float64) { x = this.mat[row*mat4Dim] y = this.mat[row*mat4Dim+1] z = this.mat[row*mat4Dim+2] w = this.mat[row*mat4Dim+3] return } // Retrieve the x,y,z,w elements from the specified column. // 0 indexed. // Does not bounds check the column. func (this Mat4) Col(col int) (x, y, z, w float64) { x = this.mat[mat4Dim*0+col] y = this.mat[mat4Dim*1+col] z = this.mat[mat4Dim*2+col] w = this.mat[mat4Dim*3+col] return } // Add in a constant value to all the terms fo the matrix. // Return a new matrix with the result. func (this Mat4) AddScalar(val float64) Mat4 { this.AddInScalar(val) return this } // Add in a constant value to all the terms fo the matrix. // Returns a pointer to 'this'. func (this *Mat4) AddInScalar(val float64) *Mat4 { for k, _ := range this.mat { this.mat[k] += val } return this } // Subtract in a constant value to all the terms fo the matrix. // Return a new matrix with the result. func (this Mat4) SubScalar(val float64) Mat4 { this.SubInScalar(val) return this } // Subtract in a constant value to all the terms fo the matrix. // Returns a pointer to 'this'. func (this *Mat4) SubInScalar(val float64) *Mat4 { for k, _ := range this.mat { this.mat[k] -= val } return this } // Multiplies in a constant value to all the terms fo the matrix. // Return a new matrix with the result. func (this Mat4) MultScalar(val float64) Mat4 { this.MultInScalar(val) return this } // Multiplies in a constant value to all the terms fo the matrix. // Returns a pointer to 'this'. func (this *Mat4) MultInScalar(val float64) *Mat4 { for k, _ := range this.mat { this.mat[k] *= val } return this } // Divides in a constant value to all the terms fo the matrix. // Return a new matrix with the result. // precondition: val > 0 func (this Mat4) DivScalar(val float64) Mat4 { this.DivInScalar(val) return this } // Divides in a constant value to all the terms fo the matrix. // Returns a pointer to 'this'. // precondition: val > 0 func (this *Mat4) DivInScalar(val float64) *Mat4 { for k, _ := range this.mat { this.mat[k] /= val } return this } // Adds the two matrices together ( ie. this + other). // Return a new matrix with the result. func (this Mat4) Add(other Mat4) Mat4 { this.AddIn(other) return this } // Adds the two matrices together ( ie. this + other). // Stores the result in this. // Returns this. func (this *Mat4) AddIn(other Mat4) *Mat4 { for k, _ := range this.mat { this.mat[k] += other.mat[k] } return this } // Subtract the two matrices together ( ie. this - other). // Return a new matrix with the result. func (this Mat4) Sub(other Mat4) Mat4 { this.SubIn(other) return this } // Subtract the two matrices together ( ie. this - other). // Stores the result in this. // Returns this. func (this *Mat4) SubIn(other Mat4) *Mat4 { for k, _ := range this.mat { this.mat[k] -= other.mat[k] } return this } // Multiply the two matrices together ( ie. this * other). // Return a new matrix with the result. func (this Mat4) Mult(other Mat4) Mat4 { this.MultIn(other) return this } // Multiplies the two matrices together ( ie. this * other). // Stores the result in this. // Returns this. func (this *Mat4) MultIn(o Mat4) *Mat4 { // 0 1 2 3 // 4 5 6 7 // 8 9 10 11 // 12 13 14 15 m := *this this.mat[0] = m.mat[0]*o.mat[0] + m.mat[1]*o.mat[4] + m.mat[2]*o.mat[8] + m.mat[3]*o.mat[12] this.mat[1] = m.mat[0]*o.mat[1] + m.mat[1]*o.mat[5] + m.mat[2]*o.mat[9] + m.mat[3]*o.mat[13] this.mat[2] = m.mat[0]*o.mat[2] + m.mat[1]*o.mat[6] + m.mat[2]*o.mat[10] + m.mat[3]*o.mat[14] this.mat[3] = m.mat[0]*o.mat[3] + m.mat[1]*o.mat[7] + m.mat[2]*o.mat[11] + m.mat[3]*o.mat[15] this.mat[4] = m.mat[4]*o.mat[0] + m.mat[5]*o.mat[4] + m.mat[6]*o.mat[8] + m.mat[7]*o.mat[12] this.mat[5] = m.mat[4]*o.mat[1] + m.mat[5]*o.mat[5] + m.mat[6]*o.mat[9] + m.mat[7]*o.mat[13] this.mat[6] = m.mat[4]*o.mat[2] + m.mat[5]*o.mat[6] + m.mat[6]*o.mat[10] + m.mat[7]*o.mat[14] this.mat[7] = m.mat[4]*o.mat[3] + m.mat[5]*o.mat[7] + m.mat[6]*o.mat[11] + m.mat[7]*o.mat[15] this.mat[8] = m.mat[8]*o.mat[0] + m.mat[9]*o.mat[4] + m.mat[10]*o.mat[8] + m.mat[11]*o.mat[12] this.mat[9] = m.mat[8]*o.mat[1] + m.mat[9]*o.mat[5] + m.mat[10]*o.mat[9] + m.mat[11]*o.mat[13] this.mat[10] = m.mat[8]*o.mat[2] + m.mat[9]*o.mat[6] + m.mat[10]*o.mat[10] + m.mat[11]*o.mat[14] this.mat[11] = m.mat[8]*o.mat[3] + m.mat[9]*o.mat[7] + m.mat[10]*o.mat[11] + m.mat[11]*o.mat[15] this.mat[12] = m.mat[12]*o.mat[0] + m.mat[13]*o.mat[4] + m.mat[14]*o.mat[8] + m.mat[15]*o.mat[12] this.mat[13] = m.mat[12]*o.mat[1] + m.mat[13]*o.mat[5] + m.mat[14]*o.mat[9] + m.mat[15]*o.mat[13] this.mat[14] = m.mat[12]*o.mat[2] + m.mat[13]*o.mat[6] + m.mat[14]*o.mat[10] + m.mat[15]*o.mat[14] this.mat[15] = m.mat[12]*o.mat[3] + m.mat[13]*o.mat[7] + m.mat[14]*o.mat[11] + m.mat[15]*o.mat[15] return this } // Returns a new matrix which is transpose to this. func (this Mat4) Transpose() Mat4 { this.TransposeIn() return this } // Take the transpose of this matrix. func (this *Mat4) TransposeIn() *Mat4 { // TODO: can definitely be way more efficient // by only exchanging the column entries. m00, m01, m02, m03 := this.Row(0) m10, m11, m12, m13 := this.Row(1) m20, m21, m22, m23 := this.Row(2) m30, m31, m32, m33 := this.Row(3) this.SetCol(0, m00, m01, m02, m03) this.SetCol(1, m10, m11, m12, m13) this.SetCol(2, m20, m21, m22, m23) this.SetCol(3, m30, m31, m32, m33) return this } // Get the determinant of the matrix. // Uses a straight-up Cramers-Rule implementation. func (this Mat4) Determinant() float64 { // 0 1 2 3 // 4 5 6 7 // 8 9 10 11 // 12 13 14 15 // Use Cramer's rule to calculate the determinant return (this.mat[0]*det3x3(this.mat[5], this.mat[6], this.mat[7], this.mat[9], this.mat[10], this.mat[11], this.mat[13], this.mat[14], this.mat[15]) - this.mat[4]*det3x3(this.mat[1], this.mat[2], this.mat[3], this.mat[9], this.mat[10], this.mat[11], this.mat[13], this.mat[14], this.mat[15]) + this.mat[8]*det3x3(this.mat[1], this.mat[2], this.mat[3], this.mat[5], this.mat[6], this.mat[7], this.mat[13], this.mat[14], this.mat[15]) - this.mat[12]*det3x3(this.mat[1], this.mat[2], this.mat[3], this.mat[5], this.mat[6], this.mat[7], this.mat[9], this.mat[10], this.mat[11])) } // Returns a new matrix which is the Adjoint matrix of this. func (this Mat4) Adjoint() Mat4 { a1, a2, a3, a4 := this.mat[0], this.mat[1], this.mat[2], this.mat[3] b1, b2, b3, b4 := this.mat[4], this.mat[5], this.mat[6], this.mat[7] c1, c2, c3, c4 := this.mat[8], this.mat[9], this.mat[10], this.mat[11] d1, d2, d3, d4 := this.mat[12], this.mat[13], this.mat[14], this.mat[15] // 0 1 2 3 a1 a2 a3 a4 // 4 5 6 7 b1 b2 b3 b4 // 8 9 10 11 c1 c2 c3 c4 // 12 13 14 15 d1 d2 d3 d4 //m := Mat4{} this.mat[0] = det3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4) this.mat[1] = -det3x3(b1, b3, b4, c1, c3, c4, d1, d3, d4) this.mat[2] = det3x3(b1, b2, b4, c1, c2, c4, d1, d2, d4) this.mat[3] = -det3x3(b1, b2, b3, c1, c2, c3, d1, d2, d3) this.mat[4] = -det3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4) this.mat[5] = det3x3(a1, a3, a4, c1, c3, c4, d1, d3, d4) this.mat[6] = -det3x3(a1, a2, a4, c1, c2, c4, d1, d2, d4) this.mat[7] = det3x3(a1, a2, a3, c1, c2, c3, d1, d2, d3) this.mat[8] = det3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4) this.mat[9] = -det3x3(a1, a3, a4, b1, b3, b4, d1, d3, d4) this.mat[10] = det3x3(a1, a2, a4, b1, b2, b4, d1, d2, d4) this.mat[11] = -det3x3(a1, a2, a3, b1, b2, b3, d1, d2, d3) this.mat[12] = -det3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4) this.mat[13] = det3x3(a1, a3, a4, b1, b3, b4, c1, c3, c4) this.mat[14] = -det3x3(a1, a2, a4, b1, b2, b4, c1, c2, c4) this.mat[15] = det3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3) this.TransposeIn() return this } // Returns a new matrix which is the inverse matrix of this. // The bool flag is false if an inverse does not exist. func (this Mat4) Inverse() Mat4 { // TODO: Needs further testing // Try out with rotation matrices. // The inverse of a valid rotation matrix should just be the transpose det := this.Determinant() return this.Adjoint().DivScalar(det) } // Returns true if the inverse of this matrix exists false otherwise. // Internally it checks to see if the determinant is zero. func (this Mat4) HasInverse() bool { return !closeEq(this.Determinant(), 0, epsilon) } // Sets the matrix to the identity matrix. func (this *Mat4) ToIdentity() *Mat4 { this.mat = [16]float64{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, } return this } //============================================================================== // Return true if the matrix is the identity matrix. func (this Mat4) IsIdentity() bool { iden := [16]float64{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, } for k, _ := range iden { if !closeEq(this.mat[k], iden[k], 0) { return false } } return true } // Check to see if the matrix is a valid rotation matrix. // The two properties it checks are // 1) Determinant() == 1 // 2) m*m.Transpose == Identity func (this Mat4) IsRotation() bool { return closeEq(this.Determinant(), 1, epsilon) && this.Mult(this.Transpose()).IsIdentity() } // Implement the Stringer interface // Prints out each row of the matrix on its own line func (this *Mat4) String() string { return fmt.Sprintf("%f %f %f %f\n%f %f %f %f\n%f %f %f %f\n%f %f %f %f", this.mat[0], this.mat[1], this.mat[2], this.mat[3], this.mat[4], this.mat[5], this.mat[6], this.mat[7], this.mat[8], this.mat[9], this.mat[10], this.mat[11], this.mat[12], this.mat[13], this.mat[14], this.mat[15]) } // ============================================================================= // Create a translation matrix for Mat4. Overwrites all values in the matrix. func (this *Mat4) ToTranslate(x, y, z float64) *Mat4 { this.ToIdentity() this.Set(0, 3, x) this.Set(1, 3, y) this.Set(2, 3, z) return this } // Create a scaling matrix for Mat4. Overwrites all values in the matrix. func (this *Mat4) ToScale(x, y, z float64) *Mat4 { this.ToIdentity() this.Set(0, 0, x) this.Set(1, 1, y) this.Set(2, 2, z) return this } // Create a shearing matrix for Mat4. Overwrites all values in the matrix. func (this *Mat4) ToShear(x, y, z float64) *Mat4 { // 0 -z y 0 // z 0 -x 0 // -y x 0 0 // 0 0 0 1 this.ToIdentity() this.Set(0, 0, 0) this.Set(1, 1, 0) this.Set(2, 2, 0) this.Set(1, 2, -x) this.Set(2, 1, x) this.Set(0, 2, y) this.Set(2, 0, -y) this.Set(0, 1, -z) this.Set(1, 0, z) return this } // Create a 3D rotation matrix about the x-axis with angles (radians) func (this *Mat4) ToRotateX(angle float64) *Mat4 { this.ToIdentity() this.Set(1, 1, math.Cos(angle)) this.Set(1, 2, -math.Sin(angle)) this.Set(2, 1, math.Sin(angle)) this.Set(2, 2, math.Cos(angle)) return this } // Create a 3D rotation matrix about the y-axis with angles (radians) func (this *Mat4) ToRotateY(angle float64) *Mat4 { this.ToIdentity() this.Set(0, 0, math.Cos(angle)) this.Set(0, 2, math.Sin(angle)) this.Set(2, 0, -math.Sin(angle)) this.Set(2, 2, math.Cos(angle)) return this } // Create a 3D rotation matrix about the z-axis with angles (radians) func (this *Mat4) ToRotateZ(angle float64) *Mat4 { this.ToIdentity() this.Set(0, 0, math.Cos(angle)) this.Set(0, 1, -math.Sin(angle)) this.Set(1, 0, math.Sin(angle)) this.Set(1, 1, math.Cos(angle)) return this } //============================================================================== // Return the upper 3x3 matrix as a Mat3 func (this Mat4) UpperMat3() (out Mat3) { out.Load([9]float64{ this.Get(0, 0), this.Get(0, 1), this.Get(0, 2), this.Get(1, 0), this.Get(1, 1), this.Get(1, 2), this.Get(2, 0), this.Get(2, 1), this.Get(2, 2), }) return out } // Return the upper 3x3 matrix to the provide Mat3 func (this *Mat4) SetUpperMat3(m Mat3) *Mat4 { this.Set(0, 0, m.Get(0, 0)) this.Set(0, 1, m.Get(0, 1)) this.Set(0, 2, m.Get(0, 2)) this.Set(1, 0, m.Get(1, 0)) this.Set(1, 1, m.Get(1, 1)) this.Set(1, 2, m.Get(1, 2)) this.Set(2, 0, m.Get(2, 0)) this.Set(2, 1, m.Get(2, 1)) this.Set(2, 2, m.Get(2, 2)) return this } // Multiplies the Vec3 against the matrix ( ie. result = Matrix * Vec). // Returns a new vector with the result. func (this Mat4) MultVec3(v Vec3) (out Vec3) { // 0 1 2 3 // 4 5 6 7 // 8 9 10 11 // 12 13 14 15 out.Set( this.mat[0]*v.X+this.mat[1]*v.Y+this.mat[2]*v.Z+this.mat[3], this.mat[4]*v.X+this.mat[5]*v.Y+this.mat[6]*v.Z+this.mat[7], this.mat[8]*v.X+this.mat[9]*v.Y+this.mat[10]*v.Z+this.mat[11], ) return } // Multiplies the Vec4 against the matrix ( ie. result = Matrix * Vec). // Returns a new vector with the result. func (this Mat4) MultVec4(v Vec4) (out Vec4) { // 0 1 2 3 // 4 5 6 7 // 8 9 10 11 // 12 13 14 15 out.Set( this.mat[0]*v.X+this.mat[1]*v.Y+this.mat[2]*v.Z+this.mat[3]*v.W, this.mat[4]*v.X+this.mat[5]*v.Y+this.mat[6]*v.Z+this.mat[7]*v.W, this.mat[8]*v.X+this.mat[9]*v.Y+this.mat[10]*v.Z+this.mat[11]*v.W, this.mat[12]*v.X+this.mat[13]*v.Y+this.mat[14]*v.Z+this.mat[15]*v.W, ) return } // ============================================================================= // Return a rotation matrix which rotates a vector about the axis [x,y,z] with // the given angle (radians). // Set this matrix as a rotation matrix from the give angle(radians) and axis. func (this *Mat4) FromAxisAngle(angle, x, y, z float64) *Mat4 { //Reference http://en.wikipedia.org/wiki/Rotation_matrix c := math.Cos(angle) s := math.Sin(angle) t := (1 - c) return this.Load([16]float64{c + x*x*t, x*y*t - z*s, x*z*t + y*s, 0, y*x*t + z*s, c + y*y*t, y*z*t - x*s, 0, z*x*t - y*s, z*y*t + x*s, c + z*z*t, 0, 0, 0, 0, 1}) } // Set this as a rotation matrix using the specified pitch,yaw, and roll paramters. // Angles are in radians. func (this *Mat4) FromEuler(pitch, yaw, roll float64) *Mat4 { cx := math.Cos(pitch) sx := math.Sin(pitch) cy := math.Cos(yaw) sy := math.Sin(yaw) cz := math.Cos(roll) sz := math.Sin(roll) // This matrix was derived by multiplying each indiviudual rotation matrix // together into a single matrix. // note the matrices are applied in reverse order compared to the application // of the rotations. // roll yaw pitch // | cz -sz 0 | | cy 0 sy | | 1 0 0 | // | sz cz 0 |x| 0 1 0 |x| 0 cx -sx | // | 0 0 1 | | -sy 0 cy | | 0 sx cx | // first row this.mat[0] = cz * cy this.mat[1] = cz*sy*sx - sz*cx this.mat[2] = sz*sx + cz*cx*sy this.mat[3] = 0 // second row this.mat[4] = sz * cy this.mat[5] = cz*cx + sx*sy*sz this.mat[6] = sz*sy*cx - cz*sx this.mat[7] = 0 // third row this.mat[8] = -sy this.mat[9] = sx * cy this.mat[10] = cy * cx this.mat[11] = 0 this.mat[12] = 0 this.mat[13] = 0 this.mat[14] = 0 this.mat[15] = 1 return this } // Return the axis (radians) and axis of this rotation matrix. // Assumes the matrix is a valid rotation matrix. func (this Mat4) AxisAngle() (angle, x, y, z float64) { // Reference // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/ m00, m01, m02 := this.Get(0, 0), this.Get(0, 1), this.Get(0, 2) m10, m11, m12 := this.Get(1, 0), this.Get(1, 1), this.Get(1, 2) m20, m21, m22 := this.Get(2, 0), this.Get(2, 1), this.Get(2, 2) if closeEq(math.Abs(m01-m10), 0, epsilon) && closeEq(math.Abs(m02-m20), 0, epsilon) && closeEq(math.Abs(m12-m21), 0, epsilon) { // singularity check // Checking for cases in which the angle is either 0 or 180 if this.IsIdentity() { // If the angle is 0, then the rotation matrix will be the identity matrix // A 0 angle means that there is an arbitrary axis. angle, x, y, z = 0, 1, 0, 0 return } // Angle is 180, we need to find the axis it rotates around angle = math.Pi xx := (m00 + 1) / 2 yy := (m11 + 1) / 2 zz := (m22 + 1) / 2 xy := (m01 + m10) / 4 xz := (m02 + m20) / 4 yz := (m12 + m21) / 4 if (xx > yy) && (xx > zz) { // m[0][0] is the largest diagonal term if xx < epsilon { x = 0 y = math.Sqrt(2) / 2 z = math.Sqrt(2) / 2 } else { x = math.Sqrt(xx) y = xy / x z = xz / x } } else if yy > zz { // m[1][1] is the largest diagonal term if yy < epsilon { x = math.Sqrt(2) / 2 y = 0 z = math.Sqrt(2) / 2 } else { y = math.Sqrt(yy) x = xy / y z = yz / y } } else { // m[2][2] is the largest diagonal term so base result on this if zz < epsilon { x = math.Sqrt(2) / 2 y = math.Sqrt(2) / 2 z = 0 } else { z = math.Sqrt(zz) x = xz / z y = yz / z } } return } // no singularity; therefore calculate as normal angle = math.Acos((m00 + m11 + m22 - 1) / 2) A := (m21 - m12) B := (m02 - m20) C := (m10 - m01) x = A / math.Sqrt(A*A+B*B+C*C) y = B / math.Sqrt(A*A+B*B+C*C) z = C / math.Sqrt(A*A+B*B+C*C) return } // Return the pitch,yaw and roll values for the given rotation matrix. // The returned euler angle may not be the exact angle in which you supplied // but they can be used to make an equilvalent rotation matrix. func (this Mat4) Euler() (pitch, yaw, roll float64) { // The method for calculating the euler angles from a rotation matrix // uses the method described in this document // http://staff.city.ac.uk/~sbbh653/publications/euler.pdf // The rotation matrix we are using will be of the following form // cos(x) is abbreviated as cx ( similarily sin(x) = sx) // This corresponds to the pitch => yaw => roll rotation matrix // cz*cy cz*sy*sx - sz*cx sz*sx + cz*cx*sy | r11 r12 r13 // sz*cy cz*cx + sx*sy*sz sz*sy*cx - cz*sx | r21 r22 r23 // -sy sx*cy cx*cy | r31 r32 r33 // We want to determine the x,y,z angles // 1) Find the 'y' angle // This is easily accomplished because term r31 is simply '-sin(y)' // 2) There are two possible angles for y because // sin(y) == sin(pi - y) // 3) To find the value of x, we observe the following // r32/r33 = tan(x) // (sin(x)cos(y)) / (cos(x)cos(y)) // (sin(x)/cos(x)) == tan(x) by defn. // 4) We can also calculate x and z by. // x = atan2(r32,r33) == atan2( (sin(x)cos(y)) / (cos(x)cos(y)) ) // z = atan2(r21,r11) == atan2( (sin(z)cos(y)) / (cos(z)cos(y)) ) var x, y, z float64 r31 := this.Get(2, 0) if closeEq(r31, 1, epsilon) { // we are in gimbal lock z = 0 y = -math.Pi / 2 x = -z + math.Atan2(-this.Get(0, 1), -this.Get(0, 2)) } else if closeEq(r31, -1, epsilon) { // we are in gimbal lock z = 0 y = math.Pi / 2 x = z + math.Atan2(this.Get(0, 1), this.Get(0, 2)) } else { y = -math.Asin(r31) cos_y := math.Cos(y) x = math.Atan2(this.Get(2, 1)/cos_y, this.Get(2, 2)/cos_y) z = math.Atan2(this.Get(1, 0)/cos_y, this.Get(0, 0)/cos_y) // There are two alternative values for y,here is the second option // y2 := math.Pi - y // cos_y2 := math.Cos(y2) // x2 := math.Atan2(this.Get(2, 1)/cos_y2, this.Get(2, 2)/cos_y2) // z2 := math.Atan2(this.Get(1, 0)/cos_y2, this.Get(0, 0)/cos_y2) } pitch = x yaw = y roll = z return } // Creates a rotation matrix from the given quaternion. Return this func (this *Mat4) FromQuat(q Quat) *Mat4 { *this = q.Mat4() return this } // Returns the quaternion represented by this rotation matrix. func (this Mat4) Quat() Quat { q := Quat{} q.FromMat4(this) return q }
lmath/mat4.go
0.778313
0.565659
mat4.go
starcoder
package cryptoapis import ( "encoding/json" ) // ListWalletTransactionsRIFungibleTokens struct for ListWalletTransactionsRIFungibleTokens type ListWalletTransactionsRIFungibleTokens struct { // Defines the amount of the fungible tokens. Amount string `json:"amount"` // Defines the tokens' converted amount value. ConvertedAmount string `json:"convertedAmount"` // Represents token's exchange rate unit. ExchangeRateUnit string `json:"exchangeRateUnit"` // Defines the token's name as a string. Name string `json:"name"` // The address which receives this transaction. In UTXO-based protocols like Bitcoin there could be several senders while in account-based protocols like Ethereum there is always only one Recipient string `json:"recipient"` // Represents the address which sends this transaction. In UTXO-based protocols like Bitcoin there could be several senders while in account-based protocols like Ethereum there is always only one sender. Sender string `json:"sender"` // Defines the symbol of the fungible tokens. Symbol string `json:"symbol"` // Defines the decimals of the token, i.e. the number of digits that come after the decimal coma of the token. TokenDecimals int32 `json:"tokenDecimals"` // Defines the specific token type. Type string `json:"type"` } // NewListWalletTransactionsRIFungibleTokens instantiates a new ListWalletTransactionsRIFungibleTokens 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 NewListWalletTransactionsRIFungibleTokens(amount string, convertedAmount string, exchangeRateUnit string, name string, recipient string, sender string, symbol string, tokenDecimals int32, type_ string) *ListWalletTransactionsRIFungibleTokens { this := ListWalletTransactionsRIFungibleTokens{} this.Amount = amount this.ConvertedAmount = convertedAmount this.ExchangeRateUnit = exchangeRateUnit this.Name = name this.Recipient = recipient this.Sender = sender this.Symbol = symbol this.TokenDecimals = tokenDecimals this.Type = type_ return &this } // NewListWalletTransactionsRIFungibleTokensWithDefaults instantiates a new ListWalletTransactionsRIFungibleTokens 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 NewListWalletTransactionsRIFungibleTokensWithDefaults() *ListWalletTransactionsRIFungibleTokens { this := ListWalletTransactionsRIFungibleTokens{} return &this } // GetAmount returns the Amount field value func (o *ListWalletTransactionsRIFungibleTokens) GetAmount() string { if o == nil { var ret string return ret } return o.Amount } // GetAmountOk returns a tuple with the Amount field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetAmountOk() (*string, bool) { if o == nil { return nil, false } return &o.Amount, true } // SetAmount sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetAmount(v string) { o.Amount = v } // GetConvertedAmount returns the ConvertedAmount field value func (o *ListWalletTransactionsRIFungibleTokens) GetConvertedAmount() string { if o == nil { var ret string return ret } return o.ConvertedAmount } // GetConvertedAmountOk returns a tuple with the ConvertedAmount field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetConvertedAmountOk() (*string, bool) { if o == nil { return nil, false } return &o.ConvertedAmount, true } // SetConvertedAmount sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetConvertedAmount(v string) { o.ConvertedAmount = v } // GetExchangeRateUnit returns the ExchangeRateUnit field value func (o *ListWalletTransactionsRIFungibleTokens) GetExchangeRateUnit() string { if o == nil { var ret string return ret } return o.ExchangeRateUnit } // GetExchangeRateUnitOk returns a tuple with the ExchangeRateUnit field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetExchangeRateUnitOk() (*string, bool) { if o == nil { return nil, false } return &o.ExchangeRateUnit, true } // SetExchangeRateUnit sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetExchangeRateUnit(v string) { o.ExchangeRateUnit = v } // GetName returns the Name field value func (o *ListWalletTransactionsRIFungibleTokens) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetName(v string) { o.Name = v } // GetRecipient returns the Recipient field value func (o *ListWalletTransactionsRIFungibleTokens) GetRecipient() string { if o == nil { var ret string return ret } return o.Recipient } // GetRecipientOk returns a tuple with the Recipient field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetRecipientOk() (*string, bool) { if o == nil { return nil, false } return &o.Recipient, true } // SetRecipient sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetRecipient(v string) { o.Recipient = v } // GetSender returns the Sender field value func (o *ListWalletTransactionsRIFungibleTokens) GetSender() string { if o == nil { var ret string return ret } return o.Sender } // GetSenderOk returns a tuple with the Sender field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetSenderOk() (*string, bool) { if o == nil { return nil, false } return &o.Sender, true } // SetSender sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetSender(v string) { o.Sender = v } // GetSymbol returns the Symbol field value func (o *ListWalletTransactionsRIFungibleTokens) GetSymbol() string { if o == nil { var ret string return ret } return o.Symbol } // GetSymbolOk returns a tuple with the Symbol field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetSymbolOk() (*string, bool) { if o == nil { return nil, false } return &o.Symbol, true } // SetSymbol sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetSymbol(v string) { o.Symbol = v } // GetTokenDecimals returns the TokenDecimals field value func (o *ListWalletTransactionsRIFungibleTokens) GetTokenDecimals() int32 { if o == nil { var ret int32 return ret } return o.TokenDecimals } // GetTokenDecimalsOk returns a tuple with the TokenDecimals field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetTokenDecimalsOk() (*int32, bool) { if o == nil { return nil, false } return &o.TokenDecimals, true } // SetTokenDecimals sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetTokenDecimals(v int32) { o.TokenDecimals = v } // GetType returns the Type field value func (o *ListWalletTransactionsRIFungibleTokens) GetType() string { if o == nil { var ret string return ret } return o.Type } // GetTypeOk returns a tuple with the Type field value // and a boolean to check if the value has been set. func (o *ListWalletTransactionsRIFungibleTokens) GetTypeOk() (*string, bool) { if o == nil { return nil, false } return &o.Type, true } // SetType sets field value func (o *ListWalletTransactionsRIFungibleTokens) SetType(v string) { o.Type = v } func (o ListWalletTransactionsRIFungibleTokens) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["amount"] = o.Amount } if true { toSerialize["convertedAmount"] = o.ConvertedAmount } if true { toSerialize["exchangeRateUnit"] = o.ExchangeRateUnit } if true { toSerialize["name"] = o.Name } if true { toSerialize["recipient"] = o.Recipient } if true { toSerialize["sender"] = o.Sender } if true { toSerialize["symbol"] = o.Symbol } if true { toSerialize["tokenDecimals"] = o.TokenDecimals } if true { toSerialize["type"] = o.Type } return json.Marshal(toSerialize) } type NullableListWalletTransactionsRIFungibleTokens struct { value *ListWalletTransactionsRIFungibleTokens isSet bool } func (v NullableListWalletTransactionsRIFungibleTokens) Get() *ListWalletTransactionsRIFungibleTokens { return v.value } func (v *NullableListWalletTransactionsRIFungibleTokens) Set(val *ListWalletTransactionsRIFungibleTokens) { v.value = val v.isSet = true } func (v NullableListWalletTransactionsRIFungibleTokens) IsSet() bool { return v.isSet } func (v *NullableListWalletTransactionsRIFungibleTokens) Unset() { v.value = nil v.isSet = false } func NewNullableListWalletTransactionsRIFungibleTokens(val *ListWalletTransactionsRIFungibleTokens) *NullableListWalletTransactionsRIFungibleTokens { return &NullableListWalletTransactionsRIFungibleTokens{value: val, isSet: true} } func (v NullableListWalletTransactionsRIFungibleTokens) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableListWalletTransactionsRIFungibleTokens) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_list_wallet_transactions_ri_fungible_tokens.go
0.827932
0.426859
model_list_wallet_transactions_ri_fungible_tokens.go
starcoder
package geogoth // Point Point structure type Point struct { Y float64 X float64 } // NewPoint Creates new Point object func NewPoint(y, x float64) Point { return Point{ Y: y, X: x, } } // Coordinates returns y,x of the Point // @ ToDo: Add pointers: func (p *Point) Coordinates() interface{} { func (p Point) Coordinates() interface{} { return []float64{p.Y, p.X} } // GetCoordinates returns longitude, latitude of Point geom func (p Point) GetCoordinates() (float64, float64) { // convert coordinates from interface to []float64 coord := (p.Coordinates()).([]float64) lon := coord[0] lat := coord[1] return lon, lat } // Type returns type of the Point (Point) func (p Point) Type() string { return "Point" } // Length returns length of the Point (0) func (p Point) Length() float64 { return 0 } // DistanceTo returns distance between two geo objects func (p Point) DistanceTo(f Feature) float64 { var distance float64 switch f.Type() { case "Point": coord1 := (p.Coordinates()).([]float64) y1, x1 := coord1[0], coord1[1] coord2 := (f.Coordinates()).([]float64) y2, x2 := coord2[0], coord2[1] distance = DistancePointPointDeg(y1, x1, y2, x2) case "MultiPoint": mpoint := f.(*MultiPoint) distance = DistancePointMultipoint(&p, mpoint) case "LineString": lstr := f.(*LineString) distance = DistancePointLinstring(&p, lstr) case "MultiLineString": mlinestr := f.(*MultiLineString) distance = DistancePointMultiLineString(&p, mlinestr) case "Polygon": polygon := f.(*Polygon) distance = DistancePointPolygon(&p, polygon) case "MultiPolygon": mpolyg := f.(*MultiPolygon) distance = DistancePointMultiPolygon(&p, mpolyg) } return distance } // IntersectsWith returns true if geoObject intersects with Feature(another geoObject) func (p Point) IntersectsWith(f Feature) bool { var intersection bool switch f.Type() { case "Point": point := f.(*Point) intersection = PointPointIntersection(p, *point) case "MultiPoint": mpoint := f.(*MultiPoint) intersection = PointMultiPointIntersection(p, *mpoint) case "LineString": lstr := f.(*LineString) if p.DistanceTo(lstr) == 0 { intersection = true } else { intersection = false } case "MultiLineString": mlstr := f.(*MultiLineString) if p.DistanceTo(mlstr) == 0 { intersection = true } else { intersection = false } case "Polygon": polygon := f.(*Polygon) if p.DistanceTo(polygon) == 0 { intersection = true } else { intersection = false } case "MultiPolygon": mpolyg := f.(*MultiPolygon) if p.DistanceTo(mpolyg) == 0 { intersection = true } else { intersection = false } } return intersection } // // AsFeature ... // func (p Point) AsFeature() Feature { // var f Feature // f = &p // return f // } // // NewPointFeature ... // func NewPointFeature(y, x float64) Feature { // point := Point{ // Y: y, // X: x, // } // return FeatureStruct{Feature: &point} // }
point.go
0.801742
0.768451
point.go
starcoder
package sampler import ( "jensmcatanho/raytracer-go/math/geometry" "math" "math/rand" "time" ) func Regular(numSamples, numSets int, samples *[]geometry.Vector) { n := math.Sqrt(float64(numSamples)) for i := 0; i < numSets; i++ { for j := 0; j < int(n); j++ { for k := 0; k < int(n); k++ { x := (float64(k) + 0.5) / n y := (float64(j) + 0.5) / n *samples = append(*samples, *geometry.NewVector(float64(x), float64(y), 0.)) } } } } func Random(numSamples, numSets int, samples *[]geometry.Vector) { rand.Seed(time.Now().UnixNano()) for i := 0; i < numSets; i++ { for j := 0; j < numSamples; j++ { *samples = append(*samples, *geometry.NewVector(rand.Float64(), rand.Float64(), .0)) } } } // Hammersley generates sample using Hammersley points // http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html func Hammersley(numSamples, numSets int, samples *[]geometry.Vector) { phi := func(j int) float64 { x := 0. f := .5 for j > 0 { x += f * float64(j%2) j /= 2 f *= .5 } return x } for i := 0; i < numSets; i++ { for j := 0; j < numSamples; j++ { x := float64(j) / float64(numSamples) y := phi(j) *samples = append(*samples, *geometry.NewVector(x, y, 0.)) } } } func NRooks(numSamples, numSets int, samples *[]geometry.Vector) { for i := 0; i < numSets; i++ { for j := 0; j < numSamples; j++ { x := (float64(j) + rand.Float64()) / float64(numSamples) y := (float64(j) + rand.Float64()) / float64(numSamples) *samples = append(*samples, *geometry.NewVector(x, y, .0)) } } shuffleX(numSamples, numSets, samples) shuffleY(numSamples, numSets, samples) } func Jittered(numSamples, numSets int, samples *[]geometry.Vector) { n := math.Sqrt(float64(numSamples)) for i := 0; i < numSets; i++ { for j := 0; float64(j) < n; j++ { for k := 0; float64(k) < n; k++ { x := (float64(k) + rand.Float64()) / n y := (float64(j) + rand.Float64()) / n *samples = append(*samples, *geometry.NewVector(x, y, .0)) } } } }
math/sampler/methods.go
0.632503
0.541045
methods.go
starcoder
package ansi256 import ( "fmt" "strings" "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...) } } // FBPrint 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 FBPrint(foregroundColor, backgroundColor pencil.ColorCode, a ...interface{}) (n int, err error) { Set(foregroundColor, pencil.Foreground).Set() Set(backgroundColor, pencil.Background).Set() fc := Set(foregroundColor, pencil.Foreground).Set() bc := Set(backgroundColor, pencil.Background).Set() defer fc.unset() defer bc.unset() if fc.isNoColorSet() { return fmt.Fprint(pencil.Output, a...) } m := len(a) if a[m-1] == "\n" { a = append(a[:m-1], pencil.GetRest(), "\n") return fmt.Fprint(pencil.Output, a...) } a = append(a, pencil.GetRest()) return fmt.Fprint(pencil.Output, a...) } // FBPrintf 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 FBPrintf(foregroundColor, backgroundColor pencil.ColorCode, format string, a ...interface{}) (n int, err error) { fc := Set(foregroundColor, pencil.Foreground).Set() bc := Set(backgroundColor, pencil.Background).Set() defer fc.unset() defer bc.unset() if fc.isNoColorSet() { return fmt.Fprintf(pencil.Output, format, a...) } fr := strings.TrimRight(format, " ") m := strings.LastIndex(fr, "\n") if m != -1 && m == len(fr)-1 { fr = fr[:m] + pencil.GetRest() + "\n" } fr += strings.Repeat(" ", len(format)-len(fr)) return fmt.Fprintf(pencil.Output, fr, a...) } // FBPrintln 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 FBPrintln(foregroundColor, backgroundColor pencil.ColorCode, a ...interface{}) (n int, err error) { fc := Set(foregroundColor, pencil.Foreground).Set() bc := Set(backgroundColor, pencil.Background).Set() defer fc.unset() defer bc.unset() if fc.isNoColorSet() { return fmt.Fprintln(pencil.Output, a...) } a = append(a, pencil.GetRest()) return fmt.Fprintln(pencil.Output, a...) } // FBPrintFunc returns a new function that prints the passed arguments as // colorized with color.Print(). func FBPrintFunc(foregroundColor, backgroundColor pencil.ColorCode) func(a ...interface{}) { return func(a ...interface{}) { FBPrint(foregroundColor, backgroundColor, a...) } } // FBPrintfFunc returns a new function that prints the passed arguments as // colorized with color.Printf(). func FBPrintfFunc(foregroundColor, backgroundColor pencil.ColorCode) func(format string, a ...interface{}) { return func(format string, a ...interface{}) { FBPrintf(foregroundColor, backgroundColor, format, a...) } } // FBPrintlnFunc returns a new function that prints the passed arguments as // colorized with color.Println(). func FBPrintlnFunc(foregroundColor, backgroundColor pencil.ColorCode) func(a ...interface{}) { return func(a ...interface{}) { FBPrintln(foregroundColor, backgroundColor, a...) } }
ansi256/print.go
0.789802
0.466906
print.go
starcoder
package dcos import ( "context" "log" "github.com/dcos/client-go/dcos" "github.com/hashicorp/terraform/helper/schema" ) func dataSourceDcosJob() *schema.Resource { return &schema.Resource{ Read: dataSourceDcosJobRead, Schema: map[string]*schema.Schema{ "name": { Type: schema.TypeString, Required: true, ForceNew: true, Description: "Unique identifier for the job.", }, "user": { Type: schema.TypeString, Computed: true, Description: "The user to use to run the tasks on the agent.", }, "description": { Type: schema.TypeString, Computed: true, Description: "A description of this job.", }, "labels": { Type: schema.TypeMap, Computed: true, Elem: &schema.Schema{Type: schema.TypeString}, Description: "Attaching metadata to jobs can be useful to expose additional information to other services.", }, "cmd": { Type: schema.TypeString, Computed: true, Description: "The command that is executed. This value is wrapped by Mesos via `/bin/sh -c ${job.cmd}`. Either `cmd` or `args` must be supplied. It is invalid to supply both `cmd` and `args` in the same job.", }, "args": { Type: schema.TypeString, Computed: true, Description: "An array of strings that represents an alternative mode of specifying the command to run. This was motivated by safe usage of containerizer features like a custom Docker ENTRYPOINT. Either `cmd` or `args` must be supplied. It is invalid to supply both `cmd` and `args` in the same job.", }, "artifacts": { Type: schema.TypeSet, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "uri": { Type: schema.TypeString, Computed: true, Description: "URI to be fetched by Mesos fetcher module.", }, "executable": { Type: schema.TypeBool, Computed: true, Description: "Set fetched artifact as executable.", }, "extract": { Type: schema.TypeBool, Computed: true, Description: "Extract fetched artifact if supported by Mesos fetcher module.", }, "cache": { Type: schema.TypeBool, Computed: true, Description: "Cache fetched artifact if supported by Mesos fetcher module.", }, }, }, }, "docker": { Type: schema.TypeMap, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "image": { Type: schema.TypeString, Computed: true, Description: "The docker repository image name.", }, }, }, }, "env": { Type: schema.TypeMap, Computed: true, Description: "Environment variables (non secret)", Elem: &schema.Schema{Type: schema.TypeString}, }, "secrets": { Type: schema.TypeMap, Computed: true, Description: "Any secrets that are necessary for the job", Elem: &schema.Schema{Type: schema.TypeString}, }, "placement_constraint": { Type: schema.TypeSet, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "attribute": { Type: schema.TypeString, Computed: true, Description: "The attribute name for this constraint.", }, "operator": { Type: schema.TypeString, Computed: true, Description: "The operator for this constraint.", }, "value": { Type: schema.TypeString, Computed: true, Description: "The value for this constraint.", }, }, }, }, "restart": { Type: schema.TypeMap, Computed: true, Description: "Defines the behavior if a task fails.", Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "active_deadline_seconds": { Type: schema.TypeInt, Computed: true, Description: "If the job fails, how long should we try to restart the job. If no value is set, this means forever.", }, "policy": { Type: schema.TypeString, Computed: true, Description: "The policy to use if a job fails. NEVER will never try to relaunch a job. ON_FAILURE will try to start a job in case of failure.", }, }, }, }, "volume": { Type: schema.TypeSet, Computed: true, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "container_path": { Type: schema.TypeString, Computed: true, Description: "The path of the volume in the container.", }, "host_path": { Type: schema.TypeString, Computed: true, Description: "The path of the volume on the host.", }, "mode": { Type: schema.TypeString, Computed: true, Description: "Possible values are RO for ReadOnly and RW for Read/Write.", }, }, }, }, "cpus": { Type: schema.TypeFloat, Computed: true, Description: "The number of CPU shares this job needs per instance. This number does not have to be integer, but can be a fraction.", }, "mem": { Type: schema.TypeInt, Computed: true, Description: "The amount of memory in MB that is needed for the job per instance.", }, "disk": { Type: schema.TypeInt, Computed: true, Description: "How much disk space is needed for this job. This number does not have to be an integer, but can be a fraction.", }, "max_launch_delay": { Type: schema.TypeInt, Computed: true, Description: "The number of seconds until the job needs to be running. If the deadline is reached without successfully running the job, the job is aborted.", }, }, } } func dataSourceDcosJobRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*dcos.APIClient) ctx := context.TODO() jobId := d.Get("name").(string) metronome_v1_job, _, err := getDCOSJobInfo(jobId, client, ctx) if err != nil { return err } log.Printf("[TRACE] MetronomeV1Job: %+v", metronome_v1_job) d.SetId(metronome_v1_job.Id) d.Set("description", metronome_v1_job.Description) d.Set("cpus", metronome_v1_job.Run.Cpus) d.Set("mem", metronome_v1_job.Run.Mem) d.Set("disk", metronome_v1_job.Run.Disk) d.Set("max_launch_delay", metronome_v1_job.Run.MaxLaunchDelay) d.Set("args", metronome_v1_job.Run.Args) d.Set("cmd", metronome_v1_job.Run.Cmd) d.Set("user", metronome_v1_job.Run.User) return nil }
dcos/data_source_dcos_job.go
0.570212
0.413418
data_source_dcos_job.go
starcoder
package template import ( "bytes" "io" "regexp" "strings" "text/template" "github.com/golang/gddo/doc" "github.com/posener/goreadme/internal/markdown" ) // Execute is used to execute the README.md template. func Execute(w io.Writer, data interface{}) error { return main.Execute(&multiNewLineEliminator{w: w}, data) } var base = template.New("base").Funcs( template.FuncMap{ "gocode": func(s string) string { return "```golang\n" + s + "\n```\n" }, "code": func(s string) string { if !strings.HasSuffix(s, "\n") { s = s + "\n" } return "```\n" + s + "```\n" }, "inlineCode": func(s string) string { return "`" + s + "`" }, "inlineCodeEllipsis": func(s string) string { r := regexp.MustCompile(`{(?s).*}`) s = r.ReplaceAllString(s, "{ ... }") return "`" + s + "`" }, "importPath": func(p *doc.Package) string { return p.ImportPath }, "fullName": func(p *doc.Package) string { return strings.TrimPrefix(p.ImportPath, "github.com/") }, "urlOrName": func(f *doc.File) string { if f.URL != "" { return f.URL } return "/" + f.Name }, "doc": func(s string) string { b := bytes.NewBuffer(nil) markdown.ToMarkdown(b, s, nil) return b.String() }, }, ) var main = template.Must(base.Parse(`# {{.Package.Name}} {{if .Config.Badges.TravisCI -}} [![Build Status](https://travis-ci.org/{{fullName .Package}}.svg?branch=master)](https://travis-ci.org/{{fullName .Package}}) {{end -}} {{if .Config.Badges.CodeCov -}} [![codecov](https://codecov.io/gh/{{fullName .Package}}/branch/master/graph/badge.svg)](https://codecov.io/gh/{{fullName .Package}}) {{end -}} {{if .Config.Badges.GolangCI -}} [![golangci](https://golangci.com/badges/{{importPath .Package}}.svg)](https://golangci.com/r/{{importPath .Package}}) {{end -}} {{if .Config.Badges.GoDoc -}} [![GoDoc](https://img.shields.io/badge/pkg.go.dev-doc-blue)](http://pkg.go.dev/{{importPath .Package}}) {{end -}} {{if .Config.Badges.GoReportCard -}} [![Go Report Card](https://goreportcard.com/badge/{{importPath .Package}})](https://goreportcard.com/report/{{importPath .Package}}) {{ end }} {{ doc .Package.Doc }} {{ if .Config.Functions }} {{ template "functions" .Package }} {{ end }} {{ if .Config.Types }} {{ template "types" .Package }} {{ end }} {{ if (not .Config.SkipSubPackages) }} {{ template "subpackages" . }} {{ end }} {{ if (not .Config.SkipExamples) }} {{ template "examples" .Package.Examples }} {{ end }} {{ if .Config.Credit }} --- Readme created from Go doc with [goreadme](https://github.com/posener/goreadme) {{ end }} `)) var functions = template.Must(base.Parse(` {{ define "functions" }} {{ if .Funcs }} ## Functions {{ range .Funcs }} ### func [{{ .Name }}]({{ urlOrName (index $.Files .Pos.File) }}#L{{ .Pos.Line }}) {{ inlineCode .Decl.Text }} {{ doc .Doc }} {{ template "examplesNoHeading" .Examples }} {{ end }} {{ end }} {{ end }} `)) var types = template.Must(base.Parse(` {{ define "types" }} {{ if .Types }} ## Types {{ range .Types }} ### type [{{ .Name }}] {{ inlineCodeEllipsis .Decl.Text }} {{ doc .Doc }} {{ template "examplesNoHeading" .Examples }} {{ end }} {{ end }} {{ end }} `)) var examples = template.Must(base.Parse(` {{ define "examples" }} {{ if . }} ## Examples {{ template "examplesNoHeading" . }} {{ end }} {{ end }} `)) var examplesNoHeading = template.Must(base.Parse(` {{ define "examplesNoHeading" }} {{ if . }} {{ range . }} {{ if .Name }}### {{.Name}}{{ end }} {{ doc .Doc }} {{ if .Play }}{{gocode .Play}}{{ else }}{{gocode .Code.Text}}{{ end }} {{ if .Output }} Output: {{ code .Output }}{{ end }} {{ end }} {{ end }} {{ end }} `)) var subPackages = template.Must(base.Parse(` {{ define "subpackages" }} {{ if .SubPackages }} ## Sub Packages {{ range .SubPackages }} * [{{.Path}}](./{{.Path}}){{if .Package.Synopsis}}: {{.Package.Synopsis}}{{end}} {{ end }} {{ end }} {{ end }} `))
internal/template/template.go
0.571288
0.5769
template.go
starcoder
package communication import ( "bytes" "errors" "fmt" "reflect" "strings" "github.com/mitchellh/mapstructure" "github.com/schoeppi5/libts" ) // UnmarshalResponse attempts to parse body to value // If value is a single struct, only the first element of body is unmarsheld // If value is a slice of structs, UnmarshalResponse will append to that slice // If value is an array of structs, UnmarshalResponse will try to set the indices of the array func UnmarshalResponse(body []map[string]interface{}, value interface{}) error { kind := reflect.Indirect(reflect.ValueOf(value)).Kind() if kind == reflect.Struct { // one item expected err := Decode(body[0], value) if err != nil { return err } } else if kind == reflect.Slice { // slice of items expected inter := getTypeOfSlice(value) v := reflect.ValueOf(value).Elem() for i := range body { err := Decode(body[i], &inter) if err != nil { return err } v.Set(reflect.Append(v, reflect.ValueOf(inter))) } } else if reflect.Indirect(reflect.ValueOf(value)).Kind() == reflect.Array { // array of items expected inter := getTypeOfSlice(value) v := reflect.ValueOf(value).Elem() for i := range body { if i > reflect.Indirect(reflect.ValueOf(value)).Len()-1 { // reached end of expected output break } err := Decode(body[i], &inter) if err != nil { return err } v.Index(i).Set(reflect.ValueOf(inter)) } } else { return fmt.Errorf("unsupported type %s. Expected type struct, slice or array", reflect.Indirect(reflect.ValueOf(value)).Kind()) } return nil } // Decode creates a new decoder and decodes m to v func Decode(m map[string]interface{}, v interface{}) error { if reflect.ValueOf(v).Kind() != reflect.Ptr { return errors.New("expected pointer to value, not value") } decodeConfig := &mapstructure.DecoderConfig{ DecodeHook: mapstructure.TextUnmarshallerHookFunc(), Metadata: nil, Result: v, WeaklyTypedInput: true, } decoder, _ := mapstructure.NewDecoder(decodeConfig) err := decoder.Decode(m) if err != nil { return err } return nil } // getTypeOfSlice returns the zero value for the type of a slice or arry // e.g.: []struct{} -> zero value of struct{} func getTypeOfSlice(s interface{}) interface{} { return reflect.Zero(reflect.ValueOf(s).Elem().Type().Elem()).Interface() } // IsError returns the error if any func IsError(r []byte) error { parts := bytes.SplitN(r, []byte(" "), 2) if bytes.Compare(parts[0], []byte("error")) == 0 { e := &QueryError{} err := UnmarshalResponse(ConvertResponse(parts[1]), e) if err != nil { return err } return *e } return nil } // ConvertResponse parses the serverquery response to a map func ConvertResponse(r []byte) []map[string]interface{} { var list []map[string]interface{} r = bytes.Trim(bytes.TrimSpace(r), "|") items := bytes.Split(r, []byte("|")) for j := range items { list = append(list, responseToMap(items[j])) } return list } func responseToMap(r []byte) map[string]interface{} { m := make(map[string]interface{}) pairs := bytes.Split(r, []byte(" ")) for i := range pairs { kV := bytes.SplitN(pairs[i], []byte("="), 2) key := string(kV[0]) if len(kV) != 2 { m[key] = "" continue } if strings.Contains(key, "client_default_channel") { // I do not know why. The client_default_channel is wrongly encoded. I don't know why kV[1] = []byte(libts.QueryDecoder.Replace(string(kV[1]))) } m[key] = libts.QueryDecoder.Replace(string(kV[1])) } return m }
communication/response.go
0.593138
0.446796
response.go
starcoder
package schedule import "time" // BetweenExpression is the struct used to create cron between expressions. type BetweenExpression struct { x int y int step int } // Between is an expression that generates integers between the provided parameters (*inclusive*). func Between(x int, y int) *BetweenExpression { if x > y { panic("schedule: invalid BetweenExpression expression") } return &BetweenExpression{ x: x, y: y, step: 1, } } // BetweenMilliseconds uses the regular between logic, ensuring valid millisecond parameters. func BetweenMilliseconds(x int, y int) *BetweenExpression { validateMillisecond(x) validateMillisecond(y) return Between(x, y) } // BetweenSeconds uses the regular between logic, ensuring valid second parameters. func BetweenSeconds(x int, y int) *BetweenExpression { validateSecond(x) validateSecond(y) return Between(x, y) } // BetweenMinutes uses the regular between logic, ensuring valid minute parameters. func BetweenMinutes(x int, y int) *BetweenExpression { validateMinute(x) validateMinute(y) return Between(x, y) } // BetweenHours uses the regular between logic, ensuring valid hour parameters. func BetweenHours(x int, y int) *BetweenExpression { validateHour(x) validateHour(y) return Between(x, y) } // BetweenDays uses the regular between logic, ensuring valid day parameters. func BetweenDays(x int, y int) *BetweenExpression { validateDay(x) validateDay(y) return Between(x, y) } // BetweenWeekdays uses the regular between logic, ensuring valid time.Weekday parameters. func BetweenWeekdays(x time.Weekday, y time.Weekday) *BetweenExpression { xI := int(x) yI := int(y) validateWeekday(xI) validateWeekday(yI) return Between(xI, yI) } // BetweenMonths uses the regular between logic, ensuring valid time.Month parameters. func BetweenMonths(x time.Month, y time.Month) *BetweenExpression { xI := int(x) yI := int(y) validateMonth(xI) validateMonth(yI) return Between(xI, yI) } // BetweenYears uses the regular between logic, ensuring valid year parameters. func BetweenYears(x int, y int) *BetweenExpression { validateYear(x) validateYear(y) return Between(x, y) } // Every allows optional specification of the stepping used for the between logic. // It's important to understand the behavior of the expression when step > 1. It may produce some unexpected values. // Example: Between(0,10).Every(3) // - Next(-1, true || false) = 0 // - Next(0, true) = 0 // - Next(0, false) = 3 // - Next(1, true || false) = 3 // - Next(3, false) = 6 // - Next(6, false) = 9 // - Next(9, false) = 10 // - Next(10, true || false) = 10 func (exp *BetweenExpression) Every(s int) *BetweenExpression { if s < 1 { panic("schedule: invalid step value") } exp.step = s return exp } // Next allows retrieval of the next value from this expression. // Expressions are stateless, the determination of their next value is based on input. // Given a valid expression value, the parameter inc is used to specify if it should be included in the output. // Given the last value of the expression or above, the inc parameter is ignored. // It returns the next value according to provided parameters and a boolean indicating if it is the last value. func (exp *BetweenExpression) Next(from int, inc bool) (int, bool) { if from < exp.x || inc && from == exp.x { return exp.x, false } if from >= exp.y { return exp.y, true } diff := exp.step - (from-exp.x)%exp.step if inc && diff == exp.step { diff = 0 } next := from + diff if next >= exp.y { return exp.y, true } return next, false } // Contains verifies if the provided value belongs to this expression. func (exp *BetweenExpression) Contains(val int) bool { if val < exp.x || val > exp.y { return false } if val == exp.x || val == exp.y { return true } return (exp.step - (val-exp.x)%exp.step) == exp.step }
between_expression.go
0.811377
0.727153
between_expression.go
starcoder
package utils import ( "fmt" "math" "github.com/campus-iot/geo-api/models" ) func isEqualLat(gw1, gw2 models.GatewayReceptionTdoa) bool { return gw1.AntennaLocation.Latitude == gw2.AntennaLocation.Latitude } func isEqualLong(gw1, gw2 models.GatewayReceptionTdoa) bool { return gw1.AntennaLocation.Longitude == gw2.AntennaLocation.Longitude } func isEqualPlace(gw1, gw2 models.GatewayReceptionTdoa) bool { return isEqualLat(gw1, gw2) && isEqualLong(gw1, gw2) } func LatLonToXY(lat, lon float64) (float64, float64) { radius := 6371.0 var x, y float64 x = radius * lon * math.Cos(1.) y = radius * lat return x, y } //Origin is set at the intersection of greenwitch and the equator, perhaps it might be changed func XYToLatLon(x, y float64) (float64, float64) { radius := 6371.0 var lat, lon float64 lat = y / radius lon = x / (radius * math.Cos(1.)) return lat, lon } func convertReceptionTdoa(g models.GatewayReceptionTdoa) (float64, float64) { return LatLonToXY(g.AntennaLocation.Latitude, g.AntennaLocation.Longitude) } func convertResult(X, Y float64) (float64, float64) { return XYToLatLon(X, Y) } func Inter3(g1, g2, g3 models.GatewayReceptionTdoa) models.LocationEstimate { G1x, G1y := convertReceptionTdoa(g1) G2x, G2y := convertReceptionTdoa(g2) G3x, G3y := convertReceptionTdoa(g3) // CX2 := 2 * (g2.AntennaLocation.Latitude - g1.AntennaLocation.Latitude) // CX3 := 2 * (g3.AntennaLocation.Latitude - g1.AntennaLocation.Latitude) // CY2 := 2 * (g2.AntennaLocation.Longitude - g1.AntennaLocation.Longitude) // CY3 := 2 * (g3.AntennaLocation.Longitude - g1.AntennaLocation.Longitude) // CR2 := math.Pow(g1.Rssi, 2) - math.Pow(g2.Rssi, 2) + (math.Pow(g2.AntennaLocation.Latitude, 2) + math.Pow(g2.AntennaLocation.Longitude, 2)) - (math.Pow(g1.AntennaLocation.Latitude, 2) + math.Pow(g1.AntennaLocation.Longitude, 2)) // CR3 := math.Pow(g1.Rssi, 2) - math.Pow(g3.Rssi, 2) + (math.Pow(g3.AntennaLocation.Latitude, 2) + math.Pow(g3.AntennaLocation.Longitude, 2)) - (math.Pow(g1.AntennaLocation.Latitude, 2) + math.Pow(g1.AntennaLocation.Longitude, 2)) CX2 := 2 * (G2y - G1y) CX3 := 2 * (G3y - G1y) CY2 := 2 * (G2x - G1x) CY3 := 2 * (G3x - G1x) CR2 := math.Pow(float64(g1.Rssi), 2) - math.Pow(float64(g2.Rssi), 2) + (math.Pow(G2y, 2) + math.Pow(G2x, 2)) - (math.Pow(G1y, 2) + math.Pow(G1x, 2)) CR3 := math.Pow(float64(g1.Rssi), 2) - math.Pow(float64(g3.Rssi), 2) + (math.Pow(G3y, 2) + math.Pow(G3x, 2)) - (math.Pow(G1y, 2) + math.Pow(G1x, 2)) var CX float64 var CY float64 if isEqualPlace(g1, g2) || isEqualPlace(g1, g3) { fmt.Println("The three gateways are not distinct") return models.LocationEstimate{0, 0, 0, 0} } else if isEqualLat(g1, g2) { // 1 et 2 même x CY = CR2 / CY2 CX = (CR3 - CY*CY3) / CX3 } else if isEqualLat(g1, g3) { // 1 et 3 même x CY = CR3 / CY3 CX = (CR2 - CY*CY2) / CX2 } else if isEqualLong(g1, g2) { // 1 et 2 même y CX = CR2 / CX2 CY = (CR3 - CX*CX3) / CY3 } else if isEqualLong(g1, g3) { // 1 et 3 même y CX = CR3 / CX3 CY = (CR2 - CX*CX2) / CY2 } else { CYnum := CR2 - CX2*CR3/CX3 CYden := CY2 - CX2*CY3/CX3 CY = CYnum / CYden CX = (CR3 - CY*CY3) / CX3 } resultlat, resultlon := convertResult(CX, CY) return models.LocationEstimate{resultlat, resultlon, 0, 0} }
utils/triloc.go
0.703244
0.503845
triloc.go
starcoder
package main import ( "log" "strings" ) type DisplayData struct { digits []string result []string } func parseDigits(line string) []string { return strings.Split(line, " ") } func parseDisplayData(line string) DisplayData { inAndOut := strings.Split(line, " | ") return DisplayData{parseDigits(inAndOut[0]), parseDigits(inAndOut[1])} } func parseAllDisplayData(data []string) []DisplayData { displays := make([]DisplayData, len(data)) for i, line := range data { displays[i] = parseDisplayData(line) } return displays } func getNumUniqueDigits(displays []DisplayData) int { total := 0 for _, display := range displays { for _, digit := range display.result { if len(digit) == 2 || len(digit) == 3 || len(digit) == 4 || len(digit) == 7 { total += 1 } } } return total } func toBits(digit string) int { bits := 0 for _, c := range digit { bits |= 1 << (c - 'a') } return bits } /** How the numbers look: 0: 1: 2: 3: 4: aaaa .... aaaa aaaa .... b c . c . c . c b c b c . c . c . c b c .... .... dddd dddd dddd e f . f e . . f . f e f . f e . . f . f gggg .... gggg gggg .... 5: 6: 7: 8: 9: aaaa aaaa aaaa aaaa aaaa b . b . . c b c b c b . b . . c b c b c dddd dddd .... dddd dddd . f e f . f e f . f . f e f . f e f . f gggg gggg .... gggg gggg Variables named sX and sXX represent bitmask value of segment X for the current display. `ds` array represents bitmask values of numbers for the current display (index is the number, value is the bitmask). */ func decodeDisplayNumber(display DisplayData) int { ds := make([]int, 10) bds := []int{} for _, digit := range display.digits { bitDigit := toBits(digit) if len(digit) == 2 { ds[1] = bitDigit } else if len(digit) == 3 { ds[7] = bitDigit } else if len(digit) == 4 { ds[4] = bitDigit } else if len(digit) == 7 { ds[8] = bitDigit } else { bds = append(bds, bitDigit) } } sA := ds[7] ^ ds[1] sCF := ds[1] sEG := ds[8] ^ (ds[4] | sA) sBD := ds[4] ^ ds[1] for _, bd := range bds { if bd&(127^sEG) == (127^sEG) && bd^sEG != sEG { ds[9] = bd } else if bd&(127^sBD) == (127^sBD) && bd^sBD != sBD { ds[0] = bd } else if bd&(127^sCF) == (127^sCF) && bd^sCF != sCF { ds[6] = bd } } sE := 127 ^ ds[9] sG := sEG ^ sE sD := 127 ^ ds[0] sB := sBD ^ sD sC := 127 ^ ds[6] sF := sCF ^ sC ds[3] = ds[7] | sD | sG ds[2] = 127 - sB - sF ds[5] = ds[6] - sE sum := 0 for _, digit := range display.result { bitDigit := toBits(digit) for n, b := range ds { if b == bitDigit { sum = sum*10 + n } } } return sum } func getDisplaysSum(displays []DisplayData) int { sum := 0 for _, d := range displays { sum += decodeDisplayNumber(d) } return sum } func main8() { data, err := ReadInputFrom("8.inp") if err != nil { log.Fatal(err) return } displays := parseAllDisplayData(data) log.Println(getNumUniqueDigits(displays)) log.Println(getDisplaysSum(displays)) }
2021/8.go
0.550849
0.41947
8.go
starcoder
package walker import ( "reflect" "strconv" "unicode" ) // Visitor is a function that will be called on each visited node. // value is a non-map value, corresponding to the above path. // branch is a slice containing consecutive interfaces used to arrive at the given value. // path is a slice containing consecutive keys used to arrive at the given value. type Visitor func(value reflect.Value, branch []interface{}, path []string, field *reflect.StructField) // Walk walks the given struct interface recursively and calls the visitor at every node func Walk(s interface{}, visitor Visitor) { walk(s, []interface{}{}, []string{}, visitor) } func getFieldKey(f reflect.StructField) string { jsonTag := f.Tag.Get("json") if jsonTag == "-" || jsonTag == "" { // lowercase first char for i, v := range f.Name { return string(unicode.ToLower(v)) + f.Name[i+1:] } } return jsonTag } func walk(node interface{}, branch []interface{}, path []string, visitor Visitor) { nodeType := reflect.TypeOf(node) nodeValue := reflect.ValueOf(node) branch = append(branch, node) switch nodeValue.Kind() { // If it is a pointer we need to unwrap and call once again case reflect.Ptr: // To get the actual value of the node we have to call Elem() // At the same time this unwraps the pointer, so we don't end up in // an infinite recursion parentValue := nodeValue.Elem() // Check if the pointer is nil if !parentValue.IsValid() { return } // Unwrap the newly created pointer walk(parentValue, branch, path, visitor) // If it is an interface (which is very similar to a pointer), do basically the // same as for the pointer. Though a pointer is not the same as an interface so // note that we have to call Elem() after creating a new object because otherwise // we would end up with an actual pointer case reflect.Interface: // Get rid of the wrapping interface parentValue := nodeValue.Elem() walk(parentValue, branch, path, visitor) case reflect.Struct: for i := 0; i < nodeValue.NumField(); i += 1 { child := nodeValue.Field(i) field := nodeType.Field(i) childPath := append(path, getFieldKey(field)) visitor(child, branch, childPath, &field) walk(child.Interface(), branch, childPath, visitor) } case reflect.Slice: for i := 0; i < nodeValue.Len(); i += 1 { child := nodeValue.Index(i) childPath := append(path, strconv.Itoa(i)) visitor(child, branch, childPath, nil) walk(child.Interface(), branch, childPath, visitor) } case reflect.Map: for _, key := range nodeValue.MapKeys() { child := nodeValue.MapIndex(key) childPath := append(path, key.String()) visitor(child, branch, childPath, nil) walk(child.Interface(), branch, childPath, visitor) } } }
walker.go
0.738198
0.449997
walker.go
starcoder
package client const walletAPIDoc = `"keybase wallet api" provides a JSON API to the Keybase wallet. EXAMPLES: List the balances in all your accounts: {"method": "balances"} See payment history in an account: {"method": "history", "params": {"options": {"account-id": "<KEY>"}}} Get details about a single transaction: {"method": "details", "params": {"options": {"txid": "e5334601b9dc2a24e031ffeec2fce37bb6a8b4b51fc711d16dec04d3e64976c4"}}} Lookup the primary Stellar account ID for a user: {"method": "lookup", "params": {"options": {"name": "patrick"}}} Get the inflation destination for an account: {"method": "get-inflation", "params": {"options": {"account-id": "<KEY>"}}} Set the inflation destination for an account to the Lumenaut pool: {"method": "set-inflation", "params": {"options": {"account-id": "<KEY>", "destination": "lumenaut"}}} Set the inflation destination for an account to some other account: {"method": "set-inflation", "params": {"options": {"account-id": "<KEY>", "destination": "GD5CR6MG5R3BADYP2RUVAGC5PKCZGS4CFSAK3FYKD7WEUTRW25UH6C2J"}}} Set the inflation destination for an account to itself: {"method": "set-inflation", "params": {"options": {"account-id": "<KEY>", "destination": "self"}}} Send XLM to a Keybase user (there is no confirmation so be careful): {"method": "send", "params": {"options": {"recipient": "patrick", "amount": "1"}}} Send $10 USD worth of XLM to a Keybase user: {"method": "send", "params": {"options": {"recipient": "patrick", "amount": "10", "currency": "USD", "message": "here's the money I owe you"}}} Find a payment path to a Keybase user between two assets: {"method": "find-payment-path", "params": {"options": {"recipient": "patrick", "amount": "10", "source-asset": "native", "destination-asset": "USD/GDUKMGUGDZQK6YHYA5Z6AY2G4XDSZPSZ3SW5UN3ARVMO6QSRDWP5YLEX"}}} Send 10 AnchorUSD to a Keybase user as a path payment by converting at most 120 XLM (there is no confirmation so be careful): {"method": "send-path-payment", "params": {"options": {"recipient": "patrick", "amount": "10", "source-max-amount": "120", "source-asset": "native", "destination-asset": "USD/GDUKMGUGDZQK6YHYA5Z6AY2G4XDSZPSZ3SW5UN3ARVMO6QSRDWP5YLEX"}}} If you send XLM to a Keybase user who has not established a wallet yet, you can cancel the payment before the recipient claims it and the XLM will be returned to your account: {"method": "cancel", "params": {"options": {"txid": "e5334601b9dc2a24e031ffeec2fce37bb6a8b4b51fc711d16dec04d3e64976c4"}}} Initialize the wallet for an account: {"method": "setup-wallet"} `
go/client/wallet_api_doc.go
0.652463
0.500427
wallet_api_doc.go
starcoder
package onshape import ( "encoding/json" ) // BTFSTable953 struct for BTFSTable953 type BTFSTable953 struct { BTTable1825 BtType *string `json:"btType,omitempty"` CrossHighlightData *BTTableBaseCrossHighlightData2609 `json:"crossHighlightData,omitempty"` } // NewBTFSTable953 instantiates a new BTFSTable953 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 NewBTFSTable953() *BTFSTable953 { this := BTFSTable953{} return &this } // NewBTFSTable953WithDefaults instantiates a new BTFSTable953 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 NewBTFSTable953WithDefaults() *BTFSTable953 { this := BTFSTable953{} return &this } // GetBtType returns the BtType field value if set, zero value otherwise. func (o *BTFSTable953) GetBtType() string { if o == nil || o.BtType == nil { var ret string return ret } return *o.BtType } // GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTFSTable953) GetBtTypeOk() (*string, bool) { if o == nil || o.BtType == nil { return nil, false } return o.BtType, true } // HasBtType returns a boolean if a field has been set. func (o *BTFSTable953) HasBtType() bool { if o != nil && o.BtType != nil { return true } return false } // SetBtType gets a reference to the given string and assigns it to the BtType field. func (o *BTFSTable953) SetBtType(v string) { o.BtType = &v } // GetCrossHighlightData returns the CrossHighlightData field value if set, zero value otherwise. func (o *BTFSTable953) GetCrossHighlightData() BTTableBaseCrossHighlightData2609 { if o == nil || o.CrossHighlightData == nil { var ret BTTableBaseCrossHighlightData2609 return ret } return *o.CrossHighlightData } // GetCrossHighlightDataOk returns a tuple with the CrossHighlightData field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTFSTable953) GetCrossHighlightDataOk() (*BTTableBaseCrossHighlightData2609, bool) { if o == nil || o.CrossHighlightData == nil { return nil, false } return o.CrossHighlightData, true } // HasCrossHighlightData returns a boolean if a field has been set. func (o *BTFSTable953) HasCrossHighlightData() bool { if o != nil && o.CrossHighlightData != nil { return true } return false } // SetCrossHighlightData gets a reference to the given BTTableBaseCrossHighlightData2609 and assigns it to the CrossHighlightData field. func (o *BTFSTable953) SetCrossHighlightData(v BTTableBaseCrossHighlightData2609) { o.CrossHighlightData = &v } func (o BTFSTable953) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} serializedBTTable1825, errBTTable1825 := json.Marshal(o.BTTable1825) if errBTTable1825 != nil { return []byte{}, errBTTable1825 } errBTTable1825 = json.Unmarshal([]byte(serializedBTTable1825), &toSerialize) if errBTTable1825 != nil { return []byte{}, errBTTable1825 } if o.BtType != nil { toSerialize["btType"] = o.BtType } if o.CrossHighlightData != nil { toSerialize["crossHighlightData"] = o.CrossHighlightData } return json.Marshal(toSerialize) } type NullableBTFSTable953 struct { value *BTFSTable953 isSet bool } func (v NullableBTFSTable953) Get() *BTFSTable953 { return v.value } func (v *NullableBTFSTable953) Set(val *BTFSTable953) { v.value = val v.isSet = true } func (v NullableBTFSTable953) IsSet() bool { return v.isSet } func (v *NullableBTFSTable953) Unset() { v.value = nil v.isSet = false } func NewNullableBTFSTable953(val *BTFSTable953) *NullableBTFSTable953 { return &NullableBTFSTable953{value: val, isSet: true} } func (v NullableBTFSTable953) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBTFSTable953) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
onshape/model_btfs_table_953.go
0.694095
0.528533
model_btfs_table_953.go
starcoder
package main import ( "fmt" "math" "os" "strconv" "strings" ) /*Parse control characters: uppercase letter: absolute coordinates : 0 lowercase letter: relative coordinates : 1 not a control character: 2 */ func IsControlCharacter(controlCharacter string) (controlValue int) { switch { case controlCharacter == "M": return 0 case controlCharacter == "m": return 1 case controlCharacter == "L": return 0 case controlCharacter == "l": return 1 } return 2 } /* convert string coordinate pair to x, y values*/ func ConvertStringCoordinate(coordinateString string) (xValue float64, yValue float64) { xyStr := strings.Split(coordinateString, ",") xValue, xerr := strconv.ParseFloat(xyStr[0], 64) //parsed x values yValue, yerr := strconv.ParseFloat(xyStr[1], 64) //parsed x values if xerr != nil || yerr != nil { fmt.Println("Error pasing string") os.Exit(0) } return } /*Read coordinate metadata*/ func ReadCoordinate(fileName string) (splitString []string) { file, err := os.Open(fileName) // For read access. if err != nil { fmt.Println("Error opening file", file) } defer file.Close() data := make([]byte, 10000000) count, err := file.Read(data) if err != nil { fmt.Println("Error reading file", file) } readString := string(data[:count]) splitString = strings.Split(readString, " ") return splitString } /* M 31.9492,20.3438 l 26.4102,0 6.9297,0.1406 */ func ParseStringCoordinate(readString []string) (x_axis []float64, y_axis []float64) { //fmt.Println(readString, len(readString)) x_axis, y_axis = make([]float64, 0), make([]float64, 0) absFlag := true //use absolute coordinate needOffset := false //offset is needed when m/l is encountered after M/L //setRef := false //set xRef, yRef when M/L is encounterred xRef, yRef := 0.0, 0.0 //yRef := 0.0 for _, str := range readString { if IsControlCharacter(str) == 0 { absFlag = true //fmt.Println("+++++++++", str) } else if IsControlCharacter(str) == 1 { absFlag = false needOffset = true //fmt.Println("*********", str) } else { //case 2: //fmt.Println("before", len(x_axis)) x, y := ConvertStringCoordinate(str) //fmt.Println("---------", str) if absFlag { //absolute coordinate, no special treatment needed x_axis = append(x_axis, x) y_axis = append(y_axis, y) xRef, yRef = x, y //yRef = y absFlag = false } else { if needOffset { x += xRef y += yRef needOffset = false } else { //relative values x += x_axis[len(x_axis)-1] y += y_axis[len(y_axis)-1] } x_axis, y_axis = append(x_axis, x), append(y_axis, y) //y_axis = append(y_axis, y) } //fmt.Println("parsed value: ", x, " ,", y) //fmt.Println("after", len(x_axis)) } } //fmt.Println(x_axis) //fmt.Println(y_axis) return } /* Translate pixel coordinates to actual coordinates Needed: reference points for lower left conor and upper right conor */ func TranslatePixelCoordinate(linear bool, startEndValues []float64, startEndPixels []float64, pixelsIn []float64) (actualCoordinates []float64) { actualCoordinates = make([]float64, 0) transCoordinate := 0.0 for _, pixelValue := range pixelsIn { if linear { transCoordinate = (pixelValue-startEndPixels[0])*(startEndValues[1]-startEndValues[0])/ (startEndPixels[1]-startEndPixels[0]) + startEndValues[0] } else { //logrithmic //their powers are linear coordinateRatio := (pixelValue-startEndPixels[0])*(math.Log10(startEndValues[1])-math.Log10(startEndValues[0]))/ (startEndPixels[1]-startEndPixels[0]) + math.Log10(startEndValues[0]) transCoordinate = math.Pow(10, coordinateRatio) } actualCoordinates = append(actualCoordinates, transCoordinate) } return } func WriteActualXY2File(fileName string, inValues []float64) { outFile, err := os.Create(fmt.Sprintf("%s.csv", fileName)) if err != nil { fmt.Println("Error creating file", outFile) } defer outFile.Close() precision := 6 for _, val := range inValues { fmt.Fprintf(outFile, "%s\n", strconv.FormatFloat(val, 'f', precision, 64)) } } func main() { pixelXAxis, pixelYAxis := make([]float64, 0), make([]float64, 0) startXPixel, endXPixel, startXValue, endXValue := 31.9492, 1602.0892, 0.01, 100000000.0 startYPixel, endYPixel, startYValue, endYValue := 20.0547, 435.6487, 0.0, 0.1 keyfix := "pdf" inputString := ReadCoordinate(fmt.Sprintf("coordinate_%s.data", keyfix)) pixelXAxis, pixelYAxis = ParseStringCoordinate(inputString) xAxis := TranslatePixelCoordinate(false, []float64{startXValue, endXValue}, []float64{startXPixel, endXPixel}, pixelXAxis) yAxis := TranslatePixelCoordinate(true, []float64{startYValue, endYValue}, []float64{startYPixel, endYPixel}, pixelYAxis) WriteActualXY2File("x", xAxis) WriteActualXY2File("y", yAxis) }
xparser.go
0.619817
0.405566
xparser.go
starcoder
package asciistat import ( "fmt" "io" "math" "sort" ) var symbols = []struct { p float64 r rune }{ {0.50, 'M'}, {0.25, '['}, {0.75, ']'}, {0.98, '}'}, {0.99, '>'}, {0.90, '|'}, {0.95, ')'}, } // Percentil represents a percentil value. type Percentil struct { P float64 // Percentil in [0, 1] V float64 // Value S rune // Symbol to display } // Data is a named list of integers. type Data struct { Name string Values []int } // https://en.wikipedia.org/wiki/Quantile formula R-8 func quantile(x []int, p float64) float64 { N := float64(len(x)) if N == 0 { return 0 } else if N == 1 { return float64(x[0]) } if p < 2.0/(3.0*(N+1.0/3.0)) { return float64(x[0]) } if p >= (N-1.0/3.0)/(N+1.0/3.0) { return float64(x[len(x)-1]) } h := (N+1.0/3.0)*p + 1.0/3.0 fh := math.Floor(h) xl := x[int(fh)-1] xr := x[int(fh)] return float64(xl) + (h-fh)*float64(xr-xl) } const maxInt = int(^uint(0) >> 1) const minInt = -maxInt - 1 // Plot the given measurement to w. The full (labels+graph) plot has the given // width. If log than a logarithmic axis is used if possible. func Plot(w io.Writer, measurements []Data, unit string, log bool, width int) { // Sort input data end determine overall data range. min, max := maxInt, minInt labelLen := 0 for i := range measurements { if k := len(measurements[i].Name); k > labelLen { labelLen = k } if len(measurements[i].Values) == 0 { continue } sort.Ints(measurements[i].Values) if measurements[i].Values[0] < min { min = measurements[i].Values[0] } n := len(measurements[i].Values) - 1 if measurements[i].Values[n] > max { max = measurements[i].Values[n] } } if min == max { min -= 1 max += 1 } if min == 0 || max == 0 || min*max < 0 { log = false } if log { plotLog(w, measurements, unit, width, labelLen, min, max) } else { plotLin(w, measurements, unit, width, labelLen, min, max) } fmt.Fprintln(w, "Percentils: [=25, M=50, ]=75, |=90, )=95, }=98, >=99") } func plotData(w io.Writer, measurements []Data, screen func(x float64) int, dWidth, labelLen int) { // Plot all measurements. for _, m := range measurements { fmt.Fprintf(w, "%*s: ", labelLen, m.Name) b := make([]rune, dWidth) for i := range b { b[i] = ' ' } a, e := screen(float64(m.Values[0])), screen(float64(m.Values[len(m.Values)-1])) for i := a; i < e; i++ { b[i] = '-' } for _, sym := range symbols { q := quantile(m.Values, sym.p) i := screen(q) b[i] = sym.r } fmt.Fprintln(w, string(b)) } } // ---------------------------------------------------------------------------- // Logarithmic scales func plotLog(w io.Writer, measurements []Data, unit string, width, labelLen int, min, max int) error { min, max = roundDown(min), roundUp(max) max += max / 20 dWidth := width - labelLen - 5 logmin, logmax := math.Log(float64(min)), math.Log(float64(max)) logRange := logmax - logmin screen := func(x float64) int { x = math.Log(x) x -= logmin x /= logRange return int(x*float64(dWidth) + 0.5) } plotData(w, measurements, screen, dWidth, labelLen) // Plot scale. b := make([]rune, dWidth+4) // 2 extra on left and right t := make([]rune, dWidth+4) // labels for i := range b { b[i] = '-' t[i] = ' ' } for x := 1; x <= max; x *= 10 { for mtics := 1; mtics <= 3; mtics++ { i := screen(float64(mtics*x)) + 2 // offset from above if i < 0 || i >= len(b) { continue } b[i] = '+' if mtics == 1 || (mtics == 2 && logRange < 4) || (mtics == 3 && logRange < 3) { label := niceloglabel(mtics * x) ll := len(label) if i-ll/2 >= 0 && i-ll/2+ll < len(t) { for j, r := range label { t[i-ll/2+j] = r } } } } } fmt.Fprintf(w, "%*s ", labelLen, "") fmt.Fprintln(w, string(b)) fmt.Fprintf(w, "%*s ", labelLen, "["+unit+"]") fmt.Fprintln(w, string(t)) return nil } func roundUp(max int) int { logmax := math.Log10(float64(max)) lmi := math.Floor(logmax) lmr := logmax - lmi var f int if lmr < 0.002 { f = 1 } else if lmr < 0.301 { f = 2 } else if lmr < 0.477 { f = 3 } else if lmr < 0.698 { f = 5 } else { f = 10 } return f * int(math.Pow10(int(lmi))) // BUG: may overflow } func roundDown(max int) int { logmax := math.Log10(float64(max)) lmi := math.Floor(logmax) lmr := logmax - lmi var f int if lmr > 0.698 { f = 5 } else if lmr > 0.477 { f = 3 } else if lmr > 0.301 { f = 2 } else { f = 1 } return f * int(math.Pow10(int(lmi))) // BUG: may underflow } func niceloglabel(x int) string { if x < 1e3 { return fmt.Sprintf("%d", x) } else if x < 1e6 { return fmt.Sprintf("%dk", x/1e3) } else if x < 1e9 { return fmt.Sprintf("%dM", x/1e6) } else if x < 1e12 { return fmt.Sprintf("%dG", x/1e9) } return fmt.Sprintf("%dT", x/1e12) } // ---------------------------------------------------------------------------- // Linear scales func plotLin(w io.Writer, measurements []Data, unit string, width, labelLen int, min, max int) error { // Data to screen coordinates. dRange := float64(max - min) dWidth := width - labelLen - 5 gap := float64(dRange) / 20 screen := func(x float64) int { x -= float64(min) - gap x /= (dRange + 2*gap) return int(x*float64(dWidth) + 0.5) } plotData(w, measurements, screen, dWidth, labelLen) // Plot scale. b := make([]rune, dWidth+4) // 2 extra left and right t := make([]rune, dWidth+4) // labels for i := range b { b[i] = '-' t[i] = ' ' } // Tick labels are of the form .01, 1, 10, 100, 1e3, 1e4 so they are 3 runes wide. // Tics need to be spaced " 0.3 " so a label is 9 rune wide, except first and // last which are only 5 wide. So n lables are 2*5 + 9*(n-2) wide which must // fit into dWidth: // dWidth >= 2*5 + 9*(n-2) // dWidth-10 >= 9*(n-2) // (dWidth-10)/9 >= n - 2 // n <= (dWidth-10)/9 + 2 numLab := int(float64(dWidth-10)/9 + 2) step := (dRange + 2*gap) / float64(numLab-1) // Increase step to be of the form {1,2,5} * 10^n: n := int(math.Log10(step)) ord := int(math.Pow10(n)) step /= float64(ord) var delta int if step <= 1.2 { delta = ord } else if step <= 2.4 { delta = 2 * ord } else if step < 8 { delta = 5 * ord } else { ord *= 10 delta = ord } for x := delta * (min / delta); x <= max; x += delta { i := screen(float64(x)) + 2 // offset from above if i < 0 || i >= len(b) { continue } b[i] = '+' label := nicelabel(x, ord) ll := len(label) if i-ll/2 >= 0 && i-ll/2+ll < len(t) { for j, r := range label { t[i-ll/2+j] = r } } } fmt.Fprintf(w, "%*s ", labelLen, "") fmt.Fprintln(w, string(b)) fmt.Fprintf(w, "%*s ", labelLen, "["+unit+"]") fmt.Fprintln(w, string(t)) return nil } func nicelabel(x int, ord int) string { if x <= 9999 || ord == 1 { return fmt.Sprintf("%d", x) } unit := "" scale := 1 if x < 1e6 { unit = "k" scale = 1e3 } else if x < 1e9 { unit = "M" scale = 1e6 } else if x < 1e12 { unit = "G" scale = 1e9 } else { return fmt.Sprintf("%g", float64(x)) } if ord >= scale { return fmt.Sprintf("%d%s", x/scale, unit) } else if ord >= scale/10 { return fmt.Sprintf("%.1f%s", float64(x)/float64(scale), unit) } else if ord >= scale/100 { return fmt.Sprintf("%.2f%s", float64(x)/float64(scale), unit) } else if ord >= scale/1000 { return fmt.Sprintf("%.3f%s", float64(x)/float64(scale), unit) } return fmt.Sprintf("%d", x) }
internal/asciistat/plot.go
0.633637
0.499634
plot.go
starcoder
package sort // A simple circular buffer of fixed length which has an empty and full // state. When full, the buffer will not accept any new entries. // CircularBuffer is an array of elements that is fixed in size and thus // will stop receiving new elements once full. Removing elements makes // room for new ones. Buffers may share a single underlying slice if // given lower and upper bounds that do not overlap. type CircularBuffer struct { buffer []interface{} // contains the buffer elements start int // position of first element end int // position of last element count int // number of elements } // NewCircularBuffer constructs a CircularBuffer with the given capacity. func NewCircularBuffer(capacity int) *CircularBuffer { cb := new(CircularBuffer) cb.buffer = make([]interface{}, capacity) return cb } // NewCircularBufferFromSlice constructs a CircularBuffer from the given // slice. All entries in the slice are assumed to be valid data such // that the buffer count will be equal to the length of the given slice. // If dupe is true, will create a new slice and copy the contents of // initial to that slice. func NewCircularBufferFromSlice(initial []interface{}, dupe bool) *CircularBuffer { cb := new(CircularBuffer) if dupe { cb.buffer = make([]interface{}, 0, len(initial)) copy(cb.buffer, initial) } else { cb.buffer = initial } cb.count = len(initial) return cb } // Add adds the given value to the buffer, returning true if // successful, or false if the buffer is full. func (cb *CircularBuffer) Add(e interface{}) bool { if cb.count == cap(cb.buffer) { return false } cb.count++ cb.buffer[cb.end] = e cb.end++ if cb.end == len(cb.buffer) { cb.end = 0 } return true } // Capacity returns the total number of elements this buffer can hold. func (cb *CircularBuffer) Capacity() int { return cap(cb.buffer) } // Drain moves the contents of the circular buffer into the given output // slice in an efficient manner, leaving this buffer empty. Returns the // number of elements copied to the slice. func (cb *CircularBuffer) Drain(sink []interface{}) int { if cb.count == 0 { return 0 // nothing to copy } if cap(sink)-len(sink) < cb.count { return 0 // insufficient space } if cb.end <= cb.start { // elements wrap around, must make two calls to copy() copy(sink, cb.buffer[cb.start:]) copy(sink, cb.buffer[:cb.end+1]) } else { // elements are in one contiguous region copy(sink, cb.buffer[cb.start:cb.end+1]) } cb.start = 0 cb.end = 0 count := cb.count cb.count = 0 return count } // Empty returns true if the buffer is empty, false otherwise. func (cb *CircularBuffer) Empty() bool { return cb.count == 0 } // Full returns true if the buffer is full, false otherwise. func (cb *CircularBuffer) Full() bool { return cb.count == cap(cb.buffer) } // Move removes the given number of elements from the circular buffer // and adds them to the sink buffer in an efficient manner. This is // equivalent to repeatedly removing elements from this buffer and // adding them to the sink. Returns the number of elements moved, which // may be less than requested if the origin has fewer items, or if the // sink has insufficient space. func (cb *CircularBuffer) Move(sink *CircularBuffer, count int) int { if cb.count < count { count = cb.count } if sink.Remaining() < count { count = sink.Remaining() } tocopy := count capacity := cap(cb.buffer) sapacity := cap(sink.buffer) for tocopy > 0 { // compute how much can be copied from source var available int if cb.start < cb.end { available = cb.end - cb.start } else { // wraps around, start with upper portion available = capacity - cb.start } // compute how much can be copied to sink var willfit int if sink.start <= sink.end { willfit = sapacity - sink.end } else { // wraps around willfit = sink.start - sink.end } willcopy := iMin(available, willfit) if willcopy <= 0 { break } copy(sink.buffer[sink.end:], cb.buffer[cb.start:cb.start+willcopy]) sink.end += willcopy if sink.end >= sapacity { sink.end = 0 } cb.start += willcopy if cb.start >= capacity { cb.start = 0 } tocopy -= willcopy } if tocopy > 0 { panic("failed to move circular buffer contents") } sink.count += count cb.count -= count return count } // Peek returns the first element in the buffer, without removing it. // If the buffer is empty, nil is returned. func (cb *CircularBuffer) Peek() interface{} { if cb.count == 0 { return nil } return cb.buffer[cb.start] } // Remove removes the first element in the buffer, reducing the // number of elements in the buffer by one. If the buffer is // empty, nil is returned. func (cb *CircularBuffer) Remove() interface{} { if cb.count == 0 { return nil } cb.count-- e := cb.buffer[cb.start] cb.start++ if cb.start == cap(cb.buffer) { cb.start = 0 } return e } // Remaining returns the number of empty spaces within this buffer. func (cb *CircularBuffer) Remaining() int { return cap(cb.buffer) - cb.count } // Size returns the number of elements in the circular buffer. func (cb *CircularBuffer) Size() int { return cb.count }
sort/circularbuffer.go
0.818084
0.596492
circularbuffer.go
starcoder
package tbox import ( "math" ) func min(x, y float64) float64 { if x > y { return y } return x } func max(x, y float64) float64 { if x > y { return x } return y } // Tile ... type Tile struct { Z, X, Y int } // BoundingBox ... type BoundingBox struct { MinLng, MinLat, MaxLng, MaxLat float64 } // Bbox returns the bounding box of a given Tile func (t Tile) Bbox() BoundingBox { return BoundingBox{ MaxLat: tileToLat(t.Y, t.Z), MinLng: tileToLng(t.X, t.Z), MinLat: tileToLat(t.Y+1, t.Z), MaxLng: tileToLng(t.X+1, t.Z), } } // FromBounds returns all tiles of a certain zoom level that intersect an input // bounding box func FromBounds(b BoundingBox, z int) ([]Tile, error) { Z := int(math.Pow(2, float64(z))) var bbs []BoundingBox if b.MinLng > b.MaxLng { bbw := BoundingBox{MaxLat: b.MaxLat, MaxLng: b.MaxLng, MinLng: -180.0, MinLat: b.MinLat} bbe := BoundingBox{MaxLat: b.MaxLat, MaxLng: 180.0, MinLng: b.MinLng, MinLat: b.MinLat} bbs = []BoundingBox{bbw, bbe} } else { bbs = []BoundingBox{b} } var tiles []Tile for _, bb := range bbs { minlng := max(-180.0, bb.MinLng) minlat := max(-85.0, bb.MinLat) maxlng := min(180.0, bb.MaxLng) maxlat := min(85.0, bb.MaxLat) ult, err := Point{Lng: minlng, Lat: maxlat}.ToTile(z) if err != nil { return nil, err } lrt, err := Point{Lng: maxlng, Lat: minlat}.ToTile(z) if err != nil { return nil, err } for i := ult.X; i <= lrt.X; i++ { for j := ult.Y; j <= lrt.Y; j++ { // ignore coordinates >= 2 ** zoom if i >= Z { continue } if j >= Z { continue } tile := Tile{X: i, Y: j, Z: z} tiles = append(tiles, tile) } } } return tiles, nil } // Contains valides whether a given Point is within a given Tile func (t Tile) Contains(p Point) (bool, error) { if !p.Valid() { return false, &invalidPointError{p: p, msg: "invalid point"} } tbox := t.Bbox() return p.Lat > tbox.MinLat && p.Lat < tbox.MaxLat && p.Lng > tbox.MinLng && p.Lng < tbox.MaxLng, nil } // Center returns the centerpoint of a given Tile func (t Tile) Center() Point { tbox := t.Bbox() cLng := tbox.MinLng + (tbox.MaxLng-tbox.MinLng)/2 cLat := tbox.MinLat + (tbox.MaxLat-tbox.MinLat)/2 return Point{Lng: cLng, Lat: cLat} } // Children returns the four children tiles of the input tile func (t Tile) Children() [4]Tile { x := t.X y := t.Y z := t.Z return [4]Tile{ {X: x * 2, Y: y * 2, Z: z + 1}, {X: x*2 + 1, Y: y * 2, Z: z + 1}, {X: x * 2, Y: y*2 + 1, Z: z + 1}, {X: x*2 + 1, Y: y*2 + 1, Z: z + 1}, } } // Parent returns the parent tile of the input tile func (t Tile) Parent() Tile { x := t.X y := t.Y z := t.Z if z == 0 { return t } if x%2 == 0 && y%2 == 0 { return Tile{Z: z - 1, X: x / 2, Y: y / 2} } else if x%2 == 0 { return Tile{Z: z - 1, X: x / 2, Y: (y - 1) / 2} } else if x%2 != 0 && y%2 == 0 { return Tile{Z: z - 1, X: (x - 1) / 2, Y: y / 2} } else { return Tile{Z: z - 1, X: (x - 1) / 2, Y: (y - 1) / 2} } }
tile.go
0.862757
0.596227
tile.go
starcoder
package rook import ( "fmt" ) type NRook struct { MaxRook int Combination []Board Board *Board UniqueMap map[string]int } //Board is the main struct of rook type Board struct { Cell map[Coordinate]CellState Properties } type Properties struct { Size Size } //Size is the rook size struct type Size struct { X int Y int } type Coordinate [2]int type CellState string const ( CellStateEmpty CellState = " " CellStateWall CellState = "#" CellStateRook CellState = "*" ) //NewNRook is initializing the n rook problem solution func NewNRook() *NRook { return &NRook{ MaxRook: 0, Combination: nil, Board: &Board{}, UniqueMap: make(map[string]int), } } //SetUsingTemplate is for set the rook with custom or defined rook template func (b *Board) SetUsingTemplate(board [][]CellState) { b.setSize(len(board), len(board[0])) b.Cell = make(map[Coordinate]CellState, len(board)*len(board[0])) for y := 0; y < len(board); y++ { for x := 0; x < len(board[y]); x++ { switch board[y][x] { case CellStateEmpty: b.SetEmpty(x, y) case CellStateRook: b.SetRook(x, y) case CellStateWall: b.SetWall(x, y) } } } } //PrintBoard is for printing the rook func (b *Board) PrintBoard() { for y := 0; y < b.Size.Y; y++ { for x := 0; x < b.Size.X; x++ { fmt.Print(b.State(x, y)) } fmt.Println() } fmt.Println("========") } //ToString is for turn board cell to string func (b *Board) ToString() (s string) { for y := 0; y < b.Size.Y; y++ { for x := 0; x < b.Size.X; x++ { s += string(b.State(x, y)) } } return } //SetSize is set the rook's size func (b *Board) setSize(y, x int) { b.Size.Y = y b.Size.X = x } //SetRook is for filling the rook func (b *Board) SetRook(x, y int) { coordinate := [2]int{x, y} b.Cell[coordinate] = CellStateRook } //IsRook is for checking if the coordinate is filled with rook func (b *Board) IsRook(x, y int) bool { coordinate := [2]int{x, y} return b.Cell[coordinate] == CellStateRook } //SetEmpty is for placing the empty cell to the rook func (b *Board) SetEmpty(x, y int) { coordinate := [2]int{x, y} b.Cell[coordinate] = CellStateEmpty } //IsEmpty is for checking if the coordinate is empty func (b *Board) IsEmpty(x, y int) bool { coordinate := [2]int{x, y} return b.Cell[coordinate] == CellStateEmpty } //SetWall is for placing the wall to the rook func (b *Board) SetWall(x, y int) { coordinate := [2]int{x, y} b.Cell[coordinate] = CellStateWall } //IsWall is for checking if the coordinate is walled func (b *Board) IsWall(x, y int) bool { coordinate := [2]int{x, y} return b.Cell[coordinate] == CellStateWall } //State is used for getting the cell state func (b *Board) State(x, y int) CellState { coordinate := [2]int{x, y} return b.Cell[coordinate] } func (b *Board) IsAboveOK(x, y int) bool { for i := y - 1; i >= 0; i-- { switch b.State(x, i) { case CellStateEmpty: continue case CellStateWall: return true case CellStateRook: return false } } return true } func (b *Board) IsLeftOK(x, y int) bool { for i := x - 1; i >= 0; i-- { switch b.State(i, y) { case CellStateEmpty: continue case CellStateWall: return true case CellStateRook: return false } } return true } //Calculate is for searching the combination and total filled func (r *NRook) Calculate(startX, startY int) { for y := startY; y < r.Board.Size.Y; y++ { for x := startX; x < r.Board.Size.X; x++ { if !r.Board.IsEmpty(x, y) || !r.Board.IsLeftOK(x, y) || !r.Board.IsAboveOK(x, y) { continue } r.Board.SetRook(x, y) r.Calculate(x, y) r.Board.SetEmpty(x, y) } startX = 0 } n := r.Board.CountFilled() if n > r.MaxRook { r.MaxRook = n r.Combination = nil } if n == r.MaxRook { if _, ok := r.UniqueMap[r.Board.ToString()]; !ok { r.UniqueMap[r.Board.ToString()]++ r.Combination = append(r.Combination, *r.Board.DuplicateBoard()) } } } //CountFilled is for counting Filled cell in board func (b *Board) CountFilled() (n int) { for y := 0; y < b.Size.Y; y++ { for x := 0; x < b.Size.X; x++ { if b.IsRook(x, y) { n++ } } } return } //DuplicateBoard is for duplicating board func (b *Board) DuplicateBoard() *Board { var newBoard Board newBoard.setSize(b.Size.Y, b.Size.X) newBoard.Cell = make(map[Coordinate]CellState, b.Size.Y*b.Size.X) for y := 0; y < b.Size.Y; y++ { for x := 0; x < b.Size.X; x++ { switch b.State(x, y) { case CellStateEmpty: newBoard.SetEmpty(x, y) case CellStateRook: newBoard.SetRook(x, y) case CellStateWall: newBoard.SetWall(x, y) } } } return &newBoard }
rook/rook.go
0.552057
0.506958
rook.go
starcoder
package iterator import ( "sync/atomic" "github.com/apache/arrow/go/arrow" "github.com/apache/arrow/go/arrow/array" "github.com/go-bullseye/bullseye/internal/debug" ) // Int64ValueIterator is an iterator for reading an Arrow Column value by value. type Int64ValueIterator struct { refCount int64 chunkIterator *Int64ChunkIterator // Things we need to maintain for the iterator index int // current value index values []int64 // current chunk values ref *array.Int64 // the chunk reference done bool // there are no more elements for this iterator } // NewInt64ValueIterator creates a new Int64ValueIterator for reading an Arrow Column. func NewInt64ValueIterator(col *array.Column) *Int64ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewInt64ChunkIterator(col) return &Int64ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Int64ValueIterator) Value() (int64, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Int64ValueIterator) ValuePointer() *int64 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Int64ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Int64ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Int64ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Int64ValueIterator. func (vr *Int64ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Int64ValueIterator. func (vr *Int64ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Uint64ValueIterator is an iterator for reading an Arrow Column value by value. type Uint64ValueIterator struct { refCount int64 chunkIterator *Uint64ChunkIterator // Things we need to maintain for the iterator index int // current value index values []uint64 // current chunk values ref *array.Uint64 // the chunk reference done bool // there are no more elements for this iterator } // NewUint64ValueIterator creates a new Uint64ValueIterator for reading an Arrow Column. func NewUint64ValueIterator(col *array.Column) *Uint64ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewUint64ChunkIterator(col) return &Uint64ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Uint64ValueIterator) Value() (uint64, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Uint64ValueIterator) ValuePointer() *uint64 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Uint64ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Uint64ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Uint64ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Uint64ValueIterator. func (vr *Uint64ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Uint64ValueIterator. func (vr *Uint64ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Float64ValueIterator is an iterator for reading an Arrow Column value by value. type Float64ValueIterator struct { refCount int64 chunkIterator *Float64ChunkIterator // Things we need to maintain for the iterator index int // current value index values []float64 // current chunk values ref *array.Float64 // the chunk reference done bool // there are no more elements for this iterator } // NewFloat64ValueIterator creates a new Float64ValueIterator for reading an Arrow Column. func NewFloat64ValueIterator(col *array.Column) *Float64ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewFloat64ChunkIterator(col) return &Float64ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Float64ValueIterator) Value() (float64, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Float64ValueIterator) ValuePointer() *float64 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Float64ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Float64ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Float64ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Float64ValueIterator. func (vr *Float64ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Float64ValueIterator. func (vr *Float64ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Int32ValueIterator is an iterator for reading an Arrow Column value by value. type Int32ValueIterator struct { refCount int64 chunkIterator *Int32ChunkIterator // Things we need to maintain for the iterator index int // current value index values []int32 // current chunk values ref *array.Int32 // the chunk reference done bool // there are no more elements for this iterator } // NewInt32ValueIterator creates a new Int32ValueIterator for reading an Arrow Column. func NewInt32ValueIterator(col *array.Column) *Int32ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewInt32ChunkIterator(col) return &Int32ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Int32ValueIterator) Value() (int32, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Int32ValueIterator) ValuePointer() *int32 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Int32ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Int32ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Int32ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Int32ValueIterator. func (vr *Int32ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Int32ValueIterator. func (vr *Int32ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Uint32ValueIterator is an iterator for reading an Arrow Column value by value. type Uint32ValueIterator struct { refCount int64 chunkIterator *Uint32ChunkIterator // Things we need to maintain for the iterator index int // current value index values []uint32 // current chunk values ref *array.Uint32 // the chunk reference done bool // there are no more elements for this iterator } // NewUint32ValueIterator creates a new Uint32ValueIterator for reading an Arrow Column. func NewUint32ValueIterator(col *array.Column) *Uint32ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewUint32ChunkIterator(col) return &Uint32ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Uint32ValueIterator) Value() (uint32, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Uint32ValueIterator) ValuePointer() *uint32 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Uint32ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Uint32ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Uint32ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Uint32ValueIterator. func (vr *Uint32ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Uint32ValueIterator. func (vr *Uint32ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Float32ValueIterator is an iterator for reading an Arrow Column value by value. type Float32ValueIterator struct { refCount int64 chunkIterator *Float32ChunkIterator // Things we need to maintain for the iterator index int // current value index values []float32 // current chunk values ref *array.Float32 // the chunk reference done bool // there are no more elements for this iterator } // NewFloat32ValueIterator creates a new Float32ValueIterator for reading an Arrow Column. func NewFloat32ValueIterator(col *array.Column) *Float32ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewFloat32ChunkIterator(col) return &Float32ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Float32ValueIterator) Value() (float32, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Float32ValueIterator) ValuePointer() *float32 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Float32ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Float32ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Float32ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Float32ValueIterator. func (vr *Float32ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Float32ValueIterator. func (vr *Float32ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Int16ValueIterator is an iterator for reading an Arrow Column value by value. type Int16ValueIterator struct { refCount int64 chunkIterator *Int16ChunkIterator // Things we need to maintain for the iterator index int // current value index values []int16 // current chunk values ref *array.Int16 // the chunk reference done bool // there are no more elements for this iterator } // NewInt16ValueIterator creates a new Int16ValueIterator for reading an Arrow Column. func NewInt16ValueIterator(col *array.Column) *Int16ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewInt16ChunkIterator(col) return &Int16ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Int16ValueIterator) Value() (int16, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Int16ValueIterator) ValuePointer() *int16 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Int16ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Int16ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Int16ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Int16ValueIterator. func (vr *Int16ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Int16ValueIterator. func (vr *Int16ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Uint16ValueIterator is an iterator for reading an Arrow Column value by value. type Uint16ValueIterator struct { refCount int64 chunkIterator *Uint16ChunkIterator // Things we need to maintain for the iterator index int // current value index values []uint16 // current chunk values ref *array.Uint16 // the chunk reference done bool // there are no more elements for this iterator } // NewUint16ValueIterator creates a new Uint16ValueIterator for reading an Arrow Column. func NewUint16ValueIterator(col *array.Column) *Uint16ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewUint16ChunkIterator(col) return &Uint16ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Uint16ValueIterator) Value() (uint16, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Uint16ValueIterator) ValuePointer() *uint16 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Uint16ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Uint16ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Uint16ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Uint16ValueIterator. func (vr *Uint16ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Uint16ValueIterator. func (vr *Uint16ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Int8ValueIterator is an iterator for reading an Arrow Column value by value. type Int8ValueIterator struct { refCount int64 chunkIterator *Int8ChunkIterator // Things we need to maintain for the iterator index int // current value index values []int8 // current chunk values ref *array.Int8 // the chunk reference done bool // there are no more elements for this iterator } // NewInt8ValueIterator creates a new Int8ValueIterator for reading an Arrow Column. func NewInt8ValueIterator(col *array.Column) *Int8ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewInt8ChunkIterator(col) return &Int8ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Int8ValueIterator) Value() (int8, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Int8ValueIterator) ValuePointer() *int8 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Int8ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Int8ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Int8ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Int8ValueIterator. func (vr *Int8ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Int8ValueIterator. func (vr *Int8ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Uint8ValueIterator is an iterator for reading an Arrow Column value by value. type Uint8ValueIterator struct { refCount int64 chunkIterator *Uint8ChunkIterator // Things we need to maintain for the iterator index int // current value index values []uint8 // current chunk values ref *array.Uint8 // the chunk reference done bool // there are no more elements for this iterator } // NewUint8ValueIterator creates a new Uint8ValueIterator for reading an Arrow Column. func NewUint8ValueIterator(col *array.Column) *Uint8ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewUint8ChunkIterator(col) return &Uint8ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Uint8ValueIterator) Value() (uint8, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Uint8ValueIterator) ValuePointer() *uint8 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Uint8ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Uint8ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Uint8ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Uint8ValueIterator. func (vr *Uint8ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Uint8ValueIterator. func (vr *Uint8ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // TimestampValueIterator is an iterator for reading an Arrow Column value by value. type TimestampValueIterator struct { refCount int64 chunkIterator *TimestampChunkIterator // Things we need to maintain for the iterator index int // current value index values []arrow.Timestamp // current chunk values ref *array.Timestamp // the chunk reference done bool // there are no more elements for this iterator } // NewTimestampValueIterator creates a new TimestampValueIterator for reading an Arrow Column. func NewTimestampValueIterator(col *array.Column) *TimestampValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewTimestampChunkIterator(col) return &TimestampValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *TimestampValueIterator) Value() (arrow.Timestamp, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *TimestampValueIterator) ValuePointer() *arrow.Timestamp { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *TimestampValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *TimestampValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *TimestampValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the TimestampValueIterator. func (vr *TimestampValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the TimestampValueIterator. func (vr *TimestampValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Time32ValueIterator is an iterator for reading an Arrow Column value by value. type Time32ValueIterator struct { refCount int64 chunkIterator *Time32ChunkIterator // Things we need to maintain for the iterator index int // current value index values []arrow.Time32 // current chunk values ref *array.Time32 // the chunk reference done bool // there are no more elements for this iterator } // NewTime32ValueIterator creates a new Time32ValueIterator for reading an Arrow Column. func NewTime32ValueIterator(col *array.Column) *Time32ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewTime32ChunkIterator(col) return &Time32ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Time32ValueIterator) Value() (arrow.Time32, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Time32ValueIterator) ValuePointer() *arrow.Time32 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Time32ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Time32ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Time32ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Time32ValueIterator. func (vr *Time32ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Time32ValueIterator. func (vr *Time32ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Time64ValueIterator is an iterator for reading an Arrow Column value by value. type Time64ValueIterator struct { refCount int64 chunkIterator *Time64ChunkIterator // Things we need to maintain for the iterator index int // current value index values []arrow.Time64 // current chunk values ref *array.Time64 // the chunk reference done bool // there are no more elements for this iterator } // NewTime64ValueIterator creates a new Time64ValueIterator for reading an Arrow Column. func NewTime64ValueIterator(col *array.Column) *Time64ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewTime64ChunkIterator(col) return &Time64ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Time64ValueIterator) Value() (arrow.Time64, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Time64ValueIterator) ValuePointer() *arrow.Time64 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Time64ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Time64ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Time64ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Time64ValueIterator. func (vr *Time64ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Time64ValueIterator. func (vr *Time64ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Date32ValueIterator is an iterator for reading an Arrow Column value by value. type Date32ValueIterator struct { refCount int64 chunkIterator *Date32ChunkIterator // Things we need to maintain for the iterator index int // current value index values []arrow.Date32 // current chunk values ref *array.Date32 // the chunk reference done bool // there are no more elements for this iterator } // NewDate32ValueIterator creates a new Date32ValueIterator for reading an Arrow Column. func NewDate32ValueIterator(col *array.Column) *Date32ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewDate32ChunkIterator(col) return &Date32ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Date32ValueIterator) Value() (arrow.Date32, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Date32ValueIterator) ValuePointer() *arrow.Date32 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Date32ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Date32ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Date32ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Date32ValueIterator. func (vr *Date32ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Date32ValueIterator. func (vr *Date32ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } } // Date64ValueIterator is an iterator for reading an Arrow Column value by value. type Date64ValueIterator struct { refCount int64 chunkIterator *Date64ChunkIterator // Things we need to maintain for the iterator index int // current value index values []arrow.Date64 // current chunk values ref *array.Date64 // the chunk reference done bool // there are no more elements for this iterator } // NewDate64ValueIterator creates a new Date64ValueIterator for reading an Arrow Column. func NewDate64ValueIterator(col *array.Column) *Date64ValueIterator { // We need a ChunkIterator to read the chunks chunkIterator := NewDate64ChunkIterator(col) return &Date64ValueIterator{ refCount: 1, chunkIterator: chunkIterator, index: 0, values: nil, } } // Value will return the current value that the iterator is on and boolean value indicating if the value is actually null. func (vr *Date64ValueIterator) Value() (arrow.Date64, bool) { return vr.values[vr.index], vr.ref.IsNull(vr.index) } // ValuePointer will return a pointer to the current value that the iterator is on. It will return nil if the value is actually null. func (vr *Date64ValueIterator) ValuePointer() *arrow.Date64 { if vr.ref.IsNull(vr.index) { return nil } return &vr.values[vr.index] } // ValueInterface returns the current value as an interface{}. func (vr *Date64ValueIterator) ValueInterface() interface{} { if vr.ref.IsNull(vr.index) { return nil } return vr.values[vr.index] } // Next moves the iterator to the next value. This will return false // when there are no more values. func (vr *Date64ValueIterator) Next() bool { if vr.done { return false } // Move the index up vr.index++ // Keep moving the chunk up until we get one with data for vr.values == nil || vr.index >= len(vr.values) { if !vr.nextChunk() { // There were no more chunks with data in them vr.done = true return false } } return true } func (vr *Date64ValueIterator) nextChunk() bool { // Advance the chunk until we get one with data in it or we are done if !vr.chunkIterator.Next() { // No more chunks return false } // There was another chunk. // We maintain the ref and the values because the ref is going to allow us to retain the memory. ref := vr.chunkIterator.Chunk() ref.Retain() if vr.ref != nil { vr.ref.Release() } vr.ref = ref vr.values = vr.chunkIterator.ChunkValues() vr.index = 0 return true } // Retain keeps a reference to the Date64ValueIterator. func (vr *Date64ValueIterator) Retain() { atomic.AddInt64(&vr.refCount, 1) } // Release removes a reference to the Date64ValueIterator. func (vr *Date64ValueIterator) Release() { refs := atomic.AddInt64(&vr.refCount, -1) debug.Assert(refs >= 0, "too many releases") if refs == 0 { if vr.chunkIterator != nil { vr.chunkIterator.Release() vr.chunkIterator = nil } if vr.ref != nil { vr.ref.Release() vr.ref = nil } vr.values = nil } }
iterator/valueiterator.gen.go
0.750278
0.467453
valueiterator.gen.go
starcoder
package drawing import ( "fmt" "math" ) // PathBuilder describes the interface for path drawing. type PathBuilder interface { // LastPoint returns the current point of the current sub path LastPoint() (x, y float64) // MoveTo creates a new subpath that start at the specified point MoveTo(x, y float64) // LineTo adds a line to the current subpath LineTo(x, y float64) // QuadCurveTo adds a quadratic Bézier curve to the current subpath QuadCurveTo(cx, cy, x, y float64) // CubicCurveTo adds a cubic Bézier curve to the current subpath CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) // ArcTo adds an arc to the current subpath ArcTo(cx, cy, rx, ry, startAngle, angle float64) // Close creates a line from the current point to the last MoveTo // point (if not the same) and mark the path as closed so the // first and last lines join nicely. Close() } // PathComponent represents component of a path type PathComponent int const ( // MoveToComponent is a MoveTo component in a Path MoveToComponent PathComponent = iota // LineToComponent is a LineTo component in a Path LineToComponent // QuadCurveToComponent is a QuadCurveTo component in a Path QuadCurveToComponent // CubicCurveToComponent is a CubicCurveTo component in a Path CubicCurveToComponent // ArcToComponent is a ArcTo component in a Path ArcToComponent // CloseComponent is a ArcTo component in a Path CloseComponent ) // Path stores points type Path struct { // Components is a slice of PathComponent in a Path and mark the role of each points in the Path Components []PathComponent // Points are combined with Components to have a specific role in the path Points []float64 // Last Point of the Path x, y float64 } func (p *Path) appendToPath(cmd PathComponent, points ...float64) { p.Components = append(p.Components, cmd) p.Points = append(p.Points, points...) } // LastPoint returns the current point of the current path func (p *Path) LastPoint() (x, y float64) { return p.x, p.y } // MoveTo starts a new path at (x, y) position func (p *Path) MoveTo(x, y float64) { p.appendToPath(MoveToComponent, x, y) p.x = x p.y = y } // LineTo adds a line to the current path func (p *Path) LineTo(x, y float64) { if len(p.Components) == 0 { //special case when no move has been done p.MoveTo(0, 0) } p.appendToPath(LineToComponent, x, y) p.x = x p.y = y } // QuadCurveTo adds a quadratic bezier curve to the current path func (p *Path) QuadCurveTo(cx, cy, x, y float64) { if len(p.Components) == 0 { //special case when no move has been done p.MoveTo(0, 0) } p.appendToPath(QuadCurveToComponent, cx, cy, x, y) p.x = x p.y = y } // CubicCurveTo adds a cubic bezier curve to the current path func (p *Path) CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) { if len(p.Components) == 0 { //special case when no move has been done p.MoveTo(0, 0) } p.appendToPath(CubicCurveToComponent, cx1, cy1, cx2, cy2, x, y) p.x = x p.y = y } // ArcTo adds an arc to the path func (p *Path) ArcTo(cx, cy, rx, ry, startAngle, delta float64) { endAngle := startAngle + delta clockWise := true if delta < 0 { clockWise = false } // normalize if clockWise { for endAngle < startAngle { endAngle += math.Pi * 2.0 } } else { for startAngle < endAngle { startAngle += math.Pi * 2.0 } } startX := cx + math.Cos(startAngle)*rx startY := cy + math.Sin(startAngle)*ry if len(p.Components) > 0 { p.LineTo(startX, startY) } else { p.MoveTo(startX, startY) } p.appendToPath(ArcToComponent, cx, cy, rx, ry, startAngle, delta) p.x = cx + math.Cos(endAngle)*rx p.y = cy + math.Sin(endAngle)*ry } // Close closes the current path func (p *Path) Close() { p.appendToPath(CloseComponent) } // Copy make a clone of the current path and return it func (p *Path) Copy() (dest *Path) { dest = new(Path) dest.Components = make([]PathComponent, len(p.Components)) copy(dest.Components, p.Components) dest.Points = make([]float64, len(p.Points)) copy(dest.Points, p.Points) dest.x, dest.y = p.x, p.y return dest } // Clear reset the path func (p *Path) Clear() { p.Components = p.Components[0:0] p.Points = p.Points[0:0] return } // IsEmpty returns true if the path is empty func (p *Path) IsEmpty() bool { return len(p.Components) == 0 } // String returns a debug text view of the path func (p *Path) String() string { s := "" j := 0 for _, cmd := range p.Components { switch cmd { case MoveToComponent: s += fmt.Sprintf("MoveTo: %f, %f\n", p.Points[j], p.Points[j+1]) j = j + 2 case LineToComponent: s += fmt.Sprintf("LineTo: %f, %f\n", p.Points[j], p.Points[j+1]) j = j + 2 case QuadCurveToComponent: s += fmt.Sprintf("QuadCurveTo: %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3]) j = j + 4 case CubicCurveToComponent: s += fmt.Sprintf("CubicCurveTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5]) j = j + 6 case ArcToComponent: s += fmt.Sprintf("ArcTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5]) j = j + 6 case CloseComponent: s += "Close\n" } } return s }
vendor/github.com/wcharczuk/go-chart/v2/drawing/path.go
0.745584
0.61144
path.go
starcoder
package sad import ( "encoding/binary" "fmt" "io" "io/ioutil" "github.com/jonathaningram/dark-omen/internal/audio" ) type Stream struct { LeftBlocks []audio.Block RightBlocks []audio.Block // Note: storing these so that a re-encoded stream is correct. sample 99 is // always a different value and index 99 is always equal to 99. Not sure if // sample 99 needs to end up in the decoded stream—currently it does not. leftSample99 int16 leftIndex99 int16 rightSample99 int16 rightIndex99 int16 } func (s *Stream) Channels() int { return 2 } // Decoder reads and decodes a SAD audio stream from an input stream. type Decoder struct { r io.Reader } // NewDecoder returns a new decoder that reads from r. func NewDecoder(r io.Reader) *Decoder { return &Decoder{r: r} } // Decode reads the encoded SAD audio stream from its input and returns a // new stream containing decoded left and right blocks. func (d *Decoder) Decode() (*Stream, error) { s := &Stream{ LeftBlocks: make([]audio.Block, 0), RightBlocks: make([]audio.Block, 0), } for { var bs [8]byte n, err := d.r.Read(bs[:]) if n != 8 { return nil, fmt.Errorf("could not read stereo sample and index data: read %d byte(s), expected %d", n, 8) } if err != nil { return nil, err } leftSample := int16(binary.LittleEndian.Uint16(bs[0:2])) leftIndex := int16(binary.LittleEndian.Uint16(bs[2:4])) rightSample := int16(binary.LittleEndian.Uint16(bs[4:6])) rightIndex := int16(binary.LittleEndian.Uint16(bs[6:8])) if leftIndex == 99 && rightIndex == 99 { s.leftSample99 = leftSample s.leftIndex99 = leftIndex s.rightSample99 = rightSample s.rightIndex99 = rightIndex break } const size = 1016 buf := make([]byte, size) n, err = d.r.Read(buf) if n != size { return nil, fmt.Errorf("could not read stereo ADPCM data: read %d byte(s), expected %d", n, size) } if err != nil { return nil, err } leftData := make([]byte, size/2) rightData := make([]byte, size/2) for i := 0; i < size/8; i++ { for j := 0; j < 4; j++ { leftData[i*4+j] = buf[i*8+j] } for j := 4; j < 8; j++ { rightData[i*4+j-4] = buf[i*8+j] } } s.LeftBlocks = append(s.LeftBlocks, audio.NewADPCMBlock(leftSample, leftIndex, leftData)) s.RightBlocks = append(s.RightBlocks, audio.NewADPCMBlock(rightSample, rightIndex, rightData)) } // Read remaining bytes. buf, err := ioutil.ReadAll(d.r) if err != nil { return nil, err } leftBuf := make([]int16, len(buf)/4) rightBuf := make([]int16, len(buf)/4) for i := 0; i < len(buf)/4; i++ { leftSample := int16(binary.LittleEndian.Uint16([]byte{buf[i*4], buf[i*4+1]})) rightSample := int16(binary.LittleEndian.Uint16([]byte{buf[i*4+2], buf[i*4+3]})) leftBuf[i] = leftSample rightBuf[i] = rightSample } s.LeftBlocks = append(s.LeftBlocks, audio.NewPCM16BlockFromInt16Slice(leftBuf)) s.RightBlocks = append(s.RightBlocks, audio.NewPCM16BlockFromInt16Slice(rightBuf)) return s, nil } // Encoder encodes and writes a SAD audio stream to an output stream. type Encoder struct { w io.Writer } // NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder { return &Encoder{w: w} } // Encode writes the encoded SAD audio stream to its output. func (e *Encoder) Encode(s *Stream) error { for i := 0; i < len(s.LeftBlocks)-1; i++ { leftBlock, ok := s.LeftBlocks[i].(*audio.ADPCMBlock) if !ok { return fmt.Errorf("left block at position %d is not an ADPCM block", i) } if err := binary.Write(e.w, binary.LittleEndian, leftBlock.Sample()); err != nil { return err } if err := binary.Write(e.w, binary.LittleEndian, leftBlock.Index()); err != nil { return err } rightBlock, ok := s.RightBlocks[i].(*audio.ADPCMBlock) if !ok { return fmt.Errorf("right block at position %d is not an ADPCM block", i) } if err := binary.Write(e.w, binary.LittleEndian, rightBlock.Sample()); err != nil { return err } if err := binary.Write(e.w, binary.LittleEndian, rightBlock.Index()); err != nil { return err } leftData, err := leftBlock.Bytes() if err != nil { return err } rightData, err := rightBlock.Bytes() if err != nil { return err } for j := 0; j < len(leftData); j += 4 { for k := 0; k < 4; k++ { n, err := e.w.Write([]byte{leftData[j+k]}) if n != 1 { return fmt.Errorf("wrote %d byte(s), expected %d", n, 1) } if err != nil { return err } } for k := 0; k < 4; k++ { n, err := e.w.Write([]byte{rightData[j+k]}) if n != 1 { return fmt.Errorf("wrote %d byte(s), expected %d", n, 1) } if err != nil { return err } } } } if err := binary.Write(e.w, binary.LittleEndian, s.leftSample99); err != nil { return err } if err := binary.Write(e.w, binary.LittleEndian, s.leftIndex99); err != nil { return err } if err := binary.Write(e.w, binary.LittleEndian, s.rightSample99); err != nil { return err } if err := binary.Write(e.w, binary.LittleEndian, s.rightIndex99); err != nil { return err } leftBytes, err := s.LeftBlocks[len(s.LeftBlocks)-1].Bytes() if err != nil { return err } rightBytes, err := s.RightBlocks[len(s.LeftBlocks)-1].Bytes() if err != nil { return err } for i := 0; i < len(leftBytes); i += 2 { if err := binary.Write(e.w, binary.LittleEndian, []byte{leftBytes[i], leftBytes[i+1]}); err != nil { return err } if err := binary.Write(e.w, binary.LittleEndian, []byte{rightBytes[i], rightBytes[i+1]}); err != nil { return err } } return nil }
encoding/sad/sad.go
0.705785
0.462776
sad.go
starcoder
package registry import ( "fmt" "net/url" "sort" "strings" ) var supportedTypes = []string{"string", "int", "float", "bool", "bytes"} // QueryStringParams is a collection of query string parameter definitions // The Format of a Query string has the following format: // "key1=<field1:type1>&key2=<field2:type1>" // The <> around field:type can be omitted // Semantic: The value for key1 will be mapped to the field field1 in a go struct and is expected to have type type1 // Supported types are int, string, float, bool, bytes // Bytes are expected to be in Base64-URL (RFC 4648 Section 5) type QueryStringParams []QSParameter // QSParameter represents the information of the mapping between parameters transported in the // query string and how they map to a go struct type QSParameter struct { Key string // Which key Field string // goes to which field in a go struct Type string // should have what type Metadata *FieldMetadatas } func qsParameterFromKeyValue(key string, value []string) (*QSParameter, error) { qsp := &QSParameter{} qsp.Key = key // one key should be defined only once if len(value) != 1 { return nil, fmt.Errorf("1 value expected, got %d (key: %s)", len(value), key) } s := value[0] s = strings.Trim(s, "<>") split := strings.Split(s, ":") if len(split) > 2 { return nil, fmt.Errorf("invalid format of the parameter defintion, at most one : allowed: %s", s) } qsp.Field = split[0] if len(split) == 2 { if !isIn(split[1], supportedTypes...) { return nil, fmt.Errorf("%s is not in the supported types %v", split[1], supportedTypes) } qsp.Type = split[1] } return qsp, nil } // GetParamForKey searches for the param with the given key in the QueryString. If non is found nil is returned. func (q *QueryStringParams) GetParamForKey(key string) *QSParameter { for _, p := range *q { if p.Key == key { return &p } } return nil } // NewQueryStringParams creates at new QueryString from the given definition string func NewQueryStringParams(definition string) (*QueryStringParams, error) { values, err := url.ParseQuery(definition) if err != nil { return nil, fmt.Errorf("error Parsing QueryString: %s", err) } sortedValues := sortParsedQueryString(values) var qs QueryStringParams for _, v := range sortedValues { p, err := qsParameterFromKeyValue(v.Key, v.Values) if err != nil { return nil, err } qs = append(qs, *p) } return &qs, nil } type SortedParsedQueryString []QueryStringKV type QueryStringKV struct { Key string Values []string } func sortParsedQueryString(vals url.Values) SortedParsedQueryString { s := make(SortedParsedQueryString, 0, len(vals)) for k, v := range vals { s = append(s, QueryStringKV{ Key: k, Values: v, }) } sort.Sort(ByKey(s)) return s } // ByAge implements sort.Interface for []Person based on // the Age field. type ByKey SortedParsedQueryString func (a ByKey) Len() int { return len(a) } func (a ByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByKey) Less(i, j int) bool { return a[i].Key < a[j].Key }
registry/querystring.go
0.716318
0.523359
querystring.go
starcoder
package marshalddb import ( "math" "reflect" "strconv" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/dynamodb" ) // ConvertFromAttributes maps a DB returned map[string]*dynamodb.AttributeValue into a specified struct. func ConvertFromAttributes(item map[string]*dynamodb.AttributeValue, v interface{}) error { to := reflect.ValueOf(v) if to.Kind() != reflect.Ptr || to.IsNil() { return ErrNilTarget } toEl := to.Elem() for key, attrValue := range item { attrValueV := reflect.ValueOf(attrValue) // This check is questionable since the compiler guarantees it // since we're checking that `attrValueV is a *dynamodb.AttributeValue`, // But for correctness the check is valid. Possibly remove for *performance* if attrValueV.Kind() == reflect.Ptr && !attrValueV.IsNil() { // At this point we have a `*dynamodb.AttributeValue` and // need to iterate through its elements as described by // https://github.com/awslabs/aws-sdk-go/blob/master/service/dynamodb/api.go#L726 // and find the first non-nil field, which will then become // our target for conversion attrValueEl := attrValueV.Elem() numFields := attrValueEl.NumField() for i := 0; i < numFields; i++ { field := attrValueEl.Field(i) fk := field.Kind() if fk == reflect.Struct || (fk == reflect.Ptr && field.IsNil()) || (fk == reflect.Slice && field.IsNil()) || (fk == reflect.Map && field.Len() == 0) { continue } // `field` is our target for conversion, now we // need to find a field by the same name in our // target struct and then make sure we can set // a value on said field // toField := toEl.FieldByName(key) toField := fieldByName(toEl, key) if toField.CanSet() { var fieldEl reflect.Value if fk == reflect.Slice || fk == reflect.Map { fieldEl = field } else { fieldEl = field.Elem() } typeOfAttrValue := attrValueEl.Type() attrValueName := typeOfAttrValue.Field(i).Name err := setFieldVal( attrValueName, fieldEl, &toField, typeOfAttrValue, ) if err != nil { return err } } break } } } return nil } // ConvertToAttributes converts a struct into a dynamodb representation func ConvertToAttributes(v interface{}) (map[string]*dynamodb.AttributeValue, error) { to := make(map[string]*dynamodb.AttributeValue) ev := reflect.ValueOf(v) if ev.Kind() == reflect.Ptr || ev.Kind() == reflect.Interface { ev = ev.Elem() } et := ev.Type() switch ev.Kind() { case reflect.Struct: for i := 0; i < ev.NumField(); i++ { f := ev.Field(i) fk := f.Kind() if fk == reflect.Ptr { f = f.Elem() fk = f.Kind() } if !f.IsValid() || reflect.Zero(f.Type()) == f { continue } fieldName := et.Field(i).Name if tn := et.Field(i).Tag.Get("json"); tn != "" { // prefer to use the struct tag name over the field name fieldName = tn } switch fk { case reflect.String: // Dynamo does not allow setting empty strings // http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html if f.String() != "" { to[fieldName] = &dynamodb.AttributeValue{ S: aws.String(f.String()), } } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: to[fieldName] = &dynamodb.AttributeValue{ N: aws.String(strconv.FormatInt(f.Int(), 10)), } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: to[fieldName] = &dynamodb.AttributeValue{ N: aws.String(strconv.FormatUint(f.Uint(), 10)), } case reflect.Float32, reflect.Float64: ff := f.Float() if math.IsInf(ff, 0) || math.IsNaN(ff) { return to, ErrInvalidFloat } to[fieldName] = &dynamodb.AttributeValue{ N: aws.String(strconv.FormatFloat(ff, 'g', -1, f.Type().Bits())), } case reflect.Bool: to[fieldName] = &dynamodb.AttributeValue{ BOOL: aws.Bool(f.Bool()), } case reflect.Slice, reflect.Array: if f.Len() == 0 { continue } switch f.Index(0).Kind() { case reflect.String: to[fieldName] = createSS(f) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Bool: fi, err := createNS(f) if err != nil { return to, err } to[fieldName] = fi case reflect.Slice: to[fieldName] = createBS(f) default: return to, ErrConversionNotSupported } case reflect.Struct, reflect.Map: fi, err := createSJSON(f) if err != nil { return to, err } to[fieldName] = fi default: return to, ErrConversionNotSupported } } default: return to, ErrConversionNotSupported } return to, nil } func setFieldVal(attributeValueName string, fieldEl reflect.Value, toField *reflect.Value, typeOfAttrValue reflect.Type) error { var err error switch attributeValueName { case "S", "N": err = setFieldWithKind(toField.Kind(), fieldEl, toField) case "BOOL", "NULL": fromVal := fieldEl.Bool() switch toField.Kind() { case reflect.String: toField.SetString(strconv.FormatBool(fromVal)) case reflect.Bool: toField.SetBool(fromVal) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if fromVal { toField.SetInt(1) } else { toField.SetInt(0) } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: if fromVal { toField.SetUint(1) } else { toField.SetUint(0) } case reflect.Float32, reflect.Float64: if fromVal { toField.SetFloat(1) } else { toField.SetFloat(0) } default: err = ErrInvalidConversion } case "B": fromVal := fieldEl.Bytes() switch toField.Kind() { case reflect.String: toField.SetString(string(fromVal)) case reflect.Slice: toField.SetBytes(fromVal) default: err = ErrInvalidConversion } case "SS", "NS": fromLen := fieldEl.Len() arr := reflect.MakeSlice(toField.Type(), fromLen, fromLen) switch toField.Type().Elem().Kind() { case reflect.String: for i := 0; i < fromLen; i++ { arr.Index(i).SetString(fieldEl.Index(i).Elem().String()) } toField.Set(arr) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: for i := 0; i < fromLen; i++ { toFieldAtIndex := arr.Index(i) if err := setInt(fieldEl.Index(i).Elem(), &toFieldAtIndex); err != nil { return err } } toField.Set(arr) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: for i := 0; i < fromLen; i++ { toFieldAtIndex := arr.Index(i) if err := setUint(fieldEl.Index(i).Elem(), &toFieldAtIndex); err != nil { return err } } toField.Set(arr) case reflect.Float32, reflect.Float64: for i := 0; i < fromLen; i++ { toFieldAtIndex := arr.Index(i) if err := setFloat(fieldEl.Index(i).Elem(), &toFieldAtIndex); err != nil { return err } } toField.Set(arr) default: return ErrInvalidConversion } case "L": fromLen := fieldEl.Len() arr := reflect.MakeSlice(toField.Type(), fromLen, fromLen) // iterate through the slice for i := 0; i < fromLen; i++ { _, v := extractAttributeFromValue(fieldEl.Index(i).Elem()) toFieldAtIndex := arr.Index(i) if err = setFieldWithKind(v.Kind(), v, &toFieldAtIndex); err != nil { break } } toField.Set(arr) case "BS": // Only covering the case of [][]byte to [][]byte if toField.Type().String() != "[][]uint8" { return ErrConversionNotSupported } fromLen := fieldEl.Len() arr := reflect.MakeSlice(toField.Type(), fromLen, fromLen) for i := 0; i < fromLen; i++ { f := fieldEl.Index(i) if f.Kind() == reflect.Ptr { f = f.Elem() } fl := f.Len() tarr := reflect.MakeSlice(arr.Index(i).Type(), fl, fl) for j := 0; j < fl; j++ { toFieldAtIndex := tarr.Index(j) if err = setFieldWithKind(toFieldAtIndex.Kind(), f.Index(j), &toFieldAtIndex); err != nil { break } } arr.Index(i).Set(tarr) } toField.Set(arr) case "M": return ErrConversionNotSupported default: return ErrConversionNotSupported } return err }
dynamo_converter.go
0.677794
0.404272
dynamo_converter.go
starcoder
package modeling import "reflect" type Port interface { GetName() string // returns the name of the Port. Length() int // returns the number of elements stored in the Port. IsEmpty() bool // returns true if the Port does not contain any element. Clear() // removes all the elements stored in the Port. AddValue(val interface{}) // adds a single value to the Port. AddValues(val interface{}) // Add multiple values to the Port. Values must be stored in a slice. GetSingleValue() interface{} // returns a single value of the Port. GetValues() interface{} // returns a slice with all the values of the Port. setParent(c Component) // sets a given DEVS model as parent of the Port. GetParent() Component // returns the parent of the Port. String() string // returns a string representation of the Port. } // NewPort returns a pointer to a structure that complies the Port interface. // name: name of the port. // portValue: slice of desired the data type of the port. // It panics if portValue is not a slice. func NewPort(name string, portValue interface{}) Port { switch reflect.ValueOf(portValue).Kind() { case reflect.Slice: p := port{name, nil, portValue} p.Clear() return &p default: panic("port Value must be of kind reflect.Slice") } } type port struct { name string // Name of the port. parent Component // Parent DEVS model that contains the port. values interface{} // Values stored in the port. It is an empty interface to allow ports of different data types. } // GetName returns the name of the port. func (p *port) GetName() string { return p.name } // Length returns the number of values stored in the port. func (p *port) Length() int { return reflect.ValueOf(p.values).Len() } // IsEmpty returns true if the port does not have any stored value. func (p *port) IsEmpty() bool { return p.Length() == 0 } // Clear removes all the values stored in the port. func (p *port) Clear() { p.values = reflect.MakeSlice(reflect.TypeOf(p.values), 0, 0).Interface() } // AddValue adds a single value to the port. func (p *port) AddValue(val interface{}) { value := reflect.ValueOf(&p.values).Elem() value.Set(reflect.Append(reflect.ValueOf(p.values), reflect.ValueOf(val))) p.values = value.Interface() } // AddValues adds multiple values to the port. Values must be provided in a slice. func (p *port) AddValues(val interface{}) { value := reflect.ValueOf(&p.values).Elem() add := reflect.ValueOf(val) for i := 0; i < add.Len(); i++ { value.Set(reflect.Append(reflect.ValueOf(p.values), add.Index(i))) } p.values = value.Interface() } // GetSingleValue returns the first value stored in the port. // It panics if port is empty (i.e., index 0 is out of range). func (p *port) GetSingleValue() interface{} { return reflect.ValueOf(p.values).Index(0).Interface() } // GetValues returns a slice containing all the values stored in the port. func (p *port) GetValues() interface{} { return p.values } // setParent sets c as the parent DEVS Component of the port. func (p *port) setParent(c Component) { p.parent = c } // GetParent returns the parent component of the port. func (p *port) GetParent() Component { return p.parent } // String returns a string representation of the port. func (p *port) String() string { name := p.name auxComponent := p.parent for auxComponent != nil { name = auxComponent.GetName() + "." + name auxComponent = auxComponent.GetParent() } return name }
pkg/modeling/port.go
0.830353
0.531757
port.go
starcoder
package v1 import ( "encoding/json" ) // SpotPricesPerFacility struct for SpotPricesPerFacility type SpotPricesPerFacility struct { Baremetal2a *SpotPricesPerBaremetal `json:"baremetal_2a,omitempty"` Baremetal2a2 *SpotPricesPerBaremetal `json:"baremetal_2a2,omitempty"` Baremetal1 *SpotPricesPerBaremetal `json:"baremetal_1,omitempty"` Baremetal3 *SpotPricesPerBaremetal `json:"baremetal_3,omitempty"` C2MediumX86 *SpotPricesPerBaremetal `json:"c2.medium.x86,omitempty"` Baremetal2 *SpotPricesPerBaremetal `json:"baremetal_2,omitempty"` M2XlargeX86 *SpotPricesPerBaremetal `json:"m2.xlarge.x86,omitempty"` BaremetalS *SpotPricesPerBaremetal `json:"baremetal_s,omitempty"` Baremetal0 *SpotPricesPerBaremetal `json:"baremetal_0,omitempty"` } // NewSpotPricesPerFacility instantiates a new SpotPricesPerFacility 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 NewSpotPricesPerFacility() *SpotPricesPerFacility { this := SpotPricesPerFacility{} return &this } // NewSpotPricesPerFacilityWithDefaults instantiates a new SpotPricesPerFacility 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 NewSpotPricesPerFacilityWithDefaults() *SpotPricesPerFacility { this := SpotPricesPerFacility{} return &this } // GetBaremetal2a returns the Baremetal2a field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetBaremetal2a() SpotPricesPerBaremetal { if o == nil || o.Baremetal2a == nil { var ret SpotPricesPerBaremetal return ret } return *o.Baremetal2a } // GetBaremetal2aOk returns a tuple with the Baremetal2a field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetBaremetal2aOk() (*SpotPricesPerBaremetal, bool) { if o == nil || o.Baremetal2a == nil { return nil, false } return o.Baremetal2a, true } // HasBaremetal2a returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasBaremetal2a() bool { if o != nil && o.Baremetal2a != nil { return true } return false } // SetBaremetal2a gets a reference to the given SpotPricesPerBaremetal and assigns it to the Baremetal2a field. func (o *SpotPricesPerFacility) SetBaremetal2a(v SpotPricesPerBaremetal) { o.Baremetal2a = &v } // GetBaremetal2a2 returns the Baremetal2a2 field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetBaremetal2a2() SpotPricesPerBaremetal { if o == nil || o.Baremetal2a2 == nil { var ret SpotPricesPerBaremetal return ret } return *o.Baremetal2a2 } // GetBaremetal2a2Ok returns a tuple with the Baremetal2a2 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetBaremetal2a2Ok() (*SpotPricesPerBaremetal, bool) { if o == nil || o.Baremetal2a2 == nil { return nil, false } return o.Baremetal2a2, true } // HasBaremetal2a2 returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasBaremetal2a2() bool { if o != nil && o.Baremetal2a2 != nil { return true } return false } // SetBaremetal2a2 gets a reference to the given SpotPricesPerBaremetal and assigns it to the Baremetal2a2 field. func (o *SpotPricesPerFacility) SetBaremetal2a2(v SpotPricesPerBaremetal) { o.Baremetal2a2 = &v } // GetBaremetal1 returns the Baremetal1 field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetBaremetal1() SpotPricesPerBaremetal { if o == nil || o.Baremetal1 == nil { var ret SpotPricesPerBaremetal return ret } return *o.Baremetal1 } // GetBaremetal1Ok returns a tuple with the Baremetal1 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetBaremetal1Ok() (*SpotPricesPerBaremetal, bool) { if o == nil || o.Baremetal1 == nil { return nil, false } return o.Baremetal1, true } // HasBaremetal1 returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasBaremetal1() bool { if o != nil && o.Baremetal1 != nil { return true } return false } // SetBaremetal1 gets a reference to the given SpotPricesPerBaremetal and assigns it to the Baremetal1 field. func (o *SpotPricesPerFacility) SetBaremetal1(v SpotPricesPerBaremetal) { o.Baremetal1 = &v } // GetBaremetal3 returns the Baremetal3 field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetBaremetal3() SpotPricesPerBaremetal { if o == nil || o.Baremetal3 == nil { var ret SpotPricesPerBaremetal return ret } return *o.Baremetal3 } // GetBaremetal3Ok returns a tuple with the Baremetal3 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetBaremetal3Ok() (*SpotPricesPerBaremetal, bool) { if o == nil || o.Baremetal3 == nil { return nil, false } return o.Baremetal3, true } // HasBaremetal3 returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasBaremetal3() bool { if o != nil && o.Baremetal3 != nil { return true } return false } // SetBaremetal3 gets a reference to the given SpotPricesPerBaremetal and assigns it to the Baremetal3 field. func (o *SpotPricesPerFacility) SetBaremetal3(v SpotPricesPerBaremetal) { o.Baremetal3 = &v } // GetC2MediumX86 returns the C2MediumX86 field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetC2MediumX86() SpotPricesPerBaremetal { if o == nil || o.C2MediumX86 == nil { var ret SpotPricesPerBaremetal return ret } return *o.C2MediumX86 } // GetC2MediumX86Ok returns a tuple with the C2MediumX86 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetC2MediumX86Ok() (*SpotPricesPerBaremetal, bool) { if o == nil || o.C2MediumX86 == nil { return nil, false } return o.C2MediumX86, true } // HasC2MediumX86 returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasC2MediumX86() bool { if o != nil && o.C2MediumX86 != nil { return true } return false } // SetC2MediumX86 gets a reference to the given SpotPricesPerBaremetal and assigns it to the C2MediumX86 field. func (o *SpotPricesPerFacility) SetC2MediumX86(v SpotPricesPerBaremetal) { o.C2MediumX86 = &v } // GetBaremetal2 returns the Baremetal2 field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetBaremetal2() SpotPricesPerBaremetal { if o == nil || o.Baremetal2 == nil { var ret SpotPricesPerBaremetal return ret } return *o.Baremetal2 } // GetBaremetal2Ok returns a tuple with the Baremetal2 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetBaremetal2Ok() (*SpotPricesPerBaremetal, bool) { if o == nil || o.Baremetal2 == nil { return nil, false } return o.Baremetal2, true } // HasBaremetal2 returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasBaremetal2() bool { if o != nil && o.Baremetal2 != nil { return true } return false } // SetBaremetal2 gets a reference to the given SpotPricesPerBaremetal and assigns it to the Baremetal2 field. func (o *SpotPricesPerFacility) SetBaremetal2(v SpotPricesPerBaremetal) { o.Baremetal2 = &v } // GetM2XlargeX86 returns the M2XlargeX86 field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetM2XlargeX86() SpotPricesPerBaremetal { if o == nil || o.M2XlargeX86 == nil { var ret SpotPricesPerBaremetal return ret } return *o.M2XlargeX86 } // GetM2XlargeX86Ok returns a tuple with the M2XlargeX86 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetM2XlargeX86Ok() (*SpotPricesPerBaremetal, bool) { if o == nil || o.M2XlargeX86 == nil { return nil, false } return o.M2XlargeX86, true } // HasM2XlargeX86 returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasM2XlargeX86() bool { if o != nil && o.M2XlargeX86 != nil { return true } return false } // SetM2XlargeX86 gets a reference to the given SpotPricesPerBaremetal and assigns it to the M2XlargeX86 field. func (o *SpotPricesPerFacility) SetM2XlargeX86(v SpotPricesPerBaremetal) { o.M2XlargeX86 = &v } // GetBaremetalS returns the BaremetalS field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetBaremetalS() SpotPricesPerBaremetal { if o == nil || o.BaremetalS == nil { var ret SpotPricesPerBaremetal return ret } return *o.BaremetalS } // GetBaremetalSOk returns a tuple with the BaremetalS field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetBaremetalSOk() (*SpotPricesPerBaremetal, bool) { if o == nil || o.BaremetalS == nil { return nil, false } return o.BaremetalS, true } // HasBaremetalS returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasBaremetalS() bool { if o != nil && o.BaremetalS != nil { return true } return false } // SetBaremetalS gets a reference to the given SpotPricesPerBaremetal and assigns it to the BaremetalS field. func (o *SpotPricesPerFacility) SetBaremetalS(v SpotPricesPerBaremetal) { o.BaremetalS = &v } // GetBaremetal0 returns the Baremetal0 field value if set, zero value otherwise. func (o *SpotPricesPerFacility) GetBaremetal0() SpotPricesPerBaremetal { if o == nil || o.Baremetal0 == nil { var ret SpotPricesPerBaremetal return ret } return *o.Baremetal0 } // GetBaremetal0Ok returns a tuple with the Baremetal0 field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SpotPricesPerFacility) GetBaremetal0Ok() (*SpotPricesPerBaremetal, bool) { if o == nil || o.Baremetal0 == nil { return nil, false } return o.Baremetal0, true } // HasBaremetal0 returns a boolean if a field has been set. func (o *SpotPricesPerFacility) HasBaremetal0() bool { if o != nil && o.Baremetal0 != nil { return true } return false } // SetBaremetal0 gets a reference to the given SpotPricesPerBaremetal and assigns it to the Baremetal0 field. func (o *SpotPricesPerFacility) SetBaremetal0(v SpotPricesPerBaremetal) { o.Baremetal0 = &v } func (o SpotPricesPerFacility) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Baremetal2a != nil { toSerialize["baremetal_2a"] = o.Baremetal2a } if o.Baremetal2a2 != nil { toSerialize["baremetal_2a2"] = o.Baremetal2a2 } if o.Baremetal1 != nil { toSerialize["baremetal_1"] = o.Baremetal1 } if o.Baremetal3 != nil { toSerialize["baremetal_3"] = o.Baremetal3 } if o.C2MediumX86 != nil { toSerialize["c2.medium.x86"] = o.C2MediumX86 } if o.Baremetal2 != nil { toSerialize["baremetal_2"] = o.Baremetal2 } if o.M2XlargeX86 != nil { toSerialize["m2.xlarge.x86"] = o.M2XlargeX86 } if o.BaremetalS != nil { toSerialize["baremetal_s"] = o.BaremetalS } if o.Baremetal0 != nil { toSerialize["baremetal_0"] = o.Baremetal0 } return json.Marshal(toSerialize) } type NullableSpotPricesPerFacility struct { value *SpotPricesPerFacility isSet bool } func (v NullableSpotPricesPerFacility) Get() *SpotPricesPerFacility { return v.value } func (v *NullableSpotPricesPerFacility) Set(val *SpotPricesPerFacility) { v.value = val v.isSet = true } func (v NullableSpotPricesPerFacility) IsSet() bool { return v.isSet } func (v *NullableSpotPricesPerFacility) Unset() { v.value = nil v.isSet = false } func NewNullableSpotPricesPerFacility(val *SpotPricesPerFacility) *NullableSpotPricesPerFacility { return &NullableSpotPricesPerFacility{value: val, isSet: true} } func (v NullableSpotPricesPerFacility) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableSpotPricesPerFacility) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
v1/model_spot_prices_per_facility.go
0.708515
0.405037
model_spot_prices_per_facility.go
starcoder
package go_tfidf import ( "errors" "fmt" "math" "strings" ) // A TfIdf represents the set of variables that are used for computing the reference documents Tf and Idf values. type TfIdf struct { // DocumentSeparator is the string that is going to be used to split the documents terms. DocumentSeparator string // documents are the set of reference documents that are going to be used to compare with input queries. documents []string // documentsNormTermFrequency are the normalized term frequencies for all TfIdf.documents (Tf). documentsNormTermFrequency []map[string]float64 // documentsTerms are the terms for all TfIdf.documents splitted by the TfIdf.DocumentSeparator. documentsTerms []string // documentsInverseFrequency are the TfIdf.documentTerms Inverse Document Frequency (Idf). documentsInverseFrequency map[string]float64 } // AddDocuments receives an array of strings containing the documents that are going to be used as references. // If the array is empty or any of the input documents are invalid, it return an error. // An invalid document has no terms or only has one, but is an empty string. func (ti *TfIdf) AddDocuments(documents []string) error { if len(documents) < 1 { return errors.New("at least one document must be passed") } for _, doc := range documents { docTerms := strings.Split(strings.ToLower(doc), ti.DocumentSeparator) if len(docTerms) < 1 || (len(docTerms) == 1 && docTerms[0] == "") { ti.documents = make([]string, 0) return fmt.Errorf("document error. %s document is invalid", doc) } ti.documents = append(ti.documents, doc) ti.documentsTerms = append(ti.documentsTerms, docTerms...) ti.documentsNormTermFrequency = append(ti.documentsNormTermFrequency, normalizedTermFrequency(docTerms)) } ti.documentsTerms = removeDuplicates(ti.documentsTerms) ti.calculateDocumentsIdf() return nil } // CalculateQueryTermsTfIdfForEachDocument receives a query string and computes Tf-Idf of its terms for every document in the *TfIdf object. // If the query term is an empty string, returns an error. func (ti *TfIdf) CalculateQueryTermsTfIdfForEachDocument(query string) ([][]float64, error) { queryTerms := strings.Split(strings.ToLower(query), ti.DocumentSeparator) termsTfIdfs := make([][]float64, 0) if len(queryTerms) == 1 && queryTerms[0] == "" { return termsTfIdfs, errors.New("query must have at least one term") } for docIdx, docNormTf := range ti.documentsNormTermFrequency { termsTfIdfs = append(termsTfIdfs, make([]float64, 0)) for _, term := range queryTerms { tf := 0.0 idf := 0.0 if v, ok := docNormTf[term]; ok { tf = v } if v, ok := ti.documentsInverseFrequency[term]; ok { idf = v } termsTfIdfs[docIdx] = append(termsTfIdfs[docIdx], tf*idf) } } return termsTfIdfs, nil } // CalculateQueryTermsTfIdf receives a query string with a separator (*TfIdf.DocumentSeparator) and computes the TfIdfs value for each term. // If the query term is an empty string, returns an error. func CalculateQueryTermsTfIdf(query string, separator string) ([]float64, error) { docs := []string{query} queryTerms := strings.Split(strings.ToLower(query), separator) queryTfIdf := make([]float64, 0) if len(queryTerms) == 1 && queryTerms[0] == "" { return queryTfIdf, errors.New("query must have at least one term") } termFrequencies := normalizedTermFrequency(queryTerms) for _, term := range queryTerms { tf := termFrequencies[term] idf := inverseDocumentFrequency(term, docs, separator) queryTfIdf = append(queryTfIdf, tf*idf) } return queryTfIdf, nil } func removeDuplicates(words []string) []string { uniqueWords := make([]string, 0) keys := make(map[string]bool) for _, w := range words { if _, exists := keys[w]; !exists { uniqueWords = append(uniqueWords, w) keys[w] = true } } return uniqueWords } func stringArrayContainsWord(words []string, word string) bool { for _, w := range words { if word == w { return true } } return false } // Documents returns the *TfIdf.documents private attribute values. func (ti *TfIdf) Documents() []string { return ti.documents } // DocumentsNormTermFrequency returns the *TfIdf.documentsNormTermFrequency private attribute values. func (ti *TfIdf) DocumentsNormTermFrequency() []map[string]float64 { return ti.documentsNormTermFrequency } // DocumentsInverseFrequency returns the *TfIdf.DocumentsInverseFrequency private attribute values. func (ti *TfIdf) DocumentsInverseFrequency() map[string]float64 { return ti.documentsInverseFrequency } // DocumentsInverseFrequency returns the *TfIdf.documentsTerms private attribute values. func (ti *TfIdf) DocumentsTerms() []string { return ti.documentsTerms } func normalizedTermFrequency(terms []string) map[string]float64 { normalizedTermFrequencies := make(map[string]float64, 0) nTerms := float64(len(terms)) for _, term := range terms { normalizedTermFrequencies[term] += 1.0 / nTerms } return normalizedTermFrequencies } func (ti *TfIdf) calculateDocumentsIdf() { for _, term := range ti.documentsTerms { ti.documentsInverseFrequency[term] = inverseDocumentFrequency(term, ti.documents, ti.DocumentSeparator) } } func inverseDocumentFrequency(term string, documents []string, separator string) float64 { countTermsInDocuments := 0 for _, doc := range documents { docTerms := strings.Split(strings.ToLower(doc), separator) if stringArrayContainsWord(docTerms, strings.ToLower(term)) { countTermsInDocuments++ } } if countTermsInDocuments > 0 { return 1.0 + math.Log(float64(len(documents))/float64(countTermsInDocuments)) } return 1.0 } func New(documents []string, separator string) (*TfIdf, error) { ti := TfIdf{ DocumentSeparator: separator, documents: make([]string, 0), documentsNormTermFrequency: make([]map[string]float64, 0), documentsTerms: make([]string, 0), documentsInverseFrequency: make(map[string]float64, 0), } err := ti.AddDocuments(documents) if err != nil { return nil, err } return &ti, nil }
go_tfidf.go
0.676299
0.42668
go_tfidf.go
starcoder
package anneal import ( "math" "math/rand" ) // A State can undergo simulated annealing optimization. type State interface { // Energy returns the energy of a State. // This is the quantity to be minimized: States with small energy are better than States with large energy. Energy() float64 // Neighbor returns a State in the state space chosen randomly from those adjacent to the current State. // Distinct States must not share memory. For example, do not reuse a slice from one State to a neighbor. Neighbor() State } // A Schedule controls the annealing process. type Schedule struct { Iter int // number of iterations Ti float64 // initial temperature, as a multiple of the input State's energy Tf float64 // final temperature, as a multiple of the input State's energy } // NewSchedule returns a pointer to a Schedule populated with default values. func NewSchedule() *Schedule { return &Schedule{ Iter: 1e6, Ti: 1, Tf: 1e-5, } } // Anneal implements simulated annealing on the input State and returns the best State encountered during the search. // Once per iteration, it calls s.Neighbor() and then calls Energy() on the neighboring State. // The new State is adopted with probability 1 if its energy E' is lower than the original State's energy E, // and with probability exp(-(E'-E)/T) otherwise, where T = Ti * exp(-i/k) is the annealing temperature of the current iteration i, // and the scale factor k = Iter / ln(Ti/Tf) is the number of iterations required for the temperature to drop by a factor of e. func Anneal(s State, sch *Schedule) State { e := s.Energy() sbest, ebest := s, e var ( T0 = e * sch.Ti k = float64(sch.Iter) / math.Log(sch.Ti/sch.Tf) ) for i := 0; i < sch.Iter; i++ { snew := s.Neighbor() enew := snew.Energy() if enew < e { if enew < ebest { sbest, ebest = snew, enew } } else { T := T0 * math.Exp(-float64(i)/k) if p := math.Exp(-(enew - e) / T); rand.Float64() > p { continue } } s, e = snew, enew } return sbest }
anneal.go
0.800887
0.621713
anneal.go
starcoder
package environment // Environment represents a deployment/execution environment where tasks can be executed type Environment interface { // Name is the human name of the environment. Examples: kubernetes, ECS, local Name() string // Configure connects to the environment with optional parameters and returns an error if unsuccessful. This may require authentication, API keys, etc // This can be called more than once to change which specific sub-environment to connect to. E.g. which k8s namespace Configure(interface{}) error // GetCurrentConfiguration returns the current environment configuration GetCurrentConfiguration() interface{} // IsValidConfiguration returns true if the current configuration is valid and a connection to the environment can be established IsValidConfiguration() bool // Describe returns information about the environment that can be serialized Describe() SerializableEnv // StartExecutor starts the Wiz Executor binary on the given node. TODO: figure out scheduling and what nodes actually mean. // For now as we're only implementing the local executor this can be anything // Additionally, start executor should fork the process or do anything necessary so the executor continues to run // It can optionally return details about the started executor such as PID or Pod ID StartExecutor(node string) (interface{}, error) } //SerializableEnv is a snapshot of the environment's state at a given time. type SerializableEnv struct { // Name is the canonical name of the Environment, hardcoded in each implementation EnvironmentID string // Description is a human readable description that may include dynamic information from the configuration: // e.g. local hostname or k8s namespace Description string //Host references a host with a valid Processor API endpoint. This can be generated from configuration or similar but must be available Host string // Configuration contains the current state of the environment's configuration Configuration interface{} // State is the state of the environment, e.g. what objects are actually applied/the real executor // This usually is a k8s Pod ID or a local process ID/PID State interface{} }
environment/environment.go
0.617859
0.454593
environment.go
starcoder
package lie import ( "math/big" "sort" "github.com/mjschust/lieprod/util" ) // An Algebra supplies representation-theoretic methods acting on Weights. type Algebra interface { RootSystem ReprDimension(Weight) *big.Int DominantChar(Weight) WeightPoly Tensor(...Weight) WeightPoly TensorProduct() PolyProduct Fusion(int, ...Weight) WeightPoly FusionProduct(int) PolyProduct WeightedFactorizationCoeff(int, []Weight, []Weight) *big.Rat } type algebraImpl struct { RootSystem } // NewAlgebra constructs and returns the lie algebra associated to the given root system. func NewAlgebra(rtsys RootSystem) Algebra { return algebraImpl{rtsys} } // ReprDimension returns the dimension of the irreducible representation for the // given highest weight. func (alg algebraImpl) ReprDimension(highestWt Weight) *big.Int { rho := alg.Rho() posRoots := alg.PositiveRoots() numer := big.NewInt(1) denom := big.NewInt(1) a := big.NewInt(0) b := big.NewInt(0) rslt := big.NewInt(0) wtForm := alg.NewWeight() for _, root := range posRoots { alg.convertRoot(root, wtForm) a.SetInt64(int64(alg.IntKillingForm(highestWt, wtForm))) b.SetInt64(int64(alg.IntKillingForm(rho, wtForm))) numer.Mul(numer, rslt.Add(a, b)) denom.Mul(denom, b) } return rslt.Div(numer, denom) } // DominantChar builds the dominant character of the representation of the given highest weight. func (alg algebraImpl) DominantChar(highestWt Weight) WeightPoly { // Construct root-level map posRoots := alg.PositiveRoots() rootLevelMap := make(map[int][]Weight) for _, root := range posRoots { level := 0 for i := range root { level += root[i] } wtForm := alg.NewWeight() alg.convertRoot(root, wtForm) rtList, present := rootLevelMap[level] if present { rootLevelMap[level] = append(rtList, wtForm) } else { rootLevelMap[level] = []Weight{wtForm} } } // Construct set of dominant weights level := 0 weightLevelDict := make(map[int]util.VectorMap) weightLevelDict[0] = util.NewVectorMap() weightLevelDict[0].Put(highestWt, true) domChar := NewWeightPolyBuilder(alg.Rank()) for { done := true for key := range weightLevelDict { if level <= key { done = false break } } if done { break } _, present := weightLevelDict[level] if !present { level++ continue } newWt := alg.NewWeight() for _, wt := range weightLevelDict[level].Keys() { for rootLevel, roots := range rootLevelMap { for _, root := range roots { newWt.SubWeights(wt, root) if isDominant(newWt) { polyWeight := domChar.addWeight(newWt) wtSet, present := weightLevelDict[level+rootLevel] if present { wtSet.Put(polyWeight, true) } else { wtSet = util.NewVectorMap() wtSet.Put(polyWeight, true) weightLevelDict[level+rootLevel] = wtSet } domChar.SetMonomial(polyWeight, big.NewInt(-1)) } } } } level++ } // Build dominant character sortedLevels := make([]int, 0, len(weightLevelDict)) for level := range weightLevelDict { sortedLevels = append(sortedLevels, level) } sort.Slice(sortedLevels, func(i, j int) bool { return sortedLevels[i] < sortedLevels[j] }) one := big.NewInt(1) domChar.SetMonomial(highestWt, one) rho := alg.Rho() for _, level := range sortedLevels { for _, wt := range weightLevelDict[level].Keys() { var freudenthalHelper func(wt Weight) freudenthalHelper = func(wt Weight) { mult := domChar.Multiplicity(wt) if mult.Sign() > 0 { return } multiplicitySum := big.NewInt(0) a := big.NewInt(0) b := big.NewInt(0) n := big.NewInt(0) rslt := big.NewInt(0) shiftedWeight := alg.NewWeight() newDomWeight := alg.NewWeight() workingEpc := alg.newEpc() for _, roots := range rootLevelMap { for _, rootWt := range roots { n.SetInt64(0) copy(shiftedWeight, wt) a.SetInt64(int64(alg.IntKillingForm(wt, rootWt))) b.SetInt64(int64(alg.IntKillingForm(rootWt, rootWt))) for { n.Add(n, one) shiftedWeight.AddWeights(shiftedWeight, rootWt) alg.convertWeightToEpc(shiftedWeight, workingEpc) alg.reflectEpcToChamber(workingEpc) alg.convertEpCoord(workingEpc, newDomWeight) if domChar.Multiplicity(newDomWeight).Sign() == 0 { break } freudenthalHelper(newDomWeight) newWeightMultiplicity := domChar.Multiplicity(newDomWeight) rslt.Add(a, rslt.Mul(n, b)) rslt.Mul(rslt, newWeightMultiplicity) multiplicitySum.Add(multiplicitySum, rslt) } } } numerator := big.NewInt(2) numerator.Mul(numerator, multiplicitySum) shiftedWeight.AddWeights(highestWt, rho) denominator := big.NewInt(int64( alg.IntKillingForm(shiftedWeight, shiftedWeight))) shiftedWeight.AddWeights(wt, rho) rslt.SetInt64(int64(alg.IntKillingForm(shiftedWeight, shiftedWeight))) denominator.Sub(denominator, rslt) domChar.SetMonomial(wt, rslt.Div(numerator, denominator)) } freudenthalHelper(wt) } } return domChar } // Tensor computes the tensor product expansion of the given list of weights. func (alg algebraImpl) Tensor(wts ...Weight) WeightPoly { polys := make([]WeightPoly, len(wts)) for i := range wts { polys[i] = wts[i] } polyProd := NewProduct(alg.tensorProduct) return polyProd.Reduce(polys...) } // TensorProduct returns a weight polynomial product based on the tensor product func (alg algebraImpl) TensorProduct() PolyProduct { return NewProduct(alg.tensorProduct) } // tensorProduct computes the tensor product decomposition of the given representations. func (alg algebraImpl) tensorProduct(wt1, wt2 Weight) MutableWeightPoly { if alg.ReprDimension(wt1).Cmp(alg.ReprDimension(wt2)) < 0 { wt1, wt2 = wt2, wt1 } // Construct constant weights rho := alg.newEpc() alg.convertWeightToEpc(alg.Rho(), rho) domChar := alg.DominantChar(wt2) lamRhoSumWt := alg.NewWeight() lamRhoSumWt.AddWeights(wt1, alg.Rho()) lamRhoSum := alg.newEpc() alg.convertWeightToEpc(lamRhoSumWt, lamRhoSum) // Construct return map retPoly := NewWeightPolyBuilder(alg.Rank()) var epc = alg.newEpc() var orbitEpc = alg.newEpc() domWeight := alg.NewWeight() rslt := big.NewInt(0) for _, charWeight := range domChar.Weights() { domWtMult := domChar.Multiplicity(charWeight) alg.convertWeightToEpc(charWeight, orbitEpc) done := false for ; !done; done = alg.nextOrbitEpc(orbitEpc) { // Shifted reflection into dominant chamber epc.addEpc(lamRhoSum, orbitEpc) parity := alg.reflectEpcToChamber(epc) epc.subEpc(epc, rho) // Check if dominant alg.convertEpCoord(epc, domWeight) if !isDominant(domWeight) { continue } // Set new multiplicity rslt.SetInt64(int64(parity)) rslt.Mul(rslt, domWtMult) retPoly.AddMonomial(domWeight, rslt) } } return retPoly } // Fusion computes the fusion product expansion of the given list of weights. func (alg algebraImpl) Fusion(ell int, wts ...Weight) WeightPoly { polys := make([]WeightPoly, len(wts)) for i := range wts { polys[i] = wts[i] } var prod WeightProduct = func(wt1, wt2 Weight) MutableWeightPoly { return alg.fusionProduct(ell, wt1, wt2) } polyProd := NewMemoizedProduct(prod) return polyProd.Reduce(polys...) } // FusionProduct returns a weight polynomial product based on the level ell fusion product func (alg algebraImpl) FusionProduct(ell int) PolyProduct { var prod WeightProduct = func(wt1, wt2 Weight) MutableWeightPoly { return alg.fusionProduct(ell, wt1, wt2) } return NewMemoizedProduct(prod) } // fusionProduct computes the tensor product decomposition of the given representations. func (alg algebraImpl) fusionProduct(ell int, wt1, wt2 Weight) MutableWeightPoly { rho := alg.newEpc() alg.convertWeightToEpc(alg.Rho(), rho) rhoLevel := alg.Level(alg.Rho()) tensorDecom := alg.tensorProduct(wt1, wt2) // Construct return map retPoly := NewWeightPolyBuilder(alg.Rank()) domWeight := alg.NewWeight() epc := alg.newEpc() rslt := big.NewInt(0) for _, wt := range tensorDecom.Weights() { if alg.Level(wt) == ell+1 { continue } // Shifted reflection into alcove alg.convertWeightToEpc(wt, epc) epc.addEpc(epc, rho) parity := alg.reflectEpcToAlcove(epc, ell+rhoLevel+1) epc.subEpc(epc, rho) // Check if dominant alg.convertEpCoord(epc, domWeight) if !isDominant(domWeight) || alg.Level(domWeight) > ell { continue } // Set new multiplicity rslt.SetInt64(int64(parity)) rslt.Mul(rslt, tensorDecom.Multiplicity(wt)) retPoly.AddMonomial(domWeight, rslt) } return retPoly } func (alg algebraImpl) WeightedFactorizationCoeff(ell int, wts1 []Weight, wts2 []Weight) *big.Rat { // Compute fusion products poly1 := alg.Fusion(ell, wts1...) poly2 := alg.Fusion(ell, wts2...) // Compute integral weighted coefficient rslt := big.NewInt(0) wfSum := big.NewInt(0) for _, mustar := range poly1.Weights() { mu := alg.Dual(mustar) rslt.SetInt64(int64(alg.IntCasimirScalar(mu))) rslt.Mul(rslt, poly1.Multiplicity(mustar)) rslt.Mul(rslt, poly2.Multiplicity(mu)) wfSum.Add(wfSum, rslt) } // Divide by Killing factor and return value retVal := big.NewRat(0, 1) retVal.SetInt(wfSum) denom := big.NewRat(int64(alg.KillingFactor()), 1) retVal.Quo(retVal, denom) return retVal } func isDominant(wt Weight) bool { for _, coord := range wt { if coord < 0 { return false } } return true }
lie/algebra.go
0.746046
0.448668
algebra.go
starcoder
package random import ( "math/rand" ) // Shuffle pseudo-randomizes the order of parameters. // it can be of any type: string, integer, floats, slices, bool, etc. // It returns the shuffled slice of type []interface{}. func Shuffle(a ...interface{}) interface{} { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleStrings pseudo-randomizes the order of provided slice (type []string). // parameter 'a' must be of type []string. // It returns the shuffled slice of type []string. func ShuffleStrings(a []string) []string { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleInt pseudo-randomizes the order of provided slice (type []int). // parameter 'a' must be of type []int. // It returns the shuffled slice of type []int. func ShuffleInt(a []int) []int { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleInt8 pseudo-randomizes the order of provided slice (type []int8). // parameter 'a' must be of type []int8. // It returns the shuffled slice of type []int8. func ShuffleInt8(a []int8) []int8 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleInt16 pseudo-randomizes the order of provided slice (type []int16). // parameter 'a' must be of type []int16. // It returns the shuffled slice of type []int16. func ShuffleInt16(a []int16) []int16 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleInt32 pseudo-randomizes the order of provided slice (type []int32). // parameter 'a' must be of type []int32. // It returns the shuffled slice of type []int32. func ShuffleInt32(a []int32) []int32 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleInt64 pseudo-randomizes the order of provided slice (type []int64). // parameter 'a' must be of type []int64. // It returns the shuffled slice of type []int64. func ShuffleInt64(a []int64) []int64 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleUint pseudo-randomizes the order of provided slice (type []uint). // parameter 'a' must be of type []uint. // It returns the shuffled slice of type []uint. func ShuffleUint(a []uint) []uint { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleUint8 pseudo-randomizes the order of provided slice (type []uint8). // parameter 'a' must be of type []uint8. // It returns the shuffled slice of type []uint8. func ShuffleUint8(a []uint8) []uint8 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleUint16 pseudo-randomizes the order of provided slice (type []uint16). // parameter 'a' must be of type []uint16. // It returns the shuffled slice of type []uint16. func ShuffleUint16(a []uint16) []uint16 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleUint32 pseudo-randomizes the order of provided slice (type []uint32). // parameter 'a' must be of type []uint32. // It returns the shuffled slice of type []uint32. func ShuffleUint32(a []uint32) []uint32 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleUint64 pseudo-randomizes the order of provided slice (type []uint64). // parameter 'a' must be of type []uint64. // It returns the shuffled slice of type []uint64. func ShuffleUint64(a []uint64) []uint64 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleFloat32 pseudo-randomizes the order of provided slice (type []float32). // parameter 'a' must be of type []float32. // It returns the shuffled slice of type []float32. func ShuffleFloat32(a []float32) []float32 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a } // ShuffleFloat64 pseudo-randomizes the order of provided slice (type []float64). // parameter 'a' must be of type []float64. // It returns the shuffled slice of type []float64. func ShuffleFloat64(a []float64) []float64 { rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] }) return a }
shuffle.go
0.698432
0.408395
shuffle.go
starcoder
package fastconvert // region Complex64 Converters // ReadByteArrayToComplex64 reads a 8 byte array to a complex64 func ReadByteArrayToComplex64(data []byte) complex64 { var r = ReadByteArrayToFloat32(data[:4]) var i = ReadByteArrayToFloat32(data[4:8]) return complex(r, i) } // ReadByteArrayToComplex64Array reads a complex64 array from specified byte buffer. // The number of items are len(data) / 8 or len(out). Which one is the lower. func ReadByteArrayToComplex64Array(data []byte, out []complex64) { var pos = 0 var itemsOnBuffer = len(data) / 8 var itemsToRead = itemsOnBuffer if len(out) < itemsToRead { itemsToRead = len(out) } for idx := 0; idx < itemsToRead; idx++ { var r = ReadByteArrayToFloat32(data[pos : pos+4]) var i = ReadByteArrayToFloat32(data[pos+4 : pos+8]) out[idx] = complex(r, i) pos += 8 } } // ByteArrayToComplex64Array reads a complex64 array from specified byte buffer. func ByteArrayToComplex64Array(data []byte) []complex64 { var out = make([]complex64, len(data)/8) ReadByteArrayToComplex64Array(data, out) return out } // endregion // region Complex128 Converters // ReadByteArrayToComplex128 reads a 16 byte array to a complex128 func ReadByteArrayToComplex128(data []byte) complex128 { var r = ReadByteArrayToFloat64(data[:8]) var i = ReadByteArrayToFloat64(data[8:16]) return complex(r, i) } // ReadByteArrayToComplex128Array reads a complex128 array from specified byte buffer. // The number of items are len(data) / 16 or len(out). Which one is the lower. func ReadByteArrayToComplex128Array(data []byte, out []complex128) { var pos = 0 var itemsOnBuffer = len(data) / 16 var itemsToRead = itemsOnBuffer if len(out) < itemsToRead { itemsToRead = len(out) } for idx := 0; idx < itemsToRead; idx++ { var r = ReadByteArrayToFloat64(data[pos : pos+8]) var i = ReadByteArrayToFloat64(data[pos+8 : pos+16]) out[idx] = complex(r, i) pos += 16 } } // ByteArrayToComplex128Array reads a complex128 array from specified byte buffer. func ByteArrayToComplex128Array(data []byte) []complex128 { var out = make([]complex128, len(data)/16) ReadByteArrayToComplex128Array(data, out) return out } // endregion
complexconverters.go
0.694303
0.661199
complexconverters.go
starcoder
package chacha20 import "github.com/tang0th/go-chacha20/chacha" // XORKeyStream crypts bytes from in to out using the given key and nonce. It // performs the 20 round chacha cipher operation. In and out may be the same // slice but otherwise should not overlap. Nonce must be 8 bytes long. Key // must be either 10, 16 or 32 byte long (32 bytes is recommended for security // purposes). func XORKeyStream(out, in []byte, nonce []byte, key []byte) { xorkeystream(out, in, nonce, key, 20) } // XORKeyStream12 crypts bytes from in to out using the given key and nonce. It // performs the 12 round chacha cipher operation. In and out may be the same // slice but otherwise should not overlap. Nonce must be 8 bytes long. Key // must be either 10, 16 or 32 byte long (32 bytes is recommended for security // purposes). func XORKeyStream12(out, in []byte, nonce []byte, key []byte) { xorkeystream(out, in, nonce, key, 12) } // XORKeyStream8 crypts bytes from in to out using the given key and nonce. It // performs the 8 round chacha cipher operation. In and out may be the same // slice but otherwise should not overlap. Nonce must be 8 bytes long. Key // must be either 10, 16 or 32 byte long (32 bytes is recommended for security // purposes). func XORKeyStream8(out, in []byte, nonce []byte, key []byte) { xorkeystream(out, in, nonce, key, 8) } // xorkeystream crypts bytes from in to out using the given key and nonce and // number of rounds. It selects the right constants, elongates the key (if // necessary) and in the future may even call HChacha20 (once it is proved secure). // We then call the underlying chahcha.XORKeyStream function. func xorkeystream(out, in []byte, nonce []byte, k []byte, rounds int) { if len(out) < len(in) { in = in[:len(out)] } var subNonce [8]byte var key [32]byte var constant *[16]byte switch len(k) { case 32: copy(key[:], k) constant = &chacha.Sigma case 16: copy(key[:16], k) copy(key[16:], k) constant = &chacha.Tau case 10: copy(key[:16], k) copy(key[16:], k) constant = &chacha.Upsilon default: panic("chacha20: key must be 32, 16 or 10 bytes") } if len(nonce) == 8 { copy(subNonce[:], nonce[:]) } else { panic("chacha20: nonce must be 8 bytes") } chacha.XORKeyStream(out, in, &subNonce, constant, &key, rounds) }
chacha20.go
0.629319
0.463869
chacha20.go
starcoder
package slice import "fmt" // SliceBasic shows how to create a slice and how to set and get values in it. func SliceBasic() { // Don't add a number between the // `[]` brackets and we `make` slices if we // want to have a capacity and length slice := make([]string, 3) fmt.Println("empty:", slice) slice[0] = "|set zeroeth value|" slice[1] = "|set first value|" slice[2] = "|set second value|" fmt.Println("full:", slice) fmt.Println("pick a value:", slice[2]) fmt.Println("capacity:", cap(slice)) fmt.Println("length:", len(slice)) inline := []int{0, 1, 2, 3, 4} fmt.Println("Can be declared inline", inline) } // SliceAppend shows how to put more elements into a slice even if we don't // have the capacity for it using `append`. func SliceAppend() { // Why wouldn't I do this always? var slice []string // Good Question! Lets answer it! fmt.Println("capacity:", cap(slice)) fmt.Println("length:", len(slice)) slice = append(slice, "append a single value") slice = append(slice, "append", "multiple", "values") fmt.Println("capacity:", cap(slice)) fmt.Println("length:", len(slice)) fmt.Println("We had to go find more space! Which takes time and effort!") fmt.Println("slice:", slice) unpackAllThese := []string{"`...`", "is used to put", "all the values in", "at the same time"} slice = append(slice, unpackAllThese...) fmt.Println("capacity:", cap(slice)) fmt.Println("length:", len(slice)) fmt.Println("We had to go find even more space!!!") fmt.Println("slice:", slice) } // SliceCopy shows how to copy one slice into another slice using the builtin // `copy` function. func SliceCopy() { // src is short for source srcSlice := make([]int, 10) fmt.Println("empty srcSlice:", srcSlice) for i := 0; i < 10; i++ { srcSlice[i] = i } fmt.Println("full srcSlice:", srcSlice) // dst is short for destination dstSlice := make([]int, len(srcSlice)) fmt.Println("empty dstSlice:", dstSlice) copy(dstSlice, srcSlice) fmt.Println("full dstSlice:", dstSlice) } // SliceIndexOutOfRangePanic shows us what happens when we try to access an // index that does not exist in a slice. func SliceIndexOutOfRangePanic() { defer func() { if r := recover(); r != nil { fmt.Println("slice paniced!\n", r) } }() sl := make([]int, 5) // Change -1 to 0 to see the panic happen at the other end of the slice. for i := -1; i < len(sl)+1; i++ { fmt.Println("NOTE(jay): this is going to panic before we ever see this!", sl[i]) } } // SliceSlices shows us why a slice is called a slice and that's because we can // take slices (pieces) of a slice depending on our needs using the `:` slice // operator. func SliceSlices() { var slice = []string{"zero", "one", "two", "three", "four", "five"} fmt.Printf("sliceUpToThirdIndex: %v\nlength: %d capacity: %d\n", slice, len(slice), cap(slice)) sliceUpToThirdIndex := slice[:3] fmt.Printf("sliceUpToThirdIndex: %v\nlength: %d capacity: %d\n", sliceUpToThirdIndex, len(sliceUpToThirdIndex), cap(sliceUpToThirdIndex)) sliceStartAtIndexTwo := slice[2:] fmt.Printf("sliceStartAtIndexTwo: %v\nlength: %d capacity: %d\n", sliceStartAtIndexTwo, len(sliceStartAtIndexTwo), cap(sliceStartAtIndexTwo)) sliceFromOneUpToFour := slice[1:4] fmt.Printf("sliceFromOneUpToFour: %v\nlength: %d capacity: %d\n", sliceFromOneUpToFour, len(sliceFromOneUpToFour), cap(sliceFromOneUpToFour)) s := "Max Efficiency" fmt.Println(s[4:], "to the", s[:3], "for substrings") } // SliceMatrix shows how to make a matrix also known as a 2d array, but still // have the flexibility of slices! func SliceMatrix() { // We will allocate three slices in a slice matrix := make([][]int, 3) fmt.Println("matrix empty:", matrix) for i := 0; i < 3; i++ { innerSliceLen := i + 1 matrix[i] = make([]int, innerSliceLen) for j := 0; j < innerSliceLen; j++ { matrix[i][j] = i + j } } fmt.Println("matrix full:", matrix) // and we can treat each slice like we would any other slice. matrix[0] = append(matrix[0], 21) fmt.Println("matrix append first slice with value:", matrix) }
basics/completed/slice/slice.go
0.596198
0.616474
slice.go
starcoder
package box2d import ( "fmt" "math" ) const b2_minPulleyLength = 2.0 /// Pulley joint definition. This requires two ground anchors, /// two dynamic body anchor points, and a pulley ratio. type B2PulleyJointDef struct { B2JointDef /// The first ground anchor in world coordinates. This point never moves. GroundAnchorA B2Vec2 /// The second ground anchor in world coordinates. This point never moves. GroundAnchorB B2Vec2 /// The local anchor point relative to bodyA's origin. LocalAnchorA B2Vec2 /// The local anchor point relative to bodyB's origin. LocalAnchorB B2Vec2 /// The a reference length for the segment attached to bodyA. LengthA float64 /// The a reference length for the segment attached to bodyB. LengthB float64 /// The pulley ratio, used to simulate a block-and-tackle. Ratio float64 } func MakeB2PulleyJointDef() B2PulleyJointDef { res := B2PulleyJointDef{ B2JointDef: MakeB2JointDef(), } res.Type = B2JointType.E_pulleyJoint res.GroundAnchorA.Set(-1.0, 1.0) res.GroundAnchorB.Set(1.0, 1.0) res.LocalAnchorA.Set(-1.0, 0.0) res.LocalAnchorB.Set(1.0, 0.0) res.LengthA = 0.0 res.LengthB = 0.0 res.Ratio = 1.0 res.CollideConnected = true return res } /// The pulley joint is connected to two bodies and two fixed ground points. /// The pulley supports a ratio such that: /// length1 + ratio * length2 <= constant /// Yes, the force transmitted is scaled by the ratio. /// Warning: the pulley joint can get a bit squirrelly by itself. They often /// work better when combined with prismatic joints. You should also cover the /// the anchor points with static shapes to prevent one side from going to /// zero length. type B2PulleyJoint struct { *B2Joint M_groundAnchorA B2Vec2 M_groundAnchorB B2Vec2 M_lengthA float64 M_lengthB float64 // Solver shared M_localAnchorA B2Vec2 M_localAnchorB B2Vec2 M_constant float64 M_ratio float64 M_impulse float64 // Solver temp M_indexA int M_indexB int M_uA B2Vec2 M_uB B2Vec2 M_rA B2Vec2 M_rB B2Vec2 M_localCenterA B2Vec2 M_localCenterB B2Vec2 M_invMassA float64 M_invMassB float64 M_invIA float64 M_invIB float64 M_mass float64 } // Pulley: // length1 = norm(p1 - s1) // length2 = norm(p2 - s2) // C0 = (length1 + ratio * length2)_initial // C = C0 - (length1 + ratio * length2) // u1 = (p1 - s1) / norm(p1 - s1) // u2 = (p2 - s2) / norm(p2 - s2) // Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) // J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) func (def *B2PulleyJointDef) Initialize(bA *B2Body, bB *B2Body, groundA B2Vec2, groundB B2Vec2, anchorA B2Vec2, anchorB B2Vec2, r float64) { def.BodyA = bA def.BodyB = bB def.GroundAnchorA = groundA def.GroundAnchorB = groundB def.LocalAnchorA = def.BodyA.GetLocalPoint(anchorA) def.LocalAnchorB = def.BodyB.GetLocalPoint(anchorB) dA := B2Vec2Sub(anchorA, groundA) def.LengthA = dA.Length() dB := B2Vec2Sub(anchorB, groundB) def.LengthB = dB.Length() def.Ratio = r B2Assert(def.Ratio > B2_epsilon) } func MakeB2PulleyJoint(def *B2PulleyJointDef) *B2PulleyJoint { res := B2PulleyJoint{ B2Joint: MakeB2Joint(def), } res.M_groundAnchorA = def.GroundAnchorA res.M_groundAnchorB = def.GroundAnchorB res.M_localAnchorA = def.LocalAnchorA res.M_localAnchorB = def.LocalAnchorB res.M_lengthA = def.LengthA res.M_lengthB = def.LengthB B2Assert(def.Ratio != 0.0) res.M_ratio = def.Ratio res.M_constant = def.LengthA + res.M_ratio*def.LengthB res.M_impulse = 0.0 return &res } func (joint *B2PulleyJoint) InitVelocityConstraints(data B2SolverData) { joint.M_indexA = joint.M_bodyA.M_islandIndex joint.M_indexB = joint.M_bodyB.M_islandIndex joint.M_localCenterA = joint.M_bodyA.M_sweep.LocalCenter joint.M_localCenterB = joint.M_bodyB.M_sweep.LocalCenter joint.M_invMassA = joint.M_bodyA.M_invMass joint.M_invMassB = joint.M_bodyB.M_invMass joint.M_invIA = joint.M_bodyA.M_invI joint.M_invIB = joint.M_bodyB.M_invI cA := data.Positions[joint.M_indexA].C aA := data.Positions[joint.M_indexA].A vA := data.Velocities[joint.M_indexA].V wA := data.Velocities[joint.M_indexA].W cB := data.Positions[joint.M_indexB].C aB := data.Positions[joint.M_indexB].A vB := data.Velocities[joint.M_indexB].V wB := data.Velocities[joint.M_indexB].W qA := MakeB2RotFromAngle(aA) qB := MakeB2RotFromAngle(aB) joint.M_rA = B2RotVec2Mul(qA, B2Vec2Sub(joint.M_localAnchorA, joint.M_localCenterA)) joint.M_rB = B2RotVec2Mul(qB, B2Vec2Sub(joint.M_localAnchorB, joint.M_localCenterB)) // Get the pulley axes. joint.M_uA = B2Vec2Sub(B2Vec2Add(cA, joint.M_rA), joint.M_groundAnchorA) joint.M_uB = B2Vec2Sub(B2Vec2Add(cB, joint.M_rB), joint.M_groundAnchorB) lengthA := joint.M_uA.Length() lengthB := joint.M_uB.Length() if lengthA > 10.0*B2_linearSlop { joint.M_uA.OperatorScalarMulInplace(1.0 / lengthA) } else { joint.M_uA.SetZero() } if lengthB > 10.0*B2_linearSlop { joint.M_uB.OperatorScalarMulInplace(1.0 / lengthB) } else { joint.M_uB.SetZero() } // Compute effective mass. ruA := B2Vec2Cross(joint.M_rA, joint.M_uA) ruB := B2Vec2Cross(joint.M_rB, joint.M_uB) mA := joint.M_invMassA + joint.M_invIA*ruA*ruA mB := joint.M_invMassB + joint.M_invIB*ruB*ruB joint.M_mass = mA + joint.M_ratio*joint.M_ratio*mB if joint.M_mass > 0.0 { joint.M_mass = 1.0 / joint.M_mass } if data.Step.WarmStarting { // Scale impulses to support variable time steps. joint.M_impulse *= data.Step.DtRatio // Warm starting. PA := B2Vec2MulScalar(-(joint.M_impulse), joint.M_uA) PB := B2Vec2MulScalar(-joint.M_ratio*joint.M_impulse, joint.M_uB) vA.OperatorPlusInplace(B2Vec2MulScalar(joint.M_invMassA, PA)) wA += joint.M_invIA * B2Vec2Cross(joint.M_rA, PA) vB.OperatorPlusInplace(B2Vec2MulScalar(joint.M_invMassB, PB)) wB += joint.M_invIB * B2Vec2Cross(joint.M_rB, PB) } else { joint.M_impulse = 0.0 } data.Velocities[joint.M_indexA].V = vA data.Velocities[joint.M_indexA].W = wA data.Velocities[joint.M_indexB].V = vB data.Velocities[joint.M_indexB].W = wB } func (joint *B2PulleyJoint) SolveVelocityConstraints(data B2SolverData) { vA := data.Velocities[joint.M_indexA].V wA := data.Velocities[joint.M_indexA].W vB := data.Velocities[joint.M_indexB].V wB := data.Velocities[joint.M_indexB].W vpA := B2Vec2Add(vA, B2Vec2CrossScalarVector(wA, joint.M_rA)) vpB := B2Vec2Add(vB, B2Vec2CrossScalarVector(wB, joint.M_rB)) Cdot := -B2Vec2Dot(joint.M_uA, vpA) - joint.M_ratio*B2Vec2Dot(joint.M_uB, vpB) impulse := -joint.M_mass * Cdot joint.M_impulse += impulse PA := B2Vec2MulScalar(-impulse, joint.M_uA) PB := B2Vec2MulScalar(-joint.M_ratio*impulse, joint.M_uB) vA.OperatorPlusInplace(B2Vec2MulScalar(joint.M_invMassA, PA)) wA += joint.M_invIA * B2Vec2Cross(joint.M_rA, PA) vB.OperatorPlusInplace(B2Vec2MulScalar(joint.M_invMassB, PB)) wB += joint.M_invIB * B2Vec2Cross(joint.M_rB, PB) data.Velocities[joint.M_indexA].V = vA data.Velocities[joint.M_indexA].W = wA data.Velocities[joint.M_indexB].V = vB data.Velocities[joint.M_indexB].W = wB } func (joint *B2PulleyJoint) SolvePositionConstraints(data B2SolverData) bool { cA := data.Positions[joint.M_indexA].C aA := data.Positions[joint.M_indexA].A cB := data.Positions[joint.M_indexB].C aB := data.Positions[joint.M_indexB].A qA := MakeB2RotFromAngle(aA) qB := MakeB2RotFromAngle(aB) rA := B2RotVec2Mul(qA, B2Vec2Sub(joint.M_localAnchorA, joint.M_localCenterA)) rB := B2RotVec2Mul(qB, B2Vec2Sub(joint.M_localAnchorB, joint.M_localCenterB)) // Get the pulley axes. uA := B2Vec2Sub(B2Vec2Add(cA, rA), joint.M_groundAnchorA) uB := B2Vec2Sub(B2Vec2Add(cB, rB), joint.M_groundAnchorB) lengthA := uA.Length() lengthB := uB.Length() if lengthA > 10.0*B2_linearSlop { uA.OperatorScalarMulInplace(1.0 / lengthA) } else { uA.SetZero() } if lengthB > 10.0*B2_linearSlop { uB.OperatorScalarMulInplace(1.0 / lengthB) } else { uB.SetZero() } // Compute effective mass. ruA := B2Vec2Cross(rA, uA) ruB := B2Vec2Cross(rB, uB) mA := joint.M_invMassA + joint.M_invIA*ruA*ruA mB := joint.M_invMassB + joint.M_invIB*ruB*ruB mass := mA + joint.M_ratio*joint.M_ratio*mB if mass > 0.0 { mass = 1.0 / mass } C := joint.M_constant - lengthA - joint.M_ratio*lengthB linearError := math.Abs(C) impulse := -mass * C PA := B2Vec2MulScalar(-impulse, uA) PB := B2Vec2MulScalar(-joint.M_ratio*impulse, uB) cA.OperatorPlusInplace(B2Vec2MulScalar(joint.M_invMassA, PA)) aA += joint.M_invIA * B2Vec2Cross(rA, PA) cB.OperatorPlusInplace(B2Vec2MulScalar(joint.M_invMassB, PB)) aB += joint.M_invIB * B2Vec2Cross(rB, PB) data.Positions[joint.M_indexA].C = cA data.Positions[joint.M_indexA].A = aA data.Positions[joint.M_indexB].C = cB data.Positions[joint.M_indexB].A = aB return linearError < B2_linearSlop } func (joint B2PulleyJoint) GetAnchorA() B2Vec2 { return joint.M_bodyA.GetWorldPoint(joint.M_localAnchorA) } func (joint B2PulleyJoint) GetAnchorB() B2Vec2 { return joint.M_bodyB.GetWorldPoint(joint.M_localAnchorB) } func (joint B2PulleyJoint) GetReactionForce(inv_dt float64) B2Vec2 { P := B2Vec2MulScalar(joint.M_impulse, joint.M_uB) return B2Vec2MulScalar(inv_dt, P) } func (joint B2PulleyJoint) GetReactionTorque(inv_dt float64) float64 { return 0.0 } func (joint B2PulleyJoint) GetGroundAnchorA() B2Vec2 { return joint.M_groundAnchorA } func (joint B2PulleyJoint) GetGroundAnchorB() B2Vec2 { return joint.M_groundAnchorB } func (joint B2PulleyJoint) GetLengthA() float64 { return joint.M_lengthA } func (joint B2PulleyJoint) GetLengthB() float64 { return joint.M_lengthB } func (joint B2PulleyJoint) GetRatio() float64 { return joint.M_ratio } func (joint B2PulleyJoint) GetCurrentLengthA() float64 { p := joint.M_bodyA.GetWorldPoint(joint.M_localAnchorA) s := joint.M_groundAnchorA d := B2Vec2Sub(p, s) return d.Length() } func (joint B2PulleyJoint) GetCurrentLengthB() float64 { p := joint.M_bodyB.GetWorldPoint(joint.M_localAnchorB) s := joint.M_groundAnchorB d := B2Vec2Sub(p, s) return d.Length() } func (joint *B2PulleyJoint) Dump() { indexA := joint.M_bodyA.M_islandIndex indexB := joint.M_bodyB.M_islandIndex fmt.Printf(" b2PulleyJointDef jd;\n") fmt.Printf(" jd.bodyA = bodies[%d];\n", indexA) fmt.Printf(" jd.bodyB = bodies[%d];\n", indexB) fmt.Printf(" jd.collideConnected = bool(%d);\n", joint.M_collideConnected) fmt.Printf(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", joint.M_groundAnchorA.X, joint.M_groundAnchorA.Y) fmt.Printf(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", joint.M_groundAnchorB.X, joint.M_groundAnchorB.Y) fmt.Printf(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", joint.M_localAnchorA.X, joint.M_localAnchorA.Y) fmt.Printf(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", joint.M_localAnchorB.X, joint.M_localAnchorB.Y) fmt.Printf(" jd.lengthA = %.15lef;\n", joint.M_lengthA) fmt.Printf(" jd.lengthB = %.15lef;\n", joint.M_lengthB) fmt.Printf(" jd.ratio = %.15lef;\n", joint.M_ratio) fmt.Printf(" joints[%d] = m_world.CreateJoint(&jd);\n", joint.M_index) } func (joint *B2PulleyJoint) ShiftOrigin(newOrigin B2Vec2) { joint.M_groundAnchorA.OperatorMinusInplace(newOrigin) joint.M_groundAnchorB.OperatorMinusInplace(newOrigin) }
DynamicsB2JointPulley.go
0.848941
0.776369
DynamicsB2JointPulley.go
starcoder
package iso20022 // Key elements used to refer the original transaction. type OriginalTransactionReference19 struct { // Amount of money to be moved between the debtor and creditor, before deduction of charges, expressed in the currency as ordered by the initiating party. Amount *AmountType3Choice `xml:"Amt,omitempty"` // Date at which the initiating party requests the clearing agent to process the payment. // Usage: This is the date on which the debtor's account is to be debited. If payment by cheque, the date when the cheque must be generated by the bank. RequestedExecutionDate *ISODate `xml:"ReqdExctnDt,omitempty"` // Set of elements used to further specify the type of transaction. PaymentTypeInformation *PaymentTypeInformation19 `xml:"PmtTpInf,omitempty"` // Specifies the means of payment that will be used to move the amount of money. PaymentMethod *PaymentMethod4Code `xml:"PmtMtd,omitempty"` // Information supplied to enable the matching of an entry with the items that the transfer is intended to settle, such as commercial invoices in an accounts' receivable system. RemittanceInformation *RemittanceInformation6 `xml:"RmtInf,omitempty"` // Ultimate party that owes an amount of money to the (ultimate) creditor. UltimateDebtor *PartyIdentification43 `xml:"UltmtDbtr,omitempty"` // Party that owes an amount of money to the (ultimate) creditor. Debtor *PartyIdentification43 `xml:"Dbtr,omitempty"` // Unambiguous identification of the account of the debtor to which a debit entry will be made as a result of the transaction. DebtorAccount *CashAccount24 `xml:"DbtrAcct,omitempty"` // Financial institution servicing an account for the debtor. DebtorAgent *BranchAndFinancialInstitutionIdentification5 `xml:"DbtrAgt,omitempty"` // Financial institution servicing an account for the creditor. CreditorAgent *BranchAndFinancialInstitutionIdentification5 `xml:"CdtrAgt"` // Party to which an amount of money is due. Creditor *PartyIdentification43 `xml:"Cdtr"` // Unambiguous identification of the account of the creditor to which a credit entry will be posted as a result of the payment transaction. CreditorAccount *CashAccount24 `xml:"CdtrAcct,omitempty"` // Ultimate party to which an amount of money is due. UltimateCreditor *PartyIdentification43 `xml:"UltmtCdtr,omitempty"` } func (o *OriginalTransactionReference19) AddAmount() *AmountType3Choice { o.Amount = new(AmountType3Choice) return o.Amount } func (o *OriginalTransactionReference19) SetRequestedExecutionDate(value string) { o.RequestedExecutionDate = (*ISODate)(&value) } func (o *OriginalTransactionReference19) AddPaymentTypeInformation() *PaymentTypeInformation19 { o.PaymentTypeInformation = new(PaymentTypeInformation19) return o.PaymentTypeInformation } func (o *OriginalTransactionReference19) SetPaymentMethod(value string) { o.PaymentMethod = (*PaymentMethod4Code)(&value) } func (o *OriginalTransactionReference19) AddRemittanceInformation() *RemittanceInformation6 { o.RemittanceInformation = new(RemittanceInformation6) return o.RemittanceInformation } func (o *OriginalTransactionReference19) AddUltimateDebtor() *PartyIdentification43 { o.UltimateDebtor = new(PartyIdentification43) return o.UltimateDebtor } func (o *OriginalTransactionReference19) AddDebtor() *PartyIdentification43 { o.Debtor = new(PartyIdentification43) return o.Debtor } func (o *OriginalTransactionReference19) AddDebtorAccount() *CashAccount24 { o.DebtorAccount = new(CashAccount24) return o.DebtorAccount } func (o *OriginalTransactionReference19) AddDebtorAgent() *BranchAndFinancialInstitutionIdentification5 { o.DebtorAgent = new(BranchAndFinancialInstitutionIdentification5) return o.DebtorAgent } func (o *OriginalTransactionReference19) AddCreditorAgent() *BranchAndFinancialInstitutionIdentification5 { o.CreditorAgent = new(BranchAndFinancialInstitutionIdentification5) return o.CreditorAgent } func (o *OriginalTransactionReference19) AddCreditor() *PartyIdentification43 { o.Creditor = new(PartyIdentification43) return o.Creditor } func (o *OriginalTransactionReference19) AddCreditorAccount() *CashAccount24 { o.CreditorAccount = new(CashAccount24) return o.CreditorAccount } func (o *OriginalTransactionReference19) AddUltimateCreditor() *PartyIdentification43 { o.UltimateCreditor = new(PartyIdentification43) return o.UltimateCreditor }
OriginalTransactionReference19.go
0.718496
0.409929
OriginalTransactionReference19.go
starcoder
package risk import ( "github.com/golang/glog" "gopkg.in/yaml.v2" "io/ioutil" "sort" ) type ScoreConfig struct { Name string `yaml:"name"` Title string `yaml:"title"` ShortDescription string `yaml:"shortDescription"` Description string `yaml:"description"` Confidentiality RiskCIACategory `yaml:"confidentiality"` ConfidentialityDescription string `yaml:"confidentialityDescription"` Integrity RiskCIACategory `yaml:"integrity"` IntegrityDescription string `yaml:"integrityDescription"` Availability RiskCIACategory `yaml:"availability"` AvailabilityDescription string `yaml:"availabilityDescription"` Exploitability RiskFactorCategory `yaml:"exploitability"` AttackVector RiskAttackVector `yaml:"attackVector"` Scope RiskScope `yaml:"scope"` Handler string `yaml:"handler"` } type ScoreRange struct { MinScore float64 `yaml:"min"` LowScore float64 `yaml:"low"` MediumScore float64 `yaml:"medium"` MaxScore float64 `yaml:"max"` } type AttackVectorConfig struct { Remote float64 `yaml:"remote"` Local float64 `yaml:"local"` } type ExploitabilityConfig struct { High float64 `yaml:"high"` Moderate float64 `yaml:"moderate"` Low float64 `yaml:"low"` VeryLow float64 `yaml:"veryLow"` } type CIAConfig struct { High float64 `yaml:"high"` Low float64 `yaml:"low"` None float64 `yaml:"none"` } type ScopeFactorConfig struct { None float64 `yaml:"none"` Host float64 `yaml:"host"` Cluster float64 `yaml:"cluster"` } type Config struct { ExpConst float64 `yaml:"expConst"` ImpactConst float64 `yaml:"impactConst"` AttackVector AttackVectorConfig `yaml:"attackVector"` Exploitability ExploitabilityConfig `yaml:"exploitability"` ScopeFactor ScopeFactorConfig `yaml:"scopeFactor"` CIAScore CIAConfig `yaml:"ciaScore"` RiskCategory ScoreRange `yaml:"riskCategory"` IndividualRiskCategory ScoreRange `yaml:"individualRiskCategory"` Basic []ScoreConfig `yaml:"basic"` Remediation []ScoreConfig `yaml:"remediation"` } func (config *Config) Validate() bool { for _, b := range config.Basic { if !validateScoreConfig(b) { return false } } for _, r := range config.Remediation { if !validateScoreConfig(r) { return false } } return true } func (config *Config) GetCIAScore(factor RiskCIACategory) float64 { switch factor { case CIAHigh: return config.CIAScore.High case CIALow: return config.CIAScore.Low default: return config.CIAScore.None } } func (config *Config) GetScopeScore(scope RiskScope) float64 { switch scope { case ScopeHost: return config.ScopeFactor.Host case ScopeCluster: return config.ScopeFactor.Cluster default: return config.ScopeFactor.None } } func (config *Config) GetAtackVectorScore(av RiskAttackVector) float64 { switch av { case AttackVectorRemote: return config.AttackVector.Remote case AttackVectorLocal: return config.AttackVector.Local default: return 0 } } func (config *Config) GetExploitabilityScore(exp RiskFactorCategory) float64 { switch exp { case FactorHigh: return config.Exploitability.High case FactorModerate: return config.Exploitability.Moderate case FactorLow: return config.Exploitability.Low case FactorVeryLow: return config.Exploitability.VeryLow default: return 0 } } func validateScoreConfig(sc ScoreConfig) bool { return ValidateCIACategory(sc.Confidentiality) && ValidateCIACategory(sc.Integrity) && ValidateCIACategory(sc.Availability) && ValidateFactorCategory(sc.Exploitability) && ValidateAttackVector(sc.AttackVector) && ValidateScope(sc.Scope) } func NewConfigFromFile(configFile string) *Config { configStr, err := ioutil.ReadFile(configFile) if err != nil { glog.Fatalf("Failed to read the risk config from file %v: %v", configFile, err) } var result *Config if err := yaml.Unmarshal(configStr, &result); err != nil { glog.Fatalf("Failed unmarshaling insights risk with err: %v (conf string = %s)", err, configStr) } if !result.Validate() { glog.Fatalf("Failed parsing insights risk config: %s", configStr) } sort.Slice(result.Basic, func(i, j int) bool { return result.Basic[i].Scope != ScopeNone }) return result }
server/src/risk/config.go
0.628293
0.415729
config.go
starcoder
package tree import ( "fmt" "strings" ) // BST interface includes basic functions for a binary search tree item type BST interface { Left() BST Right() BST Value() interface{} SetLeft(BST) SetRight(BST) SetValue(interface{}) Find(interface{}) BST Has(interface{}) bool } // BSTNode represents a binary search tree node type BSTNode struct { left BST right BST value interface{} } // NewBSTNode constructs an BSTNode instance func NewBSTNode(v interface{}, l, r BST) *BSTNode { var o = &BSTNode{value: v, left: l, right: r} return o } // Left implements BST func (o *BSTNode) Left() BST { return o.left } // SetLeft implements BST func (o *BSTNode) SetLeft(node BST) { o.left = node } // Right implements BST func (o *BSTNode) Right() BST { return o.right } // SetRight implements BST func (o *BSTNode) SetRight(node BST) { o.right = node } // SetValue implements BST func (o *BSTNode) SetValue(v interface{}) { o.value = v } // Value implements BST func (o *BSTNode) Value() interface{} { return o.value } // Find returns the node matches to the value v func (o *BSTNode) Find(v interface{}) BST { if o == nil { return nil } if o.value == v { return o } else if left := o.Left(); left != nil { return left.Find(v) } else if right := o.Right(); right != nil { return right.Find(v) } return nil } // Has returns true if value v is found in any node; otherwise false func (o *BSTNode) Has(v interface{}) bool { if o == nil { return false } hasInLeft := o.Left() != nil && o.Left().Has(v) hasInRight := o.Right() != nil && o.Right().Has(v) return o.value == v || hasInLeft || hasInRight } // String returns a string representation of StrBSTNode object func (o *BSTNode) String() string { if o == nil { return "<nil>" } return fmt.Sprintf("%v -> (%v, %v)", o.Value(), o.Left(), o.Right()) } /******************************************************************************* * Integer node and tree ******************************************************************************* */ // IntBST interface for any binary search tree item contains int value type IntBST interface { BST Sum() int } // IntBSTNode represents an integer (int) binary search tree node type IntBSTNode struct { BSTNode } // NewIntBSTNode constructs an IntBSTNode instance func NewIntBSTNode(v int, l, r IntBST) *IntBSTNode { var o IntBST = &IntBSTNode{} o.SetLeft(l) o.SetRight(r) o.SetValue(v) return o.(*IntBSTNode) } // Sum adds up values in all tree nodes func (it *IntBSTNode) Sum() int { if it == nil { return 0 } v := it.value.(int) var sumInLeft, sumInRight int if it.Left() != nil { sumInLeft = it.Left().(*IntBSTNode).Sum() } if it.Right() != nil { sumInRight = it.Right().(*IntBSTNode).Sum() } return v + sumInLeft + sumInRight } /******************************************************************************* * String node and tree ******************************************************************************* */ // StrBST interface for any binary search tree item contains string value type StrBST interface { BST Join(string) string } // StrBSTNode represents an integer (int) binary search tree node type StrBSTNode struct { BSTNode } // NewStrBSTNode constructs an StrBSTNode instance func NewStrBSTNode(v string, l, r StrBST) *StrBSTNode { var o StrBST = &StrBSTNode{} o.SetLeft(l) o.SetRight(r) o.SetValue(v) return o.(*StrBSTNode) } // Join concatenates values in all tree nodes func (it *StrBSTNode) Join(sep string) string { if it == nil { return "" } v := it.value.(string) var strInLeft, strInRight string if it.Left() != nil { if l, ok := it.Left().(*StrBSTNode); ok { strInLeft = l.Join(sep) } } if it.Right() != nil { if r, ok := it.Right().(*StrBSTNode); ok { strInRight = r.Join(sep) } } result := strings.Trim(strings.Join([]string{v, strInLeft, strInRight}, sep), sep) return strings.Replace(result, sep+sep, sep, -1) }
ds/tree/tree.go
0.723505
0.451508
tree.go
starcoder
package ldp import ( "github.com/meowpub/meow/ld" ) // Links a resource with constraints that the server requires requests like creation and update to conform to. func GetConstrainedBy(e ld.Entity) interface{} { return e.Get(Prop_ConstrainedBy.ID) } func SetConstrainedBy(e ld.Entity, v interface{}) { e.Set(Prop_ConstrainedBy.ID, v) } // Links a container with resources created through the container. func GetContains(e ld.Entity) interface{} { return e.Get(Prop_Contains.ID) } func SetContains(e ld.Entity, v interface{}) { e.Set(Prop_Contains.ID, v) } // Indicates which predicate is used in membership triples, and that the membership triple pattern is < membership-constant-URI , object-of-hasMemberRelation, member-URI >. func GetHasMemberRelation(e ld.Entity) interface{} { return e.Get(Prop_HasMemberRelation.ID) } func SetHasMemberRelation(e ld.Entity, v interface{}) { e.Set(Prop_HasMemberRelation.ID, v) } // Links a resource to a container where notifications for the resource can be created and discovered. func GetInbox(e ld.Entity) interface{} { return e.Get(Prop_Inbox.ID) } func SetInbox(e ld.Entity, v interface{}) { e.Set(Prop_Inbox.ID, v) } // Indicates which triple in a creation request should be used as the member-URI value in the membership triple added when the creation request is successful. func GetInsertedContentRelation(e ld.Entity) interface{} { return e.Get(Prop_InsertedContentRelation.ID) } func SetInsertedContentRelation(e ld.Entity, v interface{}) { e.Set(Prop_InsertedContentRelation.ID, v) } // Indicates which predicate is used in membership triples, and that the membership triple pattern is < member-URI , object-of-isMemberOfRelation, membership-constant-URI >. func GetIsMemberOfRelation(e ld.Entity) interface{} { return e.Get(Prop_IsMemberOfRelation.ID) } func SetIsMemberOfRelation(e ld.Entity, v interface{}) { e.Set(Prop_IsMemberOfRelation.ID, v) } // LDP servers should use this predicate as the membership predicate if there is no obvious predicate from an application vocabulary to use. func GetMember(e ld.Entity) interface{} { return e.Get(Prop_Member.ID) } func SetMember(e ld.Entity, v interface{}) { e.Set(Prop_Member.ID, v) } // Indicates the membership-constant-URI in a membership triple. Depending upon the membership triple pattern a container uses, as indicated by the presence of ldp:hasMemberRelation or ldp:isMemberOfRelation, the membership-constant-URI might occupy either the subject or object position in membership triples. func GetMembershipResource(e ld.Entity) interface{} { return e.Get(Prop_MembershipResource.ID) } func SetMembershipResource(e ld.Entity, v interface{}) { e.Set(Prop_MembershipResource.ID, v) } // Link to a page sequence resource, as defined by LDP Paging. Typically used to communicate the sorting criteria used to allocate LDPC members to pages. func GetPageSequence(e ld.Entity) interface{} { return e.Get(Prop_PageSequence.ID) } func SetPageSequence(e ld.Entity, v interface{}) { e.Set(Prop_PageSequence.ID, v) } // The collation used to order the members across pages in a page sequence when comparing strings. func GetPageSortCollation(e ld.Entity) interface{} { return e.Get(Prop_PageSortCollation.ID) } func SetPageSortCollation(e ld.Entity, v interface{}) { e.Set(Prop_PageSortCollation.ID, v) } // Link to the list of sorting criteria used by the server in a representation. Typically used on Link response headers as an extension link relation URI in the rel= parameter. func GetPageSortCriteria(e ld.Entity) interface{} { return e.Get(Prop_PageSortCriteria.ID) } func SetPageSortCriteria(e ld.Entity, v interface{}) { e.Set(Prop_PageSortCriteria.ID, v) } // The ascending/descending/etc order used to order the members across pages in a page sequence. func GetPageSortOrder(e ld.Entity) interface{} { return e.Get(Prop_PageSortOrder.ID) } func SetPageSortOrder(e ld.Entity, v interface{}) { e.Set(Prop_PageSortOrder.ID, v) } // Predicate used to specify the order of the members across a page sequence's in-sequence page resources; it asserts nothing about the order of members in the representation of a single page. func GetPageSortPredicate(e ld.Entity) interface{} { return e.Get(Prop_PageSortPredicate.ID) } func SetPageSortPredicate(e ld.Entity, v interface{}) { e.Set(Prop_PageSortPredicate.ID, v) }
ld/ns/ldp/properties.gen.go
0.784855
0.441131
properties.gen.go
starcoder
package processor import ( "context" "time" "github.com/Jeffail/benthos/v3/internal/interop" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/response" "github.com/Jeffail/benthos/v3/lib/types" ) func init() { Constructors[TypeResource] = TypeSpec{ constructor: NewResource, Categories: []Category{ CategoryUtility, }, Summary: ` Resource is a processor type that runs a processor resource identified by its label.`, Description: ` This processor allows you to reference the same configured processor resource in multiple places, and can also tidy up large nested configs. For example, the config: ` + "```yaml" + ` pipeline: processors: - bloblang: | root.message = this root.meta.link_count = this.links.length() root.user.age = this.user.age.number() ` + "```" + ` Is equivalent to: ` + "``` yaml" + ` pipeline: processors: - resource: foo_proc processor_resources: - label: foo_proc bloblang: | root.message = this root.meta.link_count = this.links.length() root.user.age = this.user.age.number() ` + "```" + ` You can find out more about resources [in this document.](/docs/configuration/resources)`, } } //------------------------------------------------------------------------------ // Resource is a processor that returns the result of a processor resource. type Resource struct { mgr types.Manager name string log log.Modular mCount metrics.StatCounter mErr metrics.StatCounter mErrNotFound metrics.StatCounter } // NewResource returns a resource processor. func NewResource( conf Config, mgr types.Manager, log log.Modular, stats metrics.Type, ) (Type, error) { if err := interop.ProbeProcessor(context.Background(), mgr, conf.Resource); err != nil { return nil, err } return &Resource{ mgr: mgr, name: conf.Resource, log: log, mCount: stats.GetCounter("count"), mErrNotFound: stats.GetCounter("error_not_found"), mErr: stats.GetCounter("error"), }, nil } //------------------------------------------------------------------------------ // ProcessMessage applies the processor to a message, either creating >0 // resulting messages or a response to be sent back to the message source. func (r *Resource) ProcessMessage(msg types.Message) (msgs []types.Message, res types.Response) { r.mCount.Incr(1) if err := interop.AccessProcessor(context.Background(), r.mgr, r.name, func(p types.Processor) { msgs, res = p.ProcessMessage(msg) }); err != nil { r.log.Debugf("Failed to obtain processor resource '%v': %v", r.name, err) r.mErrNotFound.Incr(1) r.mErr.Incr(1) return nil, response.NewError(err) } return msgs, res } // CloseAsync shuts down the processor and stops processing requests. func (r *Resource) CloseAsync() { } // WaitForClose blocks until the processor has closed down. func (r *Resource) WaitForClose(timeout time.Duration) error { return nil }
lib/processor/resource.go
0.767777
0.504516
resource.go
starcoder
package currency // CLDRVersion is the CLDR version from which the data is derived. const CLDRVersion = "40.0.0" type numberingSystem uint8 const ( numLatn numberingSystem = iota numArab numArabExt numBeng numDeva numMymr ) type currencyInfo struct { numericCode string digits uint8 } type symbolInfo struct { symbol string locales []string } type currencyFormat struct { pattern string numberingSystem numberingSystem minGroupingDigits uint8 primaryGroupingSize uint8 secondaryGroupingSize uint8 decimalSeparator string groupingSeparator string plusSign string minusSign string } // Defined separately to ensure consistent ordering (G10, then others). var currencyCodes = []string{ // G10 currencies https://en.wikipedia.org/wiki/G10_currencies. "AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NOK", "NZD", "SEK", "USD", // Other currencies. "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CDF", "CLP", "CNY", "COP", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "FJD", "FKP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NPR", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "UYU", "UYW", "UZS", "VES", "VND", "VUV", "WST", "XAF", "XCD", "XOF", "XPF", "YER", "ZAR", "ZMW", "ZWL", } var currencies = map[string]currencyInfo{ "AED": {"784", 2}, "AFN": {"971", 0}, "ALL": {"008", 0}, "AMD": {"051", 2}, "ANG": {"532", 2}, "AOA": {"973", 2}, "ARS": {"032", 2}, "AUD": {"036", 2}, "AWG": {"533", 2}, "AZN": {"944", 2}, "BAM": {"977", 2}, "BBD": {"052", 2}, "BDT": {"050", 2}, "BGN": {"975", 2}, "BHD": {"048", 3}, "BIF": {"108", 0}, "BMD": {"060", 2}, "BND": {"096", 2}, "BOB": {"068", 2}, "BRL": {"986", 2}, "BSD": {"044", 2}, "BTN": {"064", 2}, "BWP": {"072", 2}, "BYN": {"933", 2}, "BZD": {"084", 2}, "CAD": {"124", 2}, "CDF": {"976", 2}, "CHF": {"756", 2}, "CLP": {"152", 0}, "CNY": {"156", 2}, "COP": {"170", 2}, "CRC": {"188", 2}, "CUC": {"931", 2}, "CUP": {"192", 2}, "CVE": {"132", 2}, "CZK": {"203", 2}, "DJF": {"262", 0}, "DKK": {"208", 2}, "DOP": {"214", 2}, "DZD": {"012", 2}, "EGP": {"818", 2}, "ERN": {"232", 2}, "ETB": {"230", 2}, "EUR": {"978", 2}, "FJD": {"242", 2}, "FKP": {"238", 2}, "GBP": {"826", 2}, "GEL": {"981", 2}, "GHS": {"936", 2}, "GIP": {"292", 2}, "GMD": {"270", 2}, "GNF": {"324", 0}, "GTQ": {"320", 2}, "GYD": {"328", 2}, "HKD": {"344", 2}, "HNL": {"340", 2}, "HRK": {"191", 2}, "HTG": {"332", 2}, "HUF": {"348", 2}, "IDR": {"360", 2}, "ILS": {"376", 2}, "INR": {"356", 2}, "IQD": {"368", 0}, "IRR": {"364", 0}, "ISK": {"352", 0}, "JMD": {"388", 2}, "JOD": {"400", 3}, "JPY": {"392", 0}, "KES": {"404", 2}, "KGS": {"417", 2}, "KHR": {"116", 2}, "KMF": {"174", 0}, "KPW": {"408", 0}, "KRW": {"410", 0}, "KWD": {"414", 3}, "KYD": {"136", 2}, "KZT": {"398", 2}, "LAK": {"418", 0}, "LBP": {"422", 0}, "LKR": {"144", 2}, "LRD": {"430", 2}, "LSL": {"426", 2}, "LYD": {"434", 3}, "MAD": {"504", 2}, "MDL": {"498", 2}, "MGA": {"969", 0}, "MKD": {"807", 2}, "MMK": {"104", 0}, "MNT": {"496", 2}, "MOP": {"446", 2}, "MRU": {"929", 2}, "MUR": {"480", 2}, "MVR": {"462", 2}, "MWK": {"454", 2}, "MXN": {"484", 2}, "MYR": {"458", 2}, "MZN": {"943", 2}, "NAD": {"516", 2}, "NGN": {"566", 2}, "NIO": {"558", 2}, "NOK": {"578", 2}, "NPR": {"524", 2}, "NZD": {"554", 2}, "OMR": {"512", 3}, "PAB": {"590", 2}, "PEN": {"604", 2}, "PGK": {"598", 2}, "PHP": {"608", 2}, "PKR": {"586", 2}, "PLN": {"985", 2}, "PYG": {"600", 0}, "QAR": {"634", 2}, "RON": {"946", 2}, "RSD": {"941", 0}, "RUB": {"643", 2}, "RWF": {"646", 0}, "SAR": {"682", 2}, "SBD": {"090", 2}, "SCR": {"690", 2}, "SDG": {"938", 2}, "SEK": {"752", 2}, "SGD": {"702", 2}, "SHP": {"654", 2}, "SLL": {"694", 0}, "SOS": {"706", 0}, "SRD": {"968", 2}, "SSP": {"728", 2}, "STN": {"930", 2}, "SVC": {"222", 2}, "SYP": {"760", 0}, "SZL": {"748", 2}, "THB": {"764", 2}, "TJS": {"972", 2}, "TMT": {"934", 2}, "TND": {"788", 3}, "TOP": {"776", 2}, "TRY": {"949", 2}, "TTD": {"780", 2}, "TWD": {"901", 2}, "TZS": {"834", 2}, "UAH": {"980", 2}, "UGX": {"800", 0}, "USD": {"840", 2}, "UYU": {"858", 2}, "UYW": {"927", 4}, "UZS": {"860", 2}, "VES": {"928", 2}, "VND": {"704", 0}, "VUV": {"548", 0}, "WST": {"882", 2}, "XAF": {"950", 0}, "XCD": {"951", 2}, "XOF": {"952", 0}, "XPF": {"953", 0}, "YER": {"886", 0}, "ZAR": {"710", 2}, "ZMW": {"967", 2}, "ZWL": {"932", 2}, } var currencySymbols = map[string][]symbolInfo{ "AED": { {"AED", []string{"en"}}, {"د.إ.\u200f", []string{"ar"}}, }, "AFN": { {"AFN", []string{"en"}}, {"؋", []string{"fa", "ps"}}, }, "ALL": { {"ALL", []string{"en"}}, {"Lekë", []string{"sq"}}, }, "AMD": { {"AMD", []string{"en"}}, {"֏", []string{"hy"}}, }, "ANG": { {"ANG", []string{"en"}}, {"NAf", []string{"my"}}, {"NAf.", []string{"en-SX", "nl-CW", "nl-SX"}}, }, "AOA": { {"AOA", []string{"en"}}, {"Kz", []string{"pt-AO"}}, }, "ARS": { {"ARS", []string{"en", "fr-CA"}}, {"$", []string{"es-AR"}}, {"$AR", []string{"fr"}}, }, "AUD": { {"A$", []string{"en"}}, {"$", []string{"en-AU", "en-CC", "en-CX", "en-KI", "en-NF", "en-NR", "en-TV"}}, {"$AU", []string{"fr"}}, {"$\u00a0AU", []string{"fr-CA"}}, {"AU$", []string{"am", "ar", "ca", "cs", "da", "de", "et", "id", "ko", "lv", "nl", "pt", "th", "tr", "vi", "yue", "zh", "zh-Hant"}}, }, "AWG": { {"AWG", []string{"en"}}, {"Afl", []string{"my"}}, {"Afl.", []string{"nl-AW"}}, }, "AZN": { {"AZN", []string{"en"}}, {"₼", []string{"az"}}, }, "BAM": { {"BAM", []string{"en"}}, {"KM", []string{"bs", "hr-BA", "sr-Latn"}}, {"КМ", []string{"sr"}}, }, "BBD": { {"BBD", []string{"en"}}, {"$", []string{"en-BB"}}, {"Bds$", []string{"sv"}}, {"DBB", []string{"so"}}, }, "BDT": { {"BDT", []string{"en"}}, {"৳", []string{"bn"}}, }, "BGN": { {"BGN", []string{"en"}}, {"лв.", []string{"bg"}}, }, "BHD": { {"BHD", []string{"en"}}, {"د.ب.\u200f", []string{"ar"}}, }, "BIF": { {"BIF", []string{"en"}}, {"FBu", []string{"en-BI", "fr-BI"}}, }, "BMD": { {"BMD", []string{"en", "fr-CA"}}, {"$", []string{"en-BM"}}, {"$BM", []string{"fr"}}, {"BM$", []string{"sv"}}, }, "BND": { {"BND", []string{"en", "fr-CA"}}, {"$", []string{"ms-BN"}}, {"$BN", []string{"fr"}}, }, "BOB": { {"BOB", []string{"en"}}, {"Bs", []string{"es-BO"}}, }, "BRL": { {"R$", []string{"en"}}, {"BR$", []string{"sv"}}, }, "BSD": { {"BSD", []string{"en"}}, {"$", []string{"en-BS"}}, {"BS$", []string{"sv"}}, }, "BWP": { {"BWP", []string{"en"}}, {"P", []string{"en-BW"}}, }, "BYN": { {"BYN", []string{"en"}}, {"Br", []string{"be", "ru-BY"}}, }, "BZD": { {"BZD", []string{"en", "fr-CA"}}, {"$", []string{"en-BZ", "es-BZ"}}, {"$BZ", []string{"fr"}}, {"BZ$", []string{"sv"}}, }, "CAD": { {"CA$", []string{"en"}}, {"$", []string{"en-CA", "fr-CA"}}, {"$CA", []string{"fa", "fr"}}, {"C$", []string{"nl"}}, }, "CDF": { {"CDF", []string{"en"}}, {"FC", []string{"fr-CD", "sw-CD"}}, }, "CLP": { {"CLP", []string{"en", "fr-CA"}}, {"$", []string{"es-CL"}}, {"$CL", []string{"fr"}}, }, "CNY": { {"CN¥", []string{"en", "zh-Hans-HK", "zh-Hans-MO", "zh-Hans-SG"}}, {"¥", []string{"zh"}}, {"¥CN", []string{"fa"}}, {"\u200eCN¥\u200e", []string{"he"}}, {"元", []string{"ja"}}, }, "COP": { {"COP", []string{"en", "fr-CA"}}, {"$", []string{"es-CO"}}, {"$CO", []string{"fr"}}, }, "CRC": { {"CRC", []string{"en"}}, {"₡", []string{"es-CR"}}, }, "CUP": { {"CUP", []string{"en"}}, {"$", []string{"es-CU"}}, }, "CVE": { {"CVE", []string{"en"}}, {"\u200b", []string{"pt-CV"}}, }, "CZK": { {"CZK", []string{"en"}}, {"Kč", []string{"cs"}}, }, "DJF": { {"DJF", []string{"en"}}, {"Fdj", []string{"ar-DJ", "fr-DJ", "so-DJ"}}, }, "DKK": { {"DKK", []string{"en"}}, {"Dkr", []string{"sv"}}, {"kr.", []string{"da", "en-DK"}}, }, "DOP": { {"DOP", []string{"en"}}, {"RD$", []string{"es-DO", "sv"}}, }, "DZD": { {"DZD", []string{"en"}}, {"DA", []string{"fr-DZ"}}, {"د.ج.\u200f", []string{"ar"}}, }, "EGP": { {"EGP", []string{"en"}}, {"EG£", []string{"sv"}}, {"ج.م.\u200f", []string{"ar"}}, }, "ERN": { {"ERN", []string{"en"}}, {"Nfk", []string{"ar-ER", "en-ER"}}, }, "ETB": { {"ETB", []string{"en"}}, {"Br", []string{"so-ET"}}, {"ብር", []string{"am"}}, }, "EUR": { {"€", []string{"en"}}, }, "FJD": { {"FJD", []string{"en", "fr-CA"}}, {"$", []string{"en-FJ"}}, {"$FJ", []string{"fr"}}, {"FJ$", []string{"nl"}}, }, "FKP": { {"FKP", []string{"en", "fr-CA"}}, {"£", []string{"en-FK"}}, {"£FK", []string{"fr"}}, }, "GBP": { {"£", []string{"en", "fr-CA"}}, {"GB£", []string{"ar-SS", "en-FK", "en-GI", "en-MT", "en-SH", "en-SS"}}, {"UK£", []string{"ar"}}, {"£GB", []string{"fr"}}, }, "GEL": { {"GEL", []string{"en"}}, {"₾", []string{"ka"}}, }, "GHS": { {"GHS", []string{"en"}}, {"GH₵", []string{"en-GH"}}, }, "GIP": { {"GIP", []string{"en", "fr-CA"}}, {"£", []string{"en-GI"}}, {"£GI", []string{"fr"}}, }, "GMD": { {"GMD", []string{"en"}}, {"D", []string{"en-GM"}}, }, "GNF": { {"GNF", []string{"en"}}, {"FG", []string{"fr-GN"}}, }, "GTQ": { {"GTQ", []string{"en"}}, {"Q", []string{"es-GT"}}, }, "GYD": { {"GYD", []string{"en"}}, {"$", []string{"en-GY"}}, }, "HKD": { {"HK$", []string{"en"}}, {"$HK", []string{"fa"}}, {"$\u00a0HK", []string{"fr-CA"}}, }, "HNL": { {"HNL", []string{"en"}}, {"L", []string{"es-HN"}}, }, "HRK": { {"HRK", []string{"en"}}, {"kn", []string{"bs", "hr"}}, }, "HTG": { {"HTG", []string{"en"}}, {"G", []string{"fr-HT", "my"}}, }, "HUF": { {"HUF", []string{"en"}}, {"Ft", []string{"hu"}}, }, "IDR": { {"IDR", []string{"en"}}, {"Rp", []string{"id", "ms-ID"}}, }, "ILS": { {"₪", []string{"en"}}, {"NIS", []string{"sk"}}, }, "INR": { {"₹", []string{"en"}}, {"Rs", []string{"id"}}, }, "IQD": { {"IQD", []string{"en"}}, {"د.ع.\u200f", []string{"ar"}}, }, "IRR": { {"IRR", []string{"en"}}, {"ر.إ.", []string{"ar"}}, {"ریال", []string{"fa"}}, }, "ISK": { {"ISK", []string{"en"}}, {"Ikr", []string{"sv"}}, }, "JMD": { {"JMD", []string{"en"}}, {"$", []string{"en-JM"}}, {"JM$", []string{"sv"}}, }, "JOD": { {"JOD", []string{"en"}}, {"د.أ.\u200f", []string{"ar"}}, }, "JPY": { {"¥", []string{"en", "en-AU"}}, {"JP¥", []string{"af", "am", "ar", "as", "az", "bn", "cs", "cy", "da", "el", "en-001", "en-CA", "eu", "gl", "gu", "hi", "hy", "id", "is", "kk", "km", "ko", "ky", "lo", "mn", "mr", "ms", "my", "ne", "nl", "pa", "ps", "pt", "si", "so", "sq", "sw", "te", "tk", "ur", "uz", "zh", "zu"}}, {"¥", []string{"ja"}}, }, "KES": { {"KES", []string{"en"}}, {"Ksh", []string{"en-KE", "so-KE", "sw"}}, }, "KGS": { {"KGS", []string{"en"}}, {"сом", []string{"ky", "ru-KG"}}, }, "KHR": { {"KHR", []string{"en"}}, {"៛", []string{"km"}}, }, "KMF": { {"KMF", []string{"en"}}, {"CF", []string{"ar-KM", "fr-KM"}}, }, "KRW": { {"₩", []string{"en", "zh-Hant-HK"}}, {"₩", []string{"yue", "zh", "zh-Hant"}}, }, "KWD": { {"KWD", []string{"en"}}, {"د.ك.\u200f", []string{"ar"}}, }, "KYD": { {"KYD", []string{"en"}}, {"$", []string{"en-KY"}}, }, "KZT": { {"KZT", []string{"en"}}, {"₸", []string{"kk", "ru-KZ"}}, }, "LAK": { {"LAK", []string{"en"}}, {"₭", []string{"lo"}}, }, "LBP": { {"LBP", []string{"en", "fr-CA"}}, {"£LB", []string{"fr"}}, {"ل.ل.\u200f", []string{"ar"}}, }, "LKR": { {"LKR", []string{"en"}}, {"Rs.", []string{"ta-LK"}}, {"රු.", []string{"si"}}, }, "LRD": { {"LRD", []string{"en"}}, {"$", []string{"en-LR"}}, }, "LSL": { {"LSL", []string{"en"}}, {"ЛСЛ", []string{"kk"}}, {"ឡូទី", []string{"km"}}, }, "LYD": { {"LYD", []string{"en"}}, {"د.ل.\u200f", []string{"ar"}}, }, "MAD": { {"MAD", []string{"en"}}, {"د.م.\u200f", []string{"ar"}}, }, "MDL": { {"MDL", []string{"en"}}, {"L", []string{"ro-MD", "ru-MD"}}, }, "MGA": { {"MGA", []string{"en"}}, {"Ar", []string{"en-MG", "fr-MG"}}, }, "MKD": { {"MKD", []string{"en"}}, {"den", []string{"sq-MK"}}, {"ден.", []string{"mk"}}, }, "MMK": { {"MMK", []string{"en"}}, {"K", []string{"my"}}, }, "MNT": { {"MNT", []string{"en"}}, {"₮", []string{"mn"}}, }, "MOP": { {"MOP", []string{"en"}}, {"MOP$", []string{"en-MO", "pt-MO", "zh-Hans-MO", "zh-Hant-MO"}}, }, "MRU": { {"MRU", []string{"en"}}, {"UM", []string{"es-MX", "fr-MR"}}, {"أ.م.", []string{"ar"}}, }, "MUR": { {"MUR", []string{"en"}}, {"Rs", []string{"en-MU", "fr-MU"}}, }, "MWK": { {"MWK", []string{"en"}}, {"MK", []string{"en-MW"}}, }, "MXN": { {"MX$", []string{"en", "fr-CA"}}, {"$", []string{"es-MX"}}, {"$MX", []string{"fa", "fr", "gl"}}, }, "MYR": { {"MYR", []string{"en"}}, {"RM", []string{"en-MY", "ms", "ta-MY", "ta-SG"}}, }, "MZN": { {"MZN", []string{"en"}}, {"MTn", []string{"pt-MZ"}}, }, "NAD": { {"NAD", []string{"en", "fr-CA"}}, {"$", []string{"af-NA", "en-NA"}}, {"$NA", []string{"fr"}}, }, "NGN": { {"NGN", []string{"en"}}, {"₦", []string{"en-NG"}}, }, "NIO": { {"NIO", []string{"en"}}, {"C$", []string{"es-NI"}}, }, "NOK": { {"NOK", []string{"en"}}, {"Nkr", []string{"sv"}}, {"kr", []string{"no"}}, }, "NPR": { {"NPR", []string{"en"}}, {"नेरू", []string{"ne"}}, }, "NZD": { {"NZ$", []string{"en"}}, {"$", []string{"en-CK", "en-NU", "en-NZ", "en-PN", "en-TK"}}, {"$NZ", []string{"fa", "fr"}}, {"$\u00a0NZ", []string{"fr-CA"}}, }, "OMR": { {"OMR", []string{"en"}}, {"ر.ع.\u200f", []string{"ar"}}, }, "PAB": { {"PAB", []string{"en"}}, {"B/.", []string{"es-PA", "my"}}, }, "PEN": { {"PEN", []string{"en"}}, {"S/", []string{"es-PE"}}, }, "PGK": { {"PGK", []string{"en"}}, {"K", []string{"en-PG"}}, }, "PHP": { {"₱", []string{"en"}}, }, "PKR": { {"PKR", []string{"en", "ur-IN"}}, {"Rs", []string{"en-PK", "ps-PK", "ur"}}, }, "PLN": { {"PLN", []string{"en"}}, {"zł", []string{"pl"}}, }, "PYG": { {"PYG", []string{"en"}}, {"Gs.", []string{"es-PY"}}, }, "QAR": { {"QAR", []string{"en"}}, {"ر.ق.\u200f", []string{"ar"}}, }, "RSD": { {"RSD", []string{"en"}}, {"din.", []string{"bs"}}, }, "RUB": { {"RUB", []string{"en"}}, {"₽", []string{"be", "kk", "ru"}}, }, "RWF": { {"RWF", []string{"en"}}, {"RF", []string{"en-RW", "fr-RW"}}, }, "SAR": { {"SAR", []string{"en"}}, {"ر.س.\u200f", []string{"ar"}}, }, "SBD": { {"SBD", []string{"en", "fr-CA"}}, {"$", []string{"en-SB"}}, {"$SB", []string{"fr"}}, {"SI$", []string{"nl"}}, }, "SCR": { {"SCR", []string{"en"}}, {"Rs", []string{"en-AU"}}, {"SR", []string{"en-SC", "fr-SC"}}, }, "SDG": { {"SDG", []string{"ar-LB", "en"}}, {"ج.س.", []string{"ar"}}, }, "SEK": { {"SEK", []string{"en"}}, {"kr", []string{"en-SE", "sv"}}, }, "SGD": { {"SGD", []string{"en"}}, {"$", []string{"en-SG", "ms-SG", "ta-SG", "zh-Hans-SG"}}, {"$SG", []string{"fr"}}, {"$\u00a0SG", []string{"fr-CA"}}, {"S$", []string{"ta-MY"}}, }, "SHP": { {"SHP", []string{"en"}}, {"£", []string{"en-SH"}}, }, "SLL": { {"SLL", []string{"en"}}, {"Le", []string{"en-SL"}}, }, "SOS": { {"SOS", []string{"en"}}, {"S", []string{"ar-SO", "so"}}, }, "SRD": { {"SRD", []string{"en", "fr-CA"}}, {"$", []string{"nl-SR"}}, {"$SR", []string{"fr"}}, }, "SSP": { {"SSP", []string{"en"}}, {"£", []string{"ar-SS", "en-SS"}}, }, "STN": { {"STN", []string{"en"}}, {"Db", []string{"pt-ST"}}, }, "SYP": { {"SYP", []string{"en"}}, {"LS", []string{"fr-SY"}}, {"ل.س.\u200f", []string{"ar"}}, }, "SZL": { {"SZL", []string{"en"}}, {"E", []string{"en-SZ"}}, }, "THB": { {"THB", []string{"en", "es-419"}}, {"฿", []string{"af", "am", "ar", "az", "bn", "bs", "ca", "cy", "da", "de", "el", "es", "et", "eu", "fa", "fil", "ga", "gl", "gu", "he", "hi", "hy", "id", "it", "kk", "km", "ky", "lo", "lv", "mn", "mr", "my", "ne", "nl", "pa", "pt", "ru", "si", "sq", "sw", "ta", "te", "th", "tr", "ur", "vi", "zu"}}, }, "TMT": { {"TMT", []string{"en"}}, {"ТМТ", []string{"ru"}}, }, "TND": { {"TND", []string{"en"}}, {"DT", []string{"fr-TN"}}, {"د.ت.\u200f", []string{"ar"}}, }, "TOP": { {"TOP", []string{"en"}}, {"T$", []string{"en-TO"}}, }, "TRY": { {"TRY", []string{"en"}}, {"₺", []string{"tr"}}, }, "TTD": { {"TTD", []string{"en", "fr-CA"}}, {"$", []string{"en-TT"}}, {"$TT", []string{"fr"}}, {"TT$", []string{"my"}}, }, "TWD": { {"NT$", []string{"en", "zh-Hant-HK"}}, {"$", []string{"zh-Hant"}}, }, "TZS": { {"TZS", []string{"en"}}, {"TSh", []string{"en-TZ", "sw"}}, }, "UAH": { {"UAH", []string{"en"}}, {"₴", []string{"ru", "uk"}}, }, "UGX": { {"UGX", []string{"en"}}, {"USh", []string{"en-UG", "sw-UG"}}, }, "USD": { {"$", []string{"en", "en-IN", "es-419", "nl-BQ", "sw-KE"}}, {"$US", []string{"fr"}}, {"$\u00a0US", []string{"fr-CA"}}, {"US$", []string{"am", "ar", "as", "az", "bn", "cs", "cy", "da", "en-001", "en-CA", "es", "es-AR", "es-CL", "es-CO", "es-CU", "es-DO", "es-UY", "eu", "gu", "id", "ka", "ko", "lo", "mk", "my", "ne", "nl", "pa", "pt", "si", "so", "sq", "sr", "sr-Latn", "sv", "sw", "ta-SG", "th", "tk", "uz", "vi", "yue", "zh", "zh-Hant"}}, {"щ.д.", []string{"bg"}}, }, "UYU": { {"UYU", []string{"en", "fr-CA"}}, {"$", []string{"es-UY"}}, {"$UY", []string{"fr"}}, }, "UYW": { {"UYW", []string{"en"}}, {"UP", []string{"es-UY"}}, }, "UZS": { {"UZS", []string{"en"}}, {"soʻm", []string{"uz"}}, }, "VES": { {"VES", []string{"en"}}, {"Bs.S", []string{"es-VE"}}, }, "VND": { {"₫", []string{"en"}}, }, "VUV": { {"VUV", []string{"en"}}, {"VT", []string{"en-VU", "fr-VU"}}, }, "WST": { {"WST", []string{"en", "fr-CA"}}, {"$WS", []string{"fr"}}, {"WS$", []string{"en-WS"}}, }, "XAF": { {"FCFA", []string{"en"}}, }, "XCD": { {"EC$", []string{"en"}}, {"$", []string{"en-AG", "en-AI", "en-DM", "en-GD", "en-KN", "en-LC", "en-MS", "en-VC"}}, {"$EC", []string{"fa"}}, }, "XOF": { {"F\u202fCFA", []string{"en"}}, {"فرانک\u202fCFA", []string{"fa"}}, {"සිෆ්එ", []string{"si"}}, }, "XPF": { {"CFPF", []string{"en", "fr-CA"}}, {"CFP", []string{"en-AU"}}, {"FCFP", []string{"fr"}}, }, "YER": { {"YER", []string{"en"}}, {"ر.ي.\u200f", []string{"ar"}}, }, "ZAR": { {"ZAR", []string{"en"}}, {"R", []string{"af", "en-LS", "en-ZA", "zu"}}, }, "ZMW": { {"ZMW", []string{"en"}}, {"K", []string{"en-ZM"}}, }, } var currencyFormats = map[string]currencyFormat{ "af": {"¤0.00", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "ar": {"0.00\u00a0¤", 1, 1, 3, 3, "٫", "٬", "\u061c+", "\u061c-"}, "ar-AE": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "\u200e+", "\u200e-"}, "ar-DZ": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "\u200e+", "\u200e-"}, "ar-EH": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "\u200e+", "\u200e-"}, "ar-LY": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "\u200e+", "\u200e-"}, "ar-MA": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "\u200e+", "\u200e-"}, "ar-TN": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "\u200e+", "\u200e-"}, "as": {"¤\u00a00.00", 3, 1, 3, 2, ".", ",", "+", "-"}, "az": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "be": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "-"}, "bg": {"0.00\u00a0¤", 0, 2, 0, 0, ",", "\u00a0", "+", "-"}, "bn": {"0.00¤", 3, 1, 3, 2, ".", ",", "+", "-"}, "bs": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "ca": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "cs": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "da": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "de": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "de-AT": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "de-CH": {"¤\u00a00.00;¤-0.00", 0, 1, 3, 3, ".", "’", "+", "-"}, "de-LI": {"¤\u00a00.00", 0, 1, 3, 3, ".", "’", "+", "-"}, "el": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "en": {"¤0.00", 0, 1, 3, 3, ".", ",", "+", "-"}, "en-150": {"0.00\u00a0¤", 0, 1, 3, 3, ".", ",", "+", "-"}, "en-AT": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "en-BE": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "en-CH": {"¤\u00a00.00;¤-0.00", 0, 1, 3, 3, ".", "’", "+", "-"}, "en-DE": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "en-DK": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "en-FI": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "en-IN": {"¤0.00", 0, 1, 3, 2, ".", ",", "+", "-"}, "en-NL": {"¤\u00a00.00;¤\u00a0-0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "en-SE": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "en-SI": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "en-ZA": {"¤0.00", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "es": {"0.00\u00a0¤", 0, 2, 3, 3, ",", ".", "+", "-"}, "es-419": {"¤0.00", 0, 1, 3, 3, ".", ",", "+", "-"}, "es-AR": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "es-BO": {"¤0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "es-CL": {"¤0.00;¤-0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "es-CO": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "es-CR": {"¤0.00", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "es-EC": {"¤0.00;¤-0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "es-GQ": {"¤0.00", 0, 2, 3, 3, ",", ".", "+", "-"}, "es-PE": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "+", "-"}, "es-PY": {"¤\u00a00.00;¤\u00a0-0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "es-UY": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "es-VE": {"¤0.00;¤-0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "et": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "−"}, "eu": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "−"}, "fa": {"\u200e¤0.00", 2, 1, 3, 3, "٫", "٬", "\u200e+", "\u200e−"}, "fa-AF": {"¤\u00a00.00", 2, 1, 3, 3, "٫", "٬", "\u200e+", "\u200e−"}, "fi": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "−"}, "fr": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u202f", "+", "-"}, "fr-CA": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "fr-CH": {"0.00\u00a0¤", 0, 1, 3, 3, ".", "\u202f", "+", "-"}, "fr-LU": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "fr-MA": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "gl": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "gu": {"¤0.00", 0, 1, 3, 2, ".", ",", "+", "-"}, "he": {"\u200f0.00\u00a0¤;\u200f-0.00\u00a0¤", 0, 1, 3, 3, ".", ",", "\u200e+", "\u200e-"}, "hi": {"¤0.00", 0, 1, 3, 2, ".", ",", "+", "-"}, "hr": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "−"}, "hu": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "hy": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "id": {"¤0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "is": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "it": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "it-CH": {"¤\u00a00.00;¤-0.00", 0, 1, 3, 3, ".", "’", "+", "-"}, "ka": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "-"}, "kk": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "km": {"0.00¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "ky": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "lo": {"¤0.00;¤-0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "lt": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "−"}, "lv": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "-"}, "mk": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "mn": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "+", "-"}, "mr": {"¤0.00", 4, 1, 3, 3, ".", ",", "+", "-"}, "ms-BN": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "ms-ID": {"¤0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "my": {"0.00\u00a0¤", 5, 1, 3, 3, ".", ",", "+", "-"}, "ne": {"¤\u00a00.00", 4, 1, 3, 2, ".", ",", "+", "-"}, "nl": {"¤\u00a00.00;¤\u00a0-0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "nn": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "−"}, "no": {"¤\u00a00.00;¤\u00a0-0.00", 0, 1, 3, 3, ",", "\u00a0", "+", "−"}, "pa": {"¤\u00a00.00", 0, 1, 3, 2, ".", ",", "+", "-"}, "pl": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "-"}, "ps": {"0.00\u00a0¤", 2, 1, 3, 3, "٫", "٬", "\u200e+\u200e", "\u200e-\u200e"}, "pt": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "pt-AO": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "pt-PT": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "-"}, "ro": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "ru": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "ru-UA": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "-"}, "sk": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "sl": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "−"}, "sq": {"0.00\u00a0¤", 0, 2, 3, 3, ",", "\u00a0", "+", "-"}, "sr": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "sr-Latn": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, "sv": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "−"}, "sw": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "+", "-"}, "sw-CD": {"¤\u00a00.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "ta": {"¤\u00a00.00", 0, 1, 3, 2, ".", ",", "+", "-"}, "ta-MY": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "+", "-"}, "ta-SG": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "+", "-"}, "te": {"¤0.00", 0, 1, 3, 2, ".", ",", "+", "-"}, "tk": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "tr": {"¤0.00", 0, 1, 3, 3, ",", ".", "+", "-"}, "uk": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "ur": {"¤\u00a00.00", 0, 1, 3, 3, ".", ",", "\u200e+", "\u200e-"}, "ur-IN": {"¤\u00a00.00", 2, 1, 3, 2, "٫", "٬", "\u200e+\u200e", "\u200e-\u200e"}, "uz": {"0.00\u00a0¤", 0, 1, 3, 3, ",", "\u00a0", "+", "-"}, "vi": {"0.00\u00a0¤", 0, 1, 3, 3, ",", ".", "+", "-"}, } var parentLocales = map[string]string{ "az-Arab": "en", "az-Cyrl": "en", "bal-Latn": "en", "blt-Latn": "en", "bs-Cyrl": "en", "en-150": "en-001", "en-AG": "en-001", "en-AI": "en-001", "en-AT": "en-150", "en-AU": "en-001", "en-BB": "en-001", "en-BE": "en-150", "en-BM": "en-001", "en-BS": "en-001", "en-BW": "en-001", "en-BZ": "en-001", "en-CC": "en-001", "en-CH": "en-150", "en-CK": "en-001", "en-CM": "en-001", "en-CX": "en-001", "en-CY": "en-001", "en-DE": "en-150", "en-DG": "en-001", "en-DK": "en-150", "en-DM": "en-001", "en-ER": "en-001", "en-FI": "en-150", "en-FJ": "en-001", "en-FK": "en-001", "en-FM": "en-001", "en-GB": "en-001", "en-GD": "en-001", "en-GG": "en-001", "en-GH": "en-001", "en-GI": "en-001", "en-GM": "en-001", "en-GY": "en-001", "en-HK": "en-001", "en-IE": "en-001", "en-IL": "en-001", "en-IM": "en-001", "en-IN": "en-001", "en-IO": "en-001", "en-JE": "en-001", "en-JM": "en-001", "en-KE": "en-001", "en-KI": "en-001", "en-KN": "en-001", "en-KY": "en-001", "en-LC": "en-001", "en-LR": "en-001", "en-LS": "en-001", "en-MG": "en-001", "en-MO": "en-001", "en-MS": "en-001", "en-MT": "en-001", "en-MU": "en-001", "en-MW": "en-001", "en-MY": "en-001", "en-NA": "en-001", "en-NF": "en-001", "en-NG": "en-001", "en-NL": "en-150", "en-NR": "en-001", "en-NU": "en-001", "en-NZ": "en-001", "en-PG": "en-001", "en-PK": "en-001", "en-PN": "en-001", "en-PW": "en-001", "en-RW": "en-001", "en-SB": "en-001", "en-SC": "en-001", "en-SD": "en-001", "en-SE": "en-150", "en-SG": "en-001", "en-SH": "en-001", "en-SI": "en-150", "en-SL": "en-001", "en-SS": "en-001", "en-SX": "en-001", "en-SZ": "en-001", "en-TC": "en-001", "en-TK": "en-001", "en-TO": "en-001", "en-TT": "en-001", "en-TV": "en-001", "en-TZ": "en-001", "en-UG": "en-001", "en-VC": "en-001", "en-VG": "en-001", "en-VU": "en-001", "en-WS": "en-001", "en-ZA": "en-001", "en-ZM": "en-001", "en-ZW": "en-001", "es-AR": "es-419", "es-BO": "es-419", "es-BR": "es-419", "es-BZ": "es-419", "es-CL": "es-419", "es-CO": "es-419", "es-CR": "es-419", "es-CU": "es-419", "es-DO": "es-419", "es-EC": "es-419", "es-GT": "es-419", "es-HN": "es-419", "es-MX": "es-419", "es-NI": "es-419", "es-PA": "es-419", "es-PE": "es-419", "es-PR": "es-419", "es-PY": "es-419", "es-SV": "es-419", "es-US": "es-419", "es-UY": "es-419", "es-VE": "es-419", "hi-Latn": "en", "iu-Latn": "en", "kk-Arab": "en", "ks-Deva": "en", "ku-Arab": "en", "ky-Arab": "en", "ky-Latn": "en", "mn-Mong": "en", "mni-Mtei": "en", "ms-Arab": "en", "nb": "no", "nn": "no", "pa-Arab": "en", "pt-AO": "pt-PT", "pt-CH": "pt-PT", "pt-CV": "pt-PT", "pt-FR": "pt-PT", "pt-GQ": "pt-PT", "pt-GW": "pt-PT", "pt-LU": "pt-PT", "pt-MO": "pt-PT", "pt-MZ": "pt-PT", "pt-ST": "pt-PT", "pt-TL": "pt-PT", "so-Arab": "en", "sr-Latn": "en", "sw-Arab": "en", "tg-Arab": "en", "ug-Cyrl": "en", "uz-Arab": "en", "uz-Cyrl": "en", "yue-Hans": "en", "zh-Hant": "en", "zh-Hant-MO": "zh-Hant-HK", }
data.go
0.531696
0.418103
data.go
starcoder
package vector import ( "github.com/Quant-Team/qvm/pkg/circuit/gates" "gorgonia.org/tensor" ) type Vector struct { *tensor.Dense } type Scalar struct { *tensor.Dense } func (a *Vector) ProductVector(b Vector) Vector { if !a.Shape().IsVector() || !b.Shape().IsVector() { panic("should be vectors") } ar := a.Shape() br := b.Shape() l := ar[0] * br[0] k := tensor.New(tensor.WithShape(l), tensor.WithBacking(make([]complex128, ar[0]*br[0]))) p := 0 for i := 0; i < ar[0]; i++ { for j := 0; j < br[0]; j++ { ci, _ := a.At(i) cj, _ := b.At(j) k.Set(p, ci.(complex128)*cj.(complex128)) p = p + 1 } } return Vector{k} } func (v *Vector) Add(c complex128) *Vector { d, _ := v.Dense.Add(tensor.New(tensor.WithShape(1), tensor.WithBacking([]complex128{c}))) return &Vector{d} } func (v *Vector) Set(i int, c complex128) *Vector { v.Dense.Set(i, c) return v } func (v *Vector) MulScalar(s *Scalar) *Vector { d, err := v.Dense.MulScalar(s.Dense, false) if err != nil { panic(err) } return &Vector{d} } func (v *Vector) ApplyGate(s gates.Gate) *Vector { ij := s.Shape() l := []complex128{} for i := 0; i < ij[0]; i++ { tmp := complex(0, 0) iterator := v.Iterator() for j, err := iterator.Next(); err == nil; j, err = iterator.Next() { vAmplitude, _ := v.At(j) mAmplitude, _ := s.At(i, j) tmp = tmp + mAmplitude.(complex128)*vAmplitude.(complex128) } l = append(l, tmp) } return &Vector{tensor.New(tensor.WithShape(ij[0]), tensor.WithBacking(l))} } func (v *Vector) Size() int { size := v.Dense.Shape() return size[0] } func New(z ...complex128) *Vector { v := &Vector{tensor.New(tensor.WithShape(len(z)), tensor.WithBacking(z))} return v } func NewZero(n int) *Vector { v := []complex128{} for i := 0; i < n; i++ { v = append(v, complex128(0+0i)) } return &Vector{tensor.New(tensor.WithShape(n), tensor.WithBacking(v))} } func NewScalar(c complex128) *Scalar { d := tensor.New(tensor.WithShape(1), tensor.WithBacking([]complex128{c})) return &Scalar{d} }
pkg/math/vector/vector.go
0.671255
0.548371
vector.go
starcoder
package graph import ( "math" "github.com/moorara/algo/compare" "github.com/moorara/algo/heap" "github.com/moorara/algo/list" ) const ( listNodeSize = 1024 float64Epsilon = 1e-9 ) // TraversalStrategy is the strategy for traversing vertices in a graph. type TraversalStrategy int const ( // DFS is recursive depth-first search traversal. DFS TraversalStrategy = iota // DFSi is iterative depth-first search traversal. DFSi // BFS is breadth-first search traversal. BFS ) func isStrategyValid(strategy TraversalStrategy) bool { return strategy == DFS || strategy == DFSi || strategy == BFS } // OptimizationStrategy is the strategy for optimizing weighted graphs. type OptimizationStrategy int const ( // None ignores edge weights. None OptimizationStrategy = iota // Minimize picks the edges with minimum weight. Minimize // Maximize picks the edges with maximum weight. Maximize ) // Visitors provides a method for visiting vertices and edges when traversing a graph. // VertexPreOrder is called when visiting a vertex in a graph. // VertexPostOrder is called when visiting a vertex in a graph. // EdgePreOrder is called when visiting an edge in a graph. // The graph traversal will immediately stop if the return value from any of these functions is false. type Visitors struct { VertexPreOrder func(int) bool VertexPostOrder func(int) bool EdgePreOrder func(int, int, float64) bool } // Paths is used for finding all paths from a source vertex to every other vertex in a graph. // A path is a sequence of vertices connected by edges. type Paths struct { s int visited []bool edgeTo []int } // To returns a path between the source vertex (s) and vertex (v). // If no such path exists, the second return value will be false. func (p *Paths) To(v int) ([]int, bool) { if !p.visited[v] { return nil, false } stack := list.NewStack(listNodeSize) for x := v; x != p.s; x = p.edgeTo[x] { stack.Push(x) } stack.Push(p.s) path := make([]int, 0) for !stack.IsEmpty() { path = append(path, stack.Pop().(int)) } return path, true } // Orders is used for determining ordering of vertices in a graph. type Orders struct { preRank, postRank []int preOrder, postOrder []int } // PreRank returns the rank of a vertex in pre ordering. func (o *Orders) PreRank(v int) int { return o.preRank[v] } // PostRank returns the rank of a vertex in post ordering. func (o *Orders) PostRank(v int) int { return o.postRank[v] } // PreOrder returns the pre ordering of vertices. func (o *Orders) PreOrder() []int { return o.preOrder } // PostOrder returns the post ordering of vertices. func (o *Orders) PostOrder() []int { return o.postOrder } // ReversePostOrder returns the reverse post ordering of vertices. func (o *Orders) ReversePostOrder() []int { l := len(o.postOrder) revOrder := make([]int, l) for i, v := range o.postOrder { revOrder[l-1-i] = v } return revOrder } // ConnectedComponents is used for determining all the connected components in a an undirected graph. // A connected component is a maximal set of connected vertices // (every two vertices are connected with a path between them). type ConnectedComponents struct { count int id []int } // ID returns the component id of a vertex. func (c *ConnectedComponents) ID(v int) int { return c.id[v] } // IsConnected determines if two vertices v and w are connected. func (c *ConnectedComponents) IsConnected(v, w int) bool { return c.id[v] == c.id[w] } // Components returns the vertices partitioned in the connected components. func (c *ConnectedComponents) Components() [][]int { comps := make([][]int, c.count) for i := range comps { comps[i] = make([]int, 0) } for v, id := range c.id { comps[id] = append(comps[id], v) } return comps } // StronglyConnectedComponents is used for determining all the strongly connected components in a directed graph. // A strongly connected component is a maximal set of strongly connected vertices // (every two vertices are strongly connected with paths in both directions between them). type StronglyConnectedComponents struct { count int id []int } // ID returns the component id of a vertex. func (c *StronglyConnectedComponents) ID(v int) int { return c.id[v] } // IsStronglyConnected determines if two vertices v and w are strongly connected. func (c *StronglyConnectedComponents) IsStronglyConnected(v, w int) bool { return c.id[v] == c.id[w] } // Components returns the vertices partitioned in the connected components. func (c *StronglyConnectedComponents) Components() [][]int { comps := make([][]int, c.count) for i := range comps { comps[i] = make([]int, 0) } for v, id := range c.id { comps[id] = append(comps[id], v) } return comps } // DirectedCycle is used for determining if a directed graph has a cycle. // A cycle is a path whose first and last vertices are the same. type DirectedCycle struct { visited []bool edgeTo []int onStack []bool cycle list.Stack } func newDirectedCycle(g *Directed) *DirectedCycle { c := &DirectedCycle{ visited: make([]bool, g.V()), edgeTo: make([]int, g.V()), onStack: make([]bool, g.V()), } for v := 0; v < g.V(); v++ { if !c.visited[v] && c.cycle == nil { c.dfs(g, v) } } return c } func (c *DirectedCycle) dfs(g *Directed, v int) { c.onStack[v] = true c.visited[v] = true for _, w := range g.adj[v] { if c.cycle != nil { // short circuit if a cycle already found return } else if !c.visited[w] { c.edgeTo[w] = v c.dfs(g, w) } else if c.onStack[w] { // cycle detected c.cycle = list.NewStack(listNodeSize) for x := v; x != w; x = c.edgeTo[x] { c.cycle.Push(x) } c.cycle.Push(w) c.cycle.Push(v) } } c.onStack[v] = false } // Cycle returns a cyclic path. // If no cycle exists, the second return value will be false. func (c *DirectedCycle) Cycle() ([]int, bool) { if c.cycle == nil { return nil, false } cycle := make([]int, 0) for !c.cycle.IsEmpty() { cycle = append(cycle, c.cycle.Pop().(int)) } return cycle, true } // Topological is used for determining the topological order of a directed acyclic graph (DAG). // A directed graph has a topological order if and only if it is a DAG (no directed cycle exists). type Topological struct { order []int // holds the topological order rank []int // determines rank of a vertex in the topological order } // Order returns a topological order of the directed graph. // If the directed graph does not have a topologial order (has a cycle), the second return value will be false. func (t *Topological) Order() ([]int, bool) { if t.order == nil { return nil, false } return t.order, true } // Rank returns the rank of a vertex in the topological order. // If the directed graph does not have a topologial order (has a cycle), the second return value will be false. func (t *Topological) Rank(v int) (int, bool) { if t.rank == nil { return -1, false } return t.rank[v], true } // MinimumSpanningTree is used for calculating the minimum spanning trees (forest) of a weighted undirected graph. // Given an edge-weighted undirected graph G with positive edge weights, an MST of G is a sub-graph T that is: // Tree: connected and acyclic // Spanning: includes all of the vertices // Minimum: sum of the edge wights are minimum type MinimumSpanningTree struct { visited []bool // visited[v] = true if v on tree, false otherwise edgeTo []UndirectedEdge // edgeTo[v] = shortest edge from tree vertex to non-tree vertex distTo []float64 // distTo[v] = weight of shortest such edge (edgeTo[v].weight()) pq heap.IndexHeap // indexed priority queue of vertices connected by an edge to tree } func newMinimumSpanningTree(g *WeightedUndirected) *MinimumSpanningTree { mst := &MinimumSpanningTree{ visited: make([]bool, g.V()), edgeTo: make([]UndirectedEdge, g.V()), distTo: make([]float64, g.V()), pq: heap.NewIndexMinHeap(g.V(), compare.Float64, nil), } for v := 0; v < g.V(); v++ { mst.distTo[v] = math.MaxFloat64 } // run from each vertex to find minimum spanning forest for v := 0; v < g.V(); v++ { if !mst.visited[v] { mst.prim(g, v) } } return mst } // Prim's algorithm (eager version) for calculating minimum spanning tree. func (mst *MinimumSpanningTree) prim(g *WeightedUndirected, s int) { mst.distTo[s] = 0.0 mst.pq.Insert(s, mst.distTo[s], nil) for !mst.pq.IsEmpty() { v, _, _, _ := mst.pq.Delete() mst.visited[v] = true for _, e := range g.Adj(v) { w := e.Other(v) if mst.visited[w] { continue } if e.Weight() < mst.distTo[w] { mst.edgeTo[w] = e mst.distTo[w] = e.Weight() if mst.pq.ContainsIndex(w) { mst.pq.ChangeKey(w, mst.distTo[w]) } else { mst.pq.Insert(w, mst.distTo[w], nil) } } } } } // Edges returns the edges in a minimum spanning tree (or forest). func (mst *MinimumSpanningTree) Edges() []UndirectedEdge { zero := UndirectedEdge{} edges := make([]UndirectedEdge, 0) for _, e := range mst.edgeTo { if e != zero { edges = append(edges, e) } } return edges } // Weight returns the sum of the edge weights in a minimum spanning tree (or forest). func (mst *MinimumSpanningTree) Weight() float64 { var weight float64 for _, e := range mst.Edges() { weight += e.Weight() } return weight } // ShortestPathTree is used for calculating the shortest path tree of a weighted directed graph. // A shortest path from vertex s to vertex t in a weighted directed graph is a directed path from s to t such that no other path has a lower weight. type ShortestPathTree struct { edgeTo []DirectedEdge // edgeTo[v] = last edge on shortest path s->v distTo []float64 // distTo[v] = distance of shortest path s->v pq heap.IndexHeap // indexed priority queue of vertices } func newShortestPathTree(g *WeightedDirected, s int) *ShortestPathTree { spt := &ShortestPathTree{ edgeTo: make([]DirectedEdge, g.V()), distTo: make([]float64, g.V()), pq: heap.NewIndexMinHeap(g.V(), compare.Float64, nil), } for v := 0; v < g.V(); v++ { spt.distTo[v] = math.MaxFloat64 } spt.dijkstra(g, s) return spt } // Dijkstra's algorithm (eager version) for calculating shortest path tree. func (spt *ShortestPathTree) dijkstra(g *WeightedDirected, s int) { spt.distTo[s] = 0.0 spt.pq.Insert(s, spt.distTo[s], nil) for !spt.pq.IsEmpty() { v, _, _, _ := spt.pq.Delete() // Relaxing edges for _, e := range g.Adj(v) { v, w := e.From(), e.To() if dist := spt.distTo[v] + e.Weight(); dist < spt.distTo[w] { spt.edgeTo[w] = e spt.distTo[w] = dist if spt.pq.ContainsIndex(w) { spt.pq.ChangeKey(w, spt.distTo[w]) } else { spt.pq.Insert(w, spt.distTo[w], nil) } } } } } // PathTo returns shortest path from the source vertex (s) to vertex (v). // The second return value is distance from the source vertex (s) to vertex (v). // If no such path exists, the last return value will be false. func (spt *ShortestPathTree) PathTo(v int) ([]DirectedEdge, float64, bool) { if spt.distTo[v] == math.MaxFloat64 { return nil, -1, false } zero := DirectedEdge{} stack := list.NewStack(listNodeSize) for e := spt.edgeTo[v]; e != zero; e = spt.edgeTo[e.From()] { stack.Push(e) } path := make([]DirectedEdge, stack.Size()) for i := range path { path[i] = stack.Pop().(DirectedEdge) } return path, spt.distTo[v], true }
graph/graph.go
0.860516
0.463809
graph.go
starcoder
package asm type Registers [6]int type Instruction struct { F Op Operands [3]int } func (i Instruction) Run(r *Registers) { *r = i.F(*r, i.Operands[0], i.Operands[1], i.Operands[2]) } type Op func(Registers, int, int, int) Registers func Addr(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] + r[operB] return result } func Addi(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] + operB return result } func Mulr(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] * r[operB] return result } func Muli(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] * operB return result } func Banr(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] & r[operB] return result } func Bani(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] & operB return result } func Borr(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] | r[operB] return result } func Bori(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] | operB return result } func Setr(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = r[operA] return result } func Seti(r Registers, operA, operB, targetReg int) Registers { result := r result[targetReg] = operA return result } func Gtir(r Registers, operA, operB, targetReg int) Registers { result := r if operA > r[operB] { result[targetReg] = 1 } else { result[targetReg] = 0 } return result } func Gtri(r Registers, operA, operB, targetReg int) Registers { result := r if r[operA] > operB { result[targetReg] = 1 } else { result[targetReg] = 0 } return result } func Gtrr(r Registers, operA, operB, targetReg int) Registers { result := r if r[operA] > r[operB] { result[targetReg] = 1 } else { result[targetReg] = 0 } return result } func Eqir(r Registers, operA, operB, targetReg int) Registers { result := r if operA == r[operB] { result[targetReg] = 1 } else { result[targetReg] = 0 } return result } func Eqri(r Registers, operA, operB, targetReg int) Registers { result := r if r[operA] == operB { result[targetReg] = 1 } else { result[targetReg] = 0 } return result } func Eqrr(r Registers, operA, operB, targetReg int) Registers { result := r if r[operA] == r[operB] { result[targetReg] = 1 } else { result[targetReg] = 0 } return result } var AllOps = map[string]Op{ "addr": Addr, "addi": Addi, "mulr": Mulr, "muli": Muli, "banr": Banr, "bani": Bani, "borr": Borr, "bori": Bori, "setr": Setr, "seti": Seti, "gtir": Gtir, "gtri": Gtri, "gtrr": Gtrr, "eqir": Eqir, "eqri": Eqri, "eqrr": Eqrr, }
2018/src/asm/ops.go
0.516352
0.67832
ops.go
starcoder
Common 2D shapes. */ //----------------------------------------------------------------------------- package sdf //----------------------------------------------------------------------------- // PanelParms defines the parameters for a 2D panel. type PanelParms struct { Size V2 CornerRadius float64 HoleDiameter float64 HoleMargin [4]float64 // top, right, bottom, left HolePattern [4]string // top, right, bottom, left } // Panel2D returns a 2d panel with holes on the edges. func Panel2D(k *PanelParms) SDF2 { // panel s0 := Box2D(k.Size, k.CornerRadius) if k.HoleDiameter <= 0.0 { // no holes return s0 } // corners tl := V2{-0.5*k.Size.X + k.HoleMargin[3], 0.5*k.Size.Y - k.HoleMargin[0]} tr := V2{0.5*k.Size.X - k.HoleMargin[1], 0.5*k.Size.Y - k.HoleMargin[0]} br := V2{0.5*k.Size.X - k.HoleMargin[1], -0.5*k.Size.Y + k.HoleMargin[2]} bl := V2{-0.5*k.Size.X + k.HoleMargin[3], -0.5*k.Size.Y + k.HoleMargin[2]} // holes hole := Circle2D(0.5 * k.HoleDiameter) var holes []SDF2 // clockwise: top, right, bottom, left holes = append(holes, LineOf2D(hole, tl, tr, k.HolePattern[0])) holes = append(holes, LineOf2D(hole, tr, br, k.HolePattern[1])) holes = append(holes, LineOf2D(hole, br, bl, k.HolePattern[2])) holes = append(holes, LineOf2D(hole, bl, tl, k.HolePattern[3])) return Difference2D(s0, Union2D(holes...)) } //----------------------------------------------------------------------------- // finger button // FingerButtonParms defines the parameters for a 2D finger button. type FingerButtonParms struct { Width float64 // finger width Gap float64 // gap between finger and body Length float64 // length of the finger } // FingerButton2D returns a 2D cutout for a finger button. func FingerButton2D(k *FingerButtonParms) SDF2 { r0 := 0.5 * k.Width r1 := r0 - k.Gap l := 2.0 * k.Length s := Difference2D(Line2D(l, r0), Line2D(l, r1)) s = Cut2D(s, V2{0, 0}, V2{0, 1}) return Transform2D(s, Translate2d(V2{-k.Length, 0})) } //-----------------------------------------------------------------------------
sdf/shapes2.go
0.810028
0.47384
shapes2.go
starcoder
package processor import ( "fmt" "time" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/internal/interop" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeTry] = TypeSpec{ constructor: NewTry, Categories: []Category{ CategoryComposition, }, Summary: ` Behaves similarly to the ` + "[`for_each`](/docs/components/processors/for_each)" + ` processor, where a list of child processors are applied to individual messages of a batch. However, if a processor fails for a message then that message will skip all following processors.`, Description: ` For example, with the following config: ` + "``` yaml" + ` - try: - type: foo - type: bar - type: baz ` + "```" + ` If the processor ` + "`foo`" + ` fails for a particular message, that message will skip the processors ` + "`bar` and `baz`" + `. This processor is useful for when child processors depend on the successful output of previous processors. This processor can be followed with a ` + "[catch](/docs/components/processors/catch)" + ` processor for defining child processors to be applied only to failed messages. More information about error handing can be found [here](/docs/configuration/error_handling).`, config: docs.FieldComponent().Array().HasType(docs.FieldProcessor), } } //------------------------------------------------------------------------------ // TryConfig is a config struct containing fields for the Try processor. type TryConfig []Config // NewTryConfig returns a default TryConfig. func NewTryConfig() TryConfig { return []Config{} } //------------------------------------------------------------------------------ // Try is a processor that applies a list of child processors to each message of // a batch individually, where processors are skipped for messages that failed a // previous processor step. type Try struct { children []types.Processor log log.Modular mCount metrics.StatCounter mErr metrics.StatCounter mSent metrics.StatCounter mBatchSent metrics.StatCounter } // NewTry returns a Try processor. func NewTry( conf Config, mgr types.Manager, log log.Modular, stats metrics.Type, ) (Type, error) { var children []types.Processor for i, pconf := range conf.Try { pMgr, pLog, pStats := interop.LabelChild(fmt.Sprintf("%v", i), mgr, log, stats) proc, err := New(pconf, pMgr, pLog, pStats) if err != nil { return nil, err } children = append(children, proc) } return &Try{ children: children, log: log, mCount: stats.GetCounter("count"), mErr: stats.GetCounter("error"), mSent: stats.GetCounter("sent"), mBatchSent: stats.GetCounter("batch.sent"), }, nil } //------------------------------------------------------------------------------ // ProcessMessage applies the processor to a message, either creating >0 // resulting messages or a response to be sent back to the message source. func (p *Try) ProcessMessage(msg types.Message) ([]types.Message, types.Response) { p.mCount.Incr(1) resultMsgs := make([]types.Message, msg.Len()) msg.Iter(func(i int, p types.Part) error { tmpMsg := message.New(nil) tmpMsg.SetAll([]types.Part{p}) resultMsgs[i] = tmpMsg return nil }) var res types.Response if resultMsgs, res = ExecuteTryAll(p.children, resultMsgs...); res != nil { return nil, res } resMsg := message.New(nil) for _, m := range resultMsgs { m.Iter(func(i int, p types.Part) error { resMsg.Append(p) return nil }) } p.mBatchSent.Incr(1) p.mSent.Incr(int64(resMsg.Len())) resMsgs := [1]types.Message{resMsg} return resMsgs[:], nil } // CloseAsync shuts down the processor and stops processing requests. func (p *Try) CloseAsync() { for _, c := range p.children { c.CloseAsync() } } // WaitForClose blocks until the processor has closed down. func (p *Try) WaitForClose(timeout time.Duration) error { stopBy := time.Now().Add(timeout) for _, c := range p.children { if err := c.WaitForClose(time.Until(stopBy)); err != nil { return err } } return nil } //------------------------------------------------------------------------------
lib/processor/try.go
0.667256
0.691874
try.go
starcoder
package kriging import ( "errors" "math" "sort" vec3d "github.com/flywave/go3d/float64/vec3" ) type Kriging struct { pos []vec3d.T nugget float64 rangex float64 sill float64 A float64 n int K []float64 M []float64 model KrigingModel } func New(pos []vec3d.T) *Kriging { return &Kriging{pos: pos} } type KrigingModel func(float64, float64, float64, float64, float64) float64 func krigingKrigingGaussian(h, nugget, range_, sill, A float64) float64 { x := -(1.0 / A) * ((h / range_) * (h / range_)) return nugget + ((sill-nugget)/range_)*(1.0-math.Exp(x)) } func krigingKrigingExponential(h, nugget, range_, sill, A float64) float64 { x := -(1.0 / A) * (h / range_) return nugget + ((sill-nugget)/range_)*(1.0-math.Exp(x)) } func krigingKrigingSpherical(h, nugget, range_, sill, A float64) float64 { if h > range_ { return nugget + (sill-nugget)/range_ } else { x := h / range_ return nugget + ((sill-nugget)/range_)*(1.5*(x)-0.5*(math.Pow(x, 3))) } } func (kri *Kriging) Train(model ModelType, sigma2 float64, alpha float64) (*Kriging, error) { kri.nugget = 0.0 kri.rangex = 0.0 kri.sill = 0.0 kri.A = float64(1) / float64(3) kri.n = 0.0 switch model { case Gaussian: kri.model = krigingKrigingGaussian case Exponential: kri.model = krigingKrigingExponential case Spherical: kri.model = krigingKrigingSpherical } var i, j, k, l, n int n = len(kri.pos) distance := make([][2]float64, (n*n-n)/2) i = 0 k = 0 for ; i < n; i++ { for j = 0; j < i; { distance[k] = [2]float64{} distance[k][0] = math.Pow( math.Pow(kri.pos[i][0]-kri.pos[j][0], 2)+ math.Pow(kri.pos[i][1]-kri.pos[j][1], 2), 0.5) distance[k][1] = math.Abs(kri.pos[i][2] - kri.pos[j][2]) j++ k++ } } sort.Sort(DistanceList(distance)) kri.rangex = distance[(n*n-n)/2-1][0] var lags int if ((n*n - n) / 2) > 30 { lags = 30 } else { lags = (n*n - n) / 2 } tolerance := kri.rangex / float64(lags) lag := make([]float64, lags) semi := make([]float64, lags) if lags < 30 { for l = 0; l < lags; l++ { lag[l] = distance[l][0] semi[l] = distance[l][1] } } else { i = 0 j = 0 k = 0 l = 0 for i < lags && j < ((n*n-n)/2) { for { if distance[j][0] > (float64(i+1) * tolerance) { break } lag[l] += distance[j][0] semi[l] += distance[j][1] j++ k++ if j >= ((n*n - n) / 2) { break } } if k > 0 { lag[l] = lag[l] / float64(k) semi[l] = semi[l] / float64(k) l++ } i++ k = 0 } if l < 2 { return nil, errors.New("not enough points") } } n = l kri.rangex = lag[n-1] - lag[0] X := make([]float64, 2*n) for i := 0; i < len(X); i++ { X[i] = 1 } Y := make([]float64, n) var A = kri.A for i = 0; i < n; i++ { switch model { case Gaussian: X[i*2+1] = 1.0 - math.Exp(-(1.0/A)*math.Pow(lag[i]/kri.rangex, 2)) case Exponential: X[i*2+1] = 1.0 - math.Exp(-(1.0/A)*lag[i]/kri.rangex) case Spherical: X[i*2+1] = 1.5*(lag[i]/kri.rangex) - 0.5*math.Pow(lag[i]/kri.rangex, 3) } Y[i] = semi[i] } var Xt = matrixTranspose(X, n, 2) var Z = matrixMultiply(Xt, X, 2, n, 2) Z = matrixAdd(Z, matrixDiag(float64(1)/alpha, 2), 2, 2) var cloneZ = make([]float64, len(Z)) copy(cloneZ, Z) if matrixChol(Z, 2) { matrixChol2inv(Z, 2) } else { Z, _ = matrixInverse(cloneZ, 2) } var W = matrixMultiply(matrixMultiply(Z, Xt, 2, 2, n), Y, 2, n, 1) kri.nugget = W[0] kri.sill = W[1]*kri.rangex + kri.nugget kri.n = len(kri.pos) n = len(kri.pos) K := make([]float64, n*n) for i = 0; i < n; i++ { for j = 0; j < i; j++ { K[i*n+j] = kri.model( math.Pow(math.Pow(kri.pos[i][0]-kri.pos[j][0], 2)+ math.Pow(kri.pos[i][1]-kri.pos[j][1], 2), 0.5), kri.nugget, kri.rangex, kri.sill, kri.A) K[j*n+i] = K[i*n+j] } K[i*n+i] = kri.model(0, kri.nugget, kri.rangex, kri.sill, kri.A) } var C = matrixAdd(K, matrixDiag(sigma2, n), n, n) var cloneC = make([]float64, len(C)) copy(cloneC, C) if matrixChol(C, n) { matrixChol2inv(C, n) } else { matrixSolve(cloneC, n) C = cloneC } K = C t := make([]float64, n) for i := range kri.pos { t[i] = kri.pos[i][2] } var M = matrixMultiply(C, t, n, n, 1) kri.K = K kri.M = M return kri, nil } func (kri *Kriging) Predict(x, y float64) float64 { k := make([]float64, kri.n) for i := 0; i < kri.n; i++ { x_ := x - kri.pos[i][0] y_ := y - kri.pos[i][1] h := math.Pow(math.Pow(x_, 2)+math.Pow(y_, 2), 0.5) k[i] = kri.model( h, kri.nugget, kri.rangex, kri.sill, kri.A, ) } return matrixMultiply(k, kri.M, 1, kri.n, 1)[0] } func (kri *Kriging) Contour(xWidth, yWidth int) *ContourRectangle { xlim := [2]float64{minFloat64(kri.pos, 0), maxFloat64(kri.pos, 0)} ylim := [2]float64{minFloat64(kri.pos, 1), maxFloat64(kri.pos, 1)} zlim := [2]float64{minFloat64(kri.pos, 2), maxFloat64(kri.pos, 2)} xl := xlim[1] - xlim[0] yl := ylim[1] - ylim[0] gridW := xl / float64(xWidth) gridH := yl / float64(yWidth) var contour []float64 var xTarget, yTarget float64 for j := 0; j < yWidth; j++ { yTarget = ylim[0] + float64(j)*gridW for k := 0; k < xWidth; k++ { xTarget = xlim[0] + float64(k)*gridH contour = append(contour, kri.Predict(xTarget, yTarget)) } } contourRectangle := &ContourRectangle{ Contour: contour, XWidth: xWidth, YWidth: yWidth, Xlim: xlim, Ylim: ylim, Zlim: zlim, XResolution: 1, YResolution: 1, } return contourRectangle }
kriging.go
0.54577
0.461199
kriging.go
starcoder
package transforms import ( "image" ) // Rgb2GrayFast function converts RGB to a gray scale array. func Rgb2GrayFast(colorImg image.Image, pixels *[]float64) { bounds := colorImg.Bounds() w, h := bounds.Max.X-bounds.Min.X, bounds.Max.Y-bounds.Min.Y if w != h && w != pHashSize { return } switch c := colorImg.(type) { case *image.YCbCr: rgb2GrayYCbCR(c, *pixels, w) case *image.RGBA: rgb2GrayRGBA(c, *pixels, w) default: rgb2GrayDefault(c, *pixels, w) } } // pixel2Gray converts a pixel to grayscale value base on luminosity func pixel2Gray(r, g, b, a uint32) float64 { return 0.299*float64(r/257) + 0.587*float64(g/257) + 0.114*float64(b/256) } // rgb2GrayDefault uses the image.Image interface func rgb2GrayDefault(colorImg image.Image, pixels []float64, s int) { for i := 0; i < s; i++ { for j := 0; j < s; j++ { pixels[j+(i*s)] = pixel2Gray(colorImg.At(j, i).RGBA()) } } } // rgb2GrayYCbCR uses *image.YCbCr which is signifiantly faster than the image.Image interface. func rgb2GrayYCbCR(colorImg *image.YCbCr, pixels []float64, s int) { for i := 0; i < s; i++ { for j := 0; j < s; j++ { pixels[j+(i*s)] = pixel2Gray(colorImg.YCbCrAt(j, i).RGBA()) } } } // rgb2GrayYCbCR uses *image.RGBA which is signifiantly faster than the image.Image interface. func rgb2GrayRGBA(colorImg *image.RGBA, pixels []float64, s int) { for i := 0; i < s; i++ { for j := 0; j < s; j++ { pixels[(i*s)+j] = pixel2Gray(colorImg.At(j, i).RGBA()) } } } // Rgb2Gray function converts RGB to a gray scale array. func Rgb2Gray(colorImg image.Image) [][]float64 { bounds := colorImg.Bounds() w, h := bounds.Max.X-bounds.Min.X, bounds.Max.Y-bounds.Min.Y pixels := make([][]float64, h) for i := range pixels { pixels[i] = make([]float64, w) for j := range pixels[i] { color := colorImg.At(j, i) r, g, b, _ := color.RGBA() lum := 0.299*float64(r/257) + 0.587*float64(g/257) + 0.114*float64(b/256) pixels[i][j] = lum } } return pixels } // FlattenPixels function flattens 2d array into 1d array. func FlattenPixels(pixels [][]float64, x int, y int) []float64 { flattens := make([]float64, x*y) for i := 0; i < y; i++ { for j := 0; j < x; j++ { flattens[y*i+j] = pixels[i][j] } } return flattens } // FlattenPixelsFast64 function flattens pixels array from DCT2D into [64]float array. func FlattenPixelsFast64(pixels []float64, x int, y int) []float64 { flattens := [64]float64{} for i := 0; i < y; i++ { for j := 0; j < x; j++ { flattens[y*i+j] = pixels[(i*64)+j] } } return flattens[:] }
imagehash/transforms/pixels.go
0.846609
0.45847
pixels.go
starcoder
package search import ( "github.com/jtejido/golucene/core/index" . "github.com/jtejido/golucene/core/search/model" "github.com/jtejido/golucene/core/util" ) // search/Weight.java /* Expert: calculate query weights and build query scorers. The purpose of Weight is to ensure searching does not modify a Qurey, so that a Query instance can be reused. IndexSearcher dependent state of the query should reside in the Weight. AtomicReader dependent state should reside in the Scorer. Since Weight creates Scorer instances for a given AtomicReaderContext (scorer()), callers must maintain the relationship between the searcher's top-level IndexReaderCntext and context used to create a Scorer. A Weight is used in the following way: 1. A Weight is constructed by a top-level query, given a IndexSearcher (Query.createWeight()). 2. The valueForNormalizatin() method is called on the Weight to compute the query normalization factor Similarity.queryNorm() of the query clauses contained in the query. 3. The query normlaization factor is passed to normalize(). At this point the weighting is complete. 4. A Scorer is constructed by scorer(). */ type Weight interface { // An explanation of the score computation for the named document. Explain(*index.AtomicReaderContext, int) (Explanation, error) /** The value for normalization of contained query clauses (e.g. sum of squared weights). */ ValueForNormalization() float32 /** Assigns the query normalization factor and boost from parent queries to this. */ Normalize(norm float32, topLevelBoost float32) /** * Optional method, to return a {@link BulkScorer} to * score the query and send hits to a {@link Collector}. * Only queries that have a different top-level approach * need to override this; the default implementation * pulls a normal {@link Scorer} and iterates and * collects the resulting hits. */ BulkScorer(*index.AtomicReaderContext, bool, util.Bits) (BulkScorer, error) /** * Returns true iff this implementation scores docs only out of order. This * method is used in conjunction with {@link Collector}'s * {@link Collector#acceptsDocsOutOfOrder() acceptsDocsOutOfOrder} and * {@link #scorer(AtomicReaderContext, boolean, boolean, Bits)} to * create a matching {@link Scorer} instance for a given {@link Collector}, or * vice versa. * <p> * <b>NOTE:</b> the default implementation returns <code>false</code>, i.e. * the <code>Scorer</code> scores documents in-order. */ IsScoresDocsOutOfOrder() bool // usually false /** * Returns a {@link Scorer} which scores documents in/out-of order according * to <code>scoreDocsInOrder</code>. * <p> * <b>NOTE:</b> even if <code>scoreDocsInOrder</code> is false, it is * recommended to check whether the returned <code>Scorer</code> indeed scores * documents out of order (i.e., call {@link #scoresDocsOutOfOrder()}), as * some <code>Scorer</code> implementations will always return documents * in-order.<br> * <b>NOTE:</b> null can be returned if no documents will be scored by this * query. */ Scorer(*index.AtomicReaderContext, util.Bits) (Scorer, error) } type WeightImplSPI interface { Scorer(*index.AtomicReaderContext, util.Bits) (Scorer, error) } type WeightImpl struct { spi WeightImplSPI } func newWeightImpl(spi WeightImplSPI) *WeightImpl { return &WeightImpl{spi} } func (w *WeightImpl) BulkScorer(ctx *index.AtomicReaderContext, scoreDocsInOrder bool, acceptDoc util.Bits) (bs BulkScorer, err error) { var scorer Scorer if scorer, err = w.spi.Scorer(ctx, acceptDoc); err != nil { return nil, err } else if scorer == nil { // no docs match return nil, nil } // this impl always scores docs in order, so we can ignore scoreDocsInOrder: return newDefaultScorer(scorer), nil } /* Just wraps a Scorer and performs top scoring using it. */ type DefaultBulkScorer struct { *BulkScorerImpl scorer Scorer } func newDefaultScorer(scorer Scorer) *DefaultBulkScorer { assert(scorer != nil) ans := &DefaultBulkScorer{scorer: scorer} ans.BulkScorerImpl = newBulkScorer(ans) return ans } func (s *DefaultBulkScorer) ScoreAndCollectUpto(collector Collector, max int) (ok bool, err error) { collector.SetScorer(s.scorer) if max == NO_MORE_DOCS { return false, s.scoreAll(collector, s.scorer) } doc := s.scorer.DocId() if doc < 0 { if doc, err = s.scorer.NextDoc(); err != nil { return false, err } } return s.scoreRange(collector, s.scorer, doc, max) } func (s *DefaultBulkScorer) scoreRange(collector Collector, scorer Scorer, currentDoc, end int) (bool, error) { var err error for currentDoc < end && err == nil { if err = collector.Collect(currentDoc); err == nil { currentDoc, err = scorer.NextDoc() } } return currentDoc != NO_MORE_DOCS, err } func (s *DefaultBulkScorer) scoreAll(collector Collector, scorer Scorer) (err error) { var doc int for doc, err = scorer.NextDoc(); doc != NO_MORE_DOCS && err == nil; doc, err = scorer.NextDoc() { err = collector.Collect(doc) } return }
core/search/weights.go
0.798187
0.458227
weights.go
starcoder
package msgraph // RatingCanadaMoviesType undocumented type RatingCanadaMoviesType int const ( // RatingCanadaMoviesTypeVAllAllowed undocumented RatingCanadaMoviesTypeVAllAllowed RatingCanadaMoviesType = 0 // RatingCanadaMoviesTypeVAllBlocked undocumented RatingCanadaMoviesTypeVAllBlocked RatingCanadaMoviesType = 1 // RatingCanadaMoviesTypeVGeneral undocumented RatingCanadaMoviesTypeVGeneral RatingCanadaMoviesType = 2 // RatingCanadaMoviesTypeVParentalGuidance undocumented RatingCanadaMoviesTypeVParentalGuidance RatingCanadaMoviesType = 3 // RatingCanadaMoviesTypeVAgesAbove14 undocumented RatingCanadaMoviesTypeVAgesAbove14 RatingCanadaMoviesType = 4 // RatingCanadaMoviesTypeVAgesAbove18 undocumented RatingCanadaMoviesTypeVAgesAbove18 RatingCanadaMoviesType = 5 // RatingCanadaMoviesTypeVRestricted undocumented RatingCanadaMoviesTypeVRestricted RatingCanadaMoviesType = 6 ) // RatingCanadaMoviesTypePAllAllowed returns a pointer to RatingCanadaMoviesTypeVAllAllowed func RatingCanadaMoviesTypePAllAllowed() *RatingCanadaMoviesType { v := RatingCanadaMoviesTypeVAllAllowed return &v } // RatingCanadaMoviesTypePAllBlocked returns a pointer to RatingCanadaMoviesTypeVAllBlocked func RatingCanadaMoviesTypePAllBlocked() *RatingCanadaMoviesType { v := RatingCanadaMoviesTypeVAllBlocked return &v } // RatingCanadaMoviesTypePGeneral returns a pointer to RatingCanadaMoviesTypeVGeneral func RatingCanadaMoviesTypePGeneral() *RatingCanadaMoviesType { v := RatingCanadaMoviesTypeVGeneral return &v } // RatingCanadaMoviesTypePParentalGuidance returns a pointer to RatingCanadaMoviesTypeVParentalGuidance func RatingCanadaMoviesTypePParentalGuidance() *RatingCanadaMoviesType { v := RatingCanadaMoviesTypeVParentalGuidance return &v } // RatingCanadaMoviesTypePAgesAbove14 returns a pointer to RatingCanadaMoviesTypeVAgesAbove14 func RatingCanadaMoviesTypePAgesAbove14() *RatingCanadaMoviesType { v := RatingCanadaMoviesTypeVAgesAbove14 return &v } // RatingCanadaMoviesTypePAgesAbove18 returns a pointer to RatingCanadaMoviesTypeVAgesAbove18 func RatingCanadaMoviesTypePAgesAbove18() *RatingCanadaMoviesType { v := RatingCanadaMoviesTypeVAgesAbove18 return &v } // RatingCanadaMoviesTypePRestricted returns a pointer to RatingCanadaMoviesTypeVRestricted func RatingCanadaMoviesTypePRestricted() *RatingCanadaMoviesType { v := RatingCanadaMoviesTypeVRestricted return &v }
v1.0/RatingCanadaMoviesTypeEnum.go
0.593845
0.509215
RatingCanadaMoviesTypeEnum.go
starcoder
package rapl import "math" //parsers for turning the raw MSR uint into a struct //Handle the MSR_[DOMAIN]_POWER_LIMIT MSR func parsePowerLimit(msr uint64, units RAPLPowerUnit, singleLimit bool) RAPLPowerLimit { var powerLimit RAPLPowerLimit powerLimit.Limit1.PowerLimit = float64(msr&0x7fff) * units.PowerUnits powerLimit.Limit1.EnableLimit = ((msr >> 15) & 1) == 1 powerLimit.Limit1.ClampingLimit = ((msr >> 16) & 1) == 1 powerLimit.Limit1.TimeWindowLimit = parseTimeWindowLimit((msr>>17)&0x7f, units.TimeUnits) if singleLimit { powerLimit.Lock = ((msr >> 32) & 1) == 1 return powerLimit } powerLimit.Limit2.PowerLimit = float64((msr>>32)&0x7fff) * units.PowerUnits powerLimit.Limit2.EnableLimit = ((msr >> 47) & 1) == 1 powerLimit.Limit2.ClampingLimit = ((msr >> 48) & 1) == 1 powerLimit.Limit2.TimeWindowLimit = parseTimeWindowLimit((msr>>49)&0x7f, units.TimeUnits) powerLimit.Lock = ((msr >> 63) & 1) == 1 return powerLimit } //This equation is a pain, so we'll make our own function for it. func parseTimeWindowLimit(rawLimit uint64, timeMult float64) float64 { //This is taken from the Intel SDM, Vol 3B 14.9.3 /* Time limit = 2^Y * (1.0 + Z/4.0) * Time_Unit Here “Y” is the unsigned integer value represented by bits 21:17, “Z” is an unsigned integer represented by bits 23:22. “Time_Unit” is specified by the “Time Units” field of MSR_RAPL_POWER_UNIT. */ y := float64(rawLimit & 0x1f) z := float64(rawLimit >> 5 & 0x3) return math.Pow(2, y) * (1.0 + (z / 4.0)) * timeMult } //handle the MSR_RAPL_POWER_UNIT MSR func parsePowerUnit(msr uint64) RAPLPowerUnit { var powerUnit RAPLPowerUnit //The values from the MSR are treated as registered according to the SDM powerUnit.PowerUnits = 1 / math.Pow(2, float64(msr&0xf)) powerUnit.EnergyStatusUnits = 1 / math.Pow(2, float64((msr>>8)&0x1f)) powerUnit.TimeUnits = 1 / math.Pow(2, float64((msr>>16)&0xf)) return powerUnit } func parsePowerInfo(msr uint64, units RAPLPowerUnit) RAPLPowerInfo { var powerInfo RAPLPowerInfo powerInfo.ThermalSpecPower = float64(msr&0x7fff) * units.PowerUnits powerInfo.MinPower = float64((msr>>16)&0x7fff) * units.PowerUnits powerInfo.MaxPower = float64((msr>>32)&0x7fff) * units.PowerUnits powerInfo.MaxTimeWindow = float64((msr>>48)&0x3f) * units.TimeUnits return powerInfo }
rapl/parsers.go
0.803675
0.429848
parsers.go
starcoder
package cmd import "github.com/spf13/cobra" func AllGitSubCommands() []*cobra.Command { return []*cobra.Command{ {Use: "add", Short: "Add file contents to the index"}, {Use: "am", Short: "Apply a series of patches from a mailbox"}, {Use: "archive", Short: "Create an archive of files from a named tree"}, {Use: "bisect", Short: "Use binary search to find the commit that introduced a bug"}, {Use: "branch", Short: "List, create, or delete branches"}, {Use: "bundle", Short: "Move objects and refs by archive"}, {Use: "checkout", Short: "Switch branches or restore working tree files"}, {Use: "cherry-pick", Short: "Apply the changes introduced by some existing commits"}, {Use: "citool", Short: "Graphical alternative to git-commit"}, {Use: "clean", Short: "Remove untracked files from the working tree"}, {Use: "clone", Short: "Clone a repository into a new directory"}, {Use: "commit", Short: "Record changes to the repository"}, {Use: "describe", Short: "Give an object a human readable name based on an available ref"}, {Use: "diff", Short: "Show changes between commits, commit and working tree, etc"}, {Use: "fetch", Short: "Download objects and refs from another repository"}, {Use: "format-patch", Short: "Prepare patches for e-mail submission"}, {Use: "gc", Short: "Cleanup unnecessary files and optimize the local repository"}, {Use: "gitk", Short: "The Git repository browser"}, {Use: "grep", Short: "Print lines matching a pattern"}, {Use: "gui", Short: "A portable graphical interface to Git"}, {Use: "init", Short: "Create an empty Git repository or reinitialize an existing one"}, {Use: "log", Short: "Show commit logs"}, {Use: "merge", Short: "Join two or more development histories together"}, {Use: "mv", Short: "Move or rename a file, a directory, or a symlink"}, {Use: "notes", Short: "Add or inspect object notes"}, {Use: "pull", Short: "Fetch from and integrate with another repository or a local branch"}, {Use: "push", Short: "Update remote refs along with associated objects"}, {Use: "range-diff", Short: "Compare two commit ranges (e.g. two versions of a branch)"}, {Use: "rebase", Short: "Reapply commits on top of another base tip"}, {Use: "reset", Short: "Reset current HEAD to the specified state"}, {Use: "restore", Short: "Restore working tree files"}, {Use: "revert", Short: "Revert some existing commits"}, {Use: "rm", Short: "Remove files from the working tree and from the index"}, {Use: "shortlog", Short: "Summarize 'git log' output"}, {Use: "show", Short: "Show various types of objects"}, {Use: "stash", Short: "Stash the changes in a dirty working directory away"}, {Use: "status", Short: "Show the working tree status"}, {Use: "submodule", Short: "Initialize, update or inspect submodules"}, {Use: "switch", Short: "Switch branches"}, {Use: "tag", Short: "Create, list, delete or verify a tag object signed with GPG"}, {Use: "worktree", Short: "Manage multiple working trees"}, {Use: "config", Short: "Get and set repository or global options"}, {Use: "fast-export", Short: "Git data exporter"}, {Use: "fast-import", Short: "Backend for fast Git data importers"}, {Use: "filter-branch", Short: "Rewrite branches"}, {Use: "mergetool", Short: "Run merge conflict resolution tools to resolve merge conflicts"}, {Use: "pack-refs", Short: "Pack heads and tags for efficient repository access"}, {Use: "prune", Short: "Prune all unreachable objects from the object database"}, {Use: "reflog", Short: "Manage reflog information"}, {Use: "remote", Short: "Manage set of tracked repositories"}, {Use: "repack", Short: "Pack unpacked objects in a repository"}, {Use: "replace", Short: "Create, list, delete refs to replace objects"}, {Use: "annotate", Short: "Annotate file lines with commit information"}, {Use: "blame", Short: "Show what revision and author last modified each line of a file"}, {Use: "count-objects", Short: "Count unpacked number of objects and their disk consumption"}, {Use: "difftool", Short: "Show changes using common diff tools"}, {Use: "fsck", Short: "Verifies the connectivity and validity of the objects in the database"}, {Use: "gitweb", Short: "Git web interface (web frontend to Git repositories)"}, {Use: "help", Short: "Display help information about Git"}, {Use: "instaweb", Short: "Instantly browse your working repository in gitweb"}, {Use: "merge-tree", Short: "Show three-way merge without touching index"}, {Use: "rerere", Short: "Reuse recorded resolution of conflicted merges"}, {Use: "show-branch", Short: "Show branches and their commits"}, {Use: "verify-commit", Short: "Check the GPG signature of commits"}, {Use: "verify-tag", Short: "Check the GPG signature of tags"}, {Use: "whatchanged", Short: "Show logs with difference each commit introduces"}, {Use: "archimport", Short: "Import a GNU Arch repository into Git"}, {Use: "cvsexportcommit", Short: "Export a single commit to a CVS checkout"}, {Use: "cvsimport", Short: "Salvage your data out of another SCM people love to hate"}, {Use: "cvsserver", Short: "A CVS server emulator for Git"}, {Use: "imap-send", Short: "Send a collection of patches from stdin to an IMAP folder"}, {Use: "p4", Short: "Import from and submit to Perforce repositories"}, {Use: "rm", Short: "Remove files from the working tree and from the index"}, {Use: "fast-export", Short: "Git data exporter"}, {Use: "fast-import", Short: "Backend for fast Git data importers"}, {Use: "filter-branch", Short: "Rewrite branches"}, {Use: "mergetool", Short: "Run merge conflict resolution tools to resolve merge conflicts"}, {Use: "pack-refs", Short: "Pack heads and tags for efficient repository access"}, {Use: "reflog", Short: "Manage reflog information"}, } }
cmd/git_sub_cmds.go
0.501709
0.472562
git_sub_cmds.go
starcoder
package collisions import ( "github.com/TrashPony/Veliri/src/mechanics/gameObjects/coordinate" "github.com/TrashPony/Veliri/src/mechanics/gameObjects/map" "github.com/TrashPony/Veliri/src/mechanics/gameObjects/obstacle_point" "github.com/TrashPony/Veliri/src/mechanics/globalGame/game_math" ) func FillMapZone(x, y int, zone *_map.Zone, mp *_map.Map) { // +50 что бы в область папали пограничные препятсвия zoneRect := GetRect(float64(x), float64(y), game_math.DiscreteSize+50, game_math.DiscreteSize+50) zone.Obstacle = make([]*obstacle_point.ObstaclePoint, 0) for i := 0; i < len(mp.GeoData); i++ { if zoneRect.detectCollisionRectToCircle(&point{x: float64(mp.GeoData[i].X), y: float64(mp.GeoData[i].Y)}, mp.GeoData[i].Radius) { zone.Obstacle = append(zone.Obstacle, mp.GeoData[i]) } } zone.Cells = make([]*coordinate.Coordinate, 0) for xCell := x + game_math.DiscreteSize - game_math.CellSize; xCell >= x; xCell -= game_math.CellSize { for yCell := y + game_math.DiscreteSize - game_math.CellSize; yCell >= y; yCell -= game_math.CellSize { zone.Cells = append(zone.Cells, &coordinate.Coordinate{X: xCell, Y: yCell}) } } zone.Regions = make([]*_map.Region, 100) index := 0 // все не проходимые клетки это всегда регион 0 obstacleRegion := _map.Region{Index: index, Cells: make(map[int]map[int]*coordinate.Coordinate, 0), Zone: zone} zone.Regions[index] = &obstacleRegion for _, cell := range zone.Cells { cellRect := GetRect(float64(cell.X), float64(cell.Y), game_math.CellSize, game_math.CellSize) for i := 0; i < len(mp.GeoData); i++ { dist := game_math.GetBetweenDist(cell.X, cell.Y, mp.GeoData[i].X, mp.GeoData[i].Y) if int(dist) < mp.GeoData[i].Radius+game_math.CellSize*2 { if cellRect.detectCollisionRectToCircle(&point{x: float64(mp.GeoData[i].X), y: float64(mp.GeoData[i].Y)}, mp.GeoData[i].Radius) { cell.Find = true if obstacleRegion.Cells[cell.X/game_math.CellSize] == nil { obstacleRegion.Cells[cell.X/game_math.CellSize] = make(map[int]*coordinate.Coordinate) } obstacleRegion.Cells[cell.X/game_math.CellSize][cell.Y/game_math.CellSize] = cell continue } } } } index++ // ищем координу которую еще не искали, берем всех ее соседей то тех пока мы не упремя в стену или в предел зоны for _, cell := range zone.Cells { if !cell.Find { zone.Regions[index] = CreateRegion(zone, cell, index) index++ } } } func CreateRegion(zone *_map.Zone, start *coordinate.Coordinate, index int) *_map.Region { region := _map.Region{Index: index, Cells: make(map[int]map[int]*coordinate.Coordinate, 0), Zone: zone} openPoints := make(map[string]*coordinate.Coordinate, 0) openPoints[start.Key()] = start getCurrPoint := func() *coordinate.Coordinate { for _, point := range openPoints { return point } return nil } checkCoordinate := func(x, y int) *coordinate.Coordinate { for _, zonePoint := range zone.Cells { if zonePoint.X == x && zonePoint.Y == y && !zonePoint.Find { return zonePoint } } return nil } appendOpen := func(newCoordinate *coordinate.Coordinate) { if newCoordinate != nil { openPoints[newCoordinate.Key()] = newCoordinate } } for len(openPoints) > 0 { curr := getCurrPoint() curr.Find = true if region.Cells[curr.X/game_math.CellSize] == nil { region.Cells[curr.X/game_math.CellSize] = make(map[int]*coordinate.Coordinate) } region.Cells[curr.X/game_math.CellSize][curr.Y/game_math.CellSize] = curr delete(openPoints, curr.Key()) //строго лево appendOpen(checkCoordinate(curr.X-game_math.CellSize, curr.Y)) //строго право appendOpen(checkCoordinate(curr.X+game_math.CellSize, curr.Y)) //верх центр appendOpen(checkCoordinate(curr.X, curr.Y-game_math.CellSize)) //низ центр appendOpen(checkCoordinate(curr.X, curr.Y+game_math.CellSize)) //верх лево appendOpen(checkCoordinate(curr.X-game_math.CellSize, curr.Y-game_math.CellSize)) //верх право appendOpen(checkCoordinate(curr.X+game_math.CellSize, curr.Y-game_math.CellSize)) //низ лево appendOpen(checkCoordinate(curr.X-game_math.CellSize, curr.Y+game_math.CellSize)) //низ право appendOpen(checkCoordinate(curr.X+game_math.CellSize, curr.Y+game_math.CellSize)) } return &region }
src/mechanics/globalGame/collisions/fill_map_zone.go
0.510008
0.485234
fill_map_zone.go
starcoder
package p384 import ( "fmt" "math/big" ) // affinePoint represents an affine point of the curve. The point at // infinity is (0,0) leveraging that it is not an affine point. type affinePoint struct{ x, y fp384 } func newAffinePoint(x, y *big.Int) *affinePoint { var P affinePoint P.x.SetBigInt(x) P.y.SetBigInt(y) montEncode(&P.x, &P.x) montEncode(&P.y, &P.y) return &P } func zeroPoint() *affinePoint { return &affinePoint{} } func (ap affinePoint) String() string { if ap.isZero() { return "inf" } return fmt.Sprintf("x: %v\ny: %v", ap.x, ap.y) } func (ap *affinePoint) isZero() bool { zero := fp384{} return ap.x == zero && ap.y == zero } func (ap *affinePoint) neg() { fp384Neg(&ap.y, &ap.y) } func (ap *affinePoint) toInt() (x, y *big.Int) { var x1, y1 fp384 montDecode(&x1, &ap.x) montDecode(&y1, &ap.y) return x1.BigInt(), y1.BigInt() } func (ap *affinePoint) toJacobian() *jacobianPoint { var P jacobianPoint if ap.isZero() { montEncode(&P.x, &fp384{1}) montEncode(&P.y, &fp384{1}) } else { P.x = ap.x P.y = ap.y montEncode(&P.z, &fp384{1}) } return &P } func (ap *affinePoint) toProjective() *projectivePoint { var P projectivePoint if ap.isZero() { montEncode(&P.y, &fp384{1}) } else { P.x = ap.x P.y = ap.y montEncode(&P.z, &fp384{1}) } return &P } // OddMultiples calculates the points iP for i={1,3,5,7,..., 2^(n-1)-1} // Ensure that 1 < n < 31, otherwise it returns an empty slice. func (ap affinePoint) oddMultiples(n uint) []jacobianPoint { var t []jacobianPoint if n > 1 && n < 31 { P := ap.toJacobian() s := int32(1) << (n - 1) t = make([]jacobianPoint, s) t[0] = *P _2P := *P _2P.double() for i := int32(1); i < s; i++ { t[i].add(&t[i-1], &_2P) } } return t } // p2Point is a point in P^2 type p2Point struct{ x, y, z fp384 } func (P *p2Point) String() string { return fmt.Sprintf("x: %v\ny: %v\nz: %v", P.x, P.y, P.z) } func (P *p2Point) neg() { fp384Neg(&P.y, &P.y) } // condNeg if P is negated if b=1. func (P *p2Point) cneg(b int) { var mY fp384 fp384Neg(&mY, &P.y) fp384Cmov(&P.y, &mY, b) } // cmov sets P to Q if b=1. func (P *p2Point) cmov(Q *p2Point, b int) { fp384Cmov(&P.x, &Q.x, b) fp384Cmov(&P.y, &Q.y, b) fp384Cmov(&P.z, &Q.z, b) } func (P *p2Point) toInt() (x, y, z *big.Int) { var x1, y1, z1 fp384 montDecode(&x1, &P.x) montDecode(&y1, &P.y) montDecode(&z1, &P.z) return x1.BigInt(), y1.BigInt(), z1.BigInt() } // jacobianPoint represents a point in Jacobian coordinates. The point at // infinity is any point (x,y,0) such that x and y are different from 0. type jacobianPoint struct{ p2Point } func (P *jacobianPoint) isZero() bool { zero := fp384{} return P.x != zero && P.y != zero && P.z == zero } func (P *jacobianPoint) toAffine() *affinePoint { var aP affinePoint z, z2 := &fp384{}, &fp384{} fp384Inv(z, &P.z) fp384Sqr(z2, z) fp384Mul(&aP.x, &P.x, z2) fp384Mul(&aP.y, &P.y, z) fp384Mul(&aP.y, &aP.y, z2) return &aP } func (P *jacobianPoint) cmov(Q *jacobianPoint, b int) { P.p2Point.cmov(&Q.p2Point, b) } // add calculates P=Q+R such that Q and R are different than the identity point, // and Q!==R. This function cannot be used for doublings. func (P *jacobianPoint) add(Q, R *jacobianPoint) { if Q.isZero() { *P = *R return } else if R.isZero() { *P = *Q return } // Cohen-Miyagi-Ono (1998) // https://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-1998-cmo-2 X1, Y1, Z1 := &Q.x, &Q.y, &Q.z X2, Y2, Z2 := &R.x, &R.y, &R.z Z1Z1, Z2Z2, U1, U2 := &fp384{}, &fp384{}, &fp384{}, &fp384{} H, HH, HHH, RR := &fp384{}, &fp384{}, &fp384{}, &fp384{} V, t4, t5, t6, t7, t8 := &fp384{}, &fp384{}, &fp384{}, &fp384{}, &fp384{}, &fp384{} t0, t1, t2, t3, S1, S2 := &fp384{}, &fp384{}, &fp384{}, &fp384{}, &fp384{}, &fp384{} fp384Sqr(Z1Z1, Z1) // Z1Z1 = Z1 ^ 2 fp384Sqr(Z2Z2, Z2) // Z2Z2 = Z2 ^ 2 fp384Mul(U1, X1, Z2Z2) // U1 = X1 * Z2Z2 fp384Mul(U2, X2, Z1Z1) // U2 = X2 * Z1Z1 fp384Mul(t0, Z2, Z2Z2) // t0 = Z2 * Z2Z2 fp384Mul(S1, Y1, t0) // S1 = Y1 * t0 fp384Mul(t1, Z1, Z1Z1) // t1 = Z1 * Z1Z1 fp384Mul(S2, Y2, t1) // S2 = Y2 * t1 fp384Sub(H, U2, U1) // H = U2 - U1 fp384Sqr(HH, H) // HH = H ^ 2 fp384Mul(HHH, H, HH) // HHH = H * HH fp384Sub(RR, S2, S1) // r = S2 - S1 fp384Mul(V, U1, HH) // V = U1 * HH fp384Sqr(t2, RR) // t2 = r ^ 2 fp384Add(t3, V, V) // t3 = V + V fp384Sub(t4, t2, HHH) // t4 = t2 - HHH fp384Sub(&P.x, t4, t3) // X3 = t4 - t3 fp384Sub(t5, V, &P.x) // t5 = V - X3 fp384Mul(t6, S1, HHH) // t6 = S1 * HHH fp384Mul(t7, RR, t5) // t7 = r * t5 fp384Sub(&P.y, t7, t6) // Y3 = t7 - t6 fp384Mul(t8, Z2, H) // t8 = Z2 * H fp384Mul(&P.z, Z1, t8) // Z3 = Z1 * t8 } // mixadd calculates P=Q+R such that P and Q different than the identity point, // and Q not in {P,-P, O}. func (P *jacobianPoint) mixadd(Q *jacobianPoint, R *affinePoint) { if Q.isZero() { *P = *R.toJacobian() return } else if R.isZero() { *P = *Q return } z1z1, u2 := &fp384{}, &fp384{} fp384Sqr(z1z1, &Q.z) fp384Mul(u2, &R.x, z1z1) s2 := &fp384{} fp384Mul(s2, &R.y, &Q.z) fp384Mul(s2, s2, z1z1) if Q.x == *u2 { if Q.y != *s2 { *P = *(zeroPoint().toJacobian()) return } *P = *Q P.double() return } h, r := &fp384{}, &fp384{} fp384Sub(h, u2, &Q.x) fp384Mul(&P.z, h, &Q.z) fp384Sub(r, s2, &Q.y) h2, h3 := &fp384{}, &fp384{} fp384Sqr(h2, h) fp384Mul(h3, h2, h) h3y1 := &fp384{} fp384Mul(h3y1, h3, &Q.y) h2x1 := &fp384{} fp384Mul(h2x1, h2, &Q.x) fp384Sqr(&P.x, r) fp384Sub(&P.x, &P.x, h3) fp384Sub(&P.x, &P.x, h2x1) fp384Sub(&P.x, &P.x, h2x1) fp384Sub(&P.y, h2x1, &P.x) fp384Mul(&P.y, &P.y, r) fp384Sub(&P.y, &P.y, h3y1) } func (P *jacobianPoint) double() { delta, gamma, alpha, alpha2 := &fp384{}, &fp384{}, &fp384{}, &fp384{} fp384Sqr(delta, &P.z) fp384Sqr(gamma, &P.y) fp384Sub(alpha, &P.x, delta) fp384Add(alpha2, &P.x, delta) fp384Mul(alpha, alpha, alpha2) *alpha2 = *alpha fp384Add(alpha, alpha, alpha) fp384Add(alpha, alpha, alpha2) beta := &fp384{} fp384Mul(beta, &P.x, gamma) beta8 := &fp384{} fp384Sqr(&P.x, alpha) fp384Add(beta8, beta, beta) fp384Add(beta8, beta8, beta8) fp384Add(beta8, beta8, beta8) fp384Sub(&P.x, &P.x, beta8) fp384Add(&P.z, &P.y, &P.z) fp384Sqr(&P.z, &P.z) fp384Sub(&P.z, &P.z, gamma) fp384Sub(&P.z, &P.z, delta) fp384Add(beta, beta, beta) fp384Add(beta, beta, beta) fp384Sub(beta, beta, &P.x) fp384Mul(&P.y, alpha, beta) fp384Sqr(gamma, gamma) fp384Add(gamma, gamma, gamma) fp384Add(gamma, gamma, gamma) fp384Add(gamma, gamma, gamma) fp384Sub(&P.y, &P.y, gamma) } func (P *jacobianPoint) toProjective() *projectivePoint { var hP projectivePoint hP.y = P.y fp384Mul(&hP.x, &P.x, &P.z) fp384Sqr(&hP.z, &P.z) fp384Mul(&hP.z, &hP.z, &P.z) return &hP } // projectivePoint represents a point in projective homogeneous coordinates. // The point at infinity is (0,y,0) such that y is different from 0. type projectivePoint struct{ p2Point } func (P *projectivePoint) isZero() bool { zero := fp384{} return P.x == zero && P.y != zero && P.z == zero } func (P *projectivePoint) toAffine() *affinePoint { var aP affinePoint z := &fp384{} fp384Inv(z, &P.z) fp384Mul(&aP.x, &P.x, z) fp384Mul(&aP.y, &P.y, z) return &aP } // add calculates P=Q+R using complete addition formula for prime groups. func (P *projectivePoint) completeAdd(Q, R *projectivePoint) { // Reference: // "Complete addition formulas for prime order elliptic curves" by // Costello-Renes-Batina. [Alg.4] (eprint.iacr.org/2015/1060). X1, Y1, Z1 := &Q.x, &Q.y, &Q.z X2, Y2, Z2 := &R.x, &R.y, &R.z X3, Y3, Z3 := &fp384{}, &fp384{}, &fp384{} t0, t1, t2, t3, t4 := &fp384{}, &fp384{}, &fp384{}, &fp384{}, &fp384{} fp384Mul(t0, X1, X2) // 1. t0 ← X1 · X2 fp384Mul(t1, Y1, Y2) // 2. t1 ← Y1 · Y2 fp384Mul(t2, Z1, Z2) // 3. t2 ← Z1 · Z2 fp384Add(t3, X1, Y1) // 4. t3 ← X1 + Y1 fp384Add(t4, X2, Y2) // 5. t4 ← X2 + Y2 fp384Mul(t3, t3, t4) // 6. t3 ← t3 · t4 fp384Add(t4, t0, t1) // 7. t4 ← t0 + t1 fp384Sub(t3, t3, t4) // 8. t3 ← t3 − t4 fp384Add(t4, Y1, Z1) // 9. t4 ← Y1 + Z1 fp384Add(X3, Y2, Z2) // 10. X3 ← Y2 + Z2 fp384Mul(t4, t4, X3) // 11. t4 ← t4 · X3 fp384Add(X3, t1, t2) // 12. X3 ← t1 + t2 fp384Sub(t4, t4, X3) // 13. t4 ← t4 − X3 fp384Add(X3, X1, Z1) // 14. X3 ← X1 + Z1 fp384Add(Y3, X2, Z2) // 15. Y3 ← X2 + Z2 fp384Mul(X3, X3, Y3) // 16. X3 ← X3 · Y3 fp384Add(Y3, t0, t2) // 17. Y3 ← t0 + t2 fp384Sub(Y3, X3, Y3) // 18. Y3 ← X3 − Y3 fp384Mul(Z3, &bb, t2) // 19. Z3 ← b · t2 fp384Sub(X3, Y3, Z3) // 20. X3 ← Y3 − Z3 fp384Add(Z3, X3, X3) // 21. Z3 ← X3 + X3 fp384Add(X3, X3, Z3) // 22. X3 ← X3 + Z3 fp384Sub(Z3, t1, X3) // 23. Z3 ← t1 − X3 fp384Add(X3, t1, X3) // 24. X3 ← t1 + X3 fp384Mul(Y3, &bb, Y3) // 25. Y3 ← b · Y3 fp384Add(t1, t2, t2) // 26. t1 ← t2 + t2 fp384Add(t2, t1, t2) // 27. t2 ← t1 + t2 fp384Sub(Y3, Y3, t2) // 28. Y3 ← Y3 − t2 fp384Sub(Y3, Y3, t0) // 29. Y3 ← Y3 − t0 fp384Add(t1, Y3, Y3) // 30. t1 ← Y3 + Y3 fp384Add(Y3, t1, Y3) // 31. Y3 ← t1 + Y3 fp384Add(t1, t0, t0) // 32. t1 ← t0 + t0 fp384Add(t0, t1, t0) // 33. t0 ← t1 + t0 fp384Sub(t0, t0, t2) // 34. t0 ← t0 − t2 fp384Mul(t1, t4, Y3) // 35. t1 ← t4 · Y3 fp384Mul(t2, t0, Y3) // 36. t2 ← t0 · Y3 fp384Mul(Y3, X3, Z3) // 37. Y3 ← X3 · Z3 fp384Add(Y3, Y3, t2) // 38. Y3 ← Y3 + t2 fp384Mul(X3, t3, X3) // 39. X3 ← t3 · X3 fp384Sub(X3, X3, t1) // 40. X3 ← X3 − t1 fp384Mul(Z3, t4, Z3) // 41. Z3 ← t4 · Z3 fp384Mul(t1, t3, t0) // 42. t1 ← t3 · t0 fp384Add(Z3, Z3, t1) // 43. Z3 ← Z3 + t1 P.x, P.y, P.z = *X3, *Y3, *Z3 }
ecc/p384/point.go
0.771672
0.525491
point.go
starcoder
package gridt import ( runewidth "github.com/mattn/go-runewidth" ) const ( // LeftToRight is a direction in which the values will be written. // It goes from the first cell (0,0) to the end of the line, returning to the beginning of the second line. // Exactly the same as a typewritter. LeftToRight Direction = iota // TopToBottom is a direction in which the values will be written. // It goes from the first cell (0,0) to the bottom of the column, returning to the top of the second column. // Exactly the same as how `ls` command works by default. TopToBottom ) // Direction represents the direction in which the values will be written. type Direction int8 // Grid represents the values' grid, that will be exported as a pretty formatted string. type Grid struct { v []string d Direction sep string } // New returns a new Grid. // `d` represents the direction in which the values will be written. // `sep` represents the separator; a string that will be between each column. // `s` is the cells that will be added right after initialization. func New(d Direction, sep string, s ...string) *Grid { return (&Grid{make([]string, 0), d, sep}).Add(s...) } // Cells returns all cells of the grid. func (g Grid) Cells() []string { return g.v } // Direction returns the direction in which the grid will be written. func (g Grid) Direction() Direction { return g.d } // Separator returns the separator; the string that will be between each column. func (g Grid) Separator() string { return g.sep } // Add adds a cell to the grid. // `s` is the values that will be added. func (g *Grid) Add(s ...string) *Grid { g.v = append(g.v, s...) return g } // Insert inserts a value in a specified position in the grid. // `i` the position of the value. // `s` is the value that will be added. func (g *Grid) Insert(i int, s ...string) *Grid { g.v = g.v[0 : len(g.v)+len(s)] copy(g.v[i+len(s):], g.v[i:]) for si, ss := range s { g.v[i+si] = ss } return g } // Delete deletes a value in a specified position in the grid. // `i` the position of the value. func (g *Grid) Delete(i ...int) *Grid { for _, ii := range i { copy(g.v[ii:], g.v[ii+1:]) } g.v = g.v[0 : len(g.v)-len(i)] return g } // FitIntoWidth formats the grid, based on a maximum width. // `max` represents the maximum width of the grid, based on characters. // `dim` represents the dimensions of the grid, used for formatting. See `Dimensions`. // `ok` says whether the the grid fits in the maximum width informed. If false, discard `dim`. func (g Grid) FitIntoWidth(max int) (dim Dimensions, ok bool) { switch count := len(g.v); count { // If the slice is empty, returns empty grid that does not fit. case 0: return Dimensions{}, false // If it has one item, it is validated. case 1: if l := runewidth.StringWidth(g.v[0]); l <= max { return Dimensions{[]int{l}, 1, g}, true } return Dimensions{}, false // If it has two or more items... default: // If the maximum size is zero, it is invalid. if max <= 0 { return Dimensions{}, false } // `lines` represents the minimum number of lines necessary. // This loop will check for every possibility. for lines := 1; lines <= count; lines++ { // `columns` represents the number of columns, based on the current number of lines. // It is the cells count, divided by the number of lines, rounded up. columns := divUp(count, lines) // Calculates the free space... // Which is the maximum size, minus the total width of all the separators. // If there is no free space, this possibility is ignored. free := max - ((columns - 1) * runewidth.StringWidth(g.sep)) if free < 0 { continue } // Gets bigger widths from each column. :P widths := g.biggerFromEachColumn(lines, columns) // If the sum of all widths fits the free space, then the possibility is reality! var sum int for _, width := range widths { sum += width } if sum <= free { return Dimensions{widths, lines, g}, true } } // If no possibility worked, than the cells does not fit the maximum size. return Dimensions{}, false } } // FitIntoColumns formats the grid, based on a maximum quantity of columns. // `max` represents the maximum quantity of columns of the grid. // `dim` represents the dimensions of the grid, used for formatting. See `Dimensions`. // `ok` says whether the the grid fits in the maximum width informed. If false, discard `dim`. func (g Grid) FitIntoColumns(max int) (dim Dimensions, ok bool) { // If the maximum size is zero, it is invalid. if max <= 0 { return Dimensions{}, false } // `lines` represents the number of lines. // It is the cells count, divided by the number of maximum columns, rounded up. l := divUp(len(g.v), max) return Dimensions{g.biggerFromEachColumn(l, max), l, g}, true } func (g Grid) biggerFromEachColumn(lines, columns int) []int { // Creates a slice of the widths of the columns. widths := make([]int, columns) for i, vv := range g.v { // `v` represents the list of values. // `widths` represents the list of columns' widths. // `i` cannot be the index of the value on `v`, but its index on the line. // So, `i` is adjusted, based on the direction of the grid population. switch g.d { case TopToBottom: i /= lines case LeftToRight: i %= columns } // Now, `i` represents the index of the column (or cell on the line). // `widths[i]` is substituted by the current value, if the latter is bigger. // `widths[i]` represents the bigger value on the `i` column. if l := runewidth.StringWidth(vv); l > widths[i] { widths[i] = l } } return widths }
grid.go
0.833596
0.740362
grid.go
starcoder
package plaid import ( "encoding/json" ) // Location A representation of where a transaction took place type Location struct { // The street address where the transaction occurred. Address NullableString `json:"address"` // The city where the transaction occurred. City NullableString `json:"city"` // The region or state where the transaction occurred. Region NullableString `json:"region"` // The postal code where the transaction occurred. PostalCode NullableString `json:"postal_code"` // The ISO 3166-1 alpha-2 country code where the transaction occurred. Country NullableString `json:"country"` // The latitude where the transaction occurred. Lat NullableFloat32 `json:"lat"` // The longitude where the transaction occurred. Lon NullableFloat32 `json:"lon"` // The merchant defined store number where the transaction occurred. StoreNumber NullableString `json:"store_number"` AdditionalProperties map[string]interface{} } type _Location Location // NewLocation instantiates a new Location 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 NewLocation(address NullableString, city NullableString, region NullableString, postalCode NullableString, country NullableString, lat NullableFloat32, lon NullableFloat32, storeNumber NullableString) *Location { this := Location{} this.Address = address this.City = city this.Region = region this.PostalCode = postalCode this.Country = country this.Lat = lat this.Lon = lon this.StoreNumber = storeNumber return &this } // NewLocationWithDefaults instantiates a new Location 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 NewLocationWithDefaults() *Location { this := Location{} return &this } // GetAddress returns the Address field value // If the value is explicit nil, the zero value for string will be returned func (o *Location) GetAddress() string { if o == nil || o.Address.Get() == nil { var ret string return ret } return *o.Address.Get() } // GetAddressOk returns a tuple with the Address field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetAddressOk() (*string, bool) { if o == nil { return nil, false } return o.Address.Get(), o.Address.IsSet() } // SetAddress sets field value func (o *Location) SetAddress(v string) { o.Address.Set(&v) } // GetCity returns the City field value // If the value is explicit nil, the zero value for string will be returned func (o *Location) GetCity() string { if o == nil || o.City.Get() == nil { var ret string return ret } return *o.City.Get() } // GetCityOk returns a tuple with the City field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetCityOk() (*string, bool) { if o == nil { return nil, false } return o.City.Get(), o.City.IsSet() } // SetCity sets field value func (o *Location) SetCity(v string) { o.City.Set(&v) } // GetRegion returns the Region field value // If the value is explicit nil, the zero value for string will be returned func (o *Location) GetRegion() string { if o == nil || o.Region.Get() == nil { var ret string return ret } return *o.Region.Get() } // GetRegionOk returns a tuple with the Region field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetRegionOk() (*string, bool) { if o == nil { return nil, false } return o.Region.Get(), o.Region.IsSet() } // SetRegion sets field value func (o *Location) SetRegion(v string) { o.Region.Set(&v) } // GetPostalCode returns the PostalCode field value // If the value is explicit nil, the zero value for string will be returned func (o *Location) GetPostalCode() string { if o == nil || o.PostalCode.Get() == nil { var ret string return ret } return *o.PostalCode.Get() } // GetPostalCodeOk returns a tuple with the PostalCode field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetPostalCodeOk() (*string, bool) { if o == nil { return nil, false } return o.PostalCode.Get(), o.PostalCode.IsSet() } // SetPostalCode sets field value func (o *Location) SetPostalCode(v string) { o.PostalCode.Set(&v) } // GetCountry returns the Country field value // If the value is explicit nil, the zero value for string will be returned func (o *Location) GetCountry() string { if o == nil || o.Country.Get() == nil { var ret string return ret } return *o.Country.Get() } // GetCountryOk returns a tuple with the Country field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetCountryOk() (*string, bool) { if o == nil { return nil, false } return o.Country.Get(), o.Country.IsSet() } // SetCountry sets field value func (o *Location) SetCountry(v string) { o.Country.Set(&v) } // GetLat returns the Lat field value // If the value is explicit nil, the zero value for float32 will be returned func (o *Location) GetLat() float32 { if o == nil || o.Lat.Get() == nil { var ret float32 return ret } return *o.Lat.Get() } // GetLatOk returns a tuple with the Lat field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetLatOk() (*float32, bool) { if o == nil { return nil, false } return o.Lat.Get(), o.Lat.IsSet() } // SetLat sets field value func (o *Location) SetLat(v float32) { o.Lat.Set(&v) } // GetLon returns the Lon field value // If the value is explicit nil, the zero value for float32 will be returned func (o *Location) GetLon() float32 { if o == nil || o.Lon.Get() == nil { var ret float32 return ret } return *o.Lon.Get() } // GetLonOk returns a tuple with the Lon field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetLonOk() (*float32, bool) { if o == nil { return nil, false } return o.Lon.Get(), o.Lon.IsSet() } // SetLon sets field value func (o *Location) SetLon(v float32) { o.Lon.Set(&v) } // GetStoreNumber returns the StoreNumber field value // If the value is explicit nil, the zero value for string will be returned func (o *Location) GetStoreNumber() string { if o == nil || o.StoreNumber.Get() == nil { var ret string return ret } return *o.StoreNumber.Get() } // GetStoreNumberOk returns a tuple with the StoreNumber field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *Location) GetStoreNumberOk() (*string, bool) { if o == nil { return nil, false } return o.StoreNumber.Get(), o.StoreNumber.IsSet() } // SetStoreNumber sets field value func (o *Location) SetStoreNumber(v string) { o.StoreNumber.Set(&v) } func (o Location) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["address"] = o.Address.Get() } if true { toSerialize["city"] = o.City.Get() } if true { toSerialize["region"] = o.Region.Get() } if true { toSerialize["postal_code"] = o.PostalCode.Get() } if true { toSerialize["country"] = o.Country.Get() } if true { toSerialize["lat"] = o.Lat.Get() } if true { toSerialize["lon"] = o.Lon.Get() } if true { toSerialize["store_number"] = o.StoreNumber.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *Location) UnmarshalJSON(bytes []byte) (err error) { varLocation := _Location{} if err = json.Unmarshal(bytes, &varLocation); err == nil { *o = Location(varLocation) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "address") delete(additionalProperties, "city") delete(additionalProperties, "region") delete(additionalProperties, "postal_code") delete(additionalProperties, "country") delete(additionalProperties, "lat") delete(additionalProperties, "lon") delete(additionalProperties, "store_number") o.AdditionalProperties = additionalProperties } return err } type NullableLocation struct { value *Location isSet bool } func (v NullableLocation) Get() *Location { return v.value } func (v *NullableLocation) Set(val *Location) { v.value = val v.isSet = true } func (v NullableLocation) IsSet() bool { return v.isSet } func (v *NullableLocation) Unset() { v.value = nil v.isSet = false } func NewNullableLocation(val *Location) *NullableLocation { return &NullableLocation{value: val, isSet: true} } func (v NullableLocation) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableLocation) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_location.go
0.881977
0.451085
model_location.go
starcoder
package main import "strconv" import "strings" import "math" import "fmt" type Int struct { Value int } type Float struct { Value float64 } type Adder interface { Plus(a Data) Data } type Subtracter interface { Minus(a Data) Data } type Multiplyer interface { Multiply(a Data) Data } type Divider interface { Divide(a Data) Data } type Comparer interface { // comparing two items with one another. Returns the result // of the comparison and a bool indicating whether the items // are comparable at all. // * !comparible => comparison = 0 // * this < a => comparison < 0 // * this > a => comparison > 0 // * this == a => comparison = 0 Compare(a Data) (comparison int, comparible bool) } func (i Int) Plus(a Data) Data { switch num := a.(type) { case Int: return Int{i.Value + num.Value} case Float: return Float{float64(i.Value) + num.Value} } panic("Addition only works with Ints and Floats") } func (i Int) Minus(a Data) Data { switch num := a.(type) { case Int: return Int{i.Value - num.Value} case Float: return Float{float64(i.Value) - num.Value} } panic("Subtraction only works with Ints and Floats") } func (i Int) Multiply(a Data) Data { switch num := a.(type) { case Int: return Int{i.Value * num.Value} case Float: return Float{float64(i.Value) * num.Value} case String: return String{strings.Repeat(num.Value, i.Value)} } panic("Multiplication only works with Ints and Floats, or Strings") } func (s String) Multiply(a Data) Data { switch t := a.(type) { case Int: return String{strings.Repeat(s.Value, t.Value)} } panic("Strings can only be multiplied with Ints") } func (s String) Plus(a Data) Data { switch t := a.(type) { case String: return String{s.Value + t.Value} default: return String{s.Value + t.String()} } } func (i Int) Divide(a Data) Data { switch num := a.(type) { case Int: return Int{i.Value / num.Value} case Float: return Float{float64(i.Value) / num.Value} } panic("Division only works with Ints and Floats") } func (f Float) Plus(a Data) Data { switch num := a.(type) { case Int: return Float{f.Value + float64(num.Value)} case Float: return Float{f.Value + num.Value} } panic("Addition only works with Ints and Floats") } func (f Float) Minus(a Data) Data { switch num := a.(type) { case Int: return Float{f.Value - float64(num.Value)} case Float: return Float{f.Value - num.Value} } panic("Subtraction only works with Ints and Floats") } func (f Float) Multiply(a Data) Data { switch num := a.(type) { case Int: return Float{f.Value * float64(num.Value)} case Float: return Float{f.Value * num.Value} } panic("Multiplication only works with Ints and Floats") } func (f Float) Divide(a Data) Data { switch num := a.(type) { case Int: return Float{f.Value / float64(num.Value)} case Float: return Float{f.Value / num.Value} } panic("Division only works with Ints and Floats") } //============================================================================= // Native functions //============================================================================= func _plus(args List, context *Context) Data { args.RequireArity(2) sum, ok := args.First().(Adder) if !ok { panic("Operand not supported") } for e := args.Front().Next(); e != nil; e = e.Next() { sum = sum.Plus(e.Value.(Data)).(Adder) } return sum.(Data) } func _minus(args List, context *Context) Data { args.RequireArity(2) sum, ok := args.First().(Subtracter) if !ok { panic("Operand not supported") } for e := args.Front().Next(); e != nil; e = e.Next() { sum = sum.Minus(e.Value.(Data)).(Subtracter) } return sum.(Data) } func _multiply(args List, context *Context) Data { args.RequireArity(2) sum, ok := args.First().(Multiplyer) if !ok { panic("Operand not supported") } for e := args.Front().Next(); e != nil; e = e.Next() { sum = sum.Multiply(e.Value.(Data)).(Multiplyer) } return sum.(Data) } func _divide(args List, context *Context) Data { args.RequireArity(2) sum, ok := args.First().(Divider) if !ok { panic("Operand not supported") } for e := args.Front().Next(); e != nil; e = e.Next() { sum = sum.Divide(e.Value.(Data)).(Divider) } return sum.(Data) } func _compare(args List, context *Context) Data { args.RequireArity(2) a, ok := args.First().(Comparer) if !ok { panic("Left operand is not comparable") } comp, ok := a.Compare(args.Second()) if !ok { panic(fmt.Sprintf("Right operand cannot be compared to %s", args.First().GetType().String())) } return Int{comp} } func _lesser_than(args List, context *Context) Data { args.RequireArity(2) operand, ok := args.First().(Comparer) if !ok { panic("Left operand is not comparable") } for e := args.Front().Next(); e != nil; e = e.Next() { comparison, comparable := operand.Compare(e.Value.(Data)) if !comparable || comparison >= 0 { return Bool{false} } operand = e.Value.(Comparer) } return Bool{true} } func _greater_than(args List, context *Context) Data { args.RequireArity(2) operand, ok := args.First().(Comparer) if !ok { panic("Left operand is not comparable") } for e := args.Front().Next(); e != nil; e = e.Next() { comparison, comparable := operand.Compare(e.Value.(Data)) if !comparable || comparison <= 0 { return Bool{false} } operand = e.Value.(Comparer) } return Bool{true} } func _lesser_than_or_equal(args List, context *Context) Data { args.RequireArity(2) operand, ok := args.First().(Comparer) if !ok { panic("Left operand is not comparable") } for e := args.Front().Next(); e != nil; e = e.Next() { comparison, comparable := operand.Compare(e.Value.(Data)) if !comparable || comparison > 0 { return Bool{false} } operand = e.Value.(Comparer) } return Bool{true} } func _greater_than_or_equal(args List, context *Context) Data { args.RequireArity(2) operand, ok := args.First().(Comparer) if !ok { panic("Left operand is not comparable") } for e := args.Front().Next(); e != nil; e = e.Next() { comparison, comparable := operand.Compare(e.Value.(Data)) if !comparable || comparison < 0 { return Bool{false} } operand = e.Value.(Comparer) } return Bool{true} } //============================================================================= // Comparison //============================================================================= func (i Int) Compare(a Data) (int, bool) { switch t := a.(type) { case Int: return i.Value - t.Value, true case Float: diff := float64(i.Value) - t.Value if diff < 0 { return int(math.Min(diff, -1)), true } else if diff > 0 { return int(math.Max(diff, 1)), true } else { return 0, true } } return 0, false } func (f Float) Compare(a Data) (int, bool) { switch t := a.(type) { case Int: diff := f.Value - float64(t.Value) if diff < 0 { return int(math.Min(diff, -1)), true } else if diff > 0 { return int(math.Max(diff, 1)), true } else { return 0, true } case Float: diff := f.Value - t.Value if diff < 0 { return int(math.Min(diff, -1)), true } else if diff > 0 { return int(math.Max(diff, 1)), true } else { return 0, true } } return 0, false } //============================================================================= // String conversion //============================================================================= func (i Int) String() string { return strconv.FormatInt(int64(i.Value), 10) } func (f Float) String() string { return strconv.FormatFloat(f.Value, 'g', -1, 64) }
arithmetic.go
0.745491
0.560493
arithmetic.go
starcoder
package types import ( "math" "math/rand" u "github.com/csixteen/simulated-evolution/pkg/utils" ) type Direction int32 const ( C Direction = 0 N Direction = 1 NE Direction = 2 E Direction = 3 SE Direction = 4 S Direction = 5 SW Direction = 6 W Direction = 7 NW Direction = 8 ) const reproducingEnergy = 2000 type Animal struct { id int Pos u.Point Energy float64 Dir Direction Genes [8]float64 } func (a *Animal) GetPosition() u.Point { return a.Pos } func (a *Animal) EntityType() string { return "animal" } func NewAnimal(x, y float64) *Animal { a := &Animal{ id: rand.Int(), Pos: u.Point{x, y}, Energy: 10000, Dir: C, } for i := 0; i < len(a.Genes); i++ { a.Genes[i] = float64(rand.Intn(1000)) } return a } func (parent *Animal) Reproduce() *Animal { prob := rand.Intn(10000) if prob < 10 && parent.Energy >= reproducingEnergy { parent.Energy /= 2 child := NewAnimal( parent.Pos.X+float64(rand.Intn(50)), parent.Pos.Y+float64(rand.Intn(50)), ) child.Genes = parent.Genes mutation := rand.Intn(8) child.Genes[mutation] = float64(rand.Intn(5000)) return child } return nil } func (a *Animal) MaybeKill(o *Animal, world *World) { // One of them is agressive enough if a.Genes[0] > 500 || o.Genes[0] > 500 { newEnergy := a.Energy*a.Genes[0]*a.Genes[1] - o.Energy*o.Genes[0]*o.Genes[1] a.Energy += newEnergy o.Energy += -newEnergy if newEnergy > 0 { a.Genes[0] += 100 o.Genes[0] = math.Max(0, o.Genes[0]-100) } else { a.Genes[0] = math.Max(0, a.Genes[0]-100) o.Genes[0] += 100 } } } func (a *Animal) Eat(other Entity, world *World) { energy := other.GetEnergy() a.Energy += energy a.Genes[0] = math.Max(0, a.Genes[0]-10) world.RemoveEntity(other.GetPosition()) } func (a *Animal) Interact(other Entity, world *World) { switch other.EntityType() { case "tree": a.Eat(other, world) case "animal": a.MaybeKill(other.(*Animal), world) } } func (a *Animal) Explore(world *World) { for x := a.Pos.X - 24; x <= a.Pos.X+24; x += 1 { for y := a.Pos.Y - 24; y <= a.Pos.Y+24; y += 1 { if x != a.Pos.X && y != a.Pos.Y { p := u.Point{x, y} if !world.IsPlaceVacant(p) { a.Interact(world.Entities[p], world) } } } } } func (a *Animal) Turn() { a.Dir = Direction(rand.Intn(9)) } func (a *Animal) Move(world *World) { world.RemoveEntity(a.Pos) x := a.Pos.X y := a.Pos.Y switch a.Dir { case N, NE, NW: y += 1 case S, SE, SW: y -= 1 } switch a.Dir { case SE, E, NE: x += 1 case SW, W, NW: x -= 1 } a.Energy -= 0.01 a.Genes[0] += 0.1 // The more it walks, the more agressive it becomes a.Pos.X = x a.Pos.Y = y world.PlaceEntity(a) } func (a *Animal) Update(world *World) { a.Explore(world) a.Turn() a.Move(world) child := a.Reproduce() if child != nil { world.PlaceEntity(child) } } func (a *Animal) Id() int { return a.id } func (a *Animal) GetEnergy() float64 { return a.Energy }
pkg/types/animal.go
0.599016
0.458409
animal.go
starcoder
package ts import "fmt" // QueryTimespan describes the time range information for a query - the start // and end bounds of the query, along with the requested duration of individual // samples to be returned. Methods of this structure are mutating. type QueryTimespan struct { StartNanos int64 EndNanos int64 NowNanos int64 SampleDurationNanos int64 } // width returns the width of the timespan: the distance between its start and // and end bounds. func (qt *QueryTimespan) width() int64 { return qt.EndNanos - qt.StartNanos } // moveForward modifies the timespan so that it has the same width, but // both StartNanos and EndNanos is moved forward by the specified number of // nanoseconds. func (qt *QueryTimespan) moveForward(forwardNanos int64) { qt.StartNanos += forwardNanos qt.EndNanos += forwardNanos } // expand modifies the timespan so that its width is expanded *on each side* // by the supplied size; the resulting width will be (2 * size) larger than the // original width. func (qt *QueryTimespan) expand(size int64) { qt.StartNanos -= size qt.EndNanos += size } // normalize modifies startNanos and endNanos so that they are exact multiples // of the sampleDuration. Values are modified by subtraction. func (qt *QueryTimespan) normalize() { qt.StartNanos -= qt.StartNanos % qt.SampleDurationNanos qt.EndNanos -= qt.EndNanos % qt.SampleDurationNanos } // verifyBounds returns an error if the bounds of this QueryTimespan are // incorrect; currently, this only occurs if the width is negative. func (qt *QueryTimespan) verifyBounds() error { if qt.StartNanos > qt.EndNanos { return fmt.Errorf("startNanos %d was later than endNanos %d", qt.StartNanos, qt.EndNanos) } return nil } // verifyDiskResolution returns an error if this timespan is not suitable for // querying the supplied disk resolution. func (qt *QueryTimespan) verifyDiskResolution(diskResolution Resolution) error { resolutionSampleDuration := diskResolution.SampleDuration() // Verify that sampleDuration is a multiple of // diskResolution.SampleDuration(). if qt.SampleDurationNanos < resolutionSampleDuration { return fmt.Errorf( "sampleDuration %d was not less that queryResolution.SampleDuration %d", qt.SampleDurationNanos, resolutionSampleDuration, ) } if qt.SampleDurationNanos%resolutionSampleDuration != 0 { return fmt.Errorf( "sampleDuration %d is not a multiple of queryResolution.SampleDuration %d", qt.SampleDurationNanos, resolutionSampleDuration, ) } return nil } // adjustForCurrentTime adjusts the passed query timespan in order to prevent // certain artifacts which can occur when querying in the very recent past. func (qt *QueryTimespan) adjustForCurrentTime(diskResolution Resolution) error { // Disallow queries for the sample period containing the current system time // and any later periods. This prevents returning "incomplete" data for sample // periods where new data may yet be recorded, which in turn prevents an odd // user experience where graphs of recent metric data have a precipitous "dip" // at latest timestamp. cutoff := qt.NowNanos - qt.SampleDurationNanos // Do not allow queries in the future. if qt.StartNanos > cutoff { return fmt.Errorf( "cannot query time series in the future (start time %d was greater than current clock %d", qt.StartNanos, qt.NowNanos, ) } if qt.EndNanos > cutoff { qt.EndNanos = cutoff } return nil }
pkg/ts/timespan.go
0.850639
0.523664
timespan.go
starcoder
package vec import ( "fmt" "math" ) // Vector is the vector struct type Vector struct { slice []float64 } // At returns the ith element func (v Vector) At(i int) float64 { return v.slice[i] } // Set sets the ith element to the given float func (v Vector) Set(i int, f float64) { v.slice[i] = f } // SetData replaces the data of the vector func (v Vector) SetData(data []float64) { copy(v.slice, data) } // Add does the element wise addition with the given vector func (v Vector) Add(other Vector) { for i, n := range other.slice { v.slice[i] += n } } // AddScalar adds the given scalar to each element func (v Vector) AddScalar(f float64) { for i := range v.slice { v.slice[i] += f } } // Sub does the element wise substactions with the given vector func (v Vector) Sub(other Vector) { for i, f := range other.slice { v.slice[i] -= f } } // Mul does the element wise multiplication with the other vector func (v Vector) Mul(other Vector) { for i, f := range other.slice { v.slice[i] *= f } } // Len returns length of the vector func (v Vector) Len() int { return len(v.slice) } // Scale scales each element by the given float func (v Vector) Scale(f float64) { for i := range v.slice { v.slice[i] *= f } } // Pow applies the power function to each element with the given exponent func (v Vector) Pow(f float64) { for i := range v.slice { v.slice[i] = math.Pow(v.slice[i], f) } } // Exp applies the exponent function to each element func (v Vector) Exp() { for i := range v.slice { v.slice[i] = math.Exp(v.slice[i]) } } // Sigmoid applies the sigmoid activation function to the elements func (v Vector) Sigmoid() { v.Scale(-1) v.Exp() v.AddScalar(1) v.Pow(-1) } // SigmoidDer applies the sigmoid derivative function to the elements func (v Vector) SigmoidDer() { v.Sigmoid() copy := Copy(v) copy.Pow(2) v.Sub(copy) } // Sum returns the sum of the elements func (v Vector) Sum() float64 { sum := 0. for _, n := range v.slice { sum += n } return sum } // Ln applies the natural logorithm to the receiver func (v Vector) Ln() { for i, n := range v.slice { v.slice[i] = math.Log(n) } } // Swap swaps the ith and jth elements func (v Vector) Swap(i, j int) { v.slice[i], v.slice[j] = v.slice[j], v.slice[i] } // ReLU applies the ReLU activation function to the receiver func (v Vector) ReLU() { for i, n := range v.slice { v.slice[i] = math.Max(n, 0) } } // ReLUDer applies the ReLU derivative to the receiver func (v Vector) ReLUDer() { for i, n := range v.slice { if n > 0 { v.slice[i] = 1 } else { v.slice[i] = 0 } } } // String returns a string representation of the Vector func (v Vector) String() string { return fmt.Sprintf("%v", v.slice) } // Index returns the first index of the given float, otherwise -1 func (v Vector) Index(value float64) int { for i, f := range v.slice { if f == value { return i } } return -1 } // Append appends the given float to the vector func (v *Vector) Append(f float64) { v.slice = append(v.slice, f) } // Contains returns whether or not the vector contains the given value func (v Vector) Contains(f float64) bool { for _, n := range v.slice { if n == f { return true } } return false } func (v Vector) Indices(value float64) []int { indices := make([]int, 0) for i, f := range v.slice { if f == value { indices = append(indices, i) } } return indices } func (v *Vector) Remove(index int) { v.slice = append(v.slice[:index], v.slice[index+1:]...) } func (v Vector) Softmax() { v.Exp() sum := v.Sum() v.Scale(1. / sum) }
vec/vector.go
0.871803
0.70044
vector.go
starcoder
package facts import ( "fmt" "regexp" "strconv" "strings" "github.com/tidwall/gjson" ) func eqMatch(fact gjson.Result, value string) (bool, error) { switch fact.Type { case gjson.String: return strings.EqualFold(fact.String(), value), nil case gjson.Number: if strings.Contains(value, ".") { v, err := strconv.ParseFloat(value, 64) if err != nil { return false, err } return fact.Float() == v, nil } return strconv.Itoa(int(fact.Int())) == value, nil case gjson.True: return truthy(value), nil case gjson.False: return falsey(value), nil case gjson.Null: return false, nil case gjson.JSON: return false, nil default: return false, fmt.Errorf("do not know how to evaluate data of type %s", fact.Type) } } func reMatch(fact gjson.Result, value string) (bool, error) { switch fact.Type { case gjson.String: return regexMatch(fact.String(), value) case gjson.Number: if strings.Contains(value, ".") { return regexMatch(fmt.Sprintf("%.4f", fact.Float()), value) } return regexMatch(strconv.Itoa(int(fact.Int())), value) case gjson.True: return truthy(strings.ToLower(value)), nil case gjson.False: return falsey(strings.ToLower(value)), nil case gjson.Null: return false, nil case gjson.JSON: return false, nil default: return false, fmt.Errorf("do not know how to evaluate data of type %s", fact.Type) } } func leMatch(fact gjson.Result, value string) (bool, error) { switch fact.Type { case gjson.String: return strings.ToLower(fact.String()) <= strings.ToLower(value), nil case gjson.Number: if strings.Contains(value, ".") { v, err := strconv.ParseFloat(value, 64) if err != nil { return false, err } return fact.Float() <= v, nil } v, err := strconv.Atoi(value) if err != nil { return false, err } return int(fact.Int()) <= v, nil default: return false, fmt.Errorf("do not know how to evaluate data of type %s", fact.Type) } } func geMatch(fact gjson.Result, value string) (bool, error) { switch fact.Type { case gjson.String: return strings.ToLower(fact.String()) >= strings.ToLower(value), nil case gjson.Number: if strings.Contains(value, ".") { v, err := strconv.ParseFloat(value, 64) if err != nil { return false, err } return fact.Float() >= v, nil } v, err := strconv.Atoi(value) if err != nil { return false, err } return int(fact.Int()) >= v, nil default: return false, fmt.Errorf("do not know how to evaluate data of type %s", fact.Type) } } func ltMatch(fact gjson.Result, value string) (bool, error) { switch fact.Type { case gjson.String: return strings.ToLower(fact.String()) < strings.ToLower(value), nil case gjson.Number: if strings.Contains(value, ".") { v, err := strconv.ParseFloat(value, 64) if err != nil { return false, err } return fact.Float() < v, nil } v, err := strconv.Atoi(value) if err != nil { return false, err } return int(fact.Int()) < v, nil default: return false, fmt.Errorf("do not know how to evaluate data of type %s", fact.Type) } } func gtMatch(fact gjson.Result, value string) (bool, error) { switch fact.Type { case gjson.String: return strings.ToLower(fact.String()) > strings.ToLower(value), nil case gjson.Number: if strings.Contains(value, ".") { f, err := strconv.ParseFloat(value, 64) if err != nil { return false, err } return fact.Float() >= f, nil } v, err := strconv.Atoi(value) if err != nil { return false, err } return int(fact.Int()) > v, nil default: return false, fmt.Errorf("do not know how to evaluate data of type %s", fact.Type) } } func neMatch(fact gjson.Result, value string) (bool, error) { switch fact.Type { case gjson.String: return !strings.EqualFold(fact.String(), value), nil case gjson.Number: if strings.Contains(value, ".") { f, err := strconv.ParseFloat(value, 64) if err != nil { return false, err } return f != fact.Float(), nil } return strconv.Itoa(int(fact.Int())) != value, nil case gjson.True: return !truthy(strings.ToLower(value)), nil case gjson.False: return falsey(strings.ToLower(value)), nil case gjson.Null: return false, nil case gjson.JSON: return false, nil default: return false, fmt.Errorf("do not know how to evaluate data of type %s", fact.Type) } } func regexMatch(value string, pattern string) (bool, error) { pattern = strings.TrimLeft(pattern, "/") pattern = strings.TrimRight(pattern, "/") pattern = fmt.Sprintf("(?i)%s", pattern) re, err := regexp.Compile(pattern) if err != nil { return false, err } return re.MatchString(value), nil } func truthy(value string) bool { b, err := strconv.ParseBool(value) if err == nil && b { return true } return false } func falsey(value string) bool { return !truthy(value) }
filter/facts/matchers.go
0.60778
0.417509
matchers.go
starcoder
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // Int4RangeFromIntArray2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]int. func Int4RangeFromIntArray2(val [2]int) driver.Valuer { return int4RangeFromIntArray2{val: val} } // Int4RangeToIntArray2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]int and sets it to val. func Int4RangeToIntArray2(val *[2]int) sql.Scanner { return int4RangeToIntArray2{val: val} } // Int4RangeFromInt8Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]int8. func Int4RangeFromInt8Array2(val [2]int8) driver.Valuer { return int4RangeFromInt8Array2{val: val} } // Int4RangeToInt8Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]int8 and sets it to val. func Int4RangeToInt8Array2(val *[2]int8) sql.Scanner { return int4RangeToInt8Array2{val: val} } // Int4RangeFromInt16Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]int16. func Int4RangeFromInt16Array2(val [2]int16) driver.Valuer { return int4RangeFromInt16Array2{val: val} } // Int4RangeToInt16Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]int16 and sets it to val. func Int4RangeToInt16Array2(val *[2]int16) sql.Scanner { return int4RangeToInt16Array2{val: val} } // Int4RangeFromInt32Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]int32. func Int4RangeFromInt32Array2(val [2]int32) driver.Valuer { return int4RangeFromInt32Array2{val: val} } // Int4RangeToInt32Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]int32 and sets it to val. func Int4RangeToInt32Array2(val *[2]int32) sql.Scanner { return int4RangeToInt32Array2{val: val} } // Int4RangeFromInt64Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]int64. func Int4RangeFromInt64Array2(val [2]int64) driver.Valuer { return int4RangeFromInt64Array2{val: val} } // Int4RangeToInt64Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]int64 and sets it to val. func Int4RangeToInt64Array2(val *[2]int64) sql.Scanner { return int4RangeToInt64Array2{val: val} } // Int4RangeFromUintArray2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]uint. func Int4RangeFromUintArray2(val [2]uint) driver.Valuer { return int4RangeFromUintArray2{val: val} } // Int4RangeToUintArray2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]uint and sets it to val. func Int4RangeToUintArray2(val *[2]uint) sql.Scanner { return int4RangeToUintArray2{val: val} } // Int4RangeFromUint8Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]uint8. func Int4RangeFromUint8Array2(val [2]uint8) driver.Valuer { return int4RangeFromUint8Array2{val: val} } // Int4RangeToUint8Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]uint8 and sets it to val. func Int4RangeToUint8Array2(val *[2]uint8) sql.Scanner { return int4RangeToUint8Array2{val: val} } // Int4RangeFromUint16Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]uint16. func Int4RangeFromUint16Array2(val [2]uint16) driver.Valuer { return int4RangeFromUint16Array2{val: val} } // Int4RangeToUint16Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]uint16 and sets it to val. func Int4RangeToUint16Array2(val *[2]uint16) sql.Scanner { return int4RangeToUint16Array2{val: val} } // Int4RangeFromUint32Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]uint32. func Int4RangeFromUint32Array2(val [2]uint32) driver.Valuer { return int4RangeFromUint32Array2{val: val} } // Int4RangeToUint32Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]uint32 and sets it to val. func Int4RangeToUint32Array2(val *[2]uint32) sql.Scanner { return int4RangeToUint32Array2{val: val} } // Int4RangeFromUint64Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]uint64. func Int4RangeFromUint64Array2(val [2]uint64) driver.Valuer { return int4RangeFromUint64Array2{val: val} } // Int4RangeToUint64Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]uint64 and sets it to val. func Int4RangeToUint64Array2(val *[2]uint64) sql.Scanner { return int4RangeToUint64Array2{val: val} } // Int4RangeFromFloat32Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]float32. func Int4RangeFromFloat32Array2(val [2]float32) driver.Valuer { return int4RangeFromFloat32Array2{val: val} } // Int4RangeToFloat32Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]float32 and sets it to val. func Int4RangeToFloat32Array2(val *[2]float32) sql.Scanner { return int4RangeToFloat32Array2{val: val} } // Int4RangeFromFloat64Array2 returns a driver.Valuer that produces a PostgreSQL int4range from the given Go [2]float64. func Int4RangeFromFloat64Array2(val [2]float64) driver.Valuer { return int4RangeFromFloat64Array2{val: val} } // Int4RangeToFloat64Array2 returns an sql.Scanner that converts a PostgreSQL int4range into a Go [2]float64 and sets it to val. func Int4RangeToFloat64Array2(val *[2]float64) sql.Scanner { return int4RangeToFloat64Array2{val: val} } type int4RangeFromIntArray2 struct { val [2]int } func (v int4RangeFromIntArray2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendInt(out, int64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToIntArray2 struct { val *[2]int } func (v int4RangeToIntArray2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi int64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseInt(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseInt(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = int(lo) v.val[1] = int(hi) return nil } type int4RangeFromInt8Array2 struct { val [2]int8 } func (v int4RangeFromInt8Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendInt(out, int64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToInt8Array2 struct { val *[2]int8 } func (v int4RangeToInt8Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi int64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseInt(string(elems[0]), 10, 8); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseInt(string(elems[1]), 10, 8); err != nil { return err } } v.val[0] = int8(lo) v.val[1] = int8(hi) return nil } type int4RangeFromInt16Array2 struct { val [2]int16 } func (v int4RangeFromInt16Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendInt(out, int64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToInt16Array2 struct { val *[2]int16 } func (v int4RangeToInt16Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi int64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseInt(string(elems[0]), 10, 16); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseInt(string(elems[1]), 10, 16); err != nil { return err } } v.val[0] = int16(lo) v.val[1] = int16(hi) return nil } type int4RangeFromInt32Array2 struct { val [2]int32 } func (v int4RangeFromInt32Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendInt(out, int64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToInt32Array2 struct { val *[2]int32 } func (v int4RangeToInt32Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi int64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseInt(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseInt(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = int32(lo) v.val[1] = int32(hi) return nil } type int4RangeFromInt64Array2 struct { val [2]int64 } func (v int4RangeFromInt64Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendInt(out, v.val[0], 10) out = append(out, ',') out = strconv.AppendInt(out, v.val[1], 10) out = append(out, ')') return out, nil } type int4RangeToInt64Array2 struct { val *[2]int64 } func (v int4RangeToInt64Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi int64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseInt(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseInt(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = lo v.val[1] = hi return nil } type int4RangeFromUintArray2 struct { val [2]uint } func (v int4RangeFromUintArray2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendUint(out, uint64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToUintArray2 struct { val *[2]uint } func (v int4RangeToUintArray2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi uint64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseUint(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseUint(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = uint(lo) v.val[1] = uint(hi) return nil } type int4RangeFromUint8Array2 struct { val [2]uint8 } func (v int4RangeFromUint8Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendUint(out, uint64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToUint8Array2 struct { val *[2]uint8 } func (v int4RangeToUint8Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi uint64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseUint(string(elems[0]), 10, 8); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseUint(string(elems[1]), 10, 8); err != nil { return err } } v.val[0] = uint8(lo) v.val[1] = uint8(hi) return nil } type int4RangeFromUint16Array2 struct { val [2]uint16 } func (v int4RangeFromUint16Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendUint(out, uint64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToUint16Array2 struct { val *[2]uint16 } func (v int4RangeToUint16Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi uint64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseUint(string(elems[0]), 10, 16); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseUint(string(elems[1]), 10, 16); err != nil { return err } } v.val[0] = uint16(lo) v.val[1] = uint16(hi) return nil } type int4RangeFromUint32Array2 struct { val [2]uint32 } func (v int4RangeFromUint32Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendUint(out, uint64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendUint(out, uint64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToUint32Array2 struct { val *[2]uint32 } func (v int4RangeToUint32Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi uint64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseUint(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseUint(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = uint32(lo) v.val[1] = uint32(hi) return nil } type int4RangeFromUint64Array2 struct { val [2]uint64 } func (v int4RangeFromUint64Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendUint(out, v.val[0], 10) out = append(out, ',') out = strconv.AppendUint(out, v.val[1], 10) out = append(out, ')') return out, nil } type int4RangeToUint64Array2 struct { val *[2]uint64 } func (v int4RangeToUint64Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi uint64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseUint(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseUint(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = lo v.val[1] = hi return nil } type int4RangeFromFloat32Array2 struct { val [2]float32 } func (v int4RangeFromFloat32Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendInt(out, int64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToFloat32Array2 struct { val *[2]float32 } func (v int4RangeToFloat32Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi int64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseInt(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseInt(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = float32(lo) v.val[1] = float32(hi) return nil } type int4RangeFromFloat64Array2 struct { val [2]float64 } func (v int4RangeFromFloat64Array2) Value() (driver.Value, error) { out := []byte{'['} out = strconv.AppendInt(out, int64(v.val[0]), 10) out = append(out, ',') out = strconv.AppendInt(out, int64(v.val[1]), 10) out = append(out, ')') return out, nil } type int4RangeToFloat64Array2 struct { val *[2]float64 } func (v int4RangeToFloat64Array2) Scan(src interface{}) error { data, err := srcbytes(src) if err != nil { return err } else if data == nil { return nil } var lo, hi int64 elems := pgParseRange(data) if len(elems[0]) > 0 { if lo, err = strconv.ParseInt(string(elems[0]), 10, 32); err != nil { return err } } if len(elems[1]) > 0 { if hi, err = strconv.ParseInt(string(elems[1]), 10, 32); err != nil { return err } } v.val[0] = float64(lo) v.val[1] = float64(hi) return nil }
pgsql/int4range.go
0.796094
0.620923
int4range.go
starcoder
package material import ( "math" "time" "github.com/kasworld/h4o/_examples/app" "github.com/kasworld/h4o/_examples/util" "github.com/kasworld/h4o/eventtype" "github.com/kasworld/h4o/geometry" "github.com/kasworld/h4o/graphic" "github.com/kasworld/h4o/gui" "github.com/kasworld/h4o/light" "github.com/kasworld/h4o/material" "github.com/kasworld/h4o/math32" "github.com/kasworld/h4o/texture" ) func init() { app.DemoMap["material.physical_variations"] = &PhysicalVariations{} } type PhysicalVariations struct { p1 *util.PointLightMesh p2 *util.PointLightMesh s1 *util.SpotLightMesh s2 *util.SpotLightMesh d1 *light.Directional d2 *light.Directional d3 *light.Directional sX *material.Standard sx *material.Standard sY *material.Standard sy *material.Standard sZ *material.Standard sz *material.Standard count float64 } // Start is called once at the start of the demo. func (t *PhysicalVariations) Start(a *app.App) { a.AmbLight().SetIntensity(0.1) // Add directional red light from side t.d1 = light.NewDirectional(&math32.Color{1, 0, 0}, 1.0) t.d1.SetPosition(1, 0, 0) a.Scene().Add(t.d1) // Add directional green light from top t.d2 = light.NewDirectional(&math32.Color{0, 1, 0}, 1.0) t.d2.SetPosition(0, 1, 0) a.Scene().Add(t.d2) //Add directional blue light from front t.d3 = light.NewDirectional(&math32.Color{0, 0, 1}, 1.0) t.d3.SetPosition(0, 0, 1) a.Scene().Add(t.d3) t.p1 = util.NewPointLightMesh(&math32.Color{1, 1, 1}) t.p1.Light.SetQuadraticDecay(0.1) t.p1.Light.SetLinearDecay(0.1) a.Scene().Add(t.p1) t.p2 = util.NewPointLightMesh(&math32.Color{1, 1, 1}) t.p2.Light.SetQuadraticDecay(0.1) t.p2.Light.SetLinearDecay(0.1) a.Scene().Add(t.p2) t.s1 = util.NewSpotLightMesh(&math32.Color{0, 0, 1}) t.s1.SetPosition(0, 3, 0) t.s1.SetVisible(false) a.Scene().Add(t.s1) t.s2 = util.NewSpotLightMesh(&math32.Color{1, 0, 0}) t.s2.SetPosition(-3, 0, 0) t.s2.SetRotationZ(math.Pi / 2) t.s2.SetVisible(false) a.Scene().Add(t.s2) // Spheres sphereGeometry := geometry.NewSphere(0.4, 32, 16) sideNum := 6 offset := (float32(sideNum)+1)/2.0 - 0.5 for i := 1; i < sideNum; i += 1 { for j := 1; j < sideNum; j += 1 { for k := 1; k < sideNum; k += 1 { pbrMat := material.NewPhysical() pbrMat.SetMetallicFactor(float32(i) / float32(sideNum)) pbrMat.SetRoughnessFactor(float32(j) / float32(sideNum)) v := float32(k) / float32(sideNum) //pbrMat.SetEmissiveFactor(&math32.Color{0,0,v}) pbrMat.SetBaseColorFactor(&math32.Color4{v, v, v, 1}) sphere := graphic.NewMesh(sphereGeometry, pbrMat) sphere.SetPosition(float32(i)-offset, float32(j)-offset, float32(k)-offset) a.Scene().Add(sphere) } } } // Add labels/sprites createSprite := func(text string, pos *math32.Vector3) *material.Standard { font := gui.StyleDefault().Font font.SetPointSize(36) font.SetColor(&math32.Color4{1, 1, 1, 1}) width, height := font.MeasureText(text) img := font.DrawText(text) tex := texture.NewTexture2DFromRGBA(img) plane_mat := material.NewStandard(math32.NewColor("white")) plane_mat.AddTexture(tex) plane_mat.SetTransparent(true) div := float32(100) sprite := graphic.NewSprite(float32(width)/div, float32(height)/div, plane_mat) sprite.SetPositionVec(pos) a.Scene().Add(sprite) return plane_mat } dist := float32(4) t.sX = createSprite("+ Metalness", &math32.Vector3{dist, 0, 0}) t.sx = createSprite("- Metalness", &math32.Vector3{-dist, 0, 0}) t.sY = createSprite("+ Roughness", &math32.Vector3{0, dist, 0}) t.sy = createSprite("- Roughness", &math32.Vector3{0, -dist, 0}) t.sZ = createSprite("+ Diffuse", &math32.Vector3{0, 0, dist}) t.sz = createSprite("- Diffuse", &math32.Vector3{0, 0, -dist}) // TODO adjust zoom level (need to implement OrbitControl.SetZoom()) // a.Orbit().SetZoom() // Add controls if a.ControlFolder() == nil { return } gDirectional := a.ControlFolder().AddGroup("Directional lights") cb1 := gDirectional.AddCheckBox("Red").SetValue(t.d1.Visible()) cb1.Subscribe(eventtype.OnChange, func(evname eventtype.EventType, ev interface{}) { t.d1.SetVisible(!t.d1.Visible()) }) cb2 := gDirectional.AddCheckBox("Green").SetValue(t.d2.Visible()) cb2.Subscribe(eventtype.OnChange, func(evname eventtype.EventType, ev interface{}) { t.d2.SetVisible(!t.d2.Visible()) }) cb3 := gDirectional.AddCheckBox("Blue").SetValue(t.d3.Visible()) cb3.Subscribe(eventtype.OnChange, func(evname eventtype.EventType, ev interface{}) { t.d3.SetVisible(!t.d3.Visible()) }) gSpot := a.ControlFolder().AddGroup("Spot lights") cb4 := gSpot.AddCheckBox("Blue").SetValue(t.s1.Visible()) cb4.Subscribe(eventtype.OnChange, func(evname eventtype.EventType, ev interface{}) { t.s1.SetVisible(!t.s1.Visible()) }) cb5 := gSpot.AddCheckBox("Red").SetValue(t.s2.Visible()) cb5.Subscribe(eventtype.OnChange, func(evname eventtype.EventType, ev interface{}) { t.s2.SetVisible(!t.s2.Visible()) }) } // Update is called every frame. func (t *PhysicalVariations) Update(a *app.App, deltaTime time.Duration) { // Rotate point lights around origin t.p1.SetPosition(4*float32(math.Cos(t.count)), 4*float32(math.Sin(t.count)), 0) t.p2.SetPosition(0, 4*float32(math.Cos(t.count*1.618)), 4*float32(math.Sin(t.count*1.618))) t.count += 0.02 // Adjust transparency of sprites according to camera angle var camPos math32.Vector3 a.Camera().WorldPosition(&camPos) camPos.Normalize() X := camPos.Dot(&math32.Vector3{1, 0, 0}) x := camPos.Dot(&math32.Vector3{-1, 0, 0}) t.sX.SetOpacity(1 - math32.Max(x, X)) t.sx.SetOpacity(1 - math32.Max(x, X)) Y := camPos.Dot(&math32.Vector3{0, 1, 0}) y := camPos.Dot(&math32.Vector3{0, -1, 0}) t.sY.SetOpacity(1 - math32.Max(y, Y)) t.sy.SetOpacity(1 - math32.Max(y, Y)) Z := camPos.Dot(&math32.Vector3{0, 0, 1}) z := camPos.Dot(&math32.Vector3{0, 0, -1}) t.sZ.SetOpacity(1 - math32.Max(z, Z)) t.sz.SetOpacity(1 - math32.Max(z, Z)) } // Cleanup is called once at the end of the demo. func (t *PhysicalVariations) Cleanup(a *app.App) {}
_examples/demos/material/physical_variations.go
0.523177
0.519582
physical_variations.go
starcoder
package randomkeymap import ( "math/rand" ) type element struct { value interface{} keyIndex int } // RandomKeyMap stores key/values and provides the following // functions in O(1): // * Insert // * Delete // * Get // * GetRandomKey type RandomKeyMap struct { kv map[interface{}]element keys []interface{} } // This is the TRICK! We can remove elements from an array (slice) in O(1) for as // long as the element order is not important: we simply place the last element // at the position which is to be deleted and truncate the length of the array by 1. func (m *RandomKeyMap) removeKey(index int) { // https://github.com/golang/go/wiki/SliceTricks#delete-without-preserving-order last := len(m.keys)-1 m.keys[index] = m.keys[last] // Make sure the "internal slice pointers" are pointing to nil, for // garbage collection to take effect m.keys[last] = nil m.keys = m.keys[:last] } // New creates and returns a new RandomKeyMap. func New() *RandomKeyMap { return &RandomKeyMap{ kv: make(map[interface{}]element, 0), keys: make([]interface{}, 0), } } // Insert inserts the given value and key into the map. func (m *RandomKeyMap) Insert(key, value interface{}) { elem, ok := m.kv[key] if !ok { // new element m.keys = append(m.keys, key) newElem := element{value, len(m.keys) - 1} m.kv[key] = newElem } else { // update value of existing element elem.value = value m.kv[key] = elem } } // Get returns the value for the given key. The boolean ok // indicates whether the value was found in the map. func (m *RandomKeyMap) Get(key interface{}) (value interface{}, ok bool) { var elem element elem, ok = m.kv[key] if ok { value = elem.value } return } // Delete removes the value with the given key from the map. func (m *RandomKeyMap) Delete(key interface{}) { if elem, ok := m.kv[key]; ok { delete(m.kv, key) keyIndex := elem.keyIndex m.removeKey(keyIndex) // update the key index: the previous last element was // moved to keyIndex prevKey := m.keys[keyIndex] prevElem := m.kv[prevKey] prevElem.keyIndex = keyIndex m.kv[prevKey] = prevElem } } // GetRandomKey returns a random key of the map. func (m *RandomKeyMap) GetRandomKey() interface{} { len := len(m.keys) r := rand.Intn(len) return m.keys[r] }
apps/augmentedstruct/randomkeymap/randomkeymap.go
0.628293
0.436262
randomkeymap.go
starcoder
package main import "os" import ( "bufio" "errors" "fmt" "log" "strconv" "strings" "time" ) /** Description: main runs the entire program, including reading in a game file, solving the game, and printing the outputs. Arguments: None Returns: Nothing */ func main() { // This section of code reads in a file and produces a 9 x 9 integer matrix arguments := os.Args[1:] numArguments := len(arguments) if numArguments != 1 { fmt.Printf("usage: ./SudukoSolver <FILE_NAME>\n") os.Exit(1) } fileName := arguments[0] var matrix [9][9]int var err error matrix, err = readFile(fileName) if err != nil { fmt.Printf("Encountered an error, exiting the program: %s\n", err) os.Exit(1) } printMatrix(matrix, "Initial Matrix") // Solve the game and calculate the time it took startTime := time.Now() solved := solve(matrix) elapsed := time.Now().Sub(startTime).Nanoseconds() elapsed = elapsed / 1000000 fmt.Printf("Time: %d ms\n", elapsed) // If the game does not have a solution, print that if solved == false { fmt.Printf("No solution.\n") } } /** Description: This is the most important function: it takes a matrix and tries to fill it in recursively, while checking if each move is valid. Arguments: - matrix: a 9 x 9 integer matrix, or game board. Returns: This function returns the boolean value true if the Suduko game was solved and false if it was not. */ func solve(matrix [9][9]int) bool { // Find the next cell to try numbers at. If there are no cells left // then we have solved the game. emptyRow, emptyCol := findEmptyCell(matrix) if emptyRow == -1 && emptyCol == -1 { if checkSolution(matrix) { printMatrix(matrix, "Solved") return true } else { return false } } // Place numbers at the current empty cell, and recursively call // the solve function. If the number didn't work, put it back to // empty. var i int for i = 1; i <= 9; i++ { if canPlaceNumber(matrix, emptyRow, emptyCol, i) { matrix[emptyRow][emptyCol] = i if solve(matrix) { return true } matrix[emptyRow][emptyCol] = 0 } } return false } /** Description: This function checks the final solution to make sure the game is actually solved. Arguments: - matrix: a 9 x 9 integer matrix, or game board Returns: True if the game is solved, false otherwise. */ func checkSolution(matrix [9][9]int) bool { var i int for i = 0; i < 9; i++ { if !(rowIsUnique(matrix, i) && colIsUnique(matrix, i)) { return false } } return true } /** Description: This function checks to make sure a given row contains all unique values. Arguments: - matrix: a 9 x 9 integer matrix, or game board - row: the row to check Returns: True if the row is unique, false otherwise */ func rowIsUnique(matrix [9][9]int, row int) bool { var line [9]bool var col int for col = 0; col < 9; col++ { num := matrix[row][col] line[num-1] = !line[num-1] } return booleansSame(line) } /** Description: This function checks to make sure a given col contains all unique values. Arguments: - matrix: a 9 x 9 integer matrix, or game board - col: the col to check Returns: True if the col is unique, false otherwise */ func colIsUnique(matrix [9][9]int, col int) bool { var line [9]bool var row int for row = 0; row < 9; row++ { num := matrix[row][col] line[num-1] = !line[num-1] } return booleansSame(line) } /** Description: This function verifies if a boolean array has a constant value Arguments: - line: a boolean array containing 9 values Returns: True if the array is all true or all false, otherwise false */ func booleansSame(line [9]bool) bool { var i int value := line[0] for i = 1; i < 9; i++ { if line[i] != value { return false } } return true } /** Description: This function checks to make sure we can place a certain number in a given cell, with regards to the rules of Suduko Arguments: - matrix: a 9 x 9 integer matrix, or game board - row/col: the current cell we want to place a number in - number: the number we want to place in the cell Returns: True if we are allowed to place the number there, false otherwise. */ func canPlaceNumber(matrix [9][9]int, row, col, number int) bool { // The three rules of Suduko define that a number 'x' can be // the only 'x' in the that row, column, and 3 x 3 sub-grid. canPlaceRow := canPlaceInRow(matrix, row, number) canPlaceCol := canPlaceInCol(matrix, col, number) canPlaceArea := canPlaceInArea(matrix, row, col, number) if canPlaceRow && canPlaceCol && canPlaceArea { return true } else { return false } } /** Description: This method checks if we can place a number in a 3 x 3 sub-grid. Arguments: - matrix: a 9 x 9 integer matrix, or game board - row/col: the cell we want to place the number in - the number we want to put in the cell Returns: True if the 3 x 3 sub-grid that row/cell is in does not already contain 'number', false if it does. */ func canPlaceInArea(matrix [9][9]int, row, col, number int) bool { // The findAreaMinMax method returns the mins/maxes for the // 3 x 3 sub-grid that row/col is in. rowMin, rowMax, colMin, colMax := findAreaMinMax(row, col) var i, j int for i = rowMin; i < rowMax; i++ { for j = colMin; j < colMax; j++ { if matrix[i][j] == number { return false } } } return true } /** Description: This method finds the minimums and maximums of the current 3 x 3 sub-grid given the current row and col. Arguments: - row/col: current cell Returns: Returns the rowMin, rowMax, colMin, and colMax */ func findAreaMinMax(row, col int) (int, int, int, int) { if row < 3 { if col < 3 { return 0, 3, 0, 3 } else if col < 6 { return 0, 3, 3, 6 } else { return 0, 3, 6, 9 } } else if row < 6 { if col < 3 { return 3, 6, 0, 3 } else if col < 6 { return 3, 6, 3, 6 } else { return 3, 6, 6, 9 } } else { if col < 3 { return 6, 9, 0, 3 } else if col < 6 { return 6, 9, 3, 6 } else { return 6, 9, 6, 9 } } } /** Description: This method checks if we can place 'number' in column 'col'. Arguments: - matrix: a 9 x 9 integer matrix, or game board - col: the column we want to put 'number' in - number: the number we want to put in 'col' Returns: Returns false if 'number' is already in 'col', true if 'number' is NOT in the column already. */ func canPlaceInCol(matrix [9][9]int, col, number int) bool { var i int for i = 0; i < 9; i++ { if matrix[i][col] == number { return false } } return true } /** Description: This method check sif we can place 'number' in row 'row'. Arguments: - matrix: a 9 x 9 integer matrix, or game board - row: the row we want to put 'number' in - number: the number we want to put in 'row' Returns: Return false if 'number' is already in 'row', true if 'number' is NOT in the row already. */ func canPlaceInRow(matrix [9][9]int, row, number int) bool { var i int for i = 0; i < 9; i++ { if matrix[row][i] == number { return false } } return true } /** Description: Given a 9 x 9 matrix, this function finds the row and column of the nearest empty cell, starting on the first row and column. Arguments: - matrix: a 9 x 9 integer matrix, or game board Returns: Returns a row/col if an empty cell was found, otherwise -1,-1 is returned. */ func findEmptyCell(matrix [9][9]int) (int, int) { // We start at the first cell (upper-left-hand corner) i := 0 j := 0 for { // Only check if we are in the bounds of board if i < 9 && j < 9 { num := matrix[i][j] // If we found an empty cell, return the current row/col if num == 0 { return i, j } else { // Increment the col we are checking. If we get past // the end of the board, reset the col and increase //the row counter by one. j++ if j >= 9 { i++ j = 0 } } } else { break } } return -1, -1 } /** Description: This function prints out a matrix. Arguments: - matrix: a 9 x 9 integer matrix, or game board - message: a message to print before printing the matrix Returns: Nothing. */ func printMatrix(matrix [9][9]int, message string) { fmt.Printf("\n%s:\n", message) var i, j int for i = 0; i < 9; i++ { for j = 0; j < 9; j++ { fmt.Printf("%d", matrix[i][j]) if j == 2 || j == 5 { fmt.Printf("\t") } else { fmt.Printf(" ") } if j == 8 { fmt.Printf("\n") } } if i == 2 || i == 5 { fmt.Printf("\n") } } } /** Description: This function reads in game file and creates a 9 x 9 integer matrix from the read-in values. Arguments: - fileName: the name of the file to read Returns: Returns a 9 x 9 integer matrix and an error. If the error is nil, then the matrix was read in successfully. */ func readFile(fileName string) ([9][9]int, error) { var matrix [9][9]int var err error file, err := os.Open(fileName) if err != nil { file.Close() return matrix, err } scanner := bufio.NewScanner(file) rowIndex := 0 colIndex := 0 number := 0 for scanner.Scan() { line := scanner.Text() if len(line) == 0 { continue } parts := strings.Fields(line) partsLength := len(parts) for colIndex = 0; colIndex < partsLength; colIndex++ { number, err = strconv.Atoi(parts[colIndex]) if number < 0 || number > 9 { err = errors.New("invalid number read in. Numbers must be in the range [0, 9]") goto errorWhileReading } if err == nil { matrix[rowIndex][colIndex] = number } else { goto errorWhileReading } } rowIndex++ } goto noError errorWhileReading: file.Close() return matrix, err noError: file.Close() if err := scanner.Err(); err != nil { log.Fatal(err) } return matrix, err }
src/SudukoSolver.go
0.669096
0.474875
SudukoSolver.go
starcoder
package mathexp import ( "math" "github.com/grafana/grafana/pkg/expr/mathexp/parse" ) var builtins = map[string]parse.Func{ "abs": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: abs, }, "log": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: log, }, "nan": { Return: parse.TypeScalar, F: nan, }, "is_nan": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: isNaN, }, "inf": { Return: parse.TypeScalar, F: inf, }, "infn": { Return: parse.TypeScalar, F: infn, }, "is_inf": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: isInf, }, "null": { Return: parse.TypeScalar, F: null, }, "is_null": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: isNull, }, "is_number": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: isNumber, }, "round": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: round, }, "ceil": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: ceil, }, "floor": { Args: []parse.ReturnType{parse.TypeVariantSet}, VariantReturn: true, F: floor, }, } // abs returns the absolute value for each result in NumberSet, SeriesSet, or Scalar func abs(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perFloat(e, res, math.Abs) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // log returns the natural logarithm value for each result in NumberSet, SeriesSet, or Scalar func log(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perFloat(e, res, math.Log) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // isNaN returns 1 if the value for each result in NumberSet, SeriesSet, or Scalar is NaN, else 0. func isNaN(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perFloat(e, res, func(f float64) float64 { if math.IsNaN(f) { return 1 } return 0 }) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // isInf returns 1 if the value for each result in NumberSet, SeriesSet, or Scalar is a // positive or negative Inf, else 0. func isInf(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perFloat(e, res, func(f float64) float64 { if math.IsInf(f, 0) { return 1 } return 0 }) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // nan returns a scalar nan value func nan(e *State) Results { aNaN := math.NaN() return NewScalarResults(e.RefID, &aNaN) } // inf returns a scalar positive infinity value func inf(e *State) Results { aInf := math.Inf(0) return NewScalarResults(e.RefID, &aInf) } // infn returns a scalar negative infinity value func infn(e *State) Results { aInf := math.Inf(-1) return NewScalarResults(e.RefID, &aInf) } // null returns a null scalar value func null(e *State) Results { return NewScalarResults(e.RefID, nil) } // isNull returns 1 if the value for each result in NumberSet, SeriesSet, or Scalar is null, else 0. func isNull(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perNullableFloat(e, res, func(f *float64) *float64 { nF := float64(0) if f == nil { nF = 1 } return &nF }) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // isNumber returns 1 if the value for each result in NumberSet, SeriesSet, or Scalar is a real number, else 0. // Therefore 0 is returned if the value Inf+, Inf-, NaN, or Null. func isNumber(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perNullableFloat(e, res, func(f *float64) *float64 { nF := float64(1) if f == nil || math.IsInf(*f, 0) || math.IsNaN(*f) { nF = 0 } return &nF }) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // perFloat passes the non-null value of a Scalar/Number or each value point of a Series to floatF. // The return Value type will be the same type provided to function, (e.g. a Series input returns a series). // If input values are null the function is not called and NaN is returned for each value. func perFloat(e *State, val Value, floatF func(x float64) float64) (Value, error) { var newVal Value switch val.Type() { case parse.TypeNumberSet: n := NewNumber(e.RefID, val.GetLabels()) f := val.(Number).GetFloat64Value() nF := math.NaN() if f != nil { nF = floatF(*f) } n.SetValue(&nF) newVal = n case parse.TypeScalar: f := val.(Scalar).GetFloat64Value() nF := math.NaN() if f != nil { nF = floatF(*f) } newVal = NewScalar(e.RefID, &nF) case parse.TypeSeriesSet: resSeries := val.(Series) newSeries := NewSeries(e.RefID, resSeries.GetLabels(), resSeries.Len()) for i := 0; i < resSeries.Len(); i++ { t, f := resSeries.GetPoint(i) nF := math.NaN() if f != nil { nF = floatF(*f) } if err := newSeries.SetPoint(i, t, &nF); err != nil { return newSeries, err } } newVal = newSeries default: // TODO: Should we deal with TypeString, TypeVariantSet? } return newVal, nil } // perNullableFloat is like perFloat, but takes and returns float pointers instead of floats. // This is for instead for functions that need specific null handling. // The input float pointer should not be modified in the floatF func. func perNullableFloat(e *State, val Value, floatF func(x *float64) *float64) (Value, error) { var newVal Value switch val.Type() { case parse.TypeNumberSet: n := NewNumber(e.RefID, val.GetLabels()) f := val.(Number).GetFloat64Value() n.SetValue(floatF(f)) newVal = n case parse.TypeScalar: f := val.(Scalar).GetFloat64Value() newVal = NewScalar(e.RefID, floatF(f)) case parse.TypeSeriesSet: resSeries := val.(Series) newSeries := NewSeries(e.RefID, resSeries.GetLabels(), resSeries.Len()) for i := 0; i < resSeries.Len(); i++ { t, f := resSeries.GetPoint(i) if err := newSeries.SetPoint(i, t, floatF(f)); err != nil { return newSeries, err } } newVal = newSeries default: // TODO: Should we deal with TypeString, TypeVariantSet? } return newVal, nil } // round returns the rounded value for each result in NumberSet, SeriesSet, or Scalar func round(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perFloat(e, res, math.Round) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // ceil returns the rounded up value for each result in NumberSet, SeriesSet, or Scalar func ceil(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perFloat(e, res, math.Ceil) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil } // floor returns the rounded down value for each result in NumberSet, SeriesSet, or Scalar func floor(e *State, varSet Results) (Results, error) { newRes := Results{} for _, res := range varSet.Values { newVal, err := perFloat(e, res, math.Floor) if err != nil { return newRes, err } newRes.Values = append(newRes.Values, newVal) } return newRes, nil }
pkg/expr/mathexp/funcs.go
0.760828
0.526769
funcs.go
starcoder
package similarities import ( "fmt" "github.com/jtejido/golucene/core/search" "math" ) /** * The Pitman-Yor Process (PYP) is used for probabilistic modeling of distributions that follow a power law. * Inference on a PYP can be efficiently approximated by combining power-law discounting with a Dirichlet-smoothed language model. * * From <NAME>, <NAME>. Hierarchical Pitman-Yor Language Model for Information Retrieval. SIGIR’10,July 19–23, 2010 * From <NAME>. Cumulative Progress in Language Models for Information Retrieval. In Proceedings of Australasian Language Technology Association Workshop, pages 96−100. * * @lucene.experimental(jtejido) */ type LMPitmanYorProcessSimilarity struct { *lmSimilarityImpl mu float32 delta float32 } func NewLMPitmanYorProcessSimilarity(mu, delta float32) *LMPitmanYorProcessSimilarity { ans := new(LMPitmanYorProcessSimilarity) ans.lmSimilarityImpl = newDefaultLMSimilarity(ans) ans.mu = mu ans.delta = delta return ans } func NewLMPitmanYorProcessSimilarityWithModel(collectionModel CollectionModel, mu, delta float32) *LMPitmanYorProcessSimilarity { ans := new(LMPitmanYorProcessSimilarity) ans.lmSimilarityImpl = newLMSimilarity(ans, collectionModel) ans.mu = mu ans.delta = delta return ans } func NewDefaultLMPitmanYorProcessSimilarity() *LMPitmanYorProcessSimilarity { ans := new(LMPitmanYorProcessSimilarity) ans.lmSimilarityImpl = newDefaultLMSimilarity(ans) ans.mu = DEFAULT_MU_DIRICHLET ans.delta = DEFAULT_DELTA_AD return ans } func (d *LMPitmanYorProcessSimilarity) score(stats Stats, freq, docLen float32) float32 { var tw float64 if freq > 0 { tw = math.Pow(float64(freq), float64(d.delta)) } freqPrime := float64(freq) - (float64(d.delta) * tw) if freqPrime < 0 { freqPrime = 0 } score := stats.TotalBoost() * (float32(math.Log(1+(freqPrime/float64(d.mu*stats.(LMStats).CollectionProbability()))) + math.Log(1-float64(float32(stats.NumberOfFieldTokens())/(docLen+d.mu))))) if score > 0.0 { return score } return 0 } func (d *LMPitmanYorProcessSimilarity) explain(expl search.ExplanationSPI, stats Stats, doc int, freq, docLen float32) { if stats.TotalBoost() != 1.0 { expl.AddDetail(search.NewExplanation(stats.TotalBoost(), "boost")) } expl.AddDetail(search.NewExplanation(d.mu, "mu")) weightExpl := search.NewExplanation(float32(math.Log(1+float64(freq/(d.mu*stats.(LMStats).CollectionProbability())))), "term weight") expl.AddDetail(weightExpl) expl.AddDetail(search.NewExplanation(float32(math.Log(float64(d.mu/(docLen+d.mu)))), "document norm")) } func (d *LMPitmanYorProcessSimilarity) Name() string { return fmt.Sprintf("Pitman-Yor-Process(mu=%.2f, delta=%.2f)", d.mu, d.delta) }
core/search/similarities/lmPitmanYorProcess.go
0.836321
0.434281
lmPitmanYorProcess.go
starcoder
// Package ryu implements the Ryu algorithm for quickly converting floating // point numbers into strings. package ryu import ( "math" "reflect" "unsafe" ) //go:generate go run maketables.go const ( mantBits32 = 23 expBits32 = 8 bias32 = 127 mantBits64 = 52 expBits64 = 11 bias64 = 1023 ) // FormatFloat32 converts a 32-bit floating point number f to a string. // It behaves like strconv.FormatFloat(float64(f), 'e', -1, 32). func FormatFloat32(f float32) string { b := make([]byte, 0, 15) b = AppendFloat32(b, f) // Convert the output to a string without copying. var s string sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) sh.Data = uintptr(unsafe.Pointer(&b[0])) sh.Len = len(b) return s } // AppendFloat32 appends the string form of the 32-bit floating point number f, // as generated by FormatFloat32, to b and returns the extended buffer. func AppendFloat32(b []byte, f float32) []byte { // Step 1: Decode the floating-point number. // Unify normalized and subnormal cases. u := math.Float32bits(f) neg := u>>(mantBits32+expBits32) != 0 mant := u & (uint32(1)<<mantBits32 - 1) exp := (u >> mantBits32) & (uint32(1)<<expBits32 - 1) // Exit early for easy cases. if exp == uint32(1)<<expBits32-1 || (exp == 0 && mant == 0) { return appendSpecial(b, neg, exp == 0, mant == 0) } d, ok := float32ToDecimalExactInt(mant, exp) if !ok { d = float32ToDecimal(mant, exp) } return d.append(b, neg) } // FormatFloat64 converts a 64-bit floating point number f to a string. // It behaves like strconv.FormatFloat(f, 'e', -1, 64). func FormatFloat64(f float64) string { b := make([]byte, 0, 24) b = AppendFloat64(b, f) // Convert the output to a string without copying. var s string sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) sh.Data = uintptr(unsafe.Pointer(&b[0])) sh.Len = len(b) return s } // AppendFloat64 appends the string form of the 64-bit floating point number f, // as generated by FormatFloat64, to b and returns the extended buffer. func AppendFloat64(b []byte, f float64) []byte { // Step 1: Decode the floating-point number. // Unify normalized and subnormal cases. u := math.Float64bits(f) neg := u>>(mantBits64+expBits64) != 0 mant := u & (uint64(1)<<mantBits64 - 1) exp := (u >> mantBits64) & (uint64(1)<<expBits64 - 1) // Exit early for easy cases. if exp == uint64(1)<<expBits64-1 || (exp == 0 && mant == 0) { return appendSpecial(b, neg, exp == 0, mant == 0) } d, ok := float64ToDecimalExactInt(mant, exp) if !ok { d = float64ToDecimal(mant, exp) } return d.append(b, neg) } func appendSpecial(b []byte, neg, expZero, mantZero bool) []byte { if !mantZero { return append(b, "NaN"...) } if !expZero { if neg { return append(b, "-Inf"...) } else { return append(b, "+Inf"...) } } if neg { b = append(b, '-') } return append(b, "0e+00"...) } func assert(t bool, msg string) { if !t { panic(msg) } } // log10Pow2 returns floor(log_10(2^e)). func log10Pow2(e int32) uint32 { // The first value this approximation fails for is 2^1651 // which is just greater than 10^297. assert(e >= 0, "e >= 0") assert(e <= 1650, "e <= 1650") return (uint32(e) * 78913) >> 18 } // log10Pow5 returns floor(log_10(5^e)). func log10Pow5(e int32) uint32 { // The first value this approximation fails for is 5^2621 // which is just greater than 10^1832. assert(e >= 0, "e >= 0") assert(e <= 2620, "e <= 2620") return (uint32(e) * 732923) >> 20 } // pow5Bits returns ceil(log_2(5^e)), or else 1 if e==0. func pow5Bits(e int32) int32 { // This approximation works up to the point that the multiplication // overflows at e = 3529. If the multiplication were done in 64 bits, // it would fail at 5^4004 which is just greater than 2^9297. assert(e >= 0, "e >= 0") assert(e <= 3528, "e <= 3528") return int32((uint32(e)*1217359)>>19 + 1) } // These boolToXxx all inline as a movzx. func boolToInt(b bool) int { if b { return 1 } return 0 } func boolToUint32(b bool) uint32 { if b { return 1 } return 0 } func boolToUint64(b bool) uint64 { if b { return 1 } return 0 }
ryu.go
0.709019
0.505615
ryu.go
starcoder
package oksvg import ( "math" "github.com/srwiley/rasterx" "golang.org/x/image/math/fixed" ) type Matrix2D struct { A, B, C, D, E, F float64 } // matrix3 is a full 3x3 float64 matrix // used for inverting type matrix3 [9]float64 func otherPair(i int) (a, b int) { switch i { case 0: a, b = 1, 2 case 1: a, b = 0, 2 case 2: a, b = 0, 1 } return } func (m *matrix3) coFact(i, j int) float64 { ai, bi := otherPair(i) aj, bj := otherPair(j) a, b, c, d := m[ai+aj*3], m[bi+bj*3], m[ai+bj*3], m[bi+aj*3] return a*b - c*d } func (m *matrix3) Invert() *matrix3 { var cofact matrix3 for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { sign := float64(1 - (i+j%2)%2*2) // "checkerboard of minuses" grid cofact[i+j*3] = m.coFact(i, j) * sign } } deteriminate := m[0]*cofact[0] + m[1]*cofact[1] + m[2]*cofact[2] // transpose cofact for i := 0; i < 2; i++ { for j := i + 1; j < 3; j++ { cofact[i+j*3], cofact[j+i*3] = cofact[j+i*3], cofact[i+j*3] } } for i := 0; i < 9; i++ { cofact[i] /= deteriminate } return &cofact } func (a Matrix2D) Invert() Matrix2D { n := &matrix3{a.A, a.C, a.E, a.B, a.D, a.F, 0, 0, 1} n = n.Invert() return Matrix2D{A: n[0], C: n[1], E: n[2], B: n[3], D: n[4], F: n[5]} } func (a Matrix2D) Mult(b Matrix2D) Matrix2D { return Matrix2D{ A: a.A*b.A + a.C*b.B, B: a.B*b.A + a.D*b.B, C: a.A*b.C + a.C*b.D, D: a.B*b.C + a.D*b.D, E: a.A*b.E + a.C*b.F + a.E, F: a.B*b.E + a.D*b.F + a.F} } var Identity = Matrix2D{1, 0, 0, 1, 0, 0} // TFixed transforms a fixed.Point26_6 by the matrix func (m Matrix2D) TFixed(a fixed.Point26_6) (b fixed.Point26_6) { b.X = fixed.Int26_6((float64(a.X)*m.A + float64(a.Y)*m.C) + m.E*64) b.Y = fixed.Int26_6((float64(a.X)*m.B + float64(a.Y)*m.D) + m.F*64) return } func (m Matrix2D) Transform(x1, y1 float64) (x2, y2 float64) { x2 = x1*m.A + y1*m.C + m.E y2 = x1*m.B + y1*m.D + m.F return } func (a Matrix2D) Scale(x, y float64) Matrix2D { return a.Mult(Matrix2D{ A: x, B: 0, C: 0, D: y, E: 0, F: 0}) } func (a Matrix2D) SkewY(theta float64) Matrix2D { return a.Mult(Matrix2D{ A: 1, B: math.Tan(theta), C: 0, D: 1, E: 0, F: 0}) } func (a Matrix2D) SkewX(theta float64) Matrix2D { return a.Mult(Matrix2D{ A: 1, B: 0, C: math.Tan(theta), D: 1, E: 0, F: 0}) } func (a Matrix2D) Translate(x, y float64) Matrix2D { return a.Mult(Matrix2D{ A: 1, B: 0, C: 0, D: 1, E: x, F: y}) } func (a Matrix2D) Rotate(theta float64) Matrix2D { return a.Mult(Matrix2D{ A: math.Cos(theta), B: math.Sin(theta), C: -math.Sin(theta), D: math.Cos(theta), E: 0, F: 0}) } type MatrixAdder struct { rasterx.Adder M Matrix2D } func (t *MatrixAdder) Reset() { t.M = Identity } func (t *MatrixAdder) Start(a fixed.Point26_6) { t.Adder.Start(t.M.TFixed(a)) } // Line adds a linear segment to the current curve. func (t *MatrixAdder) Line(b fixed.Point26_6) { t.Adder.Line(t.M.TFixed(b)) } // QuadBezier adds a quadratic segment to the current curve. func (t *MatrixAdder) QuadBezier(b, c fixed.Point26_6) { t.Adder.QuadBezier(t.M.TFixed(b), t.M.TFixed(c)) } // CubeBezier adds a cubic segment to the current curve. func (t *MatrixAdder) CubeBezier(b, c, d fixed.Point26_6) { t.Adder.CubeBezier(t.M.TFixed(b), t.M.TFixed(c), t.M.TFixed(d)) }
vendor/github.com/whosonfirst/go-whosonfirst-static/vendor/github.com/whosonfirst/go-whosonfirst-image/vendor/github.com/srwiley/oksvg/matrix.go
0.783368
0.654984
matrix.go
starcoder
package main import ( "reflect" "strconv" "fmt" ) func Any(value interface{}) string { return formatAtom(reflect.ValueOf(value)) } func formatAtom(v reflect.Value) string { switch v.Kind() { case reflect.Invalid: return "invalid" case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(v.Int(), 10) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return strconv.FormatUint(v.Uint(), 10) // ... floating-point and complex cases omitted for brevity ... case reflect.Bool: return strconv.FormatBool(v.Bool()) case reflect.String: return strconv.Quote(v.String()) case reflect.Chan, reflect.Func, reflect.Ptr, reflect.Slice, reflect.Map: return v.Type().String() + " 0x" + strconv.FormatUint(uint64(v.Pointer()), 16) default: // reflect.Array, reflect.Struct, reflect.Interface return v.Type().String() + " value" } } func Display(name string, x interface{}) { fmt.Printf("Dispaly %s (%T):\n", name, x) display(name, reflect.ValueOf(x)) } func display(path string, v reflect.Value) { switch v.Kind() { case reflect.Invalid: fmt.Printf("%s = invalid\n", path) case reflect.Slice, reflect.Array: for i := 0; i < v.Len(); i++ { display(fmt.Sprintf("%s[%d]", path, i), v.Index(i)) } case reflect.Struct: for i := 0; i < v.NumField(); i++ { fieldPath := fmt.Sprintf("%s.%s", path, v.Type().Field(i).Name) display(fieldPath, v.Field(i)) } case reflect.Map: for _, key := range v.MapKeys() { display(fmt.Sprintf("%s[%s]", path, formatAtom(key)), v.MapIndex(key)) } case reflect.Ptr: if v.IsNil() { fmt.Printf("%s = nil\n", path) } else { display(fmt.Sprintf("(%s)", path), v.Elem()) } case reflect.Interface: if v.IsNil() { fmt.Printf("%s = nil\n", path) } else { fmt.Printf("%s.type = %s\n", path, v.Elem().Type()) display(path + ".value", v.Elem()) } default: // basic types, channels, func fmt.Printf("%s = %s\n", path, formatAtom(v)) } } func main() { type myinf interface { test() int } type myst struct { a int b string inf myinf } var a = myst{ 1, "adfas", nil} fmt.Println(Any(a)) fmt.Println(Any(a.a)) fmt.Println(Any(a.b)) fmt.Println(Any(a.inf)) Display("", a) }
gopl-sample/format.go
0.554953
0.438785
format.go
starcoder
package spanapi import ( "encoding/json" ) // NetworkOperator Operator holds information on the network operator. There might be several operators involved; one operator is running the network your devices are connected to and the SIM card in your device belongs to a different operator. type NetworkOperator struct { // The Mobil Country Code for the operator. Mcc *int32 `json:"mcc,omitempty"` Mnc *int32 `json:"mnc,omitempty"` Country *string `json:"country,omitempty"` Network *string `json:"network,omitempty"` CountryCode *string `json:"countryCode,omitempty"` } // NewNetworkOperator instantiates a new NetworkOperator 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 NewNetworkOperator() *NetworkOperator { this := NetworkOperator{} return &this } // NewNetworkOperatorWithDefaults instantiates a new NetworkOperator 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 NewNetworkOperatorWithDefaults() *NetworkOperator { this := NetworkOperator{} return &this } // GetMcc returns the Mcc field value if set, zero value otherwise. func (o *NetworkOperator) GetMcc() int32 { if o == nil || o.Mcc == nil { var ret int32 return ret } return *o.Mcc } // GetMccOk returns a tuple with the Mcc field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *NetworkOperator) GetMccOk() (*int32, bool) { if o == nil || o.Mcc == nil { return nil, false } return o.Mcc, true } // HasMcc returns a boolean if a field has been set. func (o *NetworkOperator) HasMcc() bool { if o != nil && o.Mcc != nil { return true } return false } // SetMcc gets a reference to the given int32 and assigns it to the Mcc field. func (o *NetworkOperator) SetMcc(v int32) { o.Mcc = &v } // GetMnc returns the Mnc field value if set, zero value otherwise. func (o *NetworkOperator) GetMnc() int32 { if o == nil || o.Mnc == nil { var ret int32 return ret } return *o.Mnc } // GetMncOk returns a tuple with the Mnc field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *NetworkOperator) GetMncOk() (*int32, bool) { if o == nil || o.Mnc == nil { return nil, false } return o.Mnc, true } // HasMnc returns a boolean if a field has been set. func (o *NetworkOperator) HasMnc() bool { if o != nil && o.Mnc != nil { return true } return false } // SetMnc gets a reference to the given int32 and assigns it to the Mnc field. func (o *NetworkOperator) SetMnc(v int32) { o.Mnc = &v } // GetCountry returns the Country field value if set, zero value otherwise. func (o *NetworkOperator) GetCountry() string { if o == nil || o.Country == nil { var ret string return ret } return *o.Country } // GetCountryOk returns a tuple with the Country field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *NetworkOperator) GetCountryOk() (*string, bool) { if o == nil || o.Country == nil { return nil, false } return o.Country, true } // HasCountry returns a boolean if a field has been set. func (o *NetworkOperator) HasCountry() bool { if o != nil && o.Country != nil { return true } return false } // SetCountry gets a reference to the given string and assigns it to the Country field. func (o *NetworkOperator) SetCountry(v string) { o.Country = &v } // GetNetwork returns the Network field value if set, zero value otherwise. func (o *NetworkOperator) GetNetwork() string { if o == nil || o.Network == nil { var ret string return ret } return *o.Network } // GetNetworkOk returns a tuple with the Network field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *NetworkOperator) GetNetworkOk() (*string, bool) { if o == nil || o.Network == nil { return nil, false } return o.Network, true } // HasNetwork returns a boolean if a field has been set. func (o *NetworkOperator) HasNetwork() bool { if o != nil && o.Network != nil { return true } return false } // SetNetwork gets a reference to the given string and assigns it to the Network field. func (o *NetworkOperator) SetNetwork(v string) { o.Network = &v } // GetCountryCode returns the CountryCode field value if set, zero value otherwise. func (o *NetworkOperator) GetCountryCode() string { if o == nil || o.CountryCode == nil { var ret string return ret } return *o.CountryCode } // GetCountryCodeOk returns a tuple with the CountryCode field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *NetworkOperator) GetCountryCodeOk() (*string, bool) { if o == nil || o.CountryCode == nil { return nil, false } return o.CountryCode, true } // HasCountryCode returns a boolean if a field has been set. func (o *NetworkOperator) HasCountryCode() bool { if o != nil && o.CountryCode != nil { return true } return false } // SetCountryCode gets a reference to the given string and assigns it to the CountryCode field. func (o *NetworkOperator) SetCountryCode(v string) { o.CountryCode = &v } func (o NetworkOperator) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Mcc != nil { toSerialize["mcc"] = o.Mcc } if o.Mnc != nil { toSerialize["mnc"] = o.Mnc } if o.Country != nil { toSerialize["country"] = o.Country } if o.Network != nil { toSerialize["network"] = o.Network } if o.CountryCode != nil { toSerialize["countryCode"] = o.CountryCode } return json.Marshal(toSerialize) } type NullableNetworkOperator struct { value *NetworkOperator isSet bool } func (v NullableNetworkOperator) Get() *NetworkOperator { return v.value } func (v *NullableNetworkOperator) Set(val *NetworkOperator) { v.value = val v.isSet = true } func (v NullableNetworkOperator) IsSet() bool { return v.isSet } func (v *NullableNetworkOperator) Unset() { v.value = nil v.isSet = false } func NewNullableNetworkOperator(val *NetworkOperator) *NullableNetworkOperator { return &NullableNetworkOperator{value: val, isSet: true} } func (v NullableNetworkOperator) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableNetworkOperator) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_network_operator.go
0.813683
0.452173
model_network_operator.go
starcoder
package drawing import ( "strconv" ) var ( // ColorTransparent is a fully transparent color. ColorTransparent = Color{} // ColorWhite is white. ColorWhite = Color{R: 255, G: 255, B: 255, A: 255} // ColorBlack is black. ColorBlack = Color{R: 0, G: 0, B: 0, A: 255} // ColorRed is red. ColorRed = Color{R: 255, G: 0, B: 0, A: 255} // ColorGreen is green. ColorGreen = Color{R: 0, G: 255, B: 0, A: 255} // ColorBlue is blue. ColorBlue = Color{R: 0, G: 0, B: 255, A: 255} ) func parseHex(hex string) uint8 { v, _ := strconv.ParseInt(hex, 16, 16) return uint8(v) } // ColorFromHex returns a color from a css hex code. func ColorFromHex(hex string) Color { var c Color if len(hex) == 3 { c.R = parseHex(string(hex[0])) * 0x11 c.G = parseHex(string(hex[1])) * 0x11 c.B = parseHex(string(hex[2])) * 0x11 } else { c.R = parseHex(hex[0:2]) c.G = parseHex(hex[2:4]) c.B = parseHex(hex[4:6]) } c.A = 255 return c } // ColorFromAlphaMixedRGBA returns the system alpha mixed rgba values. func ColorFromAlphaMixedRGBA(r, g, b, a uint32) Color { fa := float64(a) / 255.0 var c Color c.R = uint8(float64(r) / fa) c.G = uint8(float64(g) / fa) c.B = uint8(float64(b) / fa) c.A = uint8(a | (a >> 8)) return c } // ColorChannelFromFloat returns a normalized byte from a given float value. func ColorChannelFromFloat(v float64) uint8 { return uint8(v * 255) } // Color is our internal color type because color.Color is bullshit. type Color struct { R, G, B, A uint8 } // RGBA returns the color as a pre-alpha mixed color set. func (c Color) RGBA() (r, g, b, a uint32) { fa := float64(c.A) / 255.0 r = uint32(float64(uint32(c.R)) * fa) r |= r << 8 g = uint32(float64(uint32(c.G)) * fa) g |= g << 8 b = uint32(float64(uint32(c.B)) * fa) b |= b << 8 a = uint32(c.A) a |= a << 8 return } // IsZero returns if the color has been set or not. func (c Color) IsZero() bool { return c.R == 0 && c.G == 0 && c.B == 0 && c.A == 0 } // IsTransparent returns if the colors alpha channel is zero. func (c Color) IsTransparent() bool { return c.A == 0 } // WithAlpha returns a copy of the color with a given alpha. func (c Color) WithAlpha(a uint8) Color { return Color{ R: c.R, G: c.G, B: c.B, A: a, } } // Equals returns true if the color equals another. func (c Color) Equals(other Color) bool { return c.R == other.R && c.G == other.G && c.B == other.B && c.A == other.A } // AverageWith averages two colors. func (c Color) AverageWith(other Color) Color { return Color{ R: (c.R + other.R) >> 1, G: (c.G + other.G) >> 1, B: (c.B + other.B) >> 1, A: c.A, } } var cCache = make(map[Color]string) // String returns a css string representation of the color. func (c Color) String() string { if a, ok := cCache[c]; ok { return a } fa := float64(c.A) / float64(255) result := "rgba(" + strconv.FormatUint(uint64(c.R), 10) + "," + strconv.FormatUint(uint64(c.G), 10) + "," + strconv.FormatUint(uint64(c.B), 10) + "," + fastFloater(fa) + ")" cCache[c] = result return result } // F is between 0 and 1. 0 is fully transparent and 1 is fully opaque. // We should return 0.1, 0.2, 0.3 etc. func fastFloater(f float64) string { if f > 0.95 { return "1" } else if f < 0.05 { return "0" } else if f >= 0.85 && f < 0.95 { return "0.9" } else if f >= 0.75 && f < 0.85 { return "0.8" } else if f >= 0.65 && f < 0.75 { return "0.7" } else if f >= 0.55 && f < 0.65 { return "0.6" } else if f >= 0.45 && f < 0.55 { return "0.5" } else if f >= 0.35 && f < 0.45 { return "0.4" } else if f >= 0.25 && f < 0.35 { return "0.3" } else if f >= 0.15 && f < 0.25 { return "0.2" } else { return "0.1" } }
drawing/color.go
0.820001
0.404507
color.go
starcoder
package frequency import ( "fmt" "time" ) type Freq int const ( Day Freq = iota DayB Week Tenday Month Quarter Halfyear Year ) func (f Freq) String() string { switch f { case Day: return "Day" case DayB: return "DayB" case Week: return "Week" case Tenday: return "Tenday" case Month: return "Month" case Quarter: return "Quarter" case Halfyear: return "Halfyear" case Year: return "Year" } return "N/A" } type Edldate struct { freq Freq offset int } func (v *Edldate) Show() { fmt.Printf("%s %d\n", v.freq, v.freq) fmt.Println(v.offset + 15) } func getOrdinal(freq Freq, base time.Time) int { year, month, day := base.Date() switch freq { case Week: return int(base.Weekday()) case Month: fmt.Printf("%v %v %d\n", year, month, day) return base.Day() } return 0 } func getStartOfQuarter(year int, month int) time.Time { switch { case month < 4: return time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC) case month < 7: return time.Date(year, 4, 1, 0, 0, 0, 0, time.UTC) case month < 10: return time.Date(year, 7, 1, 0, 0, 0, 0, time.UTC) case month <= 12: return time.Date(year, 10, 1, 0, 0, 0, 0, time.UTC) } return time.Now() } //获取起始日期 func getRangeOfTerm(freq Freq, base time.Time) (time.Time, time.Time) { var start time.Time var end time.Time year, month, day := base.Date() switch freq { case Week: var wkd int if base.Weekday() == time.Sunday { wkd = 7 } else { wkd = int(base.Weekday()) } start = time.Date(year, month, day-wkd+1, 0, 0, 0, 0, time.UTC) end = start.AddDate(0, 0, 6) return start, end case Month: start = time.Date(year, month, 1, 0, 0, 0, 0, time.UTC) end = start.AddDate(0, 1, -1) return start, end case Quarter: start = getStartOfQuarter(year, int(month)) end = start.AddDate(0, 3, -1) return start, end } return time.Now(), time.Now() } func (v *Edldate) NextDate(base time.Time) { fmt.Printf("it is %d of %s\n", getOrdinal(v.freq, base), v.freq) s, e := getRangeOfTerm(v.freq, base) fmt.Printf("start is %v, end is %v\n", s, e) if v.freq == Day { daysLater := base.AddDate(0, 0, v.offset) fmt.Printf("next valid date of %s is %s after %d days \n", base.Format("2006-01-02"), daysLater.Format("2006-01-02"), v.offset) } else { fmt.Printf("next vald date called with %s\n", base.Format("2006-01-02")) } }
edldate.go
0.507324
0.46308
edldate.go
starcoder
package gosfmt // Int63r generates pseudo random int64 between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // random int64 func Int63r(low, high int64) int64 { return globalRand.Int63r(low, high) } // Int63s generates pseudo random integers between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // values -- slice to be filled with len(values) numbers func Int63s(values []int64, low, high int64) { globalRand.Int63s(values, low, high) } // Int63huffle shuffles a slice of integers func Int63Shuffle(values []int64) { globalRand.Int63Shuffle(values) } // Uint32 is int range generates pseudo random uint32 between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // random uint32 func Uint32r(low, high uint32) uint32 { return globalRand.Uint32r(low, high) } // Uint32s generates pseudo random integers between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // values -- slice to be filled with len(values) numbers func Uint32s(values []uint32, low, high uint32) { globalRand.Uint32s(values, low, high) } // Uint32huffle shuffles a slice of integers func Uint32Shuffle(values []uint32) { globalRand.Uint32Shuffle(values) } // Uint64r generates pseudo random uint64 between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // random uint64 func Uint64r(low, high uint64) uint64 { return globalRand.Uint64r(low, high) } // Uint64s generates pseudo random integers between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // values -- slice to be filled with len(values) numbers func Uint64s(values []uint64, low, high uint64) { globalRand.Uint64s(values, low, high) } // Uint64huffle shuffles a slice of integers func Uint64Shuffle(values []uint64) { globalRand.Uint64Shuffle(values) } // Int31r is int range generates pseudo random int32 between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // random int32 func Int31r(low, high int32) int32 { return globalRand.Int31r(low, high) } // Int31s generates pseudo random integers between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // values -- slice to be filled with len(values) numbers func Int31s(values []int32, low, high int32) { globalRand.Int31s(values, low, high) } // Int31huffle shuffles a slice of integers func Int31Shuffle(values []int32) { globalRand.Int31Shuffle(values) } // Intr is int range generates pseudo random integer between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // random integer func Intr(low, high int) int { return globalRand.Intr(low, high) } // Ints generates pseudo random integers between low and high. // Input: // low -- lower limit // high -- upper limit // Output: // values -- slice to be filled with len(values) numbers func Ints(values []int, low, high int) { globalRand.Ints(values, low, high) } // IntShuffle shuffles a slice of integers func IntShuffle(values []int) { globalRand.IntShuffle(values) } // Float64r generates a pseudo random real number between low and high; i.e. in [low, right) // Input: // low -- lower limit (closed) // high -- upper limit (open) // Output: // random float64 func Float64r(low, high float64) float64 { return globalRand.Float64r(low, high) } // Float64s generates pseudo random real numbers between low and high; i.e. in [low, right) // Input: // low -- lower limit (closed) // high -- upper limit (open) // Output: // values -- slice to be filled with len(values) numbers func Float64s(values []float64, low, high float64) { globalRand.Float64s(values, low, high) } // Float64Shuffle shuffles a slice of float point numbers func Float64Shuffle(values []float64) { globalRand.Float64Shuffle(values) } // Float32r generates a pseudo random real number between low and high; i.e. in [low, right) // Input: // low -- lower limit (closed) // high -- upper limit (open) // Output: // random float32 func Float32r(low, high float32) float32 { return globalRand.Float32r(low, high) } // Float32s generates pseudo random real numbers between low and high; i.e. in [low, right) // Input: // low -- lower limit (closed) // high -- upper limit (open) // Output: // values -- slice to be filled with len(values) numbers func Float32s(values []float32, low, high float32) { globalRand.Float32s(values, low, high) } // Float32Shuffle shuffles a slice of float point numbers func Float32Shuffle(values []float32) { globalRand.Float32Shuffle(values) } // FlipCoin generates a Bernoulli variable; throw a coin with probability p func FlipCoin(p float64) bool { return globalRand.FlipCoin(p) }
gosfmt_gosl.go
0.671363
0.467514
gosfmt_gosl.go
starcoder
package fit import ( "math" "strconv" ) const ( sint32Invalid = 0x7FFFFFFF stringInvalid = "Invalid" precision = 5 // 1.1 m ) var ( semiToDegFactor = 180 / math.Pow(2, 31) degToSemiFactor = math.Pow(2, 31) / 180 ) // Latitude represents the geographical coordinate latitude. type Latitude struct { semicircles int32 } // NewLatitude returns a new latitude from a semicircle. If semicircles is // outside the range of a latitude, (math.MinInt32/2, math.MaxInt32/2) then an // invalid latitude is returned. func NewLatitude(semicircles int32) Latitude { if semicircles == sint32Invalid { return NewLatitudeInvalid() } if semicircles < math.MinInt32/2 || semicircles > math.MaxInt32/2 { return NewLatitudeInvalid() } return Latitude{semicircles: semicircles} } // NewLatitudeDegrees returns a new latitude from a degree. If degrees is // outside the range of a latitude (+/- 90°) then an invalid latitude is // returned. func NewLatitudeDegrees(degrees float64) Latitude { if degrees >= 90 || degrees <= -90 { return NewLatitudeInvalid() } return Latitude{semicircles: int32(degrees * degToSemiFactor)} } // NewLatitudeInvalid returns an invalid latitude. The underlying storage is // set to the invalid value of the FIT base type (sint32) used to represent a // latitude. func NewLatitudeInvalid() Latitude { return Latitude{semicircles: sint32Invalid} } // Semicircles returns l in semicircles. func (l Latitude) Semicircles() int32 { return l.semicircles } // Degrees returns l in degrees. If l is invalid then NaN is returned. func (l Latitude) Degrees() float64 { if l.semicircles == sint32Invalid { return math.NaN() } return float64(l.semicircles) * semiToDegFactor } // Invalid reports whether l represents an invalid latitude. func (l Latitude) Invalid() bool { return l.semicircles == sint32Invalid } // String returns a string representation of l in degrees with 5 decimal // places. If l is invalid then the string "Invalid" is returned. func (l Latitude) String() string { if l.semicircles == sint32Invalid { return stringInvalid } return strconv.FormatFloat(l.Degrees(), 'f', precision, 32) } // Longitude represents the geographical coordinate longitude. type Longitude struct { semicircles int32 } // NewLongitude returns a new longitude from a semicircle. func NewLongitude(semicircles int32) Longitude { return Longitude{semicircles: semicircles} } // NewLongitudeDegrees returns a new longitude from a degree. If degrees is // outside the range of a longitude (+/- 180°) then an invalid longitude is // returned. func NewLongitudeDegrees(degrees float64) Longitude { if degrees >= 180 || degrees <= -180 { return Longitude{semicircles: sint32Invalid} } return Longitude{semicircles: int32(degrees * degToSemiFactor)} } // NewLongitudeInvalid returns an invalid longitude. The underlying storage is // set to the invalid value of the FIT base type (sint32) used to represent a // longitude. func NewLongitudeInvalid() Longitude { return Longitude{semicircles: sint32Invalid} } // Semicircles returns l in semicircles. func (l Longitude) Semicircles() int32 { return l.semicircles } // Degrees returns l in degrees. If l is invalid then NaN is returned. func (l Longitude) Degrees() float64 { if l.semicircles == sint32Invalid { return math.NaN() } return float64(l.semicircles) * semiToDegFactor } // Invalid reports whether l represents an invalid longitude. func (l Longitude) Invalid() bool { return l.semicircles == sint32Invalid } // String returns a string representation of l in degrees with 5 decimal // places. If l is invalid then the string "Invalid" is returned. func (l Longitude) String() string { if l.semicircles == sint32Invalid { return stringInvalid } return strconv.FormatFloat(l.Degrees(), 'f', precision, 32) }
latlng.go
0.882326
0.419588
latlng.go
starcoder
// Package negtest provides utilities for writing negative tests. package negtest import ( "fmt" "reflect" "runtime" "testing" ) // ExpectFatal fails the test if the specified function does _not_ fail fatally, // i.e. does not call any of t.{FailNow, Fatal, Fatalf}. // If it does fail fatally, returns the fatal error message it logged. // It is recommended the error message be checked to distinguish the // expected failure from unrelated failures that may have occurred. func ExpectFatal(t testing.TB, fn func(t testing.TB)) (msg string) { t.Helper() // Defer and recover to capture the expected fatal message. defer func() { switch r := recover().(type) { case failure: // panic from fatal fakeT failure, return the message msg = string(r) case nil: // no panic at all, do nothing default: // another panic was detected, re-raise panic(r) } }() fn(&fakeT{realT: t}) t.Fatalf("%s did not fail fatally as expected", funcName(fn)) return "" } // ExpectErrorSubstring determines whether t.Errorf was called, func ExpectError(t testing.TB, fn func(testing.TB)) string { ft := &fakeT{realT: t} fn(ft) if ft.err != "" { return ft.err } t.Errorf("%s did not raise an error was expected", funcName(fn)) return "" } func funcName(i interface{}) string { return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() } // fakeT is a testing.TB implementation that can be used as an input to unit tests // such that it is possible to check that the correct errors are raised. type fakeT struct { // Any methods not explicitly implemented here will panic when called. testing.TB realT testing.TB // err is used to store the errors from Errorf or Error err string } // failure is a unique type to distinguish test failures from other panics. type failure string // FailNow implements the testing.TB FailNow method so that the failure can be // retrieved by making the call within the lambda argument to ExpectFatal. func (ft *fakeT) FailNow() { ft.fatal("") } // Fatal implements the testing.TB Fatalf method so that the failure can be // retrieved by making the call within the lambda argument to ExpectFatal. func (ft *fakeT) Fatal(args ...interface{}) { ft.fatal(fmt.Sprintln(args...)) } // Fatalf implements the testing.TB Fatalf method so that the failure can be // retrieved by making the call within the lambda argument to ExpectFatal. func (ft *fakeT) Fatalf(format string, args ...interface{}) { ft.fatal(fmt.Sprintf(format, args...)) } func (ft *fakeT) fatal(msg string) { panic(failure(msg)) } // Log implements the testing.TB Log method by delegating to the real *testing.T. func (ft *fakeT) Log(args ...interface{}) { ft.realT.Log(args...) } // Log implements the testing.TB Logf method by delegating to the real *testing.T. func (ft *fakeT) Logf(format string, args ...interface{}) { ft.realT.Logf(format, args...) } // Errorf implements the testing.TB Errorf method, but rather than reporting the // error catches it in the err field of the fakeT. func (ft *fakeT) Errorf(format string, args ...interface{}) { ft.err = fmt.Sprintf(format, args...) } // Helper implements the testing.TB Helper method as a noop. func (*fakeT) Helper() {}
negtest/negtest.go
0.749087
0.518668
negtest.go
starcoder
package xcore import ( "fmt" "strconv" "time" ) // ===================== // XDatasetCollection // ===================== // XDatasetCollection is the basic collection of XDatasetDefs type XDatasetCollection []XDatasetDef // NewXDatasetCollection is used to build an XDatasetCollection from a standard []map func NewXDatasetCollection(data []map[string]interface{}) XDatasetCollectionDef { // Scan data and encapsulate it into the XDataset dsc := &XDatasetCollection{} for _, v := range data { dsc.Push(NewXDataset(v)) } return dsc } // String will transform the XDataset into a readable string func (d *XDatasetCollection) String() string { str := "XDatasetCollection[" for key, val := range *d { str += strconv.Itoa(key) + ":" + fmt.Sprint(val) + " " } str += "]" return str } // GoString will transform the XDataset into a readable string for humans func (d *XDatasetCollection) GoString() string { return d.String() } // Unshift will adds a XDatasetDef at the beginning of the collection func (d *XDatasetCollection) Unshift(data XDatasetDef) { *d = append([]XDatasetDef{data}, (*d)...) } // Shift will remove the element at the beginning of the collection func (d *XDatasetCollection) Shift() XDatasetDef { data := (*d)[0] *d = (*d)[1:] return data } // Push will adds a XDatasetDef at the end of the collection func (d *XDatasetCollection) Push(data XDatasetDef) { *d = append(*d, data) } // Pop will remove the element at the end of the collection func (d *XDatasetCollection) Pop() XDatasetDef { data := (*d)[len(*d)-1] *d = (*d)[:len(*d)-1] return data } // Count will return the quantity of elements into the collection func (d *XDatasetCollection) Count() int { return len(*d) } // Get will retrieve an element by index from the collection func (d *XDatasetCollection) Get(index int) (XDatasetDef, bool) { if index < 0 || index >= len(*d) { return nil, false } return (*d)[index], true } // GetData will retrieve the first available data identified by key from the collection ordered by index func (d *XDatasetCollection) GetData(key string) (interface{}, bool) { for i := len(*d) - 1; i >= 0; i-- { val, ok := (*d)[i].Get(key) if ok { return val, true } } return nil, false } // GetDataString will retrieve the first available data identified by key from the collection ordered by index and return it as a string func (d *XDatasetCollection) GetDataString(key string) (string, bool) { v, ok := d.GetData(key) if ok { return fmt.Sprint(v), true } return "", false } // GetDataBool will retrieve the first available data identified by key from the collection ordered by index and return it as a boolean func (d *XDatasetCollection) GetDataBool(key string) (bool, bool) { if val, ok := d.GetData(key); ok { if val2, ok2 := val.(bool); ok2 { return val2, true } } return false, false } // GetDataInt will retrieve the first available data identified by key from the collection ordered by index and return it as an integer func (d *XDatasetCollection) GetDataInt(key string) (int, bool) { if val, ok := d.GetData(key); ok { if val2, ok2 := val.(int); ok2 { return val2, true } } return 0, false } // GetDataFloat will retrieve the first available data identified by key from the collection ordered by index and return it as a float func (d *XDatasetCollection) GetDataFloat(key string) (float64, bool) { if val, ok := d.GetData(key); ok { if val2, ok2 := val.(float64); ok2 { return val2, true } } return 0, false } // GetDataTime will retrieve the first available data identified by key from the collection ordered by index and return it as a time func (d *XDatasetCollection) GetDataTime(key string) (time.Time, bool) { if val, ok := d.GetData(key); ok { if val2, ok2 := val.(time.Time); ok2 { return val2, true } } return time.Time{}, false } // GetCollection will retrieve a collection from the XDatasetCollection func (d *XDatasetCollection) GetCollection(key string) (XDatasetCollectionDef, bool) { v, ok := d.GetData(key) // Verify v IS actually a XDatasetCollectionDef to avoid the error if ok { return v.(XDatasetCollectionDef), true } return nil, false } // Clone will make a full copy of the object into memory func (d *XDatasetCollection) Clone() XDatasetCollectionDef { cloned := &XDatasetCollection{} for _, val := range *d { *cloned = append(*cloned, val.Clone()) } return cloned }
v2/xdatasetcollection.go
0.579638
0.468304
xdatasetcollection.go
starcoder
package gomini import ( "github.com/spf13/cast" ) func GetStrBool(strv string, def ...bool) (bool, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToBoolE(strv) } func GetStrFloat(strv string, def ...float64) (float64, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToFloat64E(strv) } func GetStrFloat32(strv string, def ...float32) (float32, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToFloat32E(strv) } func GetStrFloat64(strv string, def ...float64) (float64, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToFloat64E(strv) } func GetStrUint(strv string, def ...uint) (uint, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToUintE(strv) } func GetStrInt(strv string, def ...int) (int, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToIntE(strv) } func GetStrInt8(strv string, def ...int8) (int8, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToInt8E(strv) } func GetStrUint8(strv string, def ...uint8) (uint8, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToUint8E(strv) } func GetStrInt16(strv string, def ...int16) (int16, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToInt16E(strv) } func GetStrUint16(strv string, def ...uint16) (uint16, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToUint16E(strv) } func GetStrInt32(strv string, def ...int32) (int32, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToInt32E(strv) } func GetStrUint32(strv string, def ...uint32) (uint32, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToUint32E(strv) } func GetStrInt64(strv string, def ...int64) (int64, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToInt64E(strv) } func GetStrUint64(strv string, def ...uint64) (uint64, error) { if len(strv) == 0 && len(def) > 0 { return def[0], nil } return cast.ToUint64E(strv) } func GetUint64Str(d uint64) string { return cast.ToString(d) } func GetInt64Str(d int64) string { return cast.ToString(d) } func GetUint32Str(d uint32) string { return cast.ToString(d) } func GetInt32Str(d int32) string { return cast.ToString(d) } func GetUint16Str(d uint16) string { return cast.ToString(d) } func GetInt16Str(d int16) string { return cast.ToString(d) } func GetUint8Str(d uint8) string { return cast.ToString(d) } func GetInt8Str(d int8) string { return cast.ToString(d) } func GetUintStr(d uint) string { return cast.ToString(d) } func GetIntStr(d int) string { return cast.ToString(d) } func GetFloatStr(f float64) string { return cast.ToString(f) } func GetFloat32Str(f float32) string { return cast.ToString(f) } func GetFloat64Str(f float64) string { return cast.ToString(f) }
strconv.go
0.59302
0.416381
strconv.go
starcoder
package models import ( "strconv" "strings" ) var ( // CurrencyExchangeRate holds all the currency converted in chaos. CurrencyExchangeRate = map[string]float64{ "Ancient Orb": 27, "Ancient Shard": 2, "Annulment Shard": 3, "Apprentice Cartographer's Sextant": 1.1, "Armourer's Scrap": 1 / 44, "Binding Shard": 1 / 2, "Blacksmith's Whetstone": 1 / 32.3, "Blessed Orb": 3.9, "Blessing of Chayula": 162.4, "Blessing of Esh": 3.3, "Blessing of Tul": 4, "Blessing of Uul-Netol": 7.4, "Blessing of Xoph": 3, "Cartographer's Chisel": 1 / 2.3, "Chaos Orb": 1, "Chaos Shard": 1 / 20, "Chromatic Orb": 1 / 4.3, "Divine Orb": 40, "Engineer's Orb": 1 / 1.2, "Engineer's Shard": 60, "Eternal Orb": 36500, "Exalted Orb": 163.5, "Exalted Shard": 7, "Gemcutter's Prism": 1 / 1.9, "Glassblower's Bauble": 1 / 9.4, "Harbinger's Orb": 28, "Harbinger's Shard": 2, "Horizon Shard": 1 / 20, "Jeweller's Orb": 1 / 6.2, "Journeyman Cartographer's Sextant": 2.8, "Master Cartographer's Sextant": 3.7, "Mirror of Kalandra": 38700, "Mirror Shard": 38700 / 20, "Orb of Alchemy": 1 / 2.5, "Orb of Alteration": 1 / 3.6, "Orb of Annulment": 50, "Orb of Augmentation": 1 / 37.1, "Orb of Binding": 1 / 3, "Orb of Chance": 1 / 6.5, "Orb of Fusing": 1 / 1.5, "Orb of Horizons": 1, "Orb of Regret": 1.6, "Orb of Scouring": 1 / 1.2, "Orb of Transmutation": 1 / 60, "Perandus Coin": 1 / 70, "Portal Scroll": 1 / 54.9, "Regal Orb": 1 / 1.4, "Regal Shard": (1 / 1.4) / 20, "Scroll of Wisdom": 1 / 111.5, "Silver Coin": 1 / 4.1, "Splinter of Chayula": 1.9, "Splinter of Esh": 1 / 8, "Splinter of Tul": 1 / 7.1, "Splinter of Uul-Netol": 1 / 3.1, "Splinter of Xoph": 1 / 4.9, "Stacked Deck": 1 / 7.4, "Timeless Eternal Empire Splinter": 1 / 7, "Timeless Karui Splinter": 1 / 11, "Timeless Maraketh Splinter": 1 / 2, "Timeless Templar Splinter": 1 / 2, "Timeless Vaal Splinter": 1 / 6, "Vaal Orb": 1.6, } ) // getCount retrieves currency count. func getCount(properties []ItemProperty) int { for _, property := range properties { if property.Name == "Stack Size" { // In: properties/0/values/0/0. for _, row := range property.Values { rawValues, ok := row.([]interface{}) if ok { for _, subRow := range rawValues { switch rawStack := subRow.(type) { case string: // Format is "1034/20" for example. pos := strings.Index(rawStack, "/") rawNb := rawStack[:pos] nb, err := strconv.Atoi(rawNb) if err != nil { // Should never happen! panic(err) } return nb } } } } } } return 0 } // WealthBreakdown holds total wealth and its details. type WealthBreakdown struct { EstimatedChaos int NbAlch int NbChaos int NbExa int } // ComputeWealth computes the wealth in chaos orbs contained in a stash. func ComputeWealth(stashTabs []*StashTab, characters []*CharacterInventory) WealthBreakdown { var wealth WealthBreakdown var estimate float64 compute := func(item *Item) { nb := getCount(item.Properties) switch item.Type { case "Orb of Alchemy": wealth.NbAlch += nb case "Chaos Orb": wealth.NbChaos += nb case "Exalted Orb": wealth.NbExa += nb } if value, ok := CurrencyExchangeRate[item.Type]; ok { estimate += float64(nb) * value } } // Get currencies in stash. for _, tab := range stashTabs { for _, item := range tab.Items { compute(&item) } } // Get currencies in inventories. for _, character := range characters { for _, item := range character.Items { compute(item) } } wealth.EstimatedChaos = int(estimate) return wealth }
models/wealth.go
0.522933
0.452415
wealth.go
starcoder
package utils import ( "math" "sort" "time" "github.com/golang/glog" "github.com/google/cadvisor/info" ) const milliSecondsToNanoSeconds = 1000000 const secondsToMilliSeconds = 1000 type uint64Slice []uint64 func (a uint64Slice) Len() int { return len(a) } func (a uint64Slice) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a uint64Slice) Less(i, j int) bool { return a[i] < a[j] } // TODO(rjnagal): Move out when we update API. type Percentiles struct { // Average over the collected sample. Mean uint64 `json:"mean"` // Max seen over the collected sample. Max uint64 `json:"max"` // 90th percentile over the collected sample. Ninety uint64 `json:"ninety"` } // Get 90th percentile of the provided samples. Round to integer. func (self uint64Slice) Get90Percentile() uint64 { count := self.Len() if count == 0 { return 0 } sort.Sort(self) n := float64(0.9 * (float64(count) + 1)) idx, frac := math.Modf(n) index := int(idx) percentile := float64(self[index-1]) if index > 1 || index < count { percentile += frac * float64(self[index]-self[index-1]) } return uint64(percentile) } type Mean struct { // current count. count uint64 // current mean. Mean float64 } func (self *Mean) Add(value uint64) { self.count++ if self.count == 1 { self.Mean = float64(value) return } c := float64(self.count) v := float64(value) self.Mean = (self.Mean*(c-1) + v) / c } // Returns cpu and memory usage percentiles. func GetPercentiles(stats []*info.ContainerStats) (Percentiles, Percentiles) { lastCpu := uint64(0) lastTime := time.Time{} memorySamples := make(uint64Slice, 0, len(stats)) cpuSamples := make(uint64Slice, 0, len(stats)-1) numSamples := 0 memoryMean := Mean{count: 0, Mean: 0} cpuMean := Mean{count: 0, Mean: 0} memoryPercentiles := Percentiles{} cpuPercentiles := Percentiles{} for _, stat := range stats { var elapsed int64 time := stat.Timestamp if !lastTime.IsZero() { elapsed = time.UnixNano() - lastTime.UnixNano() if elapsed < 10*milliSecondsToNanoSeconds { glog.Infof("Elapsed time too small: %d ns: time now %s last %s", elapsed, time.String(), lastTime.String()) continue } } numSamples++ cpuNs := stat.Cpu.Usage.Total // Ignore actual usage and only focus on working set. memory := stat.Memory.WorkingSet if memory > memoryPercentiles.Max { memoryPercentiles.Max = memory } glog.V(2).Infof("Read sample: cpu %d, memory %d", cpuNs, memory) memoryMean.Add(memory) memorySamples = append(memorySamples, memory) if lastTime.IsZero() { lastCpu = cpuNs lastTime = time continue } cpuRate := (cpuNs - lastCpu) * secondsToMilliSeconds / uint64(elapsed) if cpuRate < 0 { glog.Infof("cpu rate too small: %f ns", cpuRate) continue } glog.V(2).Infof("Adding cpu rate sample : %d", cpuRate) lastCpu = cpuNs lastTime = time cpuSamples = append(cpuSamples, cpuRate) if cpuRate > cpuPercentiles.Max { cpuPercentiles.Max = cpuRate } cpuMean.Add(cpuRate) } cpuPercentiles.Mean = uint64(cpuMean.Mean) memoryPercentiles.Mean = uint64(memoryMean.Mean) cpuPercentiles.Ninety = cpuSamples.Get90Percentile() memoryPercentiles.Ninety = memorySamples.Get90Percentile() return cpuPercentiles, memoryPercentiles }
utils/percentiles.go
0.598782
0.435661
percentiles.go
starcoder
package main import ( "io" "io/ioutil" "strconv" "strings" "gopkg.in/yaml.v2" ) // Universe represents a set of configuration, often refered as data or database. type Universe struct { Backgrounds map[string][]Background `yaml:"backgrounds"` Aptitudes []Aptitude `yaml:"aptitudes"` Characteristics []Characteristic `yaml:"characteristics"` Gauges []Gauge `yaml:"gauges"` Skills []Skill `yaml:"skills"` Talents []Talent `yaml:"talents"` Spells []Spell `yaml:"spells"` Costs CostMatrix `yaml:"costs"` } // ParseUniverse load an from a plain YAML file. // It returns a well-formed universe that describe all the components of a game setting. func ParseUniverse(file io.Reader) (Universe, error) { // Open and parse universe. raw, err := ioutil.ReadAll(file) if err != nil { return Universe{}, err } universe := Universe{} err = yaml.Unmarshal(raw, &universe) if err != nil { return Universe{}, err } // Lowercase the types of background. backgrounds := make(map[string][]Background) for typ, b := range universe.Backgrounds { backgrounds[strings.ToLower(typ)] = b } universe.Backgrounds = backgrounds // Add it's type to each defined background. for typ, backgrounds := range universe.Backgrounds { for i := range backgrounds { universe.Backgrounds[typ][i].Type = typ } } return universe, nil } // FindCoster returns the coster associated to the label, // and false if none is. func (u Universe) FindCoster(upgrade Upgrade) (Coster, bool) { characteristic, found := u.FindCharacteristic(upgrade) if found { return characteristic, true } skill, found := u.FindSkill(upgrade) if found { return skill, true } talent, found := u.FindTalent(upgrade) if found { return talent, true } aptitude, found := u.FindAptitude(upgrade) if found { return aptitude, true } gauge, found := u.FindGauge(upgrade) if found { return gauge, true } spell, found := u.FindSpell(upgrade) if found { return spell, true } return nil, false } // FindCharacteristic returns the characteristic correponding to the given label or a zero-value, and a boolean indicating if it was found. func (u Universe) FindCharacteristic(upgrade Upgrade) (Characteristic, bool) { // Characteristics upgrades are defined by a name and a value, separated by a space, so we need to look for the first // part of the label. // Examples: STR +5, FEL -1, TOU 40. fields := split(upgrade.Name, ' ') name := fields[0] for _, characteristic := range u.Characteristics { if characteristic.Name == name { return characteristic, true } } return Characteristic{}, false } // FindSkill returns the skill corresponding to the given label or a zero-value, and a boolean indicating if it was found. func (u Universe) FindSkill(upgrade Upgrade) (Skill, bool) { // Skills upgrades are defined by a name and eventually a speciality, separated by a colon. // Examples: Common Lore: Dark Gods fields := split(upgrade.Name, ':') name := fields[0] for _, skill := range u.Skills { if strings.EqualFold(skill.Name, name) { if len(fields) == 2 { skill.Speciality = fields[1] } return skill, true } } return Skill{}, false } // FindTalent returns the talent corresponding to the given label or a zero value, and a boolean indicating if it was found. func (u Universe) FindTalent(upgrade Upgrade) (Talent, bool) { // Talents upgrades are defined by a name and eventually a speciality, separated by a colon. // Examples: Psychic Resistance: Fear fields := split(upgrade.Name, ':') name := fields[0] for _, talent := range u.Talents { if strings.EqualFold(talent.Name, name) { if len(fields) == 2 { talent.Speciality = fields[1] } return talent, true } } return Talent{}, false } // FindAptitude returns the aptitude corresponding to the given label or a zero value, and a boolean indicating if it was found. func (u Universe) FindAptitude(upgrade Upgrade) (Aptitude, bool) { for _, aptitude := range u.Aptitudes { if strings.EqualFold(string(aptitude), upgrade.Name) { return aptitude, true } } return Aptitude(""), false } // FindGauge returns the gauge corresponding to the given label or a zero value, and a boolean indicating if it was found. func (u Universe) FindGauge(upgrade Upgrade) (Gauge, bool) { // Gauges upgrades are defined by a name and a value, separated by a space. fields := split(upgrade.Name, ' ') for _, gauge := range u.Gauges { if strings.EqualFold(gauge.Name, fields[0]) { val, err := strconv.Atoi(fields[1]) if err != nil { panic(err) } gauge.Value = val return gauge, true } } return Gauge{}, false } // FindBackground returns the background corresponding to the given label, and a boolean indicating if it was found. func (u Universe) FindBackground(typ string, label string) (Background, bool) { backgrounds, found := u.Backgrounds[strings.ToLower(typ)] if !found { return Background{}, false } for _, background := range backgrounds { if strings.EqualFold(background.Name, label) { return background, true } } return Background{}, false } // FindSpell returns the spell corresponding to the given label or a zero value, and a boolean indicating if it was found. func (u Universe) FindSpell(upgrade Upgrade) (Spell, bool) { for _, spell := range u.Spells { if strings.EqualFold(spell.Name, upgrade.Name) { return spell, true } } return Spell{}, false }
src/adeptus/universe.go
0.81409
0.45048
universe.go
starcoder
// Package status provides utility functions for google_rpc status objects. package status import ( rpc "github.com/gogo/googleapis/google/rpc" ) // OK represents a status with a code of rpc.OK var OK = rpc.Status{Code: int32(rpc.OK)} // New returns an initialized status with the given error code. func New(c rpc.Code) rpc.Status { return rpc.Status{Code: int32(c)} } // WithMessage returns an initialized status with the given error code and message func WithMessage(c rpc.Code, message string) rpc.Status { return rpc.Status{Code: int32(c), Message: message} } // WithError returns an initialized status with the rpc.INTERNAL error code and the error's message. func WithError(err error) rpc.Status { return rpc.Status{Code: int32(rpc.INTERNAL), Message: err.Error()} } // WithInternal returns an initialized status with the rpc.INTERNAL error code and the error's message. func WithInternal(message string) rpc.Status { return rpc.Status{Code: int32(rpc.INTERNAL), Message: message} } // WithCancelled returns an initialized status with the rpc.CANCELLED error code and the error's message. func WithCancelled(message string) rpc.Status { return rpc.Status{Code: int32(rpc.CANCELLED), Message: message} } // WithInvalidArgument returns an initialized status with the rpc.INVALID_ARGUMENT code and the given message. func WithInvalidArgument(message string) rpc.Status { return rpc.Status{Code: int32(rpc.INVALID_ARGUMENT), Message: message} } // WithPermissionDenied returns an initialized status with the rpc.PERMISSION_DENIED code and the given message. func WithPermissionDenied(message string) rpc.Status { return rpc.Status{Code: int32(rpc.PERMISSION_DENIED), Message: message} } // WithResourceExhausted returns an initialized status with the rpc.PERMISSION_DENIED code and the given message. func WithResourceExhausted(message string) rpc.Status { return rpc.Status{Code: int32(rpc.RESOURCE_EXHAUSTED), Message: message} } // WithDeadlineExceeded returns an initialized status with the rpc.DEADLINE_EXCEEDED code and the given message. func WithDeadlineExceeded(message string) rpc.Status { return rpc.Status{Code: int32(rpc.DEADLINE_EXCEEDED), Message: message} } // WithUnknown returns an initialized status with the rpc.UNKNOWN code and the given message. func WithUnknown(message string) rpc.Status { return rpc.Status{Code: int32(rpc.UNKNOWN), Message: message} } // WithNotFound returns an initialized status with the rpc.NOT_FOUND code and the given message. func WithNotFound(message string) rpc.Status { return rpc.Status{Code: int32(rpc.NOT_FOUND), Message: message} } // WithAlreadyExists returns an initialized status with the rpc.ALREADY_EXISTS code and the given message. func WithAlreadyExists(message string) rpc.Status { return rpc.Status{Code: int32(rpc.ALREADY_EXISTS), Message: message} } // WithFailedPrecondition returns an initialized status with the rpc.FAILED_PRECONDITION code and the given message. func WithFailedPrecondition(message string) rpc.Status { return rpc.Status{Code: int32(rpc.FAILED_PRECONDITION), Message: message} } // WithAborted returns an initialized status with the rpc.ABORTED code and the given message. func WithAborted(message string) rpc.Status { return rpc.Status{Code: int32(rpc.ABORTED), Message: message} } // WithOutOfRange returns an initialized status with the rpc.OUT_OF_RANGE code and the given message. func WithOutOfRange(message string) rpc.Status { return rpc.Status{Code: int32(rpc.OUT_OF_RANGE), Message: message} } // WithUnimplemented returns an initialized status with the rpc.UNIMPLEMENTED code and the given message. func WithUnimplemented(message string) rpc.Status { return rpc.Status{Code: int32(rpc.UNIMPLEMENTED), Message: message} } // WithUnavailable returns an initialized status with the rpc.UNAVAILABLE code and the given message. func WithUnavailable(message string) rpc.Status { return rpc.Status{Code: int32(rpc.UNAVAILABLE), Message: message} } // WithDataLoss returns an initialized status with the rpc.DATA_LOSS code and the given message. func WithDataLoss(message string) rpc.Status { return rpc.Status{Code: int32(rpc.DATA_LOSS), Message: message} } // WithUnauthenticated returns an initialized status with the rpc.UNAUTHENTICATED code and the given message. func WithUnauthenticated(message string) rpc.Status { return rpc.Status{Code: int32(rpc.UNAUTHENTICATED), Message: message} } // IsOK returns true is the given status has the code rpc.OK func IsOK(status rpc.Status) bool { return status.Code == int32(rpc.OK) } // String produces a string representation of rpc.Status. func String(status rpc.Status) string { result, ok := rpc.Code_name[status.Code] if !ok { result = "Code" + string(status.Code) } if status.Message != "" { result = result + " (" + status.Message + ")" } return result }
mixer/pkg/status/status.go
0.817647
0.423696
status.go
starcoder
package onshape import ( "encoding/json" ) // BTPTopLevelConstantDeclaration283AllOf struct for BTPTopLevelConstantDeclaration283AllOf type BTPTopLevelConstantDeclaration283AllOf struct { BtType *string `json:"btType,omitempty"` Declaration *BTPStatementConstantDeclaration273 `json:"declaration,omitempty"` } // NewBTPTopLevelConstantDeclaration283AllOf instantiates a new BTPTopLevelConstantDeclaration283AllOf 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 NewBTPTopLevelConstantDeclaration283AllOf() *BTPTopLevelConstantDeclaration283AllOf { this := BTPTopLevelConstantDeclaration283AllOf{} return &this } // NewBTPTopLevelConstantDeclaration283AllOfWithDefaults instantiates a new BTPTopLevelConstantDeclaration283AllOf 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 NewBTPTopLevelConstantDeclaration283AllOfWithDefaults() *BTPTopLevelConstantDeclaration283AllOf { this := BTPTopLevelConstantDeclaration283AllOf{} return &this } // GetBtType returns the BtType field value if set, zero value otherwise. func (o *BTPTopLevelConstantDeclaration283AllOf) GetBtType() string { if o == nil || o.BtType == nil { var ret string return ret } return *o.BtType } // GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPTopLevelConstantDeclaration283AllOf) GetBtTypeOk() (*string, bool) { if o == nil || o.BtType == nil { return nil, false } return o.BtType, true } // HasBtType returns a boolean if a field has been set. func (o *BTPTopLevelConstantDeclaration283AllOf) HasBtType() bool { if o != nil && o.BtType != nil { return true } return false } // SetBtType gets a reference to the given string and assigns it to the BtType field. func (o *BTPTopLevelConstantDeclaration283AllOf) SetBtType(v string) { o.BtType = &v } // GetDeclaration returns the Declaration field value if set, zero value otherwise. func (o *BTPTopLevelConstantDeclaration283AllOf) GetDeclaration() BTPStatementConstantDeclaration273 { if o == nil || o.Declaration == nil { var ret BTPStatementConstantDeclaration273 return ret } return *o.Declaration } // GetDeclarationOk returns a tuple with the Declaration field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *BTPTopLevelConstantDeclaration283AllOf) GetDeclarationOk() (*BTPStatementConstantDeclaration273, bool) { if o == nil || o.Declaration == nil { return nil, false } return o.Declaration, true } // HasDeclaration returns a boolean if a field has been set. func (o *BTPTopLevelConstantDeclaration283AllOf) HasDeclaration() bool { if o != nil && o.Declaration != nil { return true } return false } // SetDeclaration gets a reference to the given BTPStatementConstantDeclaration273 and assigns it to the Declaration field. func (o *BTPTopLevelConstantDeclaration283AllOf) SetDeclaration(v BTPStatementConstantDeclaration273) { o.Declaration = &v } func (o BTPTopLevelConstantDeclaration283AllOf) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.BtType != nil { toSerialize["btType"] = o.BtType } if o.Declaration != nil { toSerialize["declaration"] = o.Declaration } return json.Marshal(toSerialize) } type NullableBTPTopLevelConstantDeclaration283AllOf struct { value *BTPTopLevelConstantDeclaration283AllOf isSet bool } func (v NullableBTPTopLevelConstantDeclaration283AllOf) Get() *BTPTopLevelConstantDeclaration283AllOf { return v.value } func (v *NullableBTPTopLevelConstantDeclaration283AllOf) Set(val *BTPTopLevelConstantDeclaration283AllOf) { v.value = val v.isSet = true } func (v NullableBTPTopLevelConstantDeclaration283AllOf) IsSet() bool { return v.isSet } func (v *NullableBTPTopLevelConstantDeclaration283AllOf) Unset() { v.value = nil v.isSet = false } func NewNullableBTPTopLevelConstantDeclaration283AllOf(val *BTPTopLevelConstantDeclaration283AllOf) *NullableBTPTopLevelConstantDeclaration283AllOf { return &NullableBTPTopLevelConstantDeclaration283AllOf{value: val, isSet: true} } func (v NullableBTPTopLevelConstantDeclaration283AllOf) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBTPTopLevelConstantDeclaration283AllOf) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
onshape/model_btp_top_level_constant_declaration_283_all_of.go
0.690559
0.464476
model_btp_top_level_constant_declaration_283_all_of.go
starcoder
package sorting import ( "fmt" "math/rand" "sort" "time" ) // Helper function to make a copy of a map of vectors func copyMap(m map[int][]int) map[int][]int { returnedMap := make(map[int][]int) for k, v := range m { // important, as copy to a vector with lenght 0 won't work tmp := make([]int, len(v)) copy(tmp, v) returnedMap[k] = tmp } return returnedMap } // Generates a randome slice for testing purposes. func GenerateRandomSlice(size int, maxVal int) []int { slice := make([]int, size) rand.Seed(time.Now().UnixNano()) for i := 0; i < size; i++ { slice[i] = rand.Intn(maxVal) } return slice } // Return a sorted copy of a given slice using go's built-in sort function. func MakeWant(give []int) []int { want := make([]int, len(give)) copy(want, give) sort.Ints(want) return want } // Time sorting operation // Takes a sorting function and the vector to sort as an argument func TimeOperation(f func([]int), T []int, comment string) { startTime := time.Now() f(T) // call the sorting function elapsed := time.Since(startTime) const msg = "TIME OPERATION %v size %d completed in %s\n" fmt.Printf(msg, comment, len(T), elapsed) } func SelSort(list []int) { minIndex := 0 n := len(list) // we do not sort lists with 0 or 1 element if n <= 1 { return } for i := 0; i < n-1; i++ { tmpMin := list[i] // selected value minIndex = i for j := i + 1; j < n; j++ { if list[j] < tmpMin { minIndex = j tmpMin = list[j] } } if minIndex > i { tmp := list[i] list[i] = list[minIndex] list[minIndex] = tmp } } } func MergeSort(list []int) { n := len(list) if n <= 1 { return } var left []int var right []int for i := 0; i < n; i++ { if i < n/2 { left = append(left, list[i]) } else { right = append(right, list[i]) } } MergeSort(left) MergeSort(right) list = list[:0] merge(list, left, right) } func merge(V []int, V1 []int, V2 []int) { sizeV1 := len(V1) sizeV2 := len(V2) indexV1 := 0 indexV2 := 0 for indexV1 < sizeV1 && indexV2 < sizeV2 { data1 := V1[indexV1] data2 := V2[indexV2] if data1 < data2 { V = append(V, V1[indexV1]) indexV1++ } else { V = append(V, V2[indexV2]) indexV2++ } } for indexV1 < sizeV1 { V = append(V, V1[indexV1]) indexV1++ } for indexV2 < sizeV2 { V = append(V, V2[indexV2]) indexV2++ } } // Partition a vector arround a pivot (the first element). // and returns the new index of the pivot afeter the operation. func partition(T []int, begin int, end int) int { pivot := T[begin] iForward := begin + 1 iBackward := end var pivotIndex int for { for iForward < iBackward && T[iBackward] >= pivot { iBackward-- } for iForward < iBackward && T[iForward] < pivot { iForward++ } if iForward == iBackward { break } tmp := T[iForward] T[iForward] = T[iBackward] T[iBackward] = tmp } // If iForward moved without finding an element smaller than pivot if T[iForward] >= pivot { pivotIndex = begin } else { T[begin] = T[iForward] T[iForward] = pivot pivotIndex = iForward } return pivotIndex } // Sort a vector between a set of boundaries recursively func qSort(T []int, begin int, end int) { if begin >= end { return } pivotIndex := partition(T, begin, end) qSort(T, begin, pivotIndex-1) qSort(T, pivotIndex+1, end) } // Sort the given vector inplace calling the qSort algorithm func QuickSort(T []int) { qSort(T, 0, len(T)-1) } /** * FUNCTIONS USED FUNCTIONS **/ // benchmark (compute sorting time) all the sorting algos incrementing the input func IncrementalBenchmark() { const maxRand = 1000000 // generate random vectors V1 := GenerateRandomSlice(1000, maxRand) V2 := GenerateRandomSlice(10000, maxRand) V3 := GenerateRandomSlice(100000, maxRand) V4 := GenerateRandomSlice(1000000, maxRand) // copy for selection sort V11 := make([]int, 1000) V21 := make([]int, 10000) V31 := make([]int, 100000) V41 := make([]int, 1000000) // copy for merge sort V12 := make([]int, 1000) V22 := make([]int, 10000) V32 := make([]int, 100000) V42 := make([]int, 1000000) // copy for quick sort V13 := make([]int, 1000) V23 := make([]int, 10000) V33 := make([]int, 100000) V43 := make([]int, 1000000) // start benchmarking - built in sort TimeOperation(sort.Ints, V1, "built-in sort.Ints") TimeOperation(sort.Ints, V2, "built-in sort.Ints") TimeOperation(sort.Ints, V3, "built-in sort.Ints") TimeOperation(sort.Ints, V4, "built-in sort.Ints") // start benchmarking - merge sort fmt.Println() TimeOperation(MergeSort, V12, "MergeSort") TimeOperation(MergeSort, V22, "MergeSort") TimeOperation(MergeSort, V32, "MergeSort") TimeOperation(MergeSort, V42, "MergeSort") // start benchmarking - quick sort fmt.Println() TimeOperation(QuickSort, V13, "QuickSort") TimeOperation(QuickSort, V23, "QuickSort") TimeOperation(QuickSort, V33, "QuickSort") TimeOperation(QuickSort, V43, "QuickSort") // start benchmarking - selection sort fmt.Println() TimeOperation(SelSort, V11, "Selsort") TimeOperation(SelSort, V21, "Selsort") TimeOperation(SelSort, V31, "Selsort") TimeOperation(SelSort, V41, "Selsort") } // Compute sorting time using vector of size input // nSample time func ConstBenchmark(input int, nSample int) { t := make(map[int][]int) for i := 0; i < nSample; i++ { t[i] = GenerateRandomSlice(input, input*10) } tBuiltIn := copyMap(t) tMergeSort := copyMap(t) tQuickSort := copyMap(t) tSelSort := copyMap(t) // benchmark go builting sort.Ints function for _, v := range tBuiltIn { TimeOperation(sort.Ints, v, "built-in sort.Ints") } fmt.Println() // benchmark merge sort function for _, v := range tMergeSort { TimeOperation(MergeSort, v, "MergeSort") } fmt.Println() // benchmark quick sort function for _, v := range tQuickSort { TimeOperation(QuickSort, v, "QuickSort") } fmt.Println() // benchmark selection sort function for _, v := range tSelSort { TimeOperation(SelSort, v, "SelSort") } }
sorting/sorting.go
0.672869
0.412234
sorting.go
starcoder
package helper import ( "fmt" "image" "image/color" "image/draw" _ "image/jpeg" _ "image/png" "os" ) // SubsamplingPixels 2.2.1 Implement 2:1 subsampling in the horizontal and vertical directions, so that only // 1/4-th of the input image pixels are taken into account func SubsamplingPixels(src []uint8, width, height int) [][3]int { var offset, y, x, idx int var samplingSize int var pixels [][3]int samplingSize = (width/2 + width%2) * (height/2 + height%2) pixels = make([][3]int, samplingSize) idx = 0 for y = 0; y < height; y += 2 { for x = 0; x < width; x += 2 { offset = (y*width + x) * 4 pixels[idx][0], pixels[idx][1], pixels[idx][2] = int(src[offset]), int(src[offset+1]), int(src[offset+2]) idx++ } } return pixels } // SubsamplingPixelsFromImage 2.2.1 Implement 2:1 subsampling in the horizontal and vertical directions, so that only // 1/4-th of the input image pixels are taken into account func SubsamplingPixelsFromImage(src image.Image) [][3]int { var offset, y, x, idx int var samplingSize int var pixels [][3]int bounds := src.Bounds() width, height := bounds.Max.X, bounds.Max.Y img := image.NewRGBA(bounds) draw.Draw(img, bounds, src, image.Point{}, draw.Src) samplingSize = (width/2 + width%2) * (height/2 + height%2) pixels = make([][3]int, samplingSize) idx = 0 for y = 0; y < height; y += 2 { for x = 0; x < width; x += 2 { offset = (y*width + x) * 4 pixels[idx][0], pixels[idx][1], pixels[idx][2] = int(img.Pix[offset]), int(img.Pix[offset+1]), int(img.Pix[offset+2]) idx++ } } return pixels } func Hex(c [3]int) string { return fmt.Sprintf("#%02x%02x%02x", uint8(c[0]), uint8(c[1]), uint8(c[2])) } func Color(c [3]int) color.Color { return color.RGBA{ R: uint8(c[0]), G: uint8(c[1]), B: uint8(c[2]), A: 255, } } func ReadImage(uri string) (image.Image, error) { res, err := os.Open(uri) if err != nil { return nil, err } img, _, err := image.Decode(res) if err != nil { return nil, err } if err = res.Close(); err != nil { return nil, err } return img, nil }
helper/helper.go
0.672547
0.423935
helper.go
starcoder
package graph import ( i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization" ) // RecurrenceRange type RecurrenceRange struct { // Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. additionalData map[string]interface{}; // The date to stop applying the recurrence pattern. Depending on the recurrence pattern of the event, the last occurrence of the meeting may not be this date. Required if type is endDate. endDate *string; // The number of times to repeat the event. Required and must be positive if type is numbered. numberOfOccurrences *int32; // Time zone for the startDate and endDate properties. Optional. If not specified, the time zone of the event is used. recurrenceTimeZone *string; // The date to start applying the recurrence pattern. The first occurrence of the meeting may be this date or later, depending on the recurrence pattern of the event. Must be the same value as the start property of the recurring event. Required. startDate *string; // The recurrence range. The possible values are: endDate, noEnd, numbered. Required. type_escaped *RecurrenceRangeType; } // NewRecurrenceRange instantiates a new recurrenceRange and sets the default values. func NewRecurrenceRange()(*RecurrenceRange) { m := &RecurrenceRange{ } m.SetAdditionalData(make(map[string]interface{})); return m } // GetAdditionalData gets the AdditionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *RecurrenceRange) GetAdditionalData()(map[string]interface{}) { if m == nil { return nil } else { return m.additionalData } } // GetEndDate gets the endDate property value. The date to stop applying the recurrence pattern. Depending on the recurrence pattern of the event, the last occurrence of the meeting may not be this date. Required if type is endDate. func (m *RecurrenceRange) GetEndDate()(*string) { if m == nil { return nil } else { return m.endDate } } // GetNumberOfOccurrences gets the numberOfOccurrences property value. The number of times to repeat the event. Required and must be positive if type is numbered. func (m *RecurrenceRange) GetNumberOfOccurrences()(*int32) { if m == nil { return nil } else { return m.numberOfOccurrences } } // GetRecurrenceTimeZone gets the recurrenceTimeZone property value. Time zone for the startDate and endDate properties. Optional. If not specified, the time zone of the event is used. func (m *RecurrenceRange) GetRecurrenceTimeZone()(*string) { if m == nil { return nil } else { return m.recurrenceTimeZone } } // GetStartDate gets the startDate property value. The date to start applying the recurrence pattern. The first occurrence of the meeting may be this date or later, depending on the recurrence pattern of the event. Must be the same value as the start property of the recurring event. Required. func (m *RecurrenceRange) GetStartDate()(*string) { if m == nil { return nil } else { return m.startDate } } // GetType_escaped gets the type_escaped property value. The recurrence range. The possible values are: endDate, noEnd, numbered. Required. func (m *RecurrenceRange) GetType_escaped()(*RecurrenceRangeType) { if m == nil { return nil } else { return m.type_escaped } } // GetFieldDeserializers the deserialization information for the current model func (m *RecurrenceRange) GetFieldDeserializers()(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) { res := make(map[string]func(interface{}, i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode)(error)) res["endDate"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetEndDate(val) } return nil } res["numberOfOccurrences"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetInt32Value() if err != nil { return err } if val != nil { m.SetNumberOfOccurrences(val) } return nil } res["recurrenceTimeZone"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetRecurrenceTimeZone(val) } return nil } res["startDate"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetStartDate(val) } return nil } res["type_escaped"] = func (o interface{}, n i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.ParseNode) error { val, err := n.GetEnumValue(ParseRecurrenceRangeType) if err != nil { return err } if val != nil { cast := val.(RecurrenceRangeType) m.SetType_escaped(&cast) } return nil } return res } func (m *RecurrenceRange) IsNil()(bool) { return m == nil } // Serialize serializes information the current object func (m *RecurrenceRange) Serialize(writer i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.SerializationWriter)(error) { { err := writer.WriteStringValue("endDate", m.GetEndDate()) if err != nil { return err } } { err := writer.WriteInt32Value("numberOfOccurrences", m.GetNumberOfOccurrences()) if err != nil { return err } } { err := writer.WriteStringValue("recurrenceTimeZone", m.GetRecurrenceTimeZone()) if err != nil { return err } } { err := writer.WriteStringValue("startDate", m.GetStartDate()) if err != nil { return err } } if m.GetType_escaped() != nil { cast := m.GetType_escaped().String() err := writer.WriteStringValue("type_escaped", &cast) if err != nil { return err } } { err := writer.WriteAdditionalData(m.GetAdditionalData()) if err != nil { return err } } return nil } // SetAdditionalData sets the AdditionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. func (m *RecurrenceRange) SetAdditionalData(value map[string]interface{})() { m.additionalData = value } // SetEndDate sets the endDate property value. The date to stop applying the recurrence pattern. Depending on the recurrence pattern of the event, the last occurrence of the meeting may not be this date. Required if type is endDate. func (m *RecurrenceRange) SetEndDate(value *string)() { m.endDate = value } // SetNumberOfOccurrences sets the numberOfOccurrences property value. The number of times to repeat the event. Required and must be positive if type is numbered. func (m *RecurrenceRange) SetNumberOfOccurrences(value *int32)() { m.numberOfOccurrences = value } // SetRecurrenceTimeZone sets the recurrenceTimeZone property value. Time zone for the startDate and endDate properties. Optional. If not specified, the time zone of the event is used. func (m *RecurrenceRange) SetRecurrenceTimeZone(value *string)() { m.recurrenceTimeZone = value } // SetStartDate sets the startDate property value. The date to start applying the recurrence pattern. The first occurrence of the meeting may be this date or later, depending on the recurrence pattern of the event. Must be the same value as the start property of the recurring event. Required. func (m *RecurrenceRange) SetStartDate(value *string)() { m.startDate = value } // SetType_escaped sets the type_escaped property value. The recurrence range. The possible values are: endDate, noEnd, numbered. Required. func (m *RecurrenceRange) SetType_escaped(value *RecurrenceRangeType)() { m.type_escaped = value }
models/microsoft/graph/recurrence_range.go
0.741112
0.457682
recurrence_range.go
starcoder
package propcheck import "fmt" type Pair[A, B any] struct { A A B B } func (w Pair[A, B]) String() string { return fmt.Sprintf("Pair{A: %v \n, B: %v\n}\n", w.A, w.B) } func Product[A, B any](fa func(SimpleRNG) (A, SimpleRNG), fb func(SimpleRNG) (B, SimpleRNG)) func(SimpleRNG) (Pair[A, B], SimpleRNG) { f := func(a A, b B) Pair[A, B] { return Pair[A, B]{a, b} } g := Map2(fa, fb, f) return g } // MapN are the functions that make this an Applicative Functor. These functions allow you to compose generators without the context-sensitivity that you get with FlatMap. // A good example of this is validation where you don't want the computation to stop because A Flatmap in the chain fails. func pMap2[A, B, C any](ra func(SimpleRNG) (A, SimpleRNG), rb func(SimpleRNG) (B, SimpleRNG), f func(a A, b B) C) func(rng SimpleRNG) (C, SimpleRNG) { return func(rng SimpleRNG) (C, SimpleRNG) { a, r1 := ra(rng) b, r2 := rb(r1) c := f(a, b) return c, r2 } } func Map2[A, B, C any](ra func(SimpleRNG) (A, SimpleRNG), rb func(SimpleRNG) (B, SimpleRNG), f func(a A, b B) C) func(rng SimpleRNG) (C, SimpleRNG) { return pMap2(ra, rb, f) } func Map3[A, B, C, D any](ra func(SimpleRNG) (A, SimpleRNG), rb func(SimpleRNG) (B, SimpleRNG), rc func(SimpleRNG) (C, SimpleRNG), f func(a A, b B, c C) D) func(SimpleRNG) (D, SimpleRNG) { return func(rng SimpleRNG) (D, SimpleRNG) { fab := Product[A, B](ra, rb) fg := func(abd Pair[A, B], c C) D { return f(abd.A, abd.B, c) } g := Map2(fab, rc, fg) return g(rng) } } func Map4[A, B, C, D, E any](ra func(SimpleRNG) (A, SimpleRNG), rb func(SimpleRNG) (B, SimpleRNG), rc func(SimpleRNG) (C, SimpleRNG), rd func(SimpleRNG) (D, SimpleRNG), f func(a A, b B, c C, d D) E) func(SimpleRNG) (E, SimpleRNG) { return func(rng SimpleRNG) (E, SimpleRNG) { fab := Product(ra, rb) fcd := Product(rc, rd) fg := func(ab Pair[A, B], cd Pair[C, D]) E { var abd = ab var cdd = cd return f(abd.A, abd.B, cdd.A, cdd.B) } g := Map2(fab, fcd, fg) return g(rng) } } func Map8[A, B, C, D, E, F, G, H, I any](ra func(SimpleRNG) (A, SimpleRNG), rb func(SimpleRNG) (B, SimpleRNG), rc func(SimpleRNG) (C, SimpleRNG), rd func(SimpleRNG) (D, SimpleRNG), re func(SimpleRNG) (E, SimpleRNG), rf func(SimpleRNG) (F, SimpleRNG), rg func(SimpleRNG) (G, SimpleRNG), rh func(SimpleRNG) (H, SimpleRNG), f func(a A, b B, c C, d D, e E, f F, g G, h H) I) func(SimpleRNG) (I, SimpleRNG) { return func(rng SimpleRNG) (I, SimpleRNG) { fab := Product(ra, rb) fcd := Product(rc, rd) fef := Product(re, rf) fgh := Product(rg, rh) fg := func(ab Pair[A, B], cd Pair[C, D], ef Pair[E, F], gh Pair[G, H]) I { return f(ab.A, ab.B, cd.A, cd.B, ef.A, ef.B, gh.A, gh.B) } g := Map4(fab, fcd, fef, fgh, fg) return g(rng) } } func Map16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q any](ra func(SimpleRNG) (A, SimpleRNG), rb func(SimpleRNG) (B, SimpleRNG), rc func(SimpleRNG) (C, SimpleRNG), rd func(SimpleRNG) (D, SimpleRNG), re func(SimpleRNG) (E, SimpleRNG), rf func(SimpleRNG) (F, SimpleRNG), rg func(SimpleRNG) (G, SimpleRNG), rh func(SimpleRNG) (H, SimpleRNG), ri func(SimpleRNG) (I, SimpleRNG), rj func(SimpleRNG) (J, SimpleRNG), rk func(SimpleRNG) (K, SimpleRNG), rl func(SimpleRNG) (L, SimpleRNG), rm func(SimpleRNG) (M, SimpleRNG), rn func(SimpleRNG) (N, SimpleRNG), ro func(SimpleRNG) (O, SimpleRNG), rp func(SimpleRNG) (P, SimpleRNG), f func(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J, k K, l L, m M, n N, o O, p P) Q) func(SimpleRNG) (Q, SimpleRNG) { return func(rng SimpleRNG) (Q, SimpleRNG) { fab := Product(ra, rb) fcd := Product(rc, rd) fef := Product(re, rf) fgh := Product(rg, rh) fij := Product(ri, rj) fkl := Product(rk, rl) fmn := Product(rm, rn) fop := Product(ro, rp) fg := func(ab Pair[A, B], cd Pair[C, D], ef Pair[E, F], gh Pair[G, H], ij Pair[I, J], kl Pair[K, L], mn Pair[M, N], op Pair[O, P]) Q { return f(ab.A, ab.B, cd.A, cd.B, ef.A, ef.B, gh.A, gh.B, ij.A, ij.B, kl.A, kl.B, mn.A, mn.B, op.A, op.B) } g := Map8(fab, fcd, fef, fgh, fij, fkl, fmn, fop, fg) return g(rng) } } func Map32[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, AA, BB, CC, DD, EE, FF, GG, HH, II any](ra func(SimpleRNG) (A, SimpleRNG), rb func(SimpleRNG) (B, SimpleRNG), rc func(SimpleRNG) (C, SimpleRNG), rd func(SimpleRNG) (D, SimpleRNG), re func(SimpleRNG) (E, SimpleRNG), rf func(SimpleRNG) (F, SimpleRNG), rg func(SimpleRNG) (G, SimpleRNG), rh func(SimpleRNG) (H, SimpleRNG), ri func(SimpleRNG) (I, SimpleRNG), rj func(SimpleRNG) (J, SimpleRNG), rk func(SimpleRNG) (K, SimpleRNG), rl func(SimpleRNG) (L, SimpleRNG), rm func(SimpleRNG) (M, SimpleRNG), rn func(SimpleRNG) (N, SimpleRNG), ro func(SimpleRNG) (O, SimpleRNG), rp func(SimpleRNG) (P, SimpleRNG), rq func(SimpleRNG) (Q, SimpleRNG), rr func(SimpleRNG) (R, SimpleRNG), rs func(SimpleRNG) (S, SimpleRNG), rt func(SimpleRNG) (T, SimpleRNG), ru func(SimpleRNG) (U, SimpleRNG), rv func(SimpleRNG) (V, SimpleRNG), rw func(SimpleRNG) (W, SimpleRNG), rx func(SimpleRNG) (X, SimpleRNG), raa func(SimpleRNG) (AA, SimpleRNG), rbb func(SimpleRNG) (BB, SimpleRNG), rcc func(SimpleRNG) (CC, SimpleRNG), rdd func(SimpleRNG) (DD, SimpleRNG), ree func(SimpleRNG) (EE, SimpleRNG), rff func(SimpleRNG) (FF, SimpleRNG), rgg func(SimpleRNG) (GG, SimpleRNG), rhh func(SimpleRNG) (HH, SimpleRNG), f func(a A, b B, c C, d D, e E, f F, g G, h H, i I, j J, k K, l L, m M, n N, o O, p P, q Q, r R, s S, t T, u U, v V, w W, x X, aa AA, bb BB, cc CC, dd DD, ee EE, ff FF, gg GG, hh HH) II) func(SimpleRNG) (II, SimpleRNG) { return func(rng SimpleRNG) (II, SimpleRNG) { fab := Product(ra, rb) fcd := Product(rc, rd) fef := Product(re, rf) fgh := Product(rg, rh) fij := Product(ri, rj) fkl := Product(rk, rl) fmn := Product(rm, rn) fop := Product(ro, rp) fqr := Product(rq, rr) fst := Product(rs, rt) fuv := Product(ru, rv) fxy := Product(rw, rx) faabb := Product(raa, rbb) fccdd := Product(rcc, rdd) feeff := Product(ree, rff) fgghh := Product(rgg, rhh) fg := func(ab Pair[A, B], cd Pair[C, D], ef Pair[E, F], gh Pair[G, H], ij Pair[I, J], kl Pair[K, L], mn Pair[M, N], op Pair[O, P], qr Pair[Q, R], st Pair[S, T], uv Pair[U, V], wx Pair[W, X], aabb Pair[AA, BB], ccdd Pair[CC, DD], eeff Pair[EE, FF], gghh Pair[GG, HH]) II { return f(ab.A, ab.B, cd.A, cd.B, ef.A, ef.B, gh.A, gh.B, ij.A, ij.B, kl.A, kl.B, mn.A, mn.B, op.A, op.B, qr.A, qr.B, st.A, st.B, uv.A, uv.B, wx.A, wx.B, aabb.A, aabb.B, ccdd.A, ccdd.B, eeff.A, eeff.B, gghh.A, gghh.B) } g := Map16(fab, fcd, fef, fgh, fij, fkl, fmn, fop, fqr, fst, fuv, fxy, faabb, fccdd, feeff, fgghh, fg) return g(rng) } }
propcheck/gen_applicative.go
0.739234
0.572902
gen_applicative.go
starcoder
package aggregation import ( "github.com/lindb/lindb/aggregation/fields" "github.com/lindb/lindb/aggregation/function" "github.com/lindb/lindb/pkg/collections" "github.com/lindb/lindb/pkg/timeutil" "github.com/lindb/lindb/series" "github.com/lindb/lindb/series/field" "github.com/lindb/lindb/sql/stmt" ) //go:generate mockgen -source=./expression.go -destination=./expression_mock.go -package=aggregation // Expression represents expression eval like math calc, function call etc. type Expression interface { // Eval evaluates the select item's expression Eval(timeSeries series.GroupedIterator) // ResultSet returns the eval result ResultSet() map[string]collections.FloatArray // Reset resets the expression context for reusing Reset() } // expression implement Expression interface, operator as below: // 1. prepare field store based on time series iterator // 2. eval the expression // 3. build result set type expression struct { pointCount int interval int64 timeRange timeutil.TimeRange selectItems []stmt.Expr fieldStore map[field.Name]fields.Field resultSet map[string]collections.FloatArray } // NewExpression creates an expression func NewExpression(timeRange timeutil.TimeRange, interval int64, selectItems []stmt.Expr) Expression { return &expression{ pointCount: timeutil.CalPointCount(timeRange.Start, timeRange.End, interval) + 1, interval: interval, timeRange: timeRange, selectItems: selectItems, fieldStore: make(map[field.Name]fields.Field), resultSet: make(map[string]collections.FloatArray), } } // Eval evaluates the select item's expression func (e *expression) Eval(timeSeries series.GroupedIterator) { if len(e.selectItems) == 0 { return } // prepare expression context e.prepare(timeSeries) if len(e.fieldStore) == 0 { return } for _, selectItem := range e.selectItems { values := e.eval(nil, selectItem) if len(values) != 0 { item, ok := selectItem.(*stmt.SelectItem) if ok && len(item.Alias) > 0 { e.resultSet[item.Alias] = values[0] } else { e.resultSet[item.Rewrite()] = values[0] } } } } // ResultSet returns the eval result func (e *expression) ResultSet() map[string]collections.FloatArray { return e.resultSet } // prepare prepares the field store func (e *expression) prepare(timeSeries series.GroupedIterator) { if timeSeries == nil { return } for timeSeries.HasNext() { fieldSeries := timeSeries.Next() fieldName := fieldSeries.FieldName() fieldType := fieldSeries.FieldType() f := fields.NewDynamicField(fieldType, e.timeRange.Start, e.interval, e.pointCount) e.fieldStore[fieldName] = f f.SetValue(fieldSeries) } } // eval evaluates the expression func (e *expression) eval(parentFunc *stmt.CallExpr, expr stmt.Expr) []collections.FloatArray { switch ex := expr.(type) { case *stmt.SelectItem: return e.eval(nil, ex.Expr) case *stmt.CallExpr: return e.funcCall(ex) case *stmt.ParenExpr: return e.eval(nil, ex.Expr) case *stmt.BinaryExpr: return e.binaryEval(ex) case *stmt.NumberLiteral: values := collections.NewFloatArray(e.pointCount) for i := 0; i < e.pointCount; i++ { values.SetValue(i, ex.Val) } values.SetSingle(true) return []collections.FloatArray{values} case *stmt.FieldExpr: fieldName := ex.Name fieldValues, ok := e.fieldStore[field.Name(fieldName)] if !ok { return nil } // tests if has func with field if parentFunc == nil { return fieldValues.GetDefaultValues() } // get field data by function type return fieldValues.GetValues(parentFunc.FuncType) default: return nil } } // funcCall calls the function func (e *expression) funcCall(expr *stmt.CallExpr) []collections.FloatArray { var params []collections.FloatArray for _, param := range expr.Params { paramValues := e.eval(expr, param) if len(paramValues) == 0 { return nil } params = append(params, paramValues...) } result := function.FuncCall(expr.FuncType, params...) if result == nil { return nil } return []collections.FloatArray{result} } // binaryEval evaluates binary operator func (e *expression) binaryEval(expr *stmt.BinaryExpr) []collections.FloatArray { binaryOP := expr.Operator if binaryOP == stmt.ADD || binaryOP == stmt.SUB || binaryOP == stmt.DIV || binaryOP == stmt.MUL { left := e.eval(nil, expr.Left) if len(left) != 1 { return nil } right := e.eval(nil, expr.Right) if len(right) != 1 { return nil } result := binaryEval(binaryOP, left[0], right[0]) return []collections.FloatArray{result} } return nil } // Reset resets the expression context for reusing func (e *expression) Reset() { for _, f := range e.fieldStore { f.Reset() } e.resultSet = make(map[string]collections.FloatArray) }
aggregation/expression.go
0.653459
0.436622
expression.go
starcoder
package gohome import ( "github.com/PucklaMotzer09/mathgl/mgl32" ) // A Model3D that renders instanced type InstancedModel3D struct { // The name of this object Name string meshes []InstancedMesh3D // The bounding box of this Model AABB AxisAlignedBoundingBox } // Adds a mesh to the drawn meshes func (this *InstancedModel3D) AddMesh3D(m InstancedMesh3D) { this.meshes = append(this.meshes, m) this.checkAABB(m) } // Calls the Render method on all meshes func (this *InstancedModel3D) Render() { for i := 0; i < len(this.meshes); i++ { this.meshes[i].Render() } } // Cleans everything up func (this *InstancedModel3D) Terminate() { for i := 0; i < len(this.meshes); i++ { this.meshes[i].Terminate() } this.meshes = append(this.meshes[:0], this.meshes[len(this.meshes):]...) } // Returns the mesh with the given name func (this *InstancedModel3D) GetMesh(name string) InstancedMesh3D { for i := 0; i < len(this.meshes); i++ { if this.meshes[i].GetName() == name { return this.meshes[i] } } return nil } // Returns the mesh with the given index func (this *InstancedModel3D) GetMeshIndex(index int) InstancedMesh3D { if index > len(this.meshes)-1 { return nil } else { return this.meshes[index] } } func (this *InstancedModel3D) checkAABB(m InstancedMesh3D) { for i := 0; i < 3; i++ { if m.AABB().Max[i] > this.AABB.Max[i] { this.AABB.Max[i] = m.AABB().Max[i] } if m.AABB().Min[i] < this.AABB.Min[i] { this.AABB.Min[i] = m.AABB().Min[i] } } } // Returns wether some Meshes have UV values func (this *InstancedModel3D) HasUV() bool { for i := 0; i < len(this.meshes); i++ { if !this.meshes[i].HasUV() { return false } } return true } // Adds an instanced value func (this *InstancedModel3D) AddValue(valueType int) { for _, m := range this.meshes { m.AddValue(valueType) } } // Adds an instanced value to the front of the array func (this *InstancedModel3D) AddValueFront(valueType int) { for _, m := range this.meshes { m.AddValueFront(valueType) } } // Sets the name of an instanced value func (this *InstancedModel3D) SetName(index, valueType int, value string) { for _, m := range this.meshes { m.SetName(index, valueType, value) } } // Sets the float value of index to value, value must be of size num instances func (this *InstancedModel3D) SetF(index int, value []float32) { for _, m := range this.meshes { m.SetF(index, value) } } // Sets the Vec2 value of index to value, value must be of size num instances func (this *InstancedModel3D) SetV2(index int, value []mgl32.Vec2) { for _, m := range this.meshes { m.SetV2(index, value) } } // Sets the Vec3 value of index to value, value must be of size num instances func (this *InstancedModel3D) SetV3(index int, value []mgl32.Vec3) { for _, m := range this.meshes { m.SetV3(index, value) } } // Sets the Vec4 value of index to value, value must be of size num instances func (this *InstancedModel3D) SetV4(index int, value []mgl32.Vec4) { for _, m := range this.meshes { m.SetV4(index, value) } } // Sets the Mat2 value of index to value, value must be of size num instances func (this *InstancedModel3D) SetM2(index int, value []mgl32.Mat2) { for _, m := range this.meshes { m.SetM2(index, value) } } // Sets the Mat3 value of index to value, value must be of size num instances func (this *InstancedModel3D) SetM3(index int, value []mgl32.Mat3) { for _, m := range this.meshes { m.SetM3(index, value) } } // Sets the Mat4 value of index to value, value must be of size num instances func (this *InstancedModel3D) SetM4(index int, value []mgl32.Mat4) { for _, m := range this.meshes { m.SetM4(index, value) } } // Loads all the data to the GPU func (this *InstancedModel3D) Load() { for _, m := range this.meshes { m.Load() } } // Sets the number of buffered instances func (this *InstancedModel3D) SetNumInstances(n int) { for _, m := range this.meshes { m.SetNumInstances(n) } } // Returns the number of buffered instances func (this *InstancedModel3D) GetNumInstances() int { if len(this.meshes) == 0 { return 0 } else { return this.meshes[0].GetNumInstances() } } // Sets the number of drawn instances func (this *InstancedModel3D) SetNumUsedInstances(n int) { for _, m := range this.meshes { m.SetNumUsedInstances(n) } } // Returns the number of drawn instances func (this *InstancedModel3D) GetNumUsedInstances() int { if len(this.meshes) == 0 { return 0 } else { return this.meshes[0].GetNumUsedInstances() } } // Returns wether Load has been called func (this *InstancedModel3D) LoadedToGPU() bool { for _, m := range this.meshes { if !m.LoadedToGPU() { return false } } return true } // Creates an instanced model from a Model3D func InstancedModel3DFromModel3D(m *Model3D) (im *InstancedModel3D) { im = &InstancedModel3D{} im.meshes = make([]InstancedMesh3D, len(m.meshes)) for i := 0; i < len(m.meshes); i++ { im.meshes[i] = InstancedMesh3DFromMesh3D(m.meshes[i]) } im.Name = m.Name im.AABB = m.AABB return }
src/gohome/instancedmodel3d.go
0.700895
0.505737
instancedmodel3d.go
starcoder
package q import ( "math" "math/rand" "reflect" "time" agentv1 "github.com/aunum/gold/pkg/v1/agent" "github.com/aunum/gold/pkg/v1/common" "github.com/aunum/gold/pkg/v1/common/num" envv1 "github.com/aunum/gold/pkg/v1/env" "github.com/aunum/log" "gorgonia.org/tensor" ) // Agent that utilizes the Q-Learning algorithm. type Agent struct { *agentv1.Base *Hyperparameters r *rand.Rand env *envv1.Env table Table minAlpha float32 } // Hyperparameters for a Q-learning agent. type Hyperparameters struct { // Epsilon is the rate at which the agent should explore vs exploit. The lower the value // the more exploitation. Epsilon common.Schedule // Gamma is the discount factor (0≤γ≤1). It determines how much importance we want to give to future // rewards. A high value for the discount factor (close to 1) captures the long-term effective award, whereas, // a discount factor of 0 makes our agent consider only immediate reward, hence making it greedy. Gamma float32 // Alpha is the learning rate (0<α≤1). Just like in supervised learning settings, alpha is the extent // to which our Q-values are being updated in every iteration. Alpha float32 // AdaDivisor is used in adaptive learning to tune the hyperparameters. AdaDivisor float32 } // DefaultHyperparameters is the default agent configuration. var DefaultHyperparameters = &Hyperparameters{ Epsilon: common.NewConstantSchedule(0.1), Gamma: 0.6, Alpha: 0.1, AdaDivisor: 5.0, } // AgentConfig is the config for a dqn agent. type AgentConfig struct { // Base for the agent. Base *agentv1.Base // Hyperparameters for the agent. *Hyperparameters // Table for the agent. Table Table } // DefaultAgentConfig is the default config for a dqn agent. var DefaultAgentConfig = &AgentConfig{ Hyperparameters: DefaultHyperparameters, Base: agentv1.NewBase("Q"), } // NewAgent returns a new Q-learning agent. func NewAgent(c *AgentConfig, env *envv1.Env) *Agent { actionSpaceSize := int(env.GetNumActions()) s := rand.NewSource(time.Now().Unix()) if c.Base == nil { c.Base = DefaultAgentConfig.Base } if c.Table == nil || (reflect.ValueOf(c.Table).Kind() == reflect.Ptr && reflect.ValueOf(c.Table).IsNil()) { c.Table = NewMemTable(actionSpaceSize) } a := &Agent{ Hyperparameters: c.Hyperparameters, Base: c.Base, r: rand.New(s), env: env, table: c.Table, minAlpha: c.Hyperparameters.Alpha, } return a } // Adapt will adjust the hyperparameters based on th timestep. func (a *Agent) Adapt(timestep int) { a.Alpha = adapt(timestep, a.minAlpha, a.AdaDivisor) log.Infov("set alpha to", a.Alpha) } func adapt(timestep int, min float32, ada float32) float32 { a := float32((timestep + 1)) / ada b := math.Log10(float64(a)) c := 1.0 - b adapted := math.Min(1.0, c) max := math.Max(float64(min), adapted) return float32(max) } // Action returns the action that should be taken given the state hash. func (a *Agent) Action(state *tensor.Dense) (action int, err error) { stateHash := HashState(state) if num.RandF32(float32(0.0), float32(1.0)) < a.Epsilon.Value() { // explore action, err = a.env.SampleAction() return } // exploit action, _, err = a.table.GetMax(stateHash) return } // Learn using the Q-learning algorithm. // Q(state,action)←(1−α)Q(state,action)+α(reward+γmaxaQ(next state,all actions)) func (a *Agent) Learn(action int, state *tensor.Dense, outcome *envv1.Outcome) error { stateHash := HashState(state) nextStateHash := HashState(outcome.Observation) oldVal, err := a.table.Get(stateHash, action) if err != nil { return err } _, nextMax, err := a.table.GetMax(nextStateHash) if err != nil { return err } // Q learning algorithm. newValue := (1-a.Alpha)*oldVal + a.Alpha*(outcome.Reward+a.Gamma*nextMax) err = a.table.Set(stateHash, action, newValue) if err != nil { return err } return nil } // Visualize the agents internal state. func (a *Agent) Visualize() { a.table.Print() }
pkg/v1/agent/q/agent.go
0.657209
0.428114
agent.go
starcoder
package aes // Rijndael key schedule implementation func rotWord(in [4]byte) (out [4]byte) { // Circular shift left of one byte out[0] = in[1] out[1] = in[2] out[2] = in[3] out[3] = in[0] return } func subWord(in [4]byte) (out [4]byte) { // Substitutes bytes using sbox in aes.go for i, v := range in { out[i] = sbox[v] } return } func xor(inputs ...[4]byte) (out [4]byte) { // Xor all provided arguments for _, input := range inputs { for i, _ := range out { out[i] ^= input[i] } } return } func roundConstants(rounds int) [][4]byte { // Create the output slice var out = make([][4]byte, rounds) // Gets the round constants for all rounds var rc = make([]byte, rounds) for i := 1; i < rounds; i++ { if i == 1 { rc[i] = 1 } else if rc[i-1] < 0x80 { rc[i] = 2*rc[i-1] } else { rc[i] = 2*rc[i-1] ^ 0x1B } // Expand to the full round constant out[i][0] = rc[i] } return out } func KeyExpansion(key []byte, keyLen int, rounds int) [][16]byte { // Key length in 32-bit words n := keyLen // Get slice of round constants rcon := roundConstants(rounds) // Create a slice to store the columns of the round keys var W = make([][4]byte, 4*rounds) // Expand the original key into the first n columns for i := 0; i < n; i++ { copy(W[i][:], key[i*4:i*4+4]) } // Calculate the round keys for i := n; i < 4*rounds; i++ { if i % n == 0 { W[i] = xor(W[i-n], subWord(rotWord(W[i-1])), rcon[i/n]) } else if (n > 6) && (i % n == 4) { W[i] = xor(W[i-n], subWord(W[i-1])) } else { W[i] = xor(W[i-n], W[i-1]) } } // Create the output slice var result = make([][16]byte, rounds) for round := 0; round < rounds; round++ { copy(result[round][0:4][:], W[4*round][:]) copy(result[round][4:8][:], W[4*round+1][:]) copy(result[round][8:12][:], W[4*round+2][:]) copy(result[round][12:16][:], W[4*round+3][:]) } return result } func ExpandKey128(key [16]byte) (roundKeys [11][16]byte) { expansion := KeyExpansion(key[:], 4, 11) copy(roundKeys[:], expansion) return } func ExpandKey192(key [24]byte) (roundKeys [13][16]byte) { expansion := KeyExpansion(key[:], 6, 13) copy(roundKeys[:], expansion) return } func ExpandKey256(key [32]byte) (roundKeys [15][16]byte) { expansion := KeyExpansion(key[:], 8, 15) copy(roundKeys[:], expansion) return }
keys.go
0.797557
0.4917
keys.go
starcoder
package linkedlist import "github.com/roadrunner-server/endure/pkg/vertex" // DllNode consists of the curr Vertex, Prev and Next DllNodes type DllNode struct { Vertex *vertex.Vertex Prev, Next *DllNode } // DoublyLinkedList is the node of DLL which is connected to the tail and the head type DoublyLinkedList struct { Head, Tail *DllNode } // NewDoublyLinkedList returns DLL implementation func NewDoublyLinkedList() *DoublyLinkedList { return &DoublyLinkedList{} } // SetHead O(1) time + space func (dll *DoublyLinkedList) SetHead(node *DllNode) { if dll.Head == nil { dll.Head = node dll.Tail = node return } dll.InsertBefore(dll.Head, node) } // Push used to push vertex to the head func (dll *DoublyLinkedList) Push(vertex *vertex.Vertex) { node := &DllNode{ Vertex: vertex, } if dll.Head == nil { dll.Head = node dll.Tail = node return } node.Next = dll.Head dll.Head.Prev = node node.Prev = nil dll.Head = node } // PushTail used to push vertex to the tail func (dll *DoublyLinkedList) PushTail(vertex *vertex.Vertex) { node := &DllNode{ Vertex: vertex, } node.Next = dll.Tail dll.Tail.Next = node node.Prev = dll.Head dll.Tail = node } // SetTail sets the tail, constant O(1) time and space func (dll *DoublyLinkedList) SetTail(node *DllNode) { if dll.Tail == nil { dll.SetHead(node) } dll.InsertAfter(dll.Tail, node) } // InsertBefore inserts node before the provided node func (dll *DoublyLinkedList) InsertBefore(node, nodeToInsert *DllNode) { if nodeToInsert == dll.Head && nodeToInsert == dll.Tail { //nolint:gocritic return } dll.Remove(nodeToInsert) nodeToInsert.Prev = node.Prev nodeToInsert.Next = node if node.Prev.Next == nil { dll.Head = nodeToInsert } else { node.Prev.Next = nodeToInsert } node.Prev = nodeToInsert } // InsertAfter inserts node after the provided node func (dll *DoublyLinkedList) InsertAfter(node, nodeToInsert *DllNode) { if nodeToInsert == dll.Head && nodeToInsert == dll.Tail { //nolint:gocritic return } dll.Remove(nodeToInsert) nodeToInsert.Prev = node nodeToInsert.Next = node.Next if node.Next == nil { dll.Tail = nodeToInsert } else { node.Next.Prev = nodeToInsert } node.Next = nodeToInsert } // Remove removes the node func (dll *DoublyLinkedList) Remove(node *DllNode) { if node == dll.Head { dll.Head = dll.Head.Next } if node == dll.Tail { dll.Tail = dll.Tail.Prev } dll.removeNode(node) } // Reset resets the whole DLL func (dll *DoublyLinkedList) Reset() { cNode := dll.Head for cNode != nil { cNode.Vertex.NumOfDeps = len(cNode.Vertex.Dependencies) cNode.Vertex.Visiting = false cNode.Vertex.Visited = false cNode = cNode.Next } } func (dll *DoublyLinkedList) removeNode(node *DllNode) { if node.Prev != nil { node.Prev.Next = node.Next } if node.Next != nil { node.Next.Prev = node.Prev } node.Prev = nil node.Next = nil }
pkg/linked_list/linked_list.go
0.654343
0.564579
linked_list.go
starcoder
package client // PersistentVolumeSpec is the specification of a persistent volume. type V1PersistentVolumeSpec struct { // AccessModes contains all ways the volume can be mounted. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes AccessModes []string `json:"accessModes,omitempty"` // AWSElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore AwsElasticBlockStore V1AwsElasticBlockStoreVolumeSource `json:"awsElasticBlockStore,omitempty"` // AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod. AzureDisk V1AzureDiskVolumeSource `json:"azureDisk,omitempty"` // AzureFile represents an Azure File Service mount on the host and bind mount to the pod. AzureFile V1AzureFilePersistentVolumeSource `json:"azureFile,omitempty"` // A description of the persistent volume's resources and capacity. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacity Capacity map[string]string `json:"capacity,omitempty"` // CephFS represents a Ceph FS mount on the host that shares a pod's lifetime Cephfs V1CephFsPersistentVolumeSource `json:"cephfs,omitempty"` // Cinder represents a cinder volume attached and mounted on kubelets host machine More info: https://releases.k8s.io/HEAD/examples/mysql-cinder-pd/README.md Cinder V1CinderVolumeSource `json:"cinder,omitempty"` // ClaimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. Expected to be non-nil when bound. claim.VolumeName is the authoritative bind between PV and PVC. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#binding ClaimRef V1ObjectReference `json:"claimRef,omitempty"` // FC represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod. Fc V1FcVolumeSource `json:"fc,omitempty"` // FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin. This is an alpha feature and may change in future. FlexVolume V1FlexVolumeSource `json:"flexVolume,omitempty"` // Flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running Flocker V1FlockerVolumeSource `json:"flocker,omitempty"` // GCEPersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk GcePersistentDisk V1GcePersistentDiskVolumeSource `json:"gcePersistentDisk,omitempty"` // Glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. More info: https://releases.k8s.io/HEAD/examples/volumes/glusterfs/README.md Glusterfs V1GlusterfsVolumeSource `json:"glusterfs,omitempty"` // HostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath HostPath V1HostPathVolumeSource `json:"hostPath,omitempty"` // ISCSI represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. Iscsi V1IscsiVolumeSource `json:"iscsi,omitempty"` // Local represents directly-attached storage with node affinity Local V1LocalVolumeSource `json:"local,omitempty"` // A list of mount options, e.g. [\"ro\", \"soft\"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-options MountOptions []string `json:"mountOptions,omitempty"` // NFS represents an NFS mount on the host. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs Nfs V1NfsVolumeSource `json:"nfs,omitempty"` // What happens to a persistent volume when released from its claim. Valid options are Retain (default) and Recycle. Recycling must be supported by the volume plugin underlying this persistent volume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaiming PersistentVolumeReclaimPolicy string `json:"persistentVolumeReclaimPolicy,omitempty"` // PhotonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine PhotonPersistentDisk V1PhotonPersistentDiskVolumeSource `json:"photonPersistentDisk,omitempty"` // PortworxVolume represents a portworx volume attached and mounted on kubelets host machine PortworxVolume V1PortworxVolumeSource `json:"portworxVolume,omitempty"` // Quobyte represents a Quobyte mount on the host that shares a pod's lifetime Quobyte V1QuobyteVolumeSource `json:"quobyte,omitempty"` // RBD represents a Rados Block Device mount on the host that shares a pod's lifetime. More info: https://releases.k8s.io/HEAD/examples/volumes/rbd/README.md Rbd V1RbdVolumeSource `json:"rbd,omitempty"` // ScaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes. ScaleIO V1ScaleIoVolumeSource `json:"scaleIO,omitempty"` // Name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass. StorageClassName string `json:"storageClassName,omitempty"` // StorageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod More info: https://releases.k8s.io/HEAD/examples/volumes/storageos/README.md Storageos V1StorageOsPersistentVolumeSource `json:"storageos,omitempty"` // VsphereVolume represents a vSphere volume attached and mounted on kubelets host machine VsphereVolume V1VsphereVirtualDiskVolumeSource `json:"vsphereVolume,omitempty"` }
pkg/client/v1_persistent_volume_spec.go
0.881869
0.565899
v1_persistent_volume_spec.go
starcoder
package puzzle import "reflect" // Node represents a in the search tree type Node struct { Puzzle []int Value int // the index of the "0" in the puzzle Children []*Node Parent *Node Move string // used for printing files Heuristic int G int // the depth of the node in the search tree } // NewPuzzle generates the root node func NewPuzzle(p []int) *Node { puzzle := make([]int, NumberColumns*NumberRows) for i := 0; i < len(p); i++ { puzzle[i] = p[i] } return &Node{ Puzzle: puzzle, Value: -1, Children: make([]*Node, 0), Parent: nil, Move: "0", Heuristic: -1, G: 0, } } // GenerateMoves generates the possible moves func (n *Node) GenerateMoves() { for i := 0; i < len(n.Puzzle); i++ { if n.Puzzle[i] == 0 { n.Value = i } } n.MoveUp(n.Puzzle, n.Value) n.MoveUpRight(n.Puzzle, n.Value) n.MoveRight(n.Puzzle, n.Value) n.MoveDownRight(n.Puzzle, n.Value) n.MoveDown(n.Puzzle, n.Value) n.MoveDownLeft(n.Puzzle, n.Value) n.MoveLeft(n.Puzzle, n.Value) n.MoveUpLeft(n.Puzzle, n.Value) // remove the parent from the child t := n.PathTrace() for i := 0; i < len(n.Children); i++ { if AreTheSame(n.Puzzle, n.Children[i].Puzzle) { copy(n.Children[i:], n.Children[i+1:]) n.Children[len(n.Children)-1] = nil n.Children = n.Children[:len(n.Children)-1] } else if Contains(t, n.Children[i]) { copy(n.Children[i:], n.Children[i+1:]) n.Children[len(n.Children)-1] = nil n.Children = n.Children[:len(n.Children)-1] } } } // GoalTest veries if a puzzle is the goal state func (n *Node) isGoalState() bool { for i := 0; i < len(n.Puzzle)-1; i++ { if n.Puzzle[i] != goalState[i] { return false } } return true } // PathTrace returns a slice of nodes leading to goal func (n *Node) PathTrace() []*Node { new := make([]*Node, 0) current := n new = append(new, current) for current.Parent != nil { current = current.Parent new = append(new, current) } return new } // ClonePuzzle copies the puzzle of a given Node func (n *Node) ClonePuzzle() []int { p := make([]int, NumberColumns*NumberRows) for i := 0; i < len(n.Puzzle); i++ { p[i] = n.Puzzle[i] } return p } // AreTheSame compares two slices func AreTheSame(a []int, b []int) bool { for i := 0; i < len(a); i++ { if a[i] != b[i] { return false } } return true } // Contains checks if a slice of Nodes contains a given Node func Contains(s []*Node, n *Node) bool { for i := 0; i < len(s); i++ { if AreTheSame(s[i].Puzzle, n.Puzzle) { return true } } return false } // ContainsAndRemove checks if an slice of Nodes contains a given Node // and removes the node if it is theres func ContainsAndRemove(s *[]*Node, n *Node) (bool, *Node) { for i := 0; i < len(*s); i++ { if AreTheSame((*s)[i].Puzzle, n.Puzzle) { if reflect.DeepEqual((*s)[i], n) { node := (*s)[i] (*s) = append((*s)[:i], (*s)[i+1:]...) return true, node } } } return false, nil } // MoveUp moves the empty tile up by 1 tile func (n *Node) MoveUp(p []int, i int) { if i-NumberColumns >= 0 { c := n.ClonePuzzle() temp := c[i-NumberColumns] c[i-NumberColumns] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i-NumberColumns] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } } // MoveUpRight moves the empty tile diagonally up-right by 1 tile func (n *Node) MoveUpRight(p []int, i int) { if i%NumberColumns != 3 && i > 3 { c := n.ClonePuzzle() temp := c[i-NumberRows] c[i-NumberRows] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i-NumberRows] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } } // MoveRight moves the empty tile to the right by 1 tile func (n *Node) MoveRight(p []int, i int) { if i%NumberColumns != 3 { c := n.ClonePuzzle() temp := c[i+1] c[i+1] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i+1] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } } // MoveDownRight moves the empty tile diagonally down-right by 1 tile func (n *Node) MoveDownRight(p []int, i int) { if i%NumberColumns != 3 && i < 8 { c := n.ClonePuzzle() temp := c[i+5] c[i+5] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i+5] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } } // MoveDown moves the empty tile down by 1 tile func (n *Node) MoveDown(p []int, i int) { if i < 8 { c := n.ClonePuzzle() temp := c[i+4] c[i+4] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i+4] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } } // MoveDownLeft moves the empty tile diagonally down-left by 1 tile func (n *Node) MoveDownLeft(p []int, i int) { if i%NumberColumns > 0 && i < 8 { c := n.ClonePuzzle() temp := c[i+3] c[i+3] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i+3] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } } // MoveLeft moves the empty tile left by 1 tile func (n *Node) MoveLeft(p []int, i int) { if i%NumberColumns > 0 { c := n.ClonePuzzle() temp := c[i-1] c[i-1] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i-1] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } } // MoveUpLeft moves the empty tile diagonally up-left by 1 tile func (n *Node) MoveUpLeft(p []int, i int) { if i%NumberColumns > 0 && i-NumberColumns >= 0 { c := n.ClonePuzzle() temp := c[i-5] c[i-5] = c[i] c[i] = temp child := NewPuzzle(c) child.Move = boardPositions[i-5] child.Parent = n child.G = n.G + 1 n.Children = append(n.Children, child) } }
puzzle/puzzle.go
0.625667
0.433322
puzzle.go
starcoder
package convert import ( "errors" "strconv" ) // FloatToBool -- Converts a value from float64 to boolean func FloatToBool(value float64) (bool, error) { if float64(1) == value { return true, nil } else if float64(0) == value { return false, nil } return false, errors.New(cannotConvertErrMsg) } // FloatToFloat32 -- Converts a value from float64 to float32 func FloatToFloat32(value float64) (float32, error) { valueStr, _ := FloatToString(value) result64, parseErr := strconv.ParseFloat(valueStr, 32) result := float32(result64) if parseErr != nil { return result, parseErr } resultStr := strconv.FormatFloat(float64(result), 'f', -1, 32) if resultStr != valueStr { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToInt -- Converts a value from float64 to int func FloatToInt(value float64) (int, error) { result := int(value) if float64(result) != value { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToInt8 -- Converts a value from float64 to int8 func FloatToInt8(value float64) (int8, error) { result := int8(value) if float64(result) != value { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToInt16 -- Converts a value from float64 to int16 func FloatToInt16(value float64) (int16, error) { result := int16(value) if float64(result) != value { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToInt32 -- Converts a value from float64 to int32 func FloatToInt32(value float64) (int32, error) { result := int32(value) if float64(result) != value { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToInt64 -- Converts a value from float64 to int64 func FloatToInt64(value float64) (int64, error) { result := int64(value) if float64(result) != value { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToUint -- Converts a value from float64 to uint func FloatToUint(value float64) (uint, error) { result := uint(value) if float64(result) != value || value < 0 { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToUint8 -- Converts a value from float64 to uint8 func FloatToUint8(value float64) (uint8, error) { result := uint8(value) if float64(result) != value || value < 0 { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToUint16 -- Converts a value from float64 to uint16 func FloatToUint16(value float64) (uint16, error) { result := uint16(value) if float64(result) != value || value < 0 { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToUint32 -- Converts a value from float64 to uint32 func FloatToUint32(value float64) (uint32, error) { result := uint32(value) if float64(result) != value || value < 0 { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToUint64 -- Converts a value from float64 to uint64 func FloatToUint64(value float64) (uint64, error) { result := uint64(value) if float64(result) != value || value < 0 { return result, errors.New(lossOfPrecisionErrorMsg) } return result, nil } // FloatToString -- Converts a value from float64 to string func FloatToString(value float64) (string, error) { return strconv.FormatFloat(value, 'f', -1, 64), nil }
float.go
0.857559
0.631736
float.go
starcoder
package tsi1 import ( "bytes" "encoding/binary" "fmt" "hash/crc32" "io" "sort" "github.com/influxdata/influxdb/pkg/binaryutil" ) const ( // MeasurementCardinalityStatsMagicNumber is written as the first 4 bytes // of a data file to identify the file as a tsi1 cardinality file. MeasurementCardinalityStatsMagicNumber string = "TSIS" // MeasurementCardinalityVersion indicates the version of the TSIC file format. MeasurementCardinalityStatsVersion byte = 1 ) // MeasurementCardinalityStats represents a set of measurement sizes. type MeasurementCardinalityStats map[string]int // NewMeasurementCardinality returns a new instance of MeasurementCardinality. func NewMeasurementCardinalityStats() MeasurementCardinalityStats { return make(MeasurementCardinalityStats) } // MeasurementNames returns a list of sorted measurement names. func (s MeasurementCardinalityStats) MeasurementNames() []string { a := make([]string, 0, len(s)) for name := range s { a = append(a, name) } sort.Strings(a) return a } // Inc increments a measurement count by 1. func (s MeasurementCardinalityStats) Inc(name []byte) { s[string(name)]++ } // Dec decrements a measurement count by 1. Deleted if zero. func (s MeasurementCardinalityStats) Dec(name []byte) { v := s[string(name)] if v == 1 { delete(s, string(name)) } else { s[string(name)] = v - 1 } } // Add adds the values of all measurements in other to s. func (s MeasurementCardinalityStats) Add(other MeasurementCardinalityStats) { for name, v := range other { s[name] += v } } // Sub subtracts the values of all measurements in other from s. func (s MeasurementCardinalityStats) Sub(other MeasurementCardinalityStats) { for name, v := range other { s[name] -= v } } // Clone returns a copy of s. func (s MeasurementCardinalityStats) Clone() MeasurementCardinalityStats { other := make(MeasurementCardinalityStats, len(s)) for k, v := range s { other[k] = v } return other } // ReadFrom reads stats from r in a binary format. Reader must also be an io.ByteReader. func (s MeasurementCardinalityStats) ReadFrom(r io.Reader) (n int64, err error) { br, ok := r.(io.ByteReader) if !ok { return 0, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: ByteReader required") } // Read & verify magic. magic := make([]byte, 4) nn, err := io.ReadFull(r, magic) if n += int64(nn); err != nil { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: cannot read stats magic: %s", err) } else if string(magic) != MeasurementCardinalityStatsMagicNumber { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: invalid tsm1 stats file") } // Read & verify version. version := make([]byte, 1) nn, err = io.ReadFull(r, version) if n += int64(nn); err != nil { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: cannot read stats version: %s", err) } else if version[0] != MeasurementCardinalityStatsVersion { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: incompatible tsm1 stats version: %d", version[0]) } // Read checksum. checksum := make([]byte, 4) nn, err = io.ReadFull(r, checksum) if n += int64(nn); err != nil { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: cannot read checksum: %s", err) } // Read measurement count. measurementN, err := binary.ReadVarint(br) if err != nil { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: cannot read stats measurement count: %s", err) } n += int64(binaryutil.VarintSize(measurementN)) // Read measurements. for i := int64(0); i < measurementN; i++ { nn64, err := s.readMeasurementFrom(r) if n += nn64; err != nil { return n, err } } // Expect end-of-file. buf := make([]byte, 1) if _, err := r.Read(buf); err != io.EOF { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.ReadFrom: file too large, expected EOF") } return n, nil } // readMeasurementFrom reads a measurement stat from r in a binary format. func (s MeasurementCardinalityStats) readMeasurementFrom(r io.Reader) (n int64, err error) { br, ok := r.(io.ByteReader) if !ok { return 0, fmt.Errorf("tsm1.MeasurementCardinalityStats.readMeasurementFrom: ByteReader required") } // Read measurement name length. nameLen, err := binary.ReadVarint(br) if err != nil { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.readMeasurementFrom: cannot read stats measurement name length: %s", err) } n += int64(binaryutil.VarintSize(nameLen)) // Read measurement name. Use large capacity so it can usually be stack allocated. // Go allocates unescaped variables smaller than 64KB on the stack. name := make([]byte, nameLen) nn, err := io.ReadFull(r, name) if n += int64(nn); err != nil { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.readMeasurementFrom: cannot read stats measurement name: %s", err) } // Read size. sz, err := binary.ReadVarint(br) if err != nil { return n, fmt.Errorf("tsm1.MeasurementCardinalityStats.readMeasurementFrom: cannot read stats measurement size: %s", err) } n += int64(binaryutil.VarintSize(sz)) // Insert into map. s[string(name)] = int(sz) return n, nil } // WriteTo writes stats to w in a binary format. func (s MeasurementCardinalityStats) WriteTo(w io.Writer) (n int64, err error) { // Write magic & version. nn, err := io.WriteString(w, MeasurementCardinalityStatsMagicNumber) if n += int64(nn); err != nil { return n, err } nn, err = w.Write([]byte{MeasurementCardinalityStatsVersion}) if n += int64(nn); err != nil { return n, err } // Write measurement count. var buf bytes.Buffer b := make([]byte, binary.MaxVarintLen64) if _, err = buf.Write(b[:binary.PutVarint(b, int64(len(s)))]); err != nil { return n, err } // Write all measurements in sorted order. for _, name := range s.MeasurementNames() { if _, err := s.writeMeasurementTo(&buf, name, s[name]); err != nil { return n, err } } data := buf.Bytes() // Compute & write checksum. if err := binary.Write(w, binary.BigEndian, crc32.ChecksumIEEE(data)); err != nil { return n, err } n += 4 // Write buffer. nn, err = w.Write(data) if n += int64(nn); err != nil { return n, err } return n, err } func (s MeasurementCardinalityStats) writeMeasurementTo(w io.Writer, name string, sz int) (n int64, err error) { // Write measurement name length. buf := make([]byte, binary.MaxVarintLen64) nn, err := w.Write(buf[:binary.PutVarint(buf, int64(len(name)))]) if n += int64(nn); err != nil { return n, err } // Write measurement name. nn, err = io.WriteString(w, name) if n += int64(nn); err != nil { return n, err } // Write size. nn, err = w.Write(buf[:binary.PutVarint(buf, int64(sz))]) if n += int64(nn); err != nil { return n, err } return n, err }
tsdb/tsi1/stats.go
0.753467
0.41567
stats.go
starcoder
package datetime import ( "time" ) const ( // YYYY_MM_DD_HH_MM_SS_SSS is the format "2006-01-02 15:04:05.000". YYYY_MM_DD_HH_MM_SS_SSS = "2006-01-02 15:04:05.000" // YYYY_MM_DD_HH_MM_SS is the format "2006-01-02 15:04:05". YYYY_MM_DD_HH_MM_SS = "2006-01-02 15:04:05" // YYYY_MM_DD is the format "2006-01-02". YYYY_MM_DD = "2006-01-02" // DD_MM_YYYY is the format "02-01-2006". DD_MM_YYYY = "02-01-2006" // DD_MM_YYYY_HH_MM_SS is the format "02-01-2006 15:04:05". DD_MM_YYYY_HH_MM_SS = "02-01-2006 15:04:05" // DD_MM_YYYY_HH_MM_SS_SSS is the format "02-01-2006 15:04:05.000". DD_MM_YYYY_HH_MM_SS_SSS = "02-01-2006 15:04:05.000" ) // GetCurrentLocalTime returns the current local time. func GetCurrentLocalTime() time.Time { return time.Now() } // GetCurrentMiliseconds returns the current milliseconds. func GetCurrentMiliseconds() int64 { return ConvertLocalTimeToMilliseconds(GetCurrentLocalTime()) } // ConvertCurrentLocalTimeToString converts the current local time to string with the specific format. func ConvertCurrentLocalTimeToString(format string) string { return GetCurrentLocalTime().Format(format) } // ConvertMillisecondsToString converts the milliseconds to the string with the specific format. func ConvertMillisecondsToString(millis int64, format string) string { return ConvertMillisecondsToLocalTime(millis).Format(format) } // ConvertStringToMilliseconds converts the string with specific format to milliseconds. func ConvertStringToMilliseconds(value, format string) (int64, error) { localTime, err := time.ParseInLocation(format, value, time.Local) if err != nil { return -1, err } return ConvertLocalTimeToMilliseconds(localTime), nil } // ConvertStringToLocalTime converts the string with specific format to the local time. func ConvertStringToLocalTime(value, format string) (time.Time, error) { return time.ParseInLocation(format, value, time.Local) } // ConvertLocalTimeToMilliseconds converts the local time to milliseconds. func ConvertLocalTimeToMilliseconds(t time.Time) int64 { return t.UnixNano() / 1e6 } // ConvertMillisecondsToLocalTime converts the milliseconds to local time. func ConvertMillisecondsToLocalTime(millis int64) time.Time { return time.Unix(millis/1e3, (millis%1e3)*1e6) } // ConvertLocalTimeToString converts the local time to string with specific format. func ConvertLocalTimeToString(localTime time.Time, format string) string { return localTime.Format(format) } // GetYear returns the current year. func GetYear() int { return GetCurrentLocalTime().Year() } // GetDayOfYear returns the day of the year. func GetDayOfYear() int { return GetCurrentLocalTime().YearDay() } // GetDayOfMonth returns the day of month. func GetDayOfMonth() int { return GetCurrentLocalTime().Day() } // GetMonthOfYear returns the month of year. Value from 1 to 12. func GetMonthOfYear() int { return int(GetCurrentLocalTime().Month()) } // GetStartLocalTimeOfYear returns the start local time of year. func GetStartLocalTimeOfYear() time.Time { return time.Date(GetYear(), 1, 1, 0, 0, 0, 0, time.Local) } // GetEndLocalTimeOfYear returns the end local time of year. func GetEndLocalTimeOfYear() time.Time { return time.Date(GetYear(), 12, 31, 23, 59, 59, 999999999, time.Local) } // GetStartLocalTimeOfMonth returns the start local time of month. func GetStartLocalTimeOfMonth() time.Time { return time.Date(GetYear(), GetCurrentLocalTime().Month(), 1, 0, 0, 0, 0, time.Local) } // GetEndLocalTimeOfMonth returns the end local time of month. func GetEndLocalTimeOfMonth() time.Time { return time.Date(GetYear(), GetCurrentLocalTime().Month(), 1, 23, 59, 59, 999999999, time.Local).AddDate(0, 1, -1) } // GetStartLocalTimeOfDay return the start local time of day. func GetStartLocalTimeOfDay() time.Time { return time.Date(GetYear(), GetCurrentLocalTime().Month(), GetCurrentLocalTime().Day(), 0, 0, 0, 0, time.Local) } // GetEndLocalTimeOfDay return the end local time of day. func GetEndLocalTimeOfDay() time.Time { return time.Date(GetYear(), GetCurrentLocalTime().Month(), GetCurrentLocalTime().Day(), 23, 59, 59, 999999999, time.Local) } // GetStartLocalTimeOfTime return the start local time of specific local time. func GetStartLocalTimeOfTime(inputTime time.Time) time.Time { return time.Date(inputTime.Year(), inputTime.Month(), inputTime.Day(), 0, 0, 0, 0, time.Local) } // GetEndLocalTimeOfTime return the end local time of specific local time. func GetEndLocalTimeOfTime(inputTime time.Time) time.Time { return time.Date(inputTime.Year(), inputTime.Month(), inputTime.Day(), 23, 59, 59, 999999999, time.Local) } // GetBeforeLocalTimeOfTime returns before local time with the number of days compared to specific local time. func GetBeforeLocalTimeOfTime(inputTime time.Time, numberDay int, isStartTime bool) time.Time { if isStartTime { return GetStartLocalTimeOfTime(inputTime.AddDate(0, 0, -numberDay)) } return GetEndLocalTimeOfTime(inputTime.AddDate(0, 0, -numberDay)) } // GetAfterLocalTimeOfTime returns after local time with the number of days compared to specific local time. func GetAfterLocalTimeOfTime(inputTime time.Time, numberDay int, isStartTime bool) time.Time { if isStartTime { return GetStartLocalTimeOfTime(inputTime.AddDate(0, 0, numberDay)) } return GetEndLocalTimeOfTime(inputTime.AddDate(0, 0, numberDay)) } // GetMillisecondsBetween returns the number of milliseconds between 2 local time. func GetMillisecondsBetween(startDate time.Time, endTime time.Time) int64 { return endTime.Sub(startDate).Milliseconds() }
utils/datetime/datetime.go
0.720958
0.444987
datetime.go
starcoder
package numeralsort import ( "sort" "strings" ) // Less returns true if x < y in a numeral-aware comparison. // It is suitable for use with Go's standard sort.Interface. func Less(a, b string) bool { // the idea is to scan along a and b rune-by-rune (might as well the UTF-8 ready), // until a numeric [0-9] rune is reached in both strings. Then the numbers are // decoded and compared. If equal the text comparison continues... . // numbers are assumed to be in unsigned decimal (which is common. hex typically has 0000 prefixes) digits := "0123456789" for { i := strings.IndexAny(a, digits) j := strings.IndexAny(b, digits) if i < 0 || j < 0 { // no numeral to compare. finish up with a straight string comparison return a < b } if i != j || a[:i] != b[:j] { // text differs. finish by comparing the text return a[:i] < b[:j] } // a and b match up to i (which equals j at this point), and then that is the start of a numeral a = a[i:] b = b[j:] // decode the numeral. since small numbers are common I check if it might fit in uint64 before resorting to // bignum // first find the end of each numeral. There is no strings.IndexNotAny() (at least not in go1.7), so I have to write my own // function to find the first non-numeral rune var x, y string x, a = extractNumeral(a) y, b = extractNumeral(b) if x != y { return lessNumeral(x, y) } // numeral section matched; return to matching text } } // extractNumeral extracts the numeral prefix of a. // It returns the numeral and the remaining non-numeral part of a. func extractNumeral(a string) (string, string) { for i, r := range a { if r < '0' || '9' < r { // split at this non-numeric rune return a[:i], a[i:] } } // a is entirely a numeral return a, "" } // lessNumeral compares two numerals in text form, sorting them as numbers func lessNumeral(x, y string) bool { // the trick is that x and y only contain [0-9], so they can be treated as slices of bytes lx := len(x) ly := len(y) i := lx if i < ly { i = ly } for i > 0 { var xr, yr byte if i <= lx { xr = x[lx-i] } if i <= ly { yr = y[ly-i] } // xr,yr are the corresponding digts from x and y, or 0 (which is less than any rune in the '0'-'9' range) if xr != yr { return xr < yr } i-- } // x and y are identical. thus they are not less-then // (note this case is not really reached, since the caller already checked that x != y, but in case this code // gets reused elsewhere it might as well be right) return false } // StringSlice is a slice of strings sortable in numeral-aware order // It implements sort.Interface. The name matches the equivalent type in the standard sort package. type StringSlice []string func (s StringSlice) Len() int { return len(s) } func (s StringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s StringSlice) Less(i, j int) bool { return Less(s[i], s[j]) } // Strings is a utility function to sort a slice of strings using numeral-aware sort order. // The name matched the name of the equivalent function in the standard sort package. func Strings(strs []string) { sort.Sort(StringSlice(strs)) }
numeralsort.go
0.75183
0.588919
numeralsort.go
starcoder
package main import ( "math" ) // Player contains information on a specific player used by the API type Player struct { X uint16 Y uint16 Direction Direction Speed uint8 } // ProcessAction moves the player according to action and turn. Returns visited coordinates func (player *Player) ProcessAction(action Action, turn uint16) []*Coords { if action == SpeedUp { if player.Speed != 10 { player.Speed++ } } else if action == SlowDown { if player.Speed != 1 { player.Speed-- } } else if action == TurnLeft { player.Direction = (player.Direction + 1) % 4 } else if action == TurnRight { player.Direction = (player.Direction + 3) % 4 } visitedCoords := make([]*Coords, player.Speed+1) jump := turn%6 == 0 for i := uint8(1); i <= player.Speed; i++ { if player.Direction == Up { player.Y-- } else if player.Direction == Down { player.Y++ } else if player.Direction == Right { player.X++ } else if player.Direction == Left { player.X-- } if !jump || i == 1 || i == player.Speed { visitedCoords[i] = &Coords{player.Y, player.X} } } return visitedCoords } // checkCell checks if it is legal for a player to go from a position a certain number of fields func checkCell(cells [][]bool, direction Direction, y uint16, x uint16, fields uint16, extraCellInfo map[Coords]struct{}, extraCellAllowed bool) bool { intY := int(y) intX := int(x) if direction == Up { intY = int(y) - int(fields) } else if direction == Down { intY = int(y) + int(fields) } else if direction == Left { intX = int(x) - int(fields) } else { intX = int(x) + int(fields) } if intX >= len(cells[0]) || intY >= len(cells) || intX < 0 || intY < 0 { return false } isPossible := !cells[intY][intX] if extraCellInfo != nil { _, fieldVisited := extraCellInfo[Coords{uint16(intY), uint16(intX)}] if extraCellAllowed { return isPossible || fieldVisited } return isPossible && !fieldVisited } return isPossible } // PossibleActions returns possible actions for a given situation for a player func (player *Player) PossibleActions(cells [][]bool, turn uint16, extraCellInfo map[Coords]struct{}, extraCellAllowed bool) []Action { changeNothing := true turnRight := true turnLeft := true slowDown := player.Speed != 1 speedUp := player.Speed != 10 direction := player.Direction y := player.Y x := player.X for i := uint16(1); i <= uint16(player.Speed); i++ { checkJump := turn%6 == 0 && i > 1 && i < uint16(player.Speed) checkJumpSlowDown := turn%6 == 0 && i > 1 && i < uint16(player.Speed)-1 checkJumpSpeedUp := turn%6 == 0 && i > 1 && i <= uint16(player.Speed) turnLeft = turnLeft && (checkJump || checkCell(cells, (direction+1)%4, y, x, i, extraCellInfo, extraCellAllowed)) changeNothing = changeNothing && (checkJump || checkCell(cells, direction, y, x, i, extraCellInfo, extraCellAllowed)) turnRight = turnRight && (checkJump || checkCell(cells, (direction+3)%4, y, x, i, extraCellInfo, extraCellAllowed)) if i != uint16(player.Speed) { slowDown = slowDown && (checkJumpSlowDown || checkCell(cells, direction, y, x, i, extraCellInfo, extraCellAllowed)) } speedUp = speedUp && (checkJumpSpeedUp || checkCell(cells, direction, y, x, i, extraCellInfo, extraCellAllowed)) } speedUp = speedUp && checkCell(cells, direction, y, x, uint16(player.Speed+1), extraCellInfo, extraCellAllowed) possibleActions := make([]Action, 0, 5) if changeNothing { possibleActions = append(possibleActions, ChangeNothing) } if turnLeft { possibleActions = append(possibleActions, TurnLeft) } if turnRight { possibleActions = append(possibleActions, TurnRight) } if speedUp { possibleActions = append(possibleActions, SpeedUp) } if slowDown { possibleActions = append(possibleActions, SlowDown) } return possibleActions } //DistanceTo returns the distance between to players as float64 func (player *Player) DistanceTo(p2 *Player) float64 { return math.Sqrt(math.Pow(float64(int(player.X)-int(p2.X)), 2) + math.Pow(float64(int(player.Y)-int(p2.Y)), 2)) } //Copy copies a struct of type Player func (player *Player) Copy() *Player { newPlayer := *player return &newPlayer }
client/player.go
0.61878
0.440349
player.go
starcoder