id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
11,200
ungerik/go3d
mat4/mat4.go
Mul
func (mat *T) Mul(f float32) *T { for i, col := range mat { for j := range col { mat[i][j] *= f } } return mat }
go
func (mat *T) Mul(f float32) *T { for i, col := range mat { for j := range col { mat[i][j] *= f } } return mat }
[ "func", "(", "mat", "*", "T", ")", "Mul", "(", "f", "float32", ")", "*", "T", "{", "for", "i", ",", "col", ":=", "range", "mat", "{", "for", "j", ":=", "range", "col", "{", "mat", "[", "i", "]", "[", "j", "]", "*=", "f", "\n", "}", "\n", "}", "\n", "return", "mat", "\n", "}" ]
// Mul multiplies every element by f and returns mat.
[ "Mul", "multiplies", "every", "element", "by", "f", "and", "returns", "mat", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L110-L117
11,201
ungerik/go3d
mat4/mat4.go
Muled
func (mat *T) Muled(f float32) T { result := *mat result.Mul(f) return result }
go
func (mat *T) Muled(f float32) T { result := *mat result.Mul(f) return result }
[ "func", "(", "mat", "*", "T", ")", "Muled", "(", "f", "float32", ")", "T", "{", "result", ":=", "*", "mat", "\n", "result", ".", "Mul", "(", "f", ")", "\n", "return", "result", "\n", "}" ]
// Muled returns a copy of the matrix with every element multiplied by f.
[ "Muled", "returns", "a", "copy", "of", "the", "matrix", "with", "every", "element", "multiplied", "by", "f", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L120-L124
11,202
ungerik/go3d
mat4/mat4.go
MultMatrix
func (mat *T) MultMatrix(m *T) *T { // iterate over the rows of mat for i := range mat { row := vec4.T{mat[0][i], mat[1][i], mat[2][i], mat[3][i]} mat[0][i] = vec4.Dot4(&row, &m[0]) mat[1][i] = vec4.Dot4(&row, &m[1]) mat[2][i] = vec4.Dot4(&row, &m[2]) mat[3][i] = vec4.Dot4(&row, &m[3]) } return mat }
go
func (mat *T) MultMatrix(m *T) *T { // iterate over the rows of mat for i := range mat { row := vec4.T{mat[0][i], mat[1][i], mat[2][i], mat[3][i]} mat[0][i] = vec4.Dot4(&row, &m[0]) mat[1][i] = vec4.Dot4(&row, &m[1]) mat[2][i] = vec4.Dot4(&row, &m[2]) mat[3][i] = vec4.Dot4(&row, &m[3]) } return mat }
[ "func", "(", "mat", "*", "T", ")", "MultMatrix", "(", "m", "*", "T", ")", "*", "T", "{", "// iterate over the rows of mat", "for", "i", ":=", "range", "mat", "{", "row", ":=", "vec4", ".", "T", "{", "mat", "[", "0", "]", "[", "i", "]", ",", "mat", "[", "1", "]", "[", "i", "]", ",", "mat", "[", "2", "]", "[", "i", "]", ",", "mat", "[", "3", "]", "[", "i", "]", "}", "\n", "mat", "[", "0", "]", "[", "i", "]", "=", "vec4", ".", "Dot4", "(", "&", "row", ",", "&", "m", "[", "0", "]", ")", "\n", "mat", "[", "1", "]", "[", "i", "]", "=", "vec4", ".", "Dot4", "(", "&", "row", ",", "&", "m", "[", "1", "]", ")", "\n", "mat", "[", "2", "]", "[", "i", "]", "=", "vec4", ".", "Dot4", "(", "&", "row", ",", "&", "m", "[", "2", "]", ")", "\n", "mat", "[", "3", "]", "[", "i", "]", "=", "vec4", ".", "Dot4", "(", "&", "row", ",", "&", "m", "[", "3", "]", ")", "\n", "}", "\n", "return", "mat", "\n", "}" ]
// Mult multiplies this matrix with the given matrix m and saves the result in this matrix.
[ "Mult", "multiplies", "this", "matrix", "with", "the", "given", "matrix", "m", "and", "saves", "the", "result", "in", "this", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L127-L137
11,203
ungerik/go3d
mat4/mat4.go
AssignMat3x3
func (mat *T) AssignMat3x3(m *mat3.T) *T { *mat = T{ vec4.T{m[0][0], m[1][0], m[2][0], 0}, vec4.T{m[0][1], m[1][1], m[2][1], 0}, vec4.T{m[0][2], m[1][2], m[2][2], 0}, vec4.T{0, 0, 0, 1}, } return mat }
go
func (mat *T) AssignMat3x3(m *mat3.T) *T { *mat = T{ vec4.T{m[0][0], m[1][0], m[2][0], 0}, vec4.T{m[0][1], m[1][1], m[2][1], 0}, vec4.T{m[0][2], m[1][2], m[2][2], 0}, vec4.T{0, 0, 0, 1}, } return mat }
[ "func", "(", "mat", "*", "T", ")", "AssignMat3x3", "(", "m", "*", "mat3", ".", "T", ")", "*", "T", "{", "*", "mat", "=", "T", "{", "vec4", ".", "T", "{", "m", "[", "0", "]", "[", "0", "]", ",", "m", "[", "1", "]", "[", "0", "]", ",", "m", "[", "2", "]", "[", "0", "]", ",", "0", "}", ",", "vec4", ".", "T", "{", "m", "[", "0", "]", "[", "1", "]", ",", "m", "[", "1", "]", "[", "1", "]", ",", "m", "[", "2", "]", "[", "1", "]", ",", "0", "}", ",", "vec4", ".", "T", "{", "m", "[", "0", "]", "[", "2", "]", ",", "m", "[", "1", "]", "[", "2", "]", ",", "m", "[", "2", "]", "[", "2", "]", ",", "0", "}", ",", "vec4", ".", "T", "{", "0", ",", "0", ",", "0", ",", "1", "}", ",", "}", "\n", "return", "mat", "\n", "}" ]
// AssignMat3x3 assigns a 3x3 sub-matrix and sets the rest of the matrix to the ident value.
[ "AssignMat3x3", "assigns", "a", "3x3", "sub", "-", "matrix", "and", "sets", "the", "rest", "of", "the", "matrix", "to", "the", "ident", "value", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L161-L169
11,204
ungerik/go3d
mat4/mat4.go
TransformVec4
func (mat *T) TransformVec4(v *vec4.T) { // Use intermediate variables to not alter further computations. x := mat[0][0]*v[0] + mat[1][0]*v[1] + mat[2][0]*v[2] + mat[3][0]*v[3] y := mat[0][1]*v[0] + mat[1][1]*v[1] + mat[2][1]*v[2] + mat[3][1]*v[3] z := mat[0][2]*v[0] + mat[1][2]*v[1] + mat[2][2]*v[2] + mat[3][2]*v[3] v[3] = mat[0][3]*v[0] + mat[1][3]*v[1] + mat[2][3]*v[2] + mat[3][3]*v[3] v[0] = x v[1] = y v[2] = z }
go
func (mat *T) TransformVec4(v *vec4.T) { // Use intermediate variables to not alter further computations. x := mat[0][0]*v[0] + mat[1][0]*v[1] + mat[2][0]*v[2] + mat[3][0]*v[3] y := mat[0][1]*v[0] + mat[1][1]*v[1] + mat[2][1]*v[2] + mat[3][1]*v[3] z := mat[0][2]*v[0] + mat[1][2]*v[1] + mat[2][2]*v[2] + mat[3][2]*v[3] v[3] = mat[0][3]*v[0] + mat[1][3]*v[1] + mat[2][3]*v[2] + mat[3][3]*v[3] v[0] = x v[1] = y v[2] = z }
[ "func", "(", "mat", "*", "T", ")", "TransformVec4", "(", "v", "*", "vec4", ".", "T", ")", "{", "// Use intermediate variables to not alter further computations.", "x", ":=", "mat", "[", "0", "]", "[", "0", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "0", "]", "*", "v", "[", "1", "]", "+", "mat", "[", "2", "]", "[", "0", "]", "*", "v", "[", "2", "]", "+", "mat", "[", "3", "]", "[", "0", "]", "*", "v", "[", "3", "]", "\n", "y", ":=", "mat", "[", "0", "]", "[", "1", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "1", "]", "*", "v", "[", "1", "]", "+", "mat", "[", "2", "]", "[", "1", "]", "*", "v", "[", "2", "]", "+", "mat", "[", "3", "]", "[", "1", "]", "*", "v", "[", "3", "]", "\n", "z", ":=", "mat", "[", "0", "]", "[", "2", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "2", "]", "*", "v", "[", "1", "]", "+", "mat", "[", "2", "]", "[", "2", "]", "*", "v", "[", "2", "]", "+", "mat", "[", "3", "]", "[", "2", "]", "*", "v", "[", "3", "]", "\n", "v", "[", "3", "]", "=", "mat", "[", "0", "]", "[", "3", "]", "*", "v", "[", "0", "]", "+", "mat", "[", "1", "]", "[", "3", "]", "*", "v", "[", "1", "]", "+", "mat", "[", "2", "]", "[", "3", "]", "*", "v", "[", "2", "]", "+", "mat", "[", "3", "]", "[", "3", "]", "*", "v", "[", "3", "]", "\n", "v", "[", "0", "]", "=", "x", "\n", "v", "[", "1", "]", "=", "y", "\n", "v", "[", "2", "]", "=", "z", "\n", "}" ]
// TransformVec4 multiplies v with mat and saves the result in v.
[ "TransformVec4", "multiplies", "v", "with", "mat", "and", "saves", "the", "result", "in", "v", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L191-L200
11,205
ungerik/go3d
mat4/mat4.go
SetTranslation
func (mat *T) SetTranslation(v *vec3.T) *T { mat[3][0] = v[0] mat[3][1] = v[1] mat[3][2] = v[2] return mat }
go
func (mat *T) SetTranslation(v *vec3.T) *T { mat[3][0] = v[0] mat[3][1] = v[1] mat[3][2] = v[2] return mat }
[ "func", "(", "mat", "*", "T", ")", "SetTranslation", "(", "v", "*", "vec3", ".", "T", ")", "*", "T", "{", "mat", "[", "3", "]", "[", "0", "]", "=", "v", "[", "0", "]", "\n", "mat", "[", "3", "]", "[", "1", "]", "=", "v", "[", "1", "]", "\n", "mat", "[", "3", "]", "[", "2", "]", "=", "v", "[", "2", "]", "\n", "return", "mat", "\n", "}" ]
// SetTranslation sets the translation elements of the matrix.
[ "SetTranslation", "sets", "the", "translation", "elements", "of", "the", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L246-L251
11,206
ungerik/go3d
mat4/mat4.go
Translate
func (mat *T) Translate(v *vec3.T) *T { mat[3][0] += v[0] mat[3][1] += v[1] mat[3][2] += v[2] return mat }
go
func (mat *T) Translate(v *vec3.T) *T { mat[3][0] += v[0] mat[3][1] += v[1] mat[3][2] += v[2] return mat }
[ "func", "(", "mat", "*", "T", ")", "Translate", "(", "v", "*", "vec3", ".", "T", ")", "*", "T", "{", "mat", "[", "3", "]", "[", "0", "]", "+=", "v", "[", "0", "]", "\n", "mat", "[", "3", "]", "[", "1", "]", "+=", "v", "[", "1", "]", "\n", "mat", "[", "3", "]", "[", "2", "]", "+=", "v", "[", "2", "]", "\n", "return", "mat", "\n", "}" ]
// Translate adds v to the translation part of the matrix.
[ "Translate", "adds", "v", "to", "the", "translation", "part", "of", "the", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L254-L259
11,207
ungerik/go3d
mat4/mat4.go
ScaleVec3
func (mat *T) ScaleVec3(s *vec3.T) *T { mat[0][0] *= s[0] mat[1][1] *= s[1] mat[2][2] *= s[2] return mat }
go
func (mat *T) ScaleVec3(s *vec3.T) *T { mat[0][0] *= s[0] mat[1][1] *= s[1] mat[2][2] *= s[2] return mat }
[ "func", "(", "mat", "*", "T", ")", "ScaleVec3", "(", "s", "*", "vec3", ".", "T", ")", "*", "T", "{", "mat", "[", "0", "]", "[", "0", "]", "*=", "s", "[", "0", "]", "\n", "mat", "[", "1", "]", "[", "1", "]", "*=", "s", "[", "1", "]", "\n", "mat", "[", "2", "]", "[", "2", "]", "*=", "s", "[", "2", "]", "\n", "return", "mat", "\n", "}" ]
// ScaleVec3 multiplies the scaling diagonal of the matrix by s.
[ "ScaleVec3", "multiplies", "the", "scaling", "diagonal", "of", "the", "matrix", "by", "s", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L294-L299
11,208
ungerik/go3d
mat4/mat4.go
AssignPerspectiveProjection
func (mat *T) AssignPerspectiveProjection(left, right, bottom, top, znear, zfar float32) *T { near2 := znear + znear ooFarNear := 1 / (zfar - znear) mat[0][0] = near2 / (right - left) mat[1][0] = 0 mat[2][0] = (right + left) / (right - left) mat[3][0] = 0 mat[0][1] = 0 mat[1][1] = near2 / (top - bottom) mat[2][1] = (top + bottom) / (top - bottom) mat[3][1] = 0 mat[0][2] = 0 mat[1][2] = 0 mat[2][2] = -(zfar + znear) * ooFarNear mat[3][2] = -2 * zfar * znear * ooFarNear mat[0][3] = 0 mat[1][3] = 0 mat[2][3] = -1 mat[3][3] = 0 return mat }
go
func (mat *T) AssignPerspectiveProjection(left, right, bottom, top, znear, zfar float32) *T { near2 := znear + znear ooFarNear := 1 / (zfar - znear) mat[0][0] = near2 / (right - left) mat[1][0] = 0 mat[2][0] = (right + left) / (right - left) mat[3][0] = 0 mat[0][1] = 0 mat[1][1] = near2 / (top - bottom) mat[2][1] = (top + bottom) / (top - bottom) mat[3][1] = 0 mat[0][2] = 0 mat[1][2] = 0 mat[2][2] = -(zfar + znear) * ooFarNear mat[3][2] = -2 * zfar * znear * ooFarNear mat[0][3] = 0 mat[1][3] = 0 mat[2][3] = -1 mat[3][3] = 0 return mat }
[ "func", "(", "mat", "*", "T", ")", "AssignPerspectiveProjection", "(", "left", ",", "right", ",", "bottom", ",", "top", ",", "znear", ",", "zfar", "float32", ")", "*", "T", "{", "near2", ":=", "znear", "+", "znear", "\n", "ooFarNear", ":=", "1", "/", "(", "zfar", "-", "znear", ")", "\n\n", "mat", "[", "0", "]", "[", "0", "]", "=", "near2", "/", "(", "right", "-", "left", ")", "\n", "mat", "[", "1", "]", "[", "0", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "0", "]", "=", "(", "right", "+", "left", ")", "/", "(", "right", "-", "left", ")", "\n", "mat", "[", "3", "]", "[", "0", "]", "=", "0", "\n\n", "mat", "[", "0", "]", "[", "1", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "1", "]", "=", "near2", "/", "(", "top", "-", "bottom", ")", "\n", "mat", "[", "2", "]", "[", "1", "]", "=", "(", "top", "+", "bottom", ")", "/", "(", "top", "-", "bottom", ")", "\n", "mat", "[", "3", "]", "[", "1", "]", "=", "0", "\n\n", "mat", "[", "0", "]", "[", "2", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "2", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "2", "]", "=", "-", "(", "zfar", "+", "znear", ")", "*", "ooFarNear", "\n", "mat", "[", "3", "]", "[", "2", "]", "=", "-", "2", "*", "zfar", "*", "znear", "*", "ooFarNear", "\n\n", "mat", "[", "0", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "3", "]", "=", "-", "1", "\n", "mat", "[", "3", "]", "[", "3", "]", "=", "0", "\n\n", "return", "mat", "\n", "}" ]
// AssignPerspectiveProjection assigns a perspective projection transformation.
[ "AssignPerspectiveProjection", "assigns", "a", "perspective", "projection", "transformation", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L509-L534
11,209
ungerik/go3d
mat4/mat4.go
AssignOrthogonalProjection
func (mat *T) AssignOrthogonalProjection(left, right, bottom, top, znear, zfar float32) *T { ooRightLeft := 1 / (right - left) ooTopBottom := 1 / (top - bottom) ooFarNear := 1 / (zfar - znear) mat[0][0] = 2 * ooRightLeft mat[1][0] = 0 mat[2][0] = 0 mat[3][0] = -(right + left) * ooRightLeft mat[0][1] = 0 mat[1][1] = 2 * ooTopBottom mat[2][1] = 0 mat[3][1] = -(top + bottom) * ooTopBottom mat[0][2] = 0 mat[1][2] = 0 mat[2][2] = -2 * ooFarNear mat[3][2] = -(zfar + znear) * ooFarNear mat[0][3] = 0 mat[1][3] = 0 mat[2][3] = 0 mat[3][3] = 1 return mat }
go
func (mat *T) AssignOrthogonalProjection(left, right, bottom, top, znear, zfar float32) *T { ooRightLeft := 1 / (right - left) ooTopBottom := 1 / (top - bottom) ooFarNear := 1 / (zfar - znear) mat[0][0] = 2 * ooRightLeft mat[1][0] = 0 mat[2][0] = 0 mat[3][0] = -(right + left) * ooRightLeft mat[0][1] = 0 mat[1][1] = 2 * ooTopBottom mat[2][1] = 0 mat[3][1] = -(top + bottom) * ooTopBottom mat[0][2] = 0 mat[1][2] = 0 mat[2][2] = -2 * ooFarNear mat[3][2] = -(zfar + znear) * ooFarNear mat[0][3] = 0 mat[1][3] = 0 mat[2][3] = 0 mat[3][3] = 1 return mat }
[ "func", "(", "mat", "*", "T", ")", "AssignOrthogonalProjection", "(", "left", ",", "right", ",", "bottom", ",", "top", ",", "znear", ",", "zfar", "float32", ")", "*", "T", "{", "ooRightLeft", ":=", "1", "/", "(", "right", "-", "left", ")", "\n", "ooTopBottom", ":=", "1", "/", "(", "top", "-", "bottom", ")", "\n", "ooFarNear", ":=", "1", "/", "(", "zfar", "-", "znear", ")", "\n\n", "mat", "[", "0", "]", "[", "0", "]", "=", "2", "*", "ooRightLeft", "\n", "mat", "[", "1", "]", "[", "0", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "0", "]", "=", "0", "\n", "mat", "[", "3", "]", "[", "0", "]", "=", "-", "(", "right", "+", "left", ")", "*", "ooRightLeft", "\n\n", "mat", "[", "0", "]", "[", "1", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "1", "]", "=", "2", "*", "ooTopBottom", "\n", "mat", "[", "2", "]", "[", "1", "]", "=", "0", "\n", "mat", "[", "3", "]", "[", "1", "]", "=", "-", "(", "top", "+", "bottom", ")", "*", "ooTopBottom", "\n\n", "mat", "[", "0", "]", "[", "2", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "2", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "2", "]", "=", "-", "2", "*", "ooFarNear", "\n", "mat", "[", "3", "]", "[", "2", "]", "=", "-", "(", "zfar", "+", "znear", ")", "*", "ooFarNear", "\n\n", "mat", "[", "0", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "3", "]", "[", "3", "]", "=", "1", "\n\n", "return", "mat", "\n", "}" ]
// AssignOrthogonalProjection assigns an orthogonal projection transformation.
[ "AssignOrthogonalProjection", "assigns", "an", "orthogonal", "projection", "transformation", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L537-L563
11,210
ungerik/go3d
mat4/mat4.go
Transpose3x3
func (mat *T) Transpose3x3() *T { swap(&mat[1][0], &mat[0][1]) swap(&mat[2][0], &mat[0][2]) swap(&mat[2][1], &mat[1][2]) return mat }
go
func (mat *T) Transpose3x3() *T { swap(&mat[1][0], &mat[0][1]) swap(&mat[2][0], &mat[0][2]) swap(&mat[2][1], &mat[1][2]) return mat }
[ "func", "(", "mat", "*", "T", ")", "Transpose3x3", "(", ")", "*", "T", "{", "swap", "(", "&", "mat", "[", "1", "]", "[", "0", "]", ",", "&", "mat", "[", "0", "]", "[", "1", "]", ")", "\n", "swap", "(", "&", "mat", "[", "2", "]", "[", "0", "]", ",", "&", "mat", "[", "0", "]", "[", "2", "]", ")", "\n", "swap", "(", "&", "mat", "[", "2", "]", "[", "1", "]", ",", "&", "mat", "[", "1", "]", "[", "2", "]", ")", "\n", "return", "mat", "\n", "}" ]
// Transpose3x3 transposes the 3x3 sub-matrix.
[ "Transpose3x3", "transposes", "the", "3x3", "sub", "-", "matrix", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L633-L638
11,211
ungerik/go3d
mat4/mat4.go
Adjugate
func (mat *T) Adjugate() *T { matOrig := *mat for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { // - 1 for odd i+j, 1 for even i+j sign := float32(((i+j)%2)*-2 + 1) mat[i][j] = matOrig.maskedBlock(i, j).Determinant() * sign } } return mat.Transpose() }
go
func (mat *T) Adjugate() *T { matOrig := *mat for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { // - 1 for odd i+j, 1 for even i+j sign := float32(((i+j)%2)*-2 + 1) mat[i][j] = matOrig.maskedBlock(i, j).Determinant() * sign } } return mat.Transpose() }
[ "func", "(", "mat", "*", "T", ")", "Adjugate", "(", ")", "*", "T", "{", "matOrig", ":=", "*", "mat", "\n", "for", "i", ":=", "0", ";", "i", "<", "4", ";", "i", "++", "{", "for", "j", ":=", "0", ";", "j", "<", "4", ";", "j", "++", "{", "// - 1 for odd i+j, 1 for even i+j", "sign", ":=", "float32", "(", "(", "(", "i", "+", "j", ")", "%", "2", ")", "*", "-", "2", "+", "1", ")", "\n", "mat", "[", "i", "]", "[", "j", "]", "=", "matOrig", ".", "maskedBlock", "(", "i", ",", "j", ")", ".", "Determinant", "(", ")", "*", "sign", "\n", "}", "\n", "}", "\n", "return", "mat", ".", "Transpose", "(", ")", "\n", "}" ]
// Adjugate computes the adjugate of this matrix and returns mat
[ "Adjugate", "computes", "the", "adjugate", "of", "this", "matrix", "and", "returns", "mat" ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L641-L651
11,212
ungerik/go3d
mat4/mat4.go
maskedBlock
func (mat *T) maskedBlock(blockI, blockJ int) *mat3.T { var m mat3.T m_i := 0 for i := 0; i < 4; i++ { if i == blockI { continue } m_j := 0 for j := 0; j < 4; j++ { if j == blockJ { continue } m[m_i][m_j] = mat[i][j] m_j++ } m_i++ } return &m }
go
func (mat *T) maskedBlock(blockI, blockJ int) *mat3.T { var m mat3.T m_i := 0 for i := 0; i < 4; i++ { if i == blockI { continue } m_j := 0 for j := 0; j < 4; j++ { if j == blockJ { continue } m[m_i][m_j] = mat[i][j] m_j++ } m_i++ } return &m }
[ "func", "(", "mat", "*", "T", ")", "maskedBlock", "(", "blockI", ",", "blockJ", "int", ")", "*", "mat3", ".", "T", "{", "var", "m", "mat3", ".", "T", "\n", "m_i", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "4", ";", "i", "++", "{", "if", "i", "==", "blockI", "{", "continue", "\n", "}", "\n", "m_j", ":=", "0", "\n", "for", "j", ":=", "0", ";", "j", "<", "4", ";", "j", "++", "{", "if", "j", "==", "blockJ", "{", "continue", "\n", "}", "\n", "m", "[", "m_i", "]", "[", "m_j", "]", "=", "mat", "[", "i", "]", "[", "j", "]", "\n", "m_j", "++", "\n", "}", "\n", "m_i", "++", "\n", "}", "\n", "return", "&", "m", "\n", "}" ]
// returns a 3x3 matrix without the i-th column and j-th row
[ "returns", "a", "3x3", "matrix", "without", "the", "i", "-", "th", "column", "and", "j", "-", "th", "row" ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L661-L679
11,213
ungerik/go3d
mat4/mat4.go
Invert
func (mat *T) Invert() *T { initialDet := mat.Determinant() mat.Adjugate() mat.Mul(1 / initialDet) return mat }
go
func (mat *T) Invert() *T { initialDet := mat.Determinant() mat.Adjugate() mat.Mul(1 / initialDet) return mat }
[ "func", "(", "mat", "*", "T", ")", "Invert", "(", ")", "*", "T", "{", "initialDet", ":=", "mat", ".", "Determinant", "(", ")", "\n", "mat", ".", "Adjugate", "(", ")", "\n", "mat", ".", "Mul", "(", "1", "/", "initialDet", ")", "\n", "return", "mat", "\n", "}" ]
// Inverts the given matrix. // Does not check if matrix is singular and may lead to strange results!
[ "Inverts", "the", "given", "matrix", ".", "Does", "not", "check", "if", "matrix", "is", "singular", "and", "may", "lead", "to", "strange", "results!" ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/mat4/mat4.go#L683-L688
11,214
ungerik/go3d
vec3/vec3.go
Scaled
func (vec *T) Scaled(f float32) T { return T{vec[0] * f, vec[1] * f, vec[2] * f} }
go
func (vec *T) Scaled(f float32) T { return T{vec[0] * f, vec[1] * f, vec[2] * f} }
[ "func", "(", "vec", "*", "T", ")", "Scaled", "(", "f", "float32", ")", "T", "{", "return", "T", "{", "vec", "[", "0", "]", "*", "f", ",", "vec", "[", "1", "]", "*", "f", ",", "vec", "[", "2", "]", "*", "f", "}", "\n", "}" ]
// Scaled returns a copy of vec with all elements multiplies by f.
[ "Scaled", "returns", "a", "copy", "of", "vec", "with", "all", "elements", "multiplies", "by", "f", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec3/vec3.go#L119-L121
11,215
ungerik/go3d
vec3/vec3.go
Abs
func (vec *T) Abs() *T { vec[0] = math.Abs(vec[0]) vec[1] = math.Abs(vec[1]) vec[2] = math.Abs(vec[2]) return vec }
go
func (vec *T) Abs() *T { vec[0] = math.Abs(vec[0]) vec[1] = math.Abs(vec[1]) vec[2] = math.Abs(vec[2]) return vec }
[ "func", "(", "vec", "*", "T", ")", "Abs", "(", ")", "*", "T", "{", "vec", "[", "0", "]", "=", "math", ".", "Abs", "(", "vec", "[", "0", "]", ")", "\n", "vec", "[", "1", "]", "=", "math", ".", "Abs", "(", "vec", "[", "1", "]", ")", "\n", "vec", "[", "2", "]", "=", "math", ".", "Abs", "(", "vec", "[", "2", "]", ")", "\n", "return", "vec", "\n", "}" ]
// Abs sets every component of the vector to its absolute value.
[ "Abs", "sets", "every", "component", "of", "the", "vector", "to", "its", "absolute", "value", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec3/vec3.go#L137-L142
11,216
ungerik/go3d
vec3/vec3.go
Absed
func (vec *T) Absed() T { return T{math.Abs(vec[0]), math.Abs(vec[1]), math.Abs(vec[2])} }
go
func (vec *T) Absed() T { return T{math.Abs(vec[0]), math.Abs(vec[1]), math.Abs(vec[2])} }
[ "func", "(", "vec", "*", "T", ")", "Absed", "(", ")", "T", "{", "return", "T", "{", "math", ".", "Abs", "(", "vec", "[", "0", "]", ")", ",", "math", ".", "Abs", "(", "vec", "[", "1", "]", ")", ",", "math", ".", "Abs", "(", "vec", "[", "2", "]", ")", "}", "\n", "}" ]
// Absed returns a copy of the vector containing the absolute values.
[ "Absed", "returns", "a", "copy", "of", "the", "vector", "containing", "the", "absolute", "values", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec3/vec3.go#L145-L147
11,217
ungerik/go3d
vec3/vec3.go
Mul
func (vec *T) Mul(v *T) *T { vec[0] *= v[0] vec[1] *= v[1] vec[2] *= v[2] return vec }
go
func (vec *T) Mul(v *T) *T { vec[0] *= v[0] vec[1] *= v[1] vec[2] *= v[2] return vec }
[ "func", "(", "vec", "*", "T", ")", "Mul", "(", "v", "*", "T", ")", "*", "T", "{", "vec", "[", "0", "]", "*=", "v", "[", "0", "]", "\n", "vec", "[", "1", "]", "*=", "v", "[", "1", "]", "\n", "vec", "[", "2", "]", "*=", "v", "[", "2", "]", "\n", "return", "vec", "\n", "}" ]
// Mul multiplies the components of the vector with the respective components of v.
[ "Mul", "multiplies", "the", "components", "of", "the", "vector", "with", "the", "respective", "components", "of", "v", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec3/vec3.go#L192-L197
11,218
ungerik/go3d
vec3/vec3.go
Mul
func Mul(a, b *T) T { return T{a[0] * b[0], a[1] * b[1], a[2] * b[2]} }
go
func Mul(a, b *T) T { return T{a[0] * b[0], a[1] * b[1], a[2] * b[2]} }
[ "func", "Mul", "(", "a", ",", "b", "*", "T", ")", "T", "{", "return", "T", "{", "a", "[", "0", "]", "*", "b", "[", "0", "]", ",", "a", "[", "1", "]", "*", "b", "[", "1", "]", ",", "a", "[", "2", "]", "*", "b", "[", "2", "]", "}", "\n", "}" ]
// Mul returns the component wise product of two vectors.
[ "Mul", "returns", "the", "component", "wise", "product", "of", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec3/vec3.go#L222-L224
11,219
ungerik/go3d
vec3/vec3.go
Min
func Min(a, b *T) T { min := *a if b[0] < min[0] { min[0] = b[0] } if b[1] < min[1] { min[1] = b[1] } if b[2] < min[2] { min[2] = b[2] } return min }
go
func Min(a, b *T) T { min := *a if b[0] < min[0] { min[0] = b[0] } if b[1] < min[1] { min[1] = b[1] } if b[2] < min[2] { min[2] = b[2] } return min }
[ "func", "Min", "(", "a", ",", "b", "*", "T", ")", "T", "{", "min", ":=", "*", "a", "\n", "if", "b", "[", "0", "]", "<", "min", "[", "0", "]", "{", "min", "[", "0", "]", "=", "b", "[", "0", "]", "\n", "}", "\n", "if", "b", "[", "1", "]", "<", "min", "[", "1", "]", "{", "min", "[", "1", "]", "=", "b", "[", "1", "]", "\n", "}", "\n", "if", "b", "[", "2", "]", "<", "min", "[", "2", "]", "{", "min", "[", "2", "]", "=", "b", "[", "2", "]", "\n", "}", "\n", "return", "min", "\n", "}" ]
// Min returns the component wise minimum of two vectors.
[ "Min", "returns", "the", "component", "wise", "minimum", "of", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec3/vec3.go#L253-L265
11,220
ungerik/go3d
vec3/vec3.go
Max
func Max(a, b *T) T { max := *a if b[0] > max[0] { max[0] = b[0] } if b[1] > max[1] { max[1] = b[1] } if b[2] > max[2] { max[2] = b[2] } return max }
go
func Max(a, b *T) T { max := *a if b[0] > max[0] { max[0] = b[0] } if b[1] > max[1] { max[1] = b[1] } if b[2] > max[2] { max[2] = b[2] } return max }
[ "func", "Max", "(", "a", ",", "b", "*", "T", ")", "T", "{", "max", ":=", "*", "a", "\n", "if", "b", "[", "0", "]", ">", "max", "[", "0", "]", "{", "max", "[", "0", "]", "=", "b", "[", "0", "]", "\n", "}", "\n", "if", "b", "[", "1", "]", ">", "max", "[", "1", "]", "{", "max", "[", "1", "]", "=", "b", "[", "1", "]", "\n", "}", "\n", "if", "b", "[", "2", "]", ">", "max", "[", "2", "]", "{", "max", "[", "2", "]", "=", "b", "[", "2", "]", "\n", "}", "\n", "return", "max", "\n", "}" ]
// Max returns the component wise maximum of two vectors.
[ "Max", "returns", "the", "component", "wise", "maximum", "of", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/vec3/vec3.go#L268-L280
11,221
ungerik/go3d
float64/vec3/vec3.go
Dot
func Dot(a, b *T) float64 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] }
go
func Dot(a, b *T) float64 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] }
[ "func", "Dot", "(", "a", ",", "b", "*", "T", ")", "float64", "{", "return", "a", "[", "0", "]", "*", "b", "[", "0", "]", "+", "a", "[", "1", "]", "*", "b", "[", "1", "]", "+", "a", "[", "2", "]", "*", "b", "[", "2", "]", "\n", "}" ]
// Dot returns the dot product of two vectors.
[ "Dot", "returns", "the", "dot", "product", "of", "two", "vectors", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec3/vec3.go#L226-L228
11,222
ungerik/go3d
float64/mat4/mat4.go
AssignZRotation
func (mat *T) AssignZRotation(angle float64) *T { cosine := math.Cos(angle) sine := math.Sin(angle) mat[0][0] = cosine mat[1][0] = -sine mat[2][0] = 0 mat[3][0] = 0 mat[0][1] = sine mat[1][1] = cosine mat[2][1] = 0 mat[3][1] = 0 mat[0][2] = 0 mat[1][2] = 0 mat[2][2] = 1 mat[3][2] = 0 mat[0][3] = 0 mat[1][3] = 0 mat[2][3] = 0 mat[3][3] = 1 return mat }
go
func (mat *T) AssignZRotation(angle float64) *T { cosine := math.Cos(angle) sine := math.Sin(angle) mat[0][0] = cosine mat[1][0] = -sine mat[2][0] = 0 mat[3][0] = 0 mat[0][1] = sine mat[1][1] = cosine mat[2][1] = 0 mat[3][1] = 0 mat[0][2] = 0 mat[1][2] = 0 mat[2][2] = 1 mat[3][2] = 0 mat[0][3] = 0 mat[1][3] = 0 mat[2][3] = 0 mat[3][3] = 1 return mat }
[ "func", "(", "mat", "*", "T", ")", "AssignZRotation", "(", "angle", "float64", ")", "*", "T", "{", "cosine", ":=", "math", ".", "Cos", "(", "angle", ")", "\n", "sine", ":=", "math", ".", "Sin", "(", "angle", ")", "\n\n", "mat", "[", "0", "]", "[", "0", "]", "=", "cosine", "\n", "mat", "[", "1", "]", "[", "0", "]", "=", "-", "sine", "\n", "mat", "[", "2", "]", "[", "0", "]", "=", "0", "\n", "mat", "[", "3", "]", "[", "0", "]", "=", "0", "\n\n", "mat", "[", "0", "]", "[", "1", "]", "=", "sine", "\n", "mat", "[", "1", "]", "[", "1", "]", "=", "cosine", "\n", "mat", "[", "2", "]", "[", "1", "]", "=", "0", "\n", "mat", "[", "3", "]", "[", "1", "]", "=", "0", "\n\n", "mat", "[", "0", "]", "[", "2", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "2", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "2", "]", "=", "1", "\n", "mat", "[", "3", "]", "[", "2", "]", "=", "0", "\n\n", "mat", "[", "0", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "1", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "2", "]", "[", "3", "]", "=", "0", "\n", "mat", "[", "3", "]", "[", "3", "]", "=", "1", "\n\n", "return", "mat", "\n", "}" ]
// AssignZRotation assigns a rotation around the z axis to the rotation part of the matrix and sets the remaining elements to their ident value.
[ "AssignZRotation", "assigns", "a", "rotation", "around", "the", "z", "axis", "to", "the", "rotation", "part", "of", "the", "matrix", "and", "sets", "the", "remaining", "elements", "to", "their", "ident", "value", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/mat4/mat4.go#L379-L404
11,223
ungerik/go3d
float64/vec3/box.go
ContainsPoint
func (box *Box) ContainsPoint(p *T) bool { return p[0] >= box.Min[0] && p[0] <= box.Max[0] && p[1] >= box.Min[1] && p[1] <= box.Max[1] && p[2] >= box.Min[2] && p[2] <= box.Max[2] }
go
func (box *Box) ContainsPoint(p *T) bool { return p[0] >= box.Min[0] && p[0] <= box.Max[0] && p[1] >= box.Min[1] && p[1] <= box.Max[1] && p[2] >= box.Min[2] && p[2] <= box.Max[2] }
[ "func", "(", "box", "*", "Box", ")", "ContainsPoint", "(", "p", "*", "T", ")", "bool", "{", "return", "p", "[", "0", "]", ">=", "box", ".", "Min", "[", "0", "]", "&&", "p", "[", "0", "]", "<=", "box", ".", "Max", "[", "0", "]", "&&", "p", "[", "1", "]", ">=", "box", ".", "Min", "[", "1", "]", "&&", "p", "[", "1", "]", "<=", "box", ".", "Max", "[", "1", "]", "&&", "p", "[", "2", "]", ">=", "box", ".", "Min", "[", "2", "]", "&&", "p", "[", "2", "]", "<=", "box", ".", "Max", "[", "2", "]", "\n", "}" ]
// ContainsPoint returns if a point is contained within the box.
[ "ContainsPoint", "returns", "if", "a", "point", "is", "contained", "within", "the", "box", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec3/box.go#L30-L34
11,224
ungerik/go3d
float64/vec3/box.go
Join
func (box *Box) Join(other *Box) { box.Min = Min(&box.Min, &other.Min) box.Max = Max(&box.Max, &other.Max) }
go
func (box *Box) Join(other *Box) { box.Min = Min(&box.Min, &other.Min) box.Max = Max(&box.Max, &other.Max) }
[ "func", "(", "box", "*", "Box", ")", "Join", "(", "other", "*", "Box", ")", "{", "box", ".", "Min", "=", "Min", "(", "&", "box", ".", "Min", ",", "&", "other", ".", "Min", ")", "\n", "box", ".", "Max", "=", "Max", "(", "&", "box", ".", "Max", ",", "&", "other", ".", "Max", ")", "\n", "}" ]
// Join enlarges this box to contain also the given box.
[ "Join", "enlarges", "this", "box", "to", "contain", "also", "the", "given", "box", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec3/box.go#L62-L65
11,225
ungerik/go3d
float64/vec3/box.go
Joined
func Joined(a, b *Box) Box { var joined Box joined.Min = Min(&a.Min, &b.Min) joined.Max = Max(&a.Max, &b.Max) return joined }
go
func Joined(a, b *Box) Box { var joined Box joined.Min = Min(&a.Min, &b.Min) joined.Max = Max(&a.Max, &b.Max) return joined }
[ "func", "Joined", "(", "a", ",", "b", "*", "Box", ")", "Box", "{", "var", "joined", "Box", "\n", "joined", ".", "Min", "=", "Min", "(", "&", "a", ".", "Min", ",", "&", "b", ".", "Min", ")", "\n", "joined", ".", "Max", "=", "Max", "(", "&", "a", ".", "Max", ",", "&", "b", ".", "Max", ")", "\n", "return", "joined", "\n", "}" ]
// Joined returns the minimal box containing both a and b.
[ "Joined", "returns", "the", "minimal", "box", "containing", "both", "a", "and", "b", "." ]
8e1a82526839422834f3d93efc409250b9a946d5
https://github.com/ungerik/go3d/blob/8e1a82526839422834f3d93efc409250b9a946d5/float64/vec3/box.go#L68-L73
11,226
BTBurke/caddy-jwt
flatten.go
Flatten
func Flatten(nested map[string]interface{}, prefix string, style SeparatorStyle) (map[string]interface{}, error) { flatmap := make(map[string]interface{}) err := flatten(true, flatmap, nested, prefix, style) if err != nil { return nil, err } return flatmap, nil }
go
func Flatten(nested map[string]interface{}, prefix string, style SeparatorStyle) (map[string]interface{}, error) { flatmap := make(map[string]interface{}) err := flatten(true, flatmap, nested, prefix, style) if err != nil { return nil, err } return flatmap, nil }
[ "func", "Flatten", "(", "nested", "map", "[", "string", "]", "interface", "{", "}", ",", "prefix", "string", ",", "style", "SeparatorStyle", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "flatmap", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n\n", "err", ":=", "flatten", "(", "true", ",", "flatmap", ",", "nested", ",", "prefix", ",", "style", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "flatmap", ",", "nil", "\n", "}" ]
// Flatten generates a flat map from a nested one. The original may include values of type map, slice and scalar, // but not struct. Keys in the flat map will be a compound of descending map keys and slice iterations. // The presentation of keys is set by style. A prefix is joined to each key.
[ "Flatten", "generates", "a", "flat", "map", "from", "a", "nested", "one", ".", "The", "original", "may", "include", "values", "of", "type", "map", "slice", "and", "scalar", "but", "not", "struct", ".", "Keys", "in", "the", "flat", "map", "will", "be", "a", "compound", "of", "descending", "map", "keys", "and", "slice", "iterations", ".", "The", "presentation", "of", "keys", "is", "set", "by", "style", ".", "A", "prefix", "is", "joined", "to", "each", "key", "." ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/flatten.go#L51-L60
11,227
BTBurke/caddy-jwt
config.go
Setup
func Setup(c *caddy.Controller) error { rules, err := parse(c) if err != nil { return err } c.OnStartup(func() error { fmt.Println("JWT middleware is initiated") return nil }) host := httpserver.GetConfig(c).Addr.Host httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { return &Auth{ Rules: rules, Next: next, Realm: host, } }) return nil }
go
func Setup(c *caddy.Controller) error { rules, err := parse(c) if err != nil { return err } c.OnStartup(func() error { fmt.Println("JWT middleware is initiated") return nil }) host := httpserver.GetConfig(c).Addr.Host httpserver.GetConfig(c).AddMiddleware(func(next httpserver.Handler) httpserver.Handler { return &Auth{ Rules: rules, Next: next, Realm: host, } }) return nil }
[ "func", "Setup", "(", "c", "*", "caddy", ".", "Controller", ")", "error", "{", "rules", ",", "err", ":=", "parse", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "OnStartup", "(", "func", "(", ")", "error", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", ")", "\n\n", "host", ":=", "httpserver", ".", "GetConfig", "(", "c", ")", ".", "Addr", ".", "Host", "\n\n", "httpserver", ".", "GetConfig", "(", "c", ")", ".", "AddMiddleware", "(", "func", "(", "next", "httpserver", ".", "Handler", ")", "httpserver", ".", "Handler", "{", "return", "&", "Auth", "{", "Rules", ":", "rules", ",", "Next", ":", "next", ",", "Realm", ":", "host", ",", "}", "\n", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// Setup is called by Caddy to parse the config block
[ "Setup", "is", "called", "by", "Caddy", "to", "parse", "the", "config", "block" ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/config.go#L67-L89
11,228
BTBurke/caddy-jwt
jwt.go
ExtractToken
func ExtractToken(tss []TokenSource, r *http.Request) (string, error) { effectiveTss := tss if len(effectiveTss) == 0 { // Defaults are applied here as this keeps the tests the cleanest. effectiveTss = DefaultTokenSources } for _, tss := range effectiveTss { token := tss.ExtractToken(r) if token != "" { return token, nil } } return "", fmt.Errorf("no token found") }
go
func ExtractToken(tss []TokenSource, r *http.Request) (string, error) { effectiveTss := tss if len(effectiveTss) == 0 { // Defaults are applied here as this keeps the tests the cleanest. effectiveTss = DefaultTokenSources } for _, tss := range effectiveTss { token := tss.ExtractToken(r) if token != "" { return token, nil } } return "", fmt.Errorf("no token found") }
[ "func", "ExtractToken", "(", "tss", "[", "]", "TokenSource", ",", "r", "*", "http", ".", "Request", ")", "(", "string", ",", "error", ")", "{", "effectiveTss", ":=", "tss", "\n", "if", "len", "(", "effectiveTss", ")", "==", "0", "{", "// Defaults are applied here as this keeps the tests the cleanest.", "effectiveTss", "=", "DefaultTokenSources", "\n", "}", "\n\n", "for", "_", ",", "tss", ":=", "range", "effectiveTss", "{", "token", ":=", "tss", ".", "ExtractToken", "(", "r", ")", "\n", "if", "token", "!=", "\"", "\"", "{", "return", "token", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// ExtractToken will find a JWT token in the token sources specified. // If tss is empty, the DefaultTokenSources are used.
[ "ExtractToken", "will", "find", "a", "JWT", "token", "in", "the", "token", "sources", "specified", ".", "If", "tss", "is", "empty", "the", "DefaultTokenSources", "are", "used", "." ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/jwt.go#L229-L245
11,229
BTBurke/caddy-jwt
jwt.go
handleUnauthorized
func handleUnauthorized(w http.ResponseWriter, r *http.Request, rule Rule, realm string) int { if rule.Redirect != "" { replacer := httpserver.NewReplacer(r, nil, "") http.Redirect(w, r, replacer.Replace(rule.Redirect), http.StatusSeeOther) return http.StatusSeeOther } w.Header().Add("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"%s\",error=\"invalid_token\"", realm)) return http.StatusUnauthorized }
go
func handleUnauthorized(w http.ResponseWriter, r *http.Request, rule Rule, realm string) int { if rule.Redirect != "" { replacer := httpserver.NewReplacer(r, nil, "") http.Redirect(w, r, replacer.Replace(rule.Redirect), http.StatusSeeOther) return http.StatusSeeOther } w.Header().Add("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"%s\",error=\"invalid_token\"", realm)) return http.StatusUnauthorized }
[ "func", "handleUnauthorized", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "rule", "Rule", ",", "realm", "string", ")", "int", "{", "if", "rule", ".", "Redirect", "!=", "\"", "\"", "{", "replacer", ":=", "httpserver", ".", "NewReplacer", "(", "r", ",", "nil", ",", "\"", "\"", ")", "\n", "http", ".", "Redirect", "(", "w", ",", "r", ",", "replacer", ".", "Replace", "(", "rule", ".", "Redirect", ")", ",", "http", ".", "StatusSeeOther", ")", "\n", "return", "http", ".", "StatusSeeOther", "\n", "}", "\n\n", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ",", "realm", ")", ")", "\n", "return", "http", ".", "StatusUnauthorized", "\n", "}" ]
// handleUnauthorized checks, which action should be performed if access was denied. // It returns the status code and writes the Location header in case of a redirect. // Possible caddy variables in the location value will be substituted.
[ "handleUnauthorized", "checks", "which", "action", "should", "be", "performed", "if", "access", "was", "denied", ".", "It", "returns", "the", "status", "code", "and", "writes", "the", "Location", "header", "in", "case", "of", "a", "redirect", ".", "Possible", "caddy", "variables", "in", "the", "location", "value", "will", "be", "substituted", "." ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/jwt.go#L268-L277
11,230
BTBurke/caddy-jwt
jwt.go
contains
func contains(list interface{}, value string) bool { switch l := list.(type) { case []interface{}: for _, v := range l { if v == value { return true } } } return false }
go
func contains(list interface{}, value string) bool { switch l := list.(type) { case []interface{}: for _, v := range l { if v == value { return true } } } return false }
[ "func", "contains", "(", "list", "interface", "{", "}", ",", "value", "string", ")", "bool", "{", "switch", "l", ":=", "list", ".", "(", "type", ")", "{", "case", "[", "]", "interface", "{", "}", ":", "for", "_", ",", "v", ":=", "range", "l", "{", "if", "v", "==", "value", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// contains checks weather list is a slice ans containts the // supplied string value.
[ "contains", "checks", "weather", "list", "is", "a", "slice", "ans", "containts", "the", "supplied", "string", "value", "." ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/jwt.go#L294-L304
11,231
BTBurke/caddy-jwt
keys.go
NewLazyPublicKeyFileBackend
func NewLazyPublicKeyFileBackend(value string) (*LazyPublicKeyBackend, error) { if len(value) <= 0 { return nil, fmt.Errorf("empty filename for public key provided") } return &LazyPublicKeyBackend{ filename: value, }, nil }
go
func NewLazyPublicKeyFileBackend(value string) (*LazyPublicKeyBackend, error) { if len(value) <= 0 { return nil, fmt.Errorf("empty filename for public key provided") } return &LazyPublicKeyBackend{ filename: value, }, nil }
[ "func", "NewLazyPublicKeyFileBackend", "(", "value", "string", ")", "(", "*", "LazyPublicKeyBackend", ",", "error", ")", "{", "if", "len", "(", "value", ")", "<=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "LazyPublicKeyBackend", "{", "filename", ":", "value", ",", "}", ",", "nil", "\n", "}" ]
// NewLazyPublicKeyFileBackend returns a new LazyPublicKeyBackend
[ "NewLazyPublicKeyFileBackend", "returns", "a", "new", "LazyPublicKeyBackend" ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/keys.go#L28-L35
11,232
BTBurke/caddy-jwt
keys.go
NewLazyHmacKeyBackend
func NewLazyHmacKeyBackend(value string) (*LazyHmacKeyBackend, error) { if len(value) <= 0 { return nil, fmt.Errorf("empty filename for secret provided") } return &LazyHmacKeyBackend{ filename: value, }, nil }
go
func NewLazyHmacKeyBackend(value string) (*LazyHmacKeyBackend, error) { if len(value) <= 0 { return nil, fmt.Errorf("empty filename for secret provided") } return &LazyHmacKeyBackend{ filename: value, }, nil }
[ "func", "NewLazyHmacKeyBackend", "(", "value", "string", ")", "(", "*", "LazyHmacKeyBackend", ",", "error", ")", "{", "if", "len", "(", "value", ")", "<=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "LazyHmacKeyBackend", "{", "filename", ":", "value", ",", "}", ",", "nil", "\n", "}" ]
// NewLazyHmacKeyBackend creates a new LazyHmacKeyBackend
[ "NewLazyHmacKeyBackend", "creates", "a", "new", "LazyHmacKeyBackend" ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/keys.go#L76-L83
11,233
BTBurke/caddy-jwt
keys.go
NewDefaultKeyBackends
func NewDefaultKeyBackends() ([]KeyBackend, error) { result := []KeyBackend{} secret := os.Getenv(ENV_SECRET) if len(secret) > 0 { result = append(result, &HmacKeyBackend{ secret: []byte(secret), }) } envPubKey := os.Getenv(ENV_PUBLIC_KEY) if len(envPubKey) > 0 { pub, err := ParsePublicKey([]byte(envPubKey)) if err != nil { return nil, fmt.Errorf("public key provided in environment variable %s could not be read: %v", ENV_PUBLIC_KEY, err) } result = append(result, &PublicKeyBackend{ publicKey: pub, }) } if len(result) == 0 { return nil, nil } if len(result) > 1 { return nil, fmt.Errorf("cannot configure both HMAC and RSA/ECDSA tokens on the same site") } return result, nil }
go
func NewDefaultKeyBackends() ([]KeyBackend, error) { result := []KeyBackend{} secret := os.Getenv(ENV_SECRET) if len(secret) > 0 { result = append(result, &HmacKeyBackend{ secret: []byte(secret), }) } envPubKey := os.Getenv(ENV_PUBLIC_KEY) if len(envPubKey) > 0 { pub, err := ParsePublicKey([]byte(envPubKey)) if err != nil { return nil, fmt.Errorf("public key provided in environment variable %s could not be read: %v", ENV_PUBLIC_KEY, err) } result = append(result, &PublicKeyBackend{ publicKey: pub, }) } if len(result) == 0 { return nil, nil } if len(result) > 1 { return nil, fmt.Errorf("cannot configure both HMAC and RSA/ECDSA tokens on the same site") } return result, nil }
[ "func", "NewDefaultKeyBackends", "(", ")", "(", "[", "]", "KeyBackend", ",", "error", ")", "{", "result", ":=", "[", "]", "KeyBackend", "{", "}", "\n\n", "secret", ":=", "os", ".", "Getenv", "(", "ENV_SECRET", ")", "\n", "if", "len", "(", "secret", ")", ">", "0", "{", "result", "=", "append", "(", "result", ",", "&", "HmacKeyBackend", "{", "secret", ":", "[", "]", "byte", "(", "secret", ")", ",", "}", ")", "\n", "}", "\n\n", "envPubKey", ":=", "os", ".", "Getenv", "(", "ENV_PUBLIC_KEY", ")", "\n", "if", "len", "(", "envPubKey", ")", ">", "0", "{", "pub", ",", "err", ":=", "ParsePublicKey", "(", "[", "]", "byte", "(", "envPubKey", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ENV_PUBLIC_KEY", ",", "err", ")", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "&", "PublicKeyBackend", "{", "publicKey", ":", "pub", ",", "}", ")", "\n", "}", "\n\n", "if", "len", "(", "result", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "len", "(", "result", ")", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "result", ",", "nil", "\n", "}" ]
// NewDefaultKeyBackends will read from the environment and return key backends based on // values from environment variables JWT_SECRET or JWT_PUBLIC_KEY. An error is returned if // the keys are not able to be parsed or if an inconsistent configuration is found.
[ "NewDefaultKeyBackends", "will", "read", "from", "the", "environment", "and", "return", "key", "backends", "based", "on", "values", "from", "environment", "variables", "JWT_SECRET", "or", "JWT_PUBLIC_KEY", ".", "An", "error", "is", "returned", "if", "the", "keys", "are", "not", "able", "to", "be", "parsed", "or", "if", "an", "inconsistent", "configuration", "is", "found", "." ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/keys.go#L119-L148
11,234
BTBurke/caddy-jwt
keys.go
ProvideKey
func (instance *PublicKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) { if err := AssertPublicKeyAndTokenCombination(instance.publicKey, token); err != nil { return nil, err } return instance.publicKey, nil }
go
func (instance *PublicKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) { if err := AssertPublicKeyAndTokenCombination(instance.publicKey, token); err != nil { return nil, err } return instance.publicKey, nil }
[ "func", "(", "instance", "*", "PublicKeyBackend", ")", "ProvideKey", "(", "token", "*", "jwt", ".", "Token", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "err", ":=", "AssertPublicKeyAndTokenCombination", "(", "instance", ".", "publicKey", ",", "token", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "instance", ".", "publicKey", ",", "nil", "\n", "}" ]
// ProvideKey will asssert that the token signing algorithm and the configured key match
[ "ProvideKey", "will", "asssert", "that", "the", "token", "signing", "algorithm", "and", "the", "configured", "key", "match" ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/keys.go#L156-L161
11,235
BTBurke/caddy-jwt
keys.go
ProvideKey
func (instance *HmacKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) { if err := AssertHmacToken(token); err != nil { return nil, err } return instance.secret, nil }
go
func (instance *HmacKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) { if err := AssertHmacToken(token); err != nil { return nil, err } return instance.secret, nil }
[ "func", "(", "instance", "*", "HmacKeyBackend", ")", "ProvideKey", "(", "token", "*", "jwt", ".", "Token", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "err", ":=", "AssertHmacToken", "(", "token", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "instance", ".", "secret", ",", "nil", "\n", "}" ]
// ProvideKey will assert that the token signing algorithm and the configured key match
[ "ProvideKey", "will", "assert", "that", "the", "token", "signing", "algorithm", "and", "the", "configured", "key", "match" ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/keys.go#L169-L174
11,236
BTBurke/caddy-jwt
keys.go
ProvideKey
func (instance *NoopKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) { return nil, fmt.Errorf("there is no keybackend available") }
go
func (instance *NoopKeyBackend) ProvideKey(token *jwt.Token) (interface{}, error) { return nil, fmt.Errorf("there is no keybackend available") }
[ "func", "(", "instance", "*", "NoopKeyBackend", ")", "ProvideKey", "(", "token", "*", "jwt", ".", "Token", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// ProvideKey always returns an error when no key signing method is specified
[ "ProvideKey", "always", "returns", "an", "error", "when", "no", "key", "signing", "method", "is", "specified" ]
fe13cd7e52f710341ebe9073d02d0f5531f3fc79
https://github.com/BTBurke/caddy-jwt/blob/fe13cd7e52f710341ebe9073d02d0f5531f3fc79/keys.go#L180-L182
11,237
sajari/regression
regression.go
DataPoint
func DataPoint(obs float64, vars []float64) *dataPoint { return &dataPoint{Observed: obs, Variables: vars} }
go
func DataPoint(obs float64, vars []float64) *dataPoint { return &dataPoint{Observed: obs, Variables: vars} }
[ "func", "DataPoint", "(", "obs", "float64", ",", "vars", "[", "]", "float64", ")", "*", "dataPoint", "{", "return", "&", "dataPoint", "{", "Observed", ":", "obs", ",", "Variables", ":", "vars", "}", "\n", "}" ]
// Creates a new dataPoint
[ "Creates", "a", "new", "dataPoint" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L49-L51
11,238
sajari/regression
regression.go
Predict
func (r *Regression) Predict(vars []float64) (float64, error) { if !r.initialised { return 0, errNotEnoughData } // apply any features crosses to vars for _, cross := range r.crosses { vars = append(vars, cross.Calculate(vars)...) } p := r.Coeff(0) for j := 1; j < len(r.data[0].Variables)+1; j++ { p += r.Coeff(j) * vars[j-1] } return p, nil }
go
func (r *Regression) Predict(vars []float64) (float64, error) { if !r.initialised { return 0, errNotEnoughData } // apply any features crosses to vars for _, cross := range r.crosses { vars = append(vars, cross.Calculate(vars)...) } p := r.Coeff(0) for j := 1; j < len(r.data[0].Variables)+1; j++ { p += r.Coeff(j) * vars[j-1] } return p, nil }
[ "func", "(", "r", "*", "Regression", ")", "Predict", "(", "vars", "[", "]", "float64", ")", "(", "float64", ",", "error", ")", "{", "if", "!", "r", ".", "initialised", "{", "return", "0", ",", "errNotEnoughData", "\n", "}", "\n\n", "// apply any features crosses to vars", "for", "_", ",", "cross", ":=", "range", "r", ".", "crosses", "{", "vars", "=", "append", "(", "vars", ",", "cross", ".", "Calculate", "(", "vars", ")", "...", ")", "\n", "}", "\n\n", "p", ":=", "r", ".", "Coeff", "(", "0", ")", "\n", "for", "j", ":=", "1", ";", "j", "<", "len", "(", "r", ".", "data", "[", "0", "]", ".", "Variables", ")", "+", "1", ";", "j", "++", "{", "p", "+=", "r", ".", "Coeff", "(", "j", ")", "*", "vars", "[", "j", "-", "1", "]", "\n", "}", "\n", "return", "p", ",", "nil", "\n", "}" ]
// Predict updates the "Predicted" value for the input dataPoint
[ "Predict", "updates", "the", "Predicted", "value", "for", "the", "input", "dataPoint" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L54-L69
11,239
sajari/regression
regression.go
SetVar
func (r *Regression) SetVar(i int, name string) { if len(r.names.vars) == 0 { r.names.vars = make(map[int]string, 5) } r.names.vars[i] = name }
go
func (r *Regression) SetVar(i int, name string) { if len(r.names.vars) == 0 { r.names.vars = make(map[int]string, 5) } r.names.vars[i] = name }
[ "func", "(", "r", "*", "Regression", ")", "SetVar", "(", "i", "int", ",", "name", "string", ")", "{", "if", "len", "(", "r", ".", "names", ".", "vars", ")", "==", "0", "{", "r", ".", "names", ".", "vars", "=", "make", "(", "map", "[", "int", "]", "string", ",", "5", ")", "\n", "}", "\n", "r", ".", "names", ".", "vars", "[", "i", "]", "=", "name", "\n", "}" ]
// Set the name of variable i
[ "Set", "the", "name", "of", "variable", "i" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L82-L87
11,240
sajari/regression
regression.go
GetVar
func (r *Regression) GetVar(i int) string { x := r.names.vars[i] if x == "" { s := []string{"X", strconv.Itoa(i)} return strings.Join(s, "") } return x }
go
func (r *Regression) GetVar(i int) string { x := r.names.vars[i] if x == "" { s := []string{"X", strconv.Itoa(i)} return strings.Join(s, "") } return x }
[ "func", "(", "r", "*", "Regression", ")", "GetVar", "(", "i", "int", ")", "string", "{", "x", ":=", "r", ".", "names", ".", "vars", "[", "i", "]", "\n", "if", "x", "==", "\"", "\"", "{", "s", ":=", "[", "]", "string", "{", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "i", ")", "}", "\n", "return", "strings", ".", "Join", "(", "s", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "x", "\n", "}" ]
// GetVar gets the name of variable i
[ "GetVar", "gets", "the", "name", "of", "variable", "i" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L90-L97
11,241
sajari/regression
regression.go
AddCross
func (r *Regression) AddCross(cross featureCross) { r.crosses = append(r.crosses, cross) }
go
func (r *Regression) AddCross(cross featureCross) { r.crosses = append(r.crosses, cross) }
[ "func", "(", "r", "*", "Regression", ")", "AddCross", "(", "cross", "featureCross", ")", "{", "r", ".", "crosses", "=", "append", "(", "r", ".", "crosses", ",", "cross", ")", "\n", "}" ]
// Registers a feature cross to be applied to the data points.
[ "Registers", "a", "feature", "cross", "to", "be", "applied", "to", "the", "data", "points", "." ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L100-L102
11,242
sajari/regression
regression.go
Train
func (r *Regression) Train(d ...*dataPoint) { r.data = append(r.data, d...) if len(r.data) > 2 { r.initialised = true } }
go
func (r *Regression) Train(d ...*dataPoint) { r.data = append(r.data, d...) if len(r.data) > 2 { r.initialised = true } }
[ "func", "(", "r", "*", "Regression", ")", "Train", "(", "d", "...", "*", "dataPoint", ")", "{", "r", ".", "data", "=", "append", "(", "r", ".", "data", ",", "d", "...", ")", "\n", "if", "len", "(", "r", ".", "data", ")", ">", "2", "{", "r", ".", "initialised", "=", "true", "\n", "}", "\n", "}" ]
// Train the regression with some data points
[ "Train", "the", "regression", "with", "some", "data", "points" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L105-L110
11,243
sajari/regression
regression.go
Run
func (r *Regression) Run() error { if !r.initialised { return errNotEnoughData } if r.hasRun { return errRegressionRun } //apply any features crosses r.applyCrosses() r.hasRun = true observations := len(r.data) numOfvars := len(r.data[0].Variables) if observations < (numOfvars + 1) { return errTooManyvars } // Create some blank variable space observed := mat.NewDense(observations, 1, nil) variables := mat.NewDense(observations, numOfvars+1, nil) for i := 0; i < observations; i++ { observed.Set(i, 0, r.data[i].Observed) for j := 0; j < numOfvars+1; j++ { if j == 0 { variables.Set(i, 0, 1) } else { variables.Set(i, j, r.data[i].Variables[j-1]) } } } // Now run the regression _, n := variables.Dims() // cols qr := new(mat.QR) qr.Factorize(variables) q := qr.QTo(nil) reg := qr.RTo(nil) qtr := q.T() qty := new(mat.Dense) qty.Mul(qtr, observed) c := make([]float64, n) for i := n - 1; i >= 0; i-- { c[i] = qty.At(i, 0) for j := i + 1; j < n; j++ { c[i] -= c[j] * reg.At(i, j) } c[i] /= reg.At(i, i) } // Output the regression results r.coeff = make(map[int]float64, numOfvars) for i, val := range c { r.coeff[i] = val if i == 0 { r.Formula = fmt.Sprintf("Predicted = %.2f", val) } else { r.Formula += fmt.Sprintf(" + %v*%.2f", r.GetVar(i-1), val) } } r.calcPredicted() r.calcVariance() r.calcR2() return nil }
go
func (r *Regression) Run() error { if !r.initialised { return errNotEnoughData } if r.hasRun { return errRegressionRun } //apply any features crosses r.applyCrosses() r.hasRun = true observations := len(r.data) numOfvars := len(r.data[0].Variables) if observations < (numOfvars + 1) { return errTooManyvars } // Create some blank variable space observed := mat.NewDense(observations, 1, nil) variables := mat.NewDense(observations, numOfvars+1, nil) for i := 0; i < observations; i++ { observed.Set(i, 0, r.data[i].Observed) for j := 0; j < numOfvars+1; j++ { if j == 0 { variables.Set(i, 0, 1) } else { variables.Set(i, j, r.data[i].Variables[j-1]) } } } // Now run the regression _, n := variables.Dims() // cols qr := new(mat.QR) qr.Factorize(variables) q := qr.QTo(nil) reg := qr.RTo(nil) qtr := q.T() qty := new(mat.Dense) qty.Mul(qtr, observed) c := make([]float64, n) for i := n - 1; i >= 0; i-- { c[i] = qty.At(i, 0) for j := i + 1; j < n; j++ { c[i] -= c[j] * reg.At(i, j) } c[i] /= reg.At(i, i) } // Output the regression results r.coeff = make(map[int]float64, numOfvars) for i, val := range c { r.coeff[i] = val if i == 0 { r.Formula = fmt.Sprintf("Predicted = %.2f", val) } else { r.Formula += fmt.Sprintf(" + %v*%.2f", r.GetVar(i-1), val) } } r.calcPredicted() r.calcVariance() r.calcR2() return nil }
[ "func", "(", "r", "*", "Regression", ")", "Run", "(", ")", "error", "{", "if", "!", "r", ".", "initialised", "{", "return", "errNotEnoughData", "\n", "}", "\n", "if", "r", ".", "hasRun", "{", "return", "errRegressionRun", "\n", "}", "\n\n", "//apply any features crosses", "r", ".", "applyCrosses", "(", ")", "\n", "r", ".", "hasRun", "=", "true", "\n\n", "observations", ":=", "len", "(", "r", ".", "data", ")", "\n", "numOfvars", ":=", "len", "(", "r", ".", "data", "[", "0", "]", ".", "Variables", ")", "\n\n", "if", "observations", "<", "(", "numOfvars", "+", "1", ")", "{", "return", "errTooManyvars", "\n", "}", "\n\n", "// Create some blank variable space", "observed", ":=", "mat", ".", "NewDense", "(", "observations", ",", "1", ",", "nil", ")", "\n", "variables", ":=", "mat", ".", "NewDense", "(", "observations", ",", "numOfvars", "+", "1", ",", "nil", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "observations", ";", "i", "++", "{", "observed", ".", "Set", "(", "i", ",", "0", ",", "r", ".", "data", "[", "i", "]", ".", "Observed", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "numOfvars", "+", "1", ";", "j", "++", "{", "if", "j", "==", "0", "{", "variables", ".", "Set", "(", "i", ",", "0", ",", "1", ")", "\n", "}", "else", "{", "variables", ".", "Set", "(", "i", ",", "j", ",", "r", ".", "data", "[", "i", "]", ".", "Variables", "[", "j", "-", "1", "]", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Now run the regression", "_", ",", "n", ":=", "variables", ".", "Dims", "(", ")", "// cols", "\n", "qr", ":=", "new", "(", "mat", ".", "QR", ")", "\n", "qr", ".", "Factorize", "(", "variables", ")", "\n", "q", ":=", "qr", ".", "QTo", "(", "nil", ")", "\n", "reg", ":=", "qr", ".", "RTo", "(", "nil", ")", "\n\n", "qtr", ":=", "q", ".", "T", "(", ")", "\n", "qty", ":=", "new", "(", "mat", ".", "Dense", ")", "\n", "qty", ".", "Mul", "(", "qtr", ",", "observed", ")", "\n\n", "c", ":=", "make", "(", "[", "]", "float64", ",", "n", ")", "\n", "for", "i", ":=", "n", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "c", "[", "i", "]", "=", "qty", ".", "At", "(", "i", ",", "0", ")", "\n", "for", "j", ":=", "i", "+", "1", ";", "j", "<", "n", ";", "j", "++", "{", "c", "[", "i", "]", "-=", "c", "[", "j", "]", "*", "reg", ".", "At", "(", "i", ",", "j", ")", "\n", "}", "\n", "c", "[", "i", "]", "/=", "reg", ".", "At", "(", "i", ",", "i", ")", "\n", "}", "\n\n", "// Output the regression results", "r", ".", "coeff", "=", "make", "(", "map", "[", "int", "]", "float64", ",", "numOfvars", ")", "\n", "for", "i", ",", "val", ":=", "range", "c", "{", "r", ".", "coeff", "[", "i", "]", "=", "val", "\n", "if", "i", "==", "0", "{", "r", ".", "Formula", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "val", ")", "\n", "}", "else", "{", "r", ".", "Formula", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "GetVar", "(", "i", "-", "1", ")", ",", "val", ")", "\n", "}", "\n", "}", "\n\n", "r", ".", "calcPredicted", "(", ")", "\n", "r", ".", "calcVariance", "(", ")", "\n", "r", ".", "calcR2", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Run the regression
[ "Run", "the", "regression" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L132-L201
11,244
sajari/regression
regression.go
Coeff
func (r *Regression) Coeff(i int) float64 { if len(r.coeff) == 0 { return 0 } return r.coeff[i] }
go
func (r *Regression) Coeff(i int) float64 { if len(r.coeff) == 0 { return 0 } return r.coeff[i] }
[ "func", "(", "r", "*", "Regression", ")", "Coeff", "(", "i", "int", ")", "float64", "{", "if", "len", "(", "r", ".", "coeff", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "r", ".", "coeff", "[", "i", "]", "\n", "}" ]
// Coeff returns the calculated coefficient for variable i
[ "Coeff", "returns", "the", "calculated", "coefficient", "for", "variable", "i" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L204-L209
11,245
sajari/regression
regression.go
String
func (d *dataPoint) String() string { str := fmt.Sprintf("%.2f", d.Observed) for _, v := range d.Variables { str += fmt.Sprintf("|\t%.2f", v) } return str }
go
func (d *dataPoint) String() string { str := fmt.Sprintf("%.2f", d.Observed) for _, v := range d.Variables { str += fmt.Sprintf("|\t%.2f", v) } return str }
[ "func", "(", "d", "*", "dataPoint", ")", "String", "(", ")", "string", "{", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ".", "Observed", ")", "\n", "for", "_", ",", "v", ":=", "range", "d", ".", "Variables", "{", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\"", ",", "v", ")", "\n", "}", "\n", "return", "str", "\n", "}" ]
// Display a dataPoint as a string
[ "Display", "a", "dataPoint", "as", "a", "string" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L258-L264
11,246
sajari/regression
regression.go
String
func (r *Regression) String() string { if !r.initialised { return errNotEnoughData.Error() } str := fmt.Sprintf("%v", r.GetObserved()) for i := 0; i < len(r.names.vars); i++ { str += fmt.Sprintf("|\t%v", r.GetVar(i)) } str += "\n" for _, d := range r.data { str += fmt.Sprintf("%v\n", d) } fmt.Println(r.calcResiduals()) str += fmt.Sprintf("\nN = %v\nVariance observed = %v\nVariance Predicted = %v", len(r.data), r.Varianceobserved, r.VariancePredicted) str += fmt.Sprintf("\nR2 = %v\n", r.R2) return str }
go
func (r *Regression) String() string { if !r.initialised { return errNotEnoughData.Error() } str := fmt.Sprintf("%v", r.GetObserved()) for i := 0; i < len(r.names.vars); i++ { str += fmt.Sprintf("|\t%v", r.GetVar(i)) } str += "\n" for _, d := range r.data { str += fmt.Sprintf("%v\n", d) } fmt.Println(r.calcResiduals()) str += fmt.Sprintf("\nN = %v\nVariance observed = %v\nVariance Predicted = %v", len(r.data), r.Varianceobserved, r.VariancePredicted) str += fmt.Sprintf("\nR2 = %v\n", r.R2) return str }
[ "func", "(", "r", "*", "Regression", ")", "String", "(", ")", "string", "{", "if", "!", "r", ".", "initialised", "{", "return", "errNotEnoughData", ".", "Error", "(", ")", "\n", "}", "\n", "str", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "GetObserved", "(", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "r", ".", "names", ".", "vars", ")", ";", "i", "++", "{", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\"", ",", "r", ".", "GetVar", "(", "i", ")", ")", "\n", "}", "\n", "str", "+=", "\"", "\\n", "\"", "\n", "for", "_", ",", "d", ":=", "range", "r", ".", "data", "{", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "d", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", "r", ".", "calcResiduals", "(", ")", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "len", "(", "r", ".", "data", ")", ",", "r", ".", "Varianceobserved", ",", "r", ".", "VariancePredicted", ")", "\n", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "r", ".", "R2", ")", "\n", "return", "str", "\n", "}" ]
// Display a regression as a string
[ "Display", "a", "regression", "as", "a", "string" ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/regression.go#L267-L283
11,247
sajari/regression
crosses.go
PowCross
func PowCross(i int, power float64) featureCross { return &functionalCross{ functionName: "^" + strconv.FormatFloat(power, 'f', -1, 64), boundVars: []int{i}, crossFn: func(vars []float64) []float64 { return []float64{math.Pow(vars[i], power)} }, } }
go
func PowCross(i int, power float64) featureCross { return &functionalCross{ functionName: "^" + strconv.FormatFloat(power, 'f', -1, 64), boundVars: []int{i}, crossFn: func(vars []float64) []float64 { return []float64{math.Pow(vars[i], power)} }, } }
[ "func", "PowCross", "(", "i", "int", ",", "power", "float64", ")", "featureCross", "{", "return", "&", "functionalCross", "{", "functionName", ":", "\"", "\"", "+", "strconv", ".", "FormatFloat", "(", "power", ",", "'f'", ",", "-", "1", ",", "64", ")", ",", "boundVars", ":", "[", "]", "int", "{", "i", "}", ",", "crossFn", ":", "func", "(", "vars", "[", "]", "float64", ")", "[", "]", "float64", "{", "return", "[", "]", "float64", "{", "math", ".", "Pow", "(", "vars", "[", "i", "]", ",", "power", ")", "}", "\n", "}", ",", "}", "\n", "}" ]
// Feature cross based on computing the power of an input.
[ "Feature", "cross", "based", "on", "computing", "the", "power", "of", "an", "input", "." ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/crosses.go#L33-L42
11,248
sajari/regression
crosses.go
MultiplierCross
func MultiplierCross(vars ...int) featureCross { name := "" for i, v := range vars { name += strconv.Itoa(v) if i < (len(vars) - 1) { name += "*" } } return &functionalCross{ functionName: name, boundVars: vars, crossFn: func(input []float64) []float64 { var output float64 = 1 for _, variableIndex := range vars { output *= input[variableIndex] } return []float64{output} }, } }
go
func MultiplierCross(vars ...int) featureCross { name := "" for i, v := range vars { name += strconv.Itoa(v) if i < (len(vars) - 1) { name += "*" } } return &functionalCross{ functionName: name, boundVars: vars, crossFn: func(input []float64) []float64 { var output float64 = 1 for _, variableIndex := range vars { output *= input[variableIndex] } return []float64{output} }, } }
[ "func", "MultiplierCross", "(", "vars", "...", "int", ")", "featureCross", "{", "name", ":=", "\"", "\"", "\n", "for", "i", ",", "v", ":=", "range", "vars", "{", "name", "+=", "strconv", ".", "Itoa", "(", "v", ")", "\n", "if", "i", "<", "(", "len", "(", "vars", ")", "-", "1", ")", "{", "name", "+=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "return", "&", "functionalCross", "{", "functionName", ":", "name", ",", "boundVars", ":", "vars", ",", "crossFn", ":", "func", "(", "input", "[", "]", "float64", ")", "[", "]", "float64", "{", "var", "output", "float64", "=", "1", "\n", "for", "_", ",", "variableIndex", ":=", "range", "vars", "{", "output", "*=", "input", "[", "variableIndex", "]", "\n", "}", "\n", "return", "[", "]", "float64", "{", "output", "}", "\n", "}", ",", "}", "\n", "}" ]
// Feature cross based on the multiplication of multiple inputs.
[ "Feature", "cross", "based", "on", "the", "multiplication", "of", "multiple", "inputs", "." ]
866afa2c981c68576c1483917177099f715e5b6d
https://github.com/sajari/regression/blob/866afa2c981c68576c1483917177099f715e5b6d/crosses.go#L45-L65
11,249
micro/go-web
options.go
MicroService
func MicroService(s micro.Service) Option { return func(o *Options) { o.Service = s } }
go
func MicroService(s micro.Service) Option { return func(o *Options) { o.Service = s } }
[ "func", "MicroService", "(", "s", "micro", ".", "Service", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "Service", "=", "s", "\n", "}", "\n", "}" ]
// MicroService sets the micro.Service used internally
[ "MicroService", "sets", "the", "micro", ".", "Service", "used", "internally" ]
caa2c0bcb37fdae1662b797ab54274902e29040e
https://github.com/micro/go-web/blob/caa2c0bcb37fdae1662b797ab54274902e29040e/options.go#L146-L150
11,250
micro/go-web
options.go
Flags
func Flags(flags ...cli.Flag) Option { return func(o *Options) { o.Flags = append(o.Flags, flags...) } }
go
func Flags(flags ...cli.Flag) Option { return func(o *Options) { o.Flags = append(o.Flags, flags...) } }
[ "func", "Flags", "(", "flags", "...", "cli", ".", "Flag", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "Flags", "=", "append", "(", "o", ".", "Flags", ",", "flags", "...", ")", "\n", "}", "\n", "}" ]
// Flags sets the command flags.
[ "Flags", "sets", "the", "command", "flags", "." ]
caa2c0bcb37fdae1662b797ab54274902e29040e
https://github.com/micro/go-web/blob/caa2c0bcb37fdae1662b797ab54274902e29040e/options.go#L153-L157
11,251
micro/go-web
options.go
Action
func Action(a func(*cli.Context)) Option { return func(o *Options) { o.Action = a } }
go
func Action(a func(*cli.Context)) Option { return func(o *Options) { o.Action = a } }
[ "func", "Action", "(", "a", "func", "(", "*", "cli", ".", "Context", ")", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "Action", "=", "a", "\n", "}", "\n", "}" ]
// Action sets the command action.
[ "Action", "sets", "the", "command", "action", "." ]
caa2c0bcb37fdae1662b797ab54274902e29040e
https://github.com/micro/go-web/blob/caa2c0bcb37fdae1662b797ab54274902e29040e/options.go#L160-L164
11,252
cloudfoundry/cf-acceptance-tests
windows/running_security_groups_win.go
warmUpRequest
func warmUpRequest(appName string) { Expect(helpers.CurlAppRoot(Config, appName)).To(ContainSubstring("hello i am nora running on")) }
go
func warmUpRequest(appName string) { Expect(helpers.CurlAppRoot(Config, appName)).To(ContainSubstring("hello i am nora running on")) }
[ "func", "warmUpRequest", "(", "appName", "string", ")", "{", "Expect", "(", "helpers", ".", "CurlAppRoot", "(", "Config", ",", "appName", ")", ")", ".", "To", "(", "ContainSubstring", "(", "\"", "\"", ")", ")", "\n", "}" ]
// When a .NET app running via HWC buildpack receives its first HTTP request, // it has to do just-in-time compilation, which can take ~10 seconds.
[ "When", "a", ".", "NET", "app", "running", "via", "HWC", "buildpack", "receives", "its", "first", "HTTP", "request", "it", "has", "to", "do", "just", "-", "in", "-", "time", "compilation", "which", "can", "take", "~10", "seconds", "." ]
47a27ae0b3f41d38a63793cf56f5df807661e18d
https://github.com/cloudfoundry/cf-acceptance-tests/blob/47a27ae0b3f41d38a63793cf56f5df807661e18d/windows/running_security_groups_win.go#L58-L60
11,253
cloudfoundry/cf-acceptance-tests
helpers/app_helpers/app_usage_events.go
UsageEventsAfterGuid
func UsageEventsAfterGuid(guid string) []AppUsageEvent { resources := make([]AppUsageEvent, 0) workflowhelpers.AsUser(TestSetup.AdminUserContext(), Config.DefaultTimeoutDuration(), func() { firstPageUrl := "/v2/app_usage_events?results-per-page=150&order-direction=desc&page=1&after_guid=" + guid url := firstPageUrl for { var response AppUsageEvents workflowhelpers.ApiRequest("GET", url, &response, Config.DefaultTimeoutDuration()) resources = append(resources, response.Resources...) if len(response.Resources) == 0 || response.NextUrl == "" { break } url = response.NextUrl } }) return resources }
go
func UsageEventsAfterGuid(guid string) []AppUsageEvent { resources := make([]AppUsageEvent, 0) workflowhelpers.AsUser(TestSetup.AdminUserContext(), Config.DefaultTimeoutDuration(), func() { firstPageUrl := "/v2/app_usage_events?results-per-page=150&order-direction=desc&page=1&after_guid=" + guid url := firstPageUrl for { var response AppUsageEvents workflowhelpers.ApiRequest("GET", url, &response, Config.DefaultTimeoutDuration()) resources = append(resources, response.Resources...) if len(response.Resources) == 0 || response.NextUrl == "" { break } url = response.NextUrl } }) return resources }
[ "func", "UsageEventsAfterGuid", "(", "guid", "string", ")", "[", "]", "AppUsageEvent", "{", "resources", ":=", "make", "(", "[", "]", "AppUsageEvent", ",", "0", ")", "\n\n", "workflowhelpers", ".", "AsUser", "(", "TestSetup", ".", "AdminUserContext", "(", ")", ",", "Config", ".", "DefaultTimeoutDuration", "(", ")", ",", "func", "(", ")", "{", "firstPageUrl", ":=", "\"", "\"", "+", "guid", "\n", "url", ":=", "firstPageUrl", "\n\n", "for", "{", "var", "response", "AppUsageEvents", "\n", "workflowhelpers", ".", "ApiRequest", "(", "\"", "\"", ",", "url", ",", "&", "response", ",", "Config", ".", "DefaultTimeoutDuration", "(", ")", ")", "\n\n", "resources", "=", "append", "(", "resources", ",", "response", ".", "Resources", "...", ")", "\n\n", "if", "len", "(", "response", ".", "Resources", ")", "==", "0", "||", "response", ".", "NextUrl", "==", "\"", "\"", "{", "break", "\n", "}", "\n\n", "url", "=", "response", ".", "NextUrl", "\n", "}", "\n", "}", ")", "\n\n", "return", "resources", "\n", "}" ]
// Returns all app usage events that occured since the given app usage event guid
[ "Returns", "all", "app", "usage", "events", "that", "occured", "since", "the", "given", "app", "usage", "event", "guid" ]
47a27ae0b3f41d38a63793cf56f5df807661e18d
https://github.com/cloudfoundry/cf-acceptance-tests/blob/47a27ae0b3f41d38a63793cf56f5df807661e18d/helpers/app_helpers/app_usage_events.go#L61-L83
11,254
abbot/go-http-auth
digest.go
Purge
func (da *DigestAuth) Purge(count int) { da.mutex.Lock() defer da.mutex.Unlock() entries := make([]digestCacheEntry, 0, len(da.clients)) for nonce, client := range da.clients { entries = append(entries, digestCacheEntry{nonce, client.lastSeen}) } cache := digestCache(entries) sort.Sort(cache) for _, client := range cache[:count] { delete(da.clients, client.nonce) } }
go
func (da *DigestAuth) Purge(count int) { da.mutex.Lock() defer da.mutex.Unlock() entries := make([]digestCacheEntry, 0, len(da.clients)) for nonce, client := range da.clients { entries = append(entries, digestCacheEntry{nonce, client.lastSeen}) } cache := digestCache(entries) sort.Sort(cache) for _, client := range cache[:count] { delete(da.clients, client.nonce) } }
[ "func", "(", "da", "*", "DigestAuth", ")", "Purge", "(", "count", "int", ")", "{", "da", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "da", ".", "mutex", ".", "Unlock", "(", ")", "\n", "entries", ":=", "make", "(", "[", "]", "digestCacheEntry", ",", "0", ",", "len", "(", "da", ".", "clients", ")", ")", "\n", "for", "nonce", ",", "client", ":=", "range", "da", ".", "clients", "{", "entries", "=", "append", "(", "entries", ",", "digestCacheEntry", "{", "nonce", ",", "client", ".", "lastSeen", "}", ")", "\n", "}", "\n", "cache", ":=", "digestCache", "(", "entries", ")", "\n", "sort", ".", "Sort", "(", "cache", ")", "\n", "for", "_", ",", "client", ":=", "range", "cache", "[", ":", "count", "]", "{", "delete", "(", "da", ".", "clients", ",", "client", ".", "nonce", ")", "\n", "}", "\n", "}" ]
// Purge removes count oldest entries from DigestAuth.clients
[ "Purge", "removes", "count", "oldest", "entries", "from", "DigestAuth", ".", "clients" ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/digest.go#L74-L86
11,255
abbot/go-http-auth
digest.go
DigestAuthParams
func DigestAuthParams(authorization string) map[string]string { s := strings.SplitN(authorization, " ", 2) if len(s) != 2 || s[0] != "Digest" { return nil } return ParsePairs(s[1]) }
go
func DigestAuthParams(authorization string) map[string]string { s := strings.SplitN(authorization, " ", 2) if len(s) != 2 || s[0] != "Digest" { return nil } return ParsePairs(s[1]) }
[ "func", "DigestAuthParams", "(", "authorization", "string", ")", "map", "[", "string", "]", "string", "{", "s", ":=", "strings", ".", "SplitN", "(", "authorization", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "s", ")", "!=", "2", "||", "s", "[", "0", "]", "!=", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "return", "ParsePairs", "(", "s", "[", "1", "]", ")", "\n", "}" ]
// DigestAuthParams parses Authorization header from the // http.Request. Returns a map of auth parameters or nil if the header // is not a valid parsable Digest auth header.
[ "DigestAuthParams", "parses", "Authorization", "header", "from", "the", "http", ".", "Request", ".", "Returns", "a", "map", "of", "auth", "parameters", "or", "nil", "if", "the", "header", "is", "not", "a", "valid", "parsable", "Digest", "auth", "header", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/digest.go#L117-L124
11,256
abbot/go-http-auth
digest.go
JustCheck
func (da *DigestAuth) JustCheck(wrapped http.HandlerFunc) http.HandlerFunc { return da.Wrap(func(w http.ResponseWriter, ar *AuthenticatedRequest) { ar.Header.Set(AuthUsernameHeader, ar.Username) wrapped(w, &ar.Request) }) }
go
func (da *DigestAuth) JustCheck(wrapped http.HandlerFunc) http.HandlerFunc { return da.Wrap(func(w http.ResponseWriter, ar *AuthenticatedRequest) { ar.Header.Set(AuthUsernameHeader, ar.Username) wrapped(w, &ar.Request) }) }
[ "func", "(", "da", "*", "DigestAuth", ")", "JustCheck", "(", "wrapped", "http", ".", "HandlerFunc", ")", "http", ".", "HandlerFunc", "{", "return", "da", ".", "Wrap", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "ar", "*", "AuthenticatedRequest", ")", "{", "ar", ".", "Header", ".", "Set", "(", "AuthUsernameHeader", ",", "ar", ".", "Username", ")", "\n", "wrapped", "(", "w", ",", "&", "ar", ".", "Request", ")", "\n", "}", ")", "\n", "}" ]
// JustCheck returns a new http.HandlerFunc, which requires // DigestAuth to successfully authenticate a user before calling // wrapped http.HandlerFunc. // // Authenticated Username is passed as an extra // X-Authenticated-Username header to the wrapped HandlerFunc.
[ "JustCheck", "returns", "a", "new", "http", ".", "HandlerFunc", "which", "requires", "DigestAuth", "to", "successfully", "authenticate", "a", "user", "before", "calling", "wrapped", "http", ".", "HandlerFunc", ".", "Authenticated", "Username", "is", "passed", "as", "an", "extra", "X", "-", "Authenticated", "-", "Username", "header", "to", "the", "wrapped", "HandlerFunc", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/digest.go#L244-L249
11,257
abbot/go-http-auth
digest.go
NewDigestAuthenticator
func NewDigestAuthenticator(realm string, secrets SecretProvider) *DigestAuth { da := &DigestAuth{ Opaque: RandomKey(), Realm: realm, Secrets: secrets, PlainTextSecrets: false, ClientCacheSize: DefaultClientCacheSize, ClientCacheTolerance: DefaultClientCacheTolerance, clients: map[string]*digestClient{}} return da }
go
func NewDigestAuthenticator(realm string, secrets SecretProvider) *DigestAuth { da := &DigestAuth{ Opaque: RandomKey(), Realm: realm, Secrets: secrets, PlainTextSecrets: false, ClientCacheSize: DefaultClientCacheSize, ClientCacheTolerance: DefaultClientCacheTolerance, clients: map[string]*digestClient{}} return da }
[ "func", "NewDigestAuthenticator", "(", "realm", "string", ",", "secrets", "SecretProvider", ")", "*", "DigestAuth", "{", "da", ":=", "&", "DigestAuth", "{", "Opaque", ":", "RandomKey", "(", ")", ",", "Realm", ":", "realm", ",", "Secrets", ":", "secrets", ",", "PlainTextSecrets", ":", "false", ",", "ClientCacheSize", ":", "DefaultClientCacheSize", ",", "ClientCacheTolerance", ":", "DefaultClientCacheTolerance", ",", "clients", ":", "map", "[", "string", "]", "*", "digestClient", "{", "}", "}", "\n", "return", "da", "\n", "}" ]
// NewDigestAuthenticator generates a new DigestAuth object
[ "NewDigestAuthenticator", "generates", "a", "new", "DigestAuth", "object" ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/digest.go#L275-L285
11,258
abbot/go-http-auth
auth.go
UpdateHeaders
func (i *Info) UpdateHeaders(headers http.Header) { if i == nil { return } for k, values := range i.ResponseHeaders { for _, v := range values { headers.Add(k, v) } } }
go
func (i *Info) UpdateHeaders(headers http.Header) { if i == nil { return } for k, values := range i.ResponseHeaders { for _, v := range values { headers.Add(k, v) } } }
[ "func", "(", "i", "*", "Info", ")", "UpdateHeaders", "(", "headers", "http", ".", "Header", ")", "{", "if", "i", "==", "nil", "{", "return", "\n", "}", "\n", "for", "k", ",", "values", ":=", "range", "i", ".", "ResponseHeaders", "{", "for", "_", ",", "v", ":=", "range", "values", "{", "headers", ".", "Add", "(", "k", ",", "v", ")", "\n", "}", "\n", "}", "\n", "}" ]
// UpdateHeaders updates headers with this Info's ResponseHeaders. It is // safe to call this function on nil Info.
[ "UpdateHeaders", "updates", "headers", "with", "this", "Info", "s", "ResponseHeaders", ".", "It", "is", "safe", "to", "call", "this", "function", "on", "nil", "Info", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/auth.go#L56-L65
11,259
abbot/go-http-auth
auth.go
FromContext
func FromContext(ctx context.Context) *Info { info, ok := ctx.Value(infoKey).(*Info) if !ok { return nil } return info }
go
func FromContext(ctx context.Context) *Info { info, ok := ctx.Value(infoKey).(*Info) if !ok { return nil } return info }
[ "func", "FromContext", "(", "ctx", "context", ".", "Context", ")", "*", "Info", "{", "info", ",", "ok", ":=", "ctx", ".", "Value", "(", "infoKey", ")", ".", "(", "*", "Info", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "return", "info", "\n", "}" ]
// FromContext returns authentication information from the context or // nil if no such information present.
[ "FromContext", "returns", "authentication", "information", "from", "the", "context", "or", "nil", "if", "no", "such", "information", "present", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/auth.go#L90-L96
11,260
abbot/go-http-auth
auth.go
JustCheck
func JustCheck(auth AuthenticatorInterface, wrapped http.HandlerFunc) http.HandlerFunc { return auth.Wrap(func(w http.ResponseWriter, ar *AuthenticatedRequest) { ar.Header.Set(AuthUsernameHeader, ar.Username) wrapped(w, &ar.Request) }) }
go
func JustCheck(auth AuthenticatorInterface, wrapped http.HandlerFunc) http.HandlerFunc { return auth.Wrap(func(w http.ResponseWriter, ar *AuthenticatedRequest) { ar.Header.Set(AuthUsernameHeader, ar.Username) wrapped(w, &ar.Request) }) }
[ "func", "JustCheck", "(", "auth", "AuthenticatorInterface", ",", "wrapped", "http", ".", "HandlerFunc", ")", "http", ".", "HandlerFunc", "{", "return", "auth", ".", "Wrap", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "ar", "*", "AuthenticatedRequest", ")", "{", "ar", ".", "Header", ".", "Set", "(", "AuthUsernameHeader", ",", "ar", ".", "Username", ")", "\n", "wrapped", "(", "w", ",", "&", "ar", ".", "Request", ")", "\n", "}", ")", "\n", "}" ]
// JustCheck returns a new http.HandlerFunc, which requires // authenticator to successfully authenticate a user before calling // wrapped http.HandlerFunc.
[ "JustCheck", "returns", "a", "new", "http", ".", "HandlerFunc", "which", "requires", "authenticator", "to", "successfully", "authenticate", "a", "user", "before", "calling", "wrapped", "http", ".", "HandlerFunc", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/auth.go#L106-L111
11,261
abbot/go-http-auth
misc.go
RandomKey
func RandomKey() string { k := make([]byte, 12) for bytes := 0; bytes < len(k); { n, err := rand.Read(k[bytes:]) if err != nil { panic("rand.Read() failed") } bytes += n } return base64.StdEncoding.EncodeToString(k) }
go
func RandomKey() string { k := make([]byte, 12) for bytes := 0; bytes < len(k); { n, err := rand.Read(k[bytes:]) if err != nil { panic("rand.Read() failed") } bytes += n } return base64.StdEncoding.EncodeToString(k) }
[ "func", "RandomKey", "(", ")", "string", "{", "k", ":=", "make", "(", "[", "]", "byte", ",", "12", ")", "\n", "for", "bytes", ":=", "0", ";", "bytes", "<", "len", "(", "k", ")", ";", "{", "n", ",", "err", ":=", "rand", ".", "Read", "(", "k", "[", "bytes", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "bytes", "+=", "n", "\n", "}", "\n", "return", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "k", ")", "\n", "}" ]
// RandomKey returns a random 16-byte base64 alphabet string
[ "RandomKey", "returns", "a", "random", "16", "-", "byte", "base64", "alphabet", "string" ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/misc.go#L14-L24
11,262
abbot/go-http-auth
basic.go
CheckSecret
func CheckSecret(password, secret string) bool { compare := compareFuncs[0].compare for _, cmp := range compareFuncs[1:] { if strings.HasPrefix(secret, cmp.prefix) { compare = cmp.compare break } } return compare([]byte(secret), []byte(password)) == nil }
go
func CheckSecret(password, secret string) bool { compare := compareFuncs[0].compare for _, cmp := range compareFuncs[1:] { if strings.HasPrefix(secret, cmp.prefix) { compare = cmp.compare break } } return compare([]byte(secret), []byte(password)) == nil }
[ "func", "CheckSecret", "(", "password", ",", "secret", "string", ")", "bool", "{", "compare", ":=", "compareFuncs", "[", "0", "]", ".", "compare", "\n", "for", "_", ",", "cmp", ":=", "range", "compareFuncs", "[", "1", ":", "]", "{", "if", "strings", ".", "HasPrefix", "(", "secret", ",", "cmp", ".", "prefix", ")", "{", "compare", "=", "cmp", ".", "compare", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "compare", "(", "[", "]", "byte", "(", "secret", ")", ",", "[", "]", "byte", "(", "password", ")", ")", "==", "nil", "\n", "}" ]
// CheckSecret returns true if the password matches the encrypted // secret.
[ "CheckSecret", "returns", "true", "if", "the", "password", "matches", "the", "encrypted", "secret", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/basic.go#L86-L95
11,263
abbot/go-http-auth
users.go
HtdigestFileProvider
func HtdigestFileProvider(filename string) SecretProvider { hf := &HtdigestFile{File: File{Path: filename}} hf.Reload = func() { reloadHTDigest(hf) } return func(user, realm string) string { hf.ReloadIfNeeded() hf.mu.RLock() defer hf.mu.RUnlock() _, exists := hf.Users[realm] if !exists { return "" } digest, exists := hf.Users[realm][user] if !exists { return "" } return digest } }
go
func HtdigestFileProvider(filename string) SecretProvider { hf := &HtdigestFile{File: File{Path: filename}} hf.Reload = func() { reloadHTDigest(hf) } return func(user, realm string) string { hf.ReloadIfNeeded() hf.mu.RLock() defer hf.mu.RUnlock() _, exists := hf.Users[realm] if !exists { return "" } digest, exists := hf.Users[realm][user] if !exists { return "" } return digest } }
[ "func", "HtdigestFileProvider", "(", "filename", "string", ")", "SecretProvider", "{", "hf", ":=", "&", "HtdigestFile", "{", "File", ":", "File", "{", "Path", ":", "filename", "}", "}", "\n", "hf", ".", "Reload", "=", "func", "(", ")", "{", "reloadHTDigest", "(", "hf", ")", "}", "\n", "return", "func", "(", "user", ",", "realm", "string", ")", "string", "{", "hf", ".", "ReloadIfNeeded", "(", ")", "\n", "hf", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "hf", ".", "mu", ".", "RUnlock", "(", ")", "\n", "_", ",", "exists", ":=", "hf", ".", "Users", "[", "realm", "]", "\n", "if", "!", "exists", "{", "return", "\"", "\"", "\n", "}", "\n", "digest", ",", "exists", ":=", "hf", ".", "Users", "[", "realm", "]", "[", "user", "]", "\n", "if", "!", "exists", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "digest", "\n", "}", "\n", "}" ]
// HtdigestFileProvider is a SecretProvider implementation based on // htdigest-formated files. It will automatically reload htdigest file // on changes. It panics on syntax errors in htdigest files.
[ "HtdigestFileProvider", "is", "a", "SecretProvider", "implementation", "based", "on", "htdigest", "-", "formated", "files", ".", "It", "will", "automatically", "reload", "htdigest", "file", "on", "changes", ".", "It", "panics", "on", "syntax", "errors", "in", "htdigest", "files", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/users.go#L82-L99
11,264
abbot/go-http-auth
users.go
HtpasswdFileProvider
func HtpasswdFileProvider(filename string) SecretProvider { h := &HtpasswdFile{File: File{Path: filename}} h.Reload = func() { reloadHTPasswd(h) } return func(user, realm string) string { h.ReloadIfNeeded() h.mu.RLock() password, exists := h.Users[user] h.mu.RUnlock() if !exists { return "" } return password } }
go
func HtpasswdFileProvider(filename string) SecretProvider { h := &HtpasswdFile{File: File{Path: filename}} h.Reload = func() { reloadHTPasswd(h) } return func(user, realm string) string { h.ReloadIfNeeded() h.mu.RLock() password, exists := h.Users[user] h.mu.RUnlock() if !exists { return "" } return password } }
[ "func", "HtpasswdFileProvider", "(", "filename", "string", ")", "SecretProvider", "{", "h", ":=", "&", "HtpasswdFile", "{", "File", ":", "File", "{", "Path", ":", "filename", "}", "}", "\n", "h", ".", "Reload", "=", "func", "(", ")", "{", "reloadHTPasswd", "(", "h", ")", "}", "\n", "return", "func", "(", "user", ",", "realm", "string", ")", "string", "{", "h", ".", "ReloadIfNeeded", "(", ")", "\n", "h", ".", "mu", ".", "RLock", "(", ")", "\n", "password", ",", "exists", ":=", "h", ".", "Users", "[", "user", "]", "\n", "h", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "!", "exists", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "password", "\n", "}", "\n", "}" ]
// HtpasswdFileProvider is a SecretProvider implementation based on // htpasswd-formated files. It will automatically reload htpasswd file // on changes. It panics on syntax errors in htpasswd files. Realm // argument of the SecretProvider is ignored.
[ "HtpasswdFileProvider", "is", "a", "SecretProvider", "implementation", "based", "on", "htpasswd", "-", "formated", "files", ".", "It", "will", "automatically", "reload", "htpasswd", "file", "on", "changes", ".", "It", "panics", "on", "syntax", "errors", "in", "htpasswd", "files", ".", "Realm", "argument", "of", "the", "SecretProvider", "is", "ignored", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/users.go#L138-L151
11,265
abbot/go-http-auth
md5crypt.go
MD5Crypt
func MD5Crypt(password, salt, magic []byte) []byte { d := md5.New() d.Write(password) d.Write(magic) d.Write(salt) d2 := md5.New() d2.Write(password) d2.Write(salt) d2.Write(password) for i, mixin := 0, d2.Sum(nil); i < len(password); i++ { d.Write([]byte{mixin[i%16]}) } for i := len(password); i != 0; i >>= 1 { if i&1 == 0 { d.Write([]byte{password[0]}) } else { d.Write([]byte{0}) } } final := d.Sum(nil) for i := 0; i < 1000; i++ { d2 := md5.New() if i&1 == 0 { d2.Write(final) } else { d2.Write(password) } if i%3 != 0 { d2.Write(salt) } if i%7 != 0 { d2.Write(password) } if i&1 == 0 { d2.Write(password) } else { d2.Write(final) } final = d2.Sum(nil) } result := make([]byte, 0, 22) v := uint(0) bits := uint(0) for _, i := range md5CryptSwaps { v |= (uint(final[i]) << bits) for bits = bits + 8; bits > 6; bits -= 6 { result = append(result, itoa64[v&0x3f]) v >>= 6 } } result = append(result, itoa64[v&0x3f]) return append(append(append(magic, salt...), '$'), result...) }
go
func MD5Crypt(password, salt, magic []byte) []byte { d := md5.New() d.Write(password) d.Write(magic) d.Write(salt) d2 := md5.New() d2.Write(password) d2.Write(salt) d2.Write(password) for i, mixin := 0, d2.Sum(nil); i < len(password); i++ { d.Write([]byte{mixin[i%16]}) } for i := len(password); i != 0; i >>= 1 { if i&1 == 0 { d.Write([]byte{password[0]}) } else { d.Write([]byte{0}) } } final := d.Sum(nil) for i := 0; i < 1000; i++ { d2 := md5.New() if i&1 == 0 { d2.Write(final) } else { d2.Write(password) } if i%3 != 0 { d2.Write(salt) } if i%7 != 0 { d2.Write(password) } if i&1 == 0 { d2.Write(password) } else { d2.Write(final) } final = d2.Sum(nil) } result := make([]byte, 0, 22) v := uint(0) bits := uint(0) for _, i := range md5CryptSwaps { v |= (uint(final[i]) << bits) for bits = bits + 8; bits > 6; bits -= 6 { result = append(result, itoa64[v&0x3f]) v >>= 6 } } result = append(result, itoa64[v&0x3f]) return append(append(append(magic, salt...), '$'), result...) }
[ "func", "MD5Crypt", "(", "password", ",", "salt", ",", "magic", "[", "]", "byte", ")", "[", "]", "byte", "{", "d", ":=", "md5", ".", "New", "(", ")", "\n\n", "d", ".", "Write", "(", "password", ")", "\n", "d", ".", "Write", "(", "magic", ")", "\n", "d", ".", "Write", "(", "salt", ")", "\n\n", "d2", ":=", "md5", ".", "New", "(", ")", "\n", "d2", ".", "Write", "(", "password", ")", "\n", "d2", ".", "Write", "(", "salt", ")", "\n", "d2", ".", "Write", "(", "password", ")", "\n\n", "for", "i", ",", "mixin", ":=", "0", ",", "d2", ".", "Sum", "(", "nil", ")", ";", "i", "<", "len", "(", "password", ")", ";", "i", "++", "{", "d", ".", "Write", "(", "[", "]", "byte", "{", "mixin", "[", "i", "%", "16", "]", "}", ")", "\n", "}", "\n\n", "for", "i", ":=", "len", "(", "password", ")", ";", "i", "!=", "0", ";", "i", ">>=", "1", "{", "if", "i", "&", "1", "==", "0", "{", "d", ".", "Write", "(", "[", "]", "byte", "{", "password", "[", "0", "]", "}", ")", "\n", "}", "else", "{", "d", ".", "Write", "(", "[", "]", "byte", "{", "0", "}", ")", "\n", "}", "\n", "}", "\n\n", "final", ":=", "d", ".", "Sum", "(", "nil", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "1000", ";", "i", "++", "{", "d2", ":=", "md5", ".", "New", "(", ")", "\n", "if", "i", "&", "1", "==", "0", "{", "d2", ".", "Write", "(", "final", ")", "\n", "}", "else", "{", "d2", ".", "Write", "(", "password", ")", "\n", "}", "\n\n", "if", "i", "%", "3", "!=", "0", "{", "d2", ".", "Write", "(", "salt", ")", "\n", "}", "\n\n", "if", "i", "%", "7", "!=", "0", "{", "d2", ".", "Write", "(", "password", ")", "\n", "}", "\n\n", "if", "i", "&", "1", "==", "0", "{", "d2", ".", "Write", "(", "password", ")", "\n", "}", "else", "{", "d2", ".", "Write", "(", "final", ")", "\n", "}", "\n", "final", "=", "d2", ".", "Sum", "(", "nil", ")", "\n", "}", "\n\n", "result", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "22", ")", "\n", "v", ":=", "uint", "(", "0", ")", "\n", "bits", ":=", "uint", "(", "0", ")", "\n", "for", "_", ",", "i", ":=", "range", "md5CryptSwaps", "{", "v", "|=", "(", "uint", "(", "final", "[", "i", "]", ")", "<<", "bits", ")", "\n", "for", "bits", "=", "bits", "+", "8", ";", "bits", ">", "6", ";", "bits", "-=", "6", "{", "result", "=", "append", "(", "result", ",", "itoa64", "[", "v", "&", "0x3f", "]", ")", "\n", "v", ">>=", "6", "\n", "}", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "itoa64", "[", "v", "&", "0x3f", "]", ")", "\n\n", "return", "append", "(", "append", "(", "append", "(", "magic", ",", "salt", "...", ")", ",", "'$'", ")", ",", "result", "...", ")", "\n", "}" ]
// MD5Crypt is the MD5 password crypt implementation.
[ "MD5Crypt", "is", "the", "MD5", "password", "crypt", "implementation", "." ]
860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86
https://github.com/abbot/go-http-auth/blob/860ed7f246ff5abfdbd5c7ce618fd37b49fd3d86/md5crypt.go#L10-L73
11,266
prometheus/prom2json
prom2json.go
NewFamily
func NewFamily(dtoMF *dto.MetricFamily) *Family { mf := &Family{ //Time: time.Now(), Name: dtoMF.GetName(), Help: dtoMF.GetHelp(), Type: dtoMF.GetType().String(), Metrics: make([]interface{}, len(dtoMF.Metric)), } for i, m := range dtoMF.Metric { if dtoMF.GetType() == dto.MetricType_SUMMARY { mf.Metrics[i] = Summary{ Labels: makeLabels(m), Quantiles: makeQuantiles(m), Count: fmt.Sprint(m.GetSummary().GetSampleCount()), Sum: fmt.Sprint(m.GetSummary().GetSampleSum()), } } else if dtoMF.GetType() == dto.MetricType_HISTOGRAM { mf.Metrics[i] = Histogram{ Labels: makeLabels(m), Buckets: makeBuckets(m), Count: fmt.Sprint(m.GetHistogram().GetSampleCount()), Sum: fmt.Sprint(m.GetSummary().GetSampleSum()), } } else { mf.Metrics[i] = Metric{ Labels: makeLabels(m), Value: fmt.Sprint(getValue(m)), } } } return mf }
go
func NewFamily(dtoMF *dto.MetricFamily) *Family { mf := &Family{ //Time: time.Now(), Name: dtoMF.GetName(), Help: dtoMF.GetHelp(), Type: dtoMF.GetType().String(), Metrics: make([]interface{}, len(dtoMF.Metric)), } for i, m := range dtoMF.Metric { if dtoMF.GetType() == dto.MetricType_SUMMARY { mf.Metrics[i] = Summary{ Labels: makeLabels(m), Quantiles: makeQuantiles(m), Count: fmt.Sprint(m.GetSummary().GetSampleCount()), Sum: fmt.Sprint(m.GetSummary().GetSampleSum()), } } else if dtoMF.GetType() == dto.MetricType_HISTOGRAM { mf.Metrics[i] = Histogram{ Labels: makeLabels(m), Buckets: makeBuckets(m), Count: fmt.Sprint(m.GetHistogram().GetSampleCount()), Sum: fmt.Sprint(m.GetSummary().GetSampleSum()), } } else { mf.Metrics[i] = Metric{ Labels: makeLabels(m), Value: fmt.Sprint(getValue(m)), } } } return mf }
[ "func", "NewFamily", "(", "dtoMF", "*", "dto", ".", "MetricFamily", ")", "*", "Family", "{", "mf", ":=", "&", "Family", "{", "//Time: time.Now(),", "Name", ":", "dtoMF", ".", "GetName", "(", ")", ",", "Help", ":", "dtoMF", ".", "GetHelp", "(", ")", ",", "Type", ":", "dtoMF", ".", "GetType", "(", ")", ".", "String", "(", ")", ",", "Metrics", ":", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "dtoMF", ".", "Metric", ")", ")", ",", "}", "\n", "for", "i", ",", "m", ":=", "range", "dtoMF", ".", "Metric", "{", "if", "dtoMF", ".", "GetType", "(", ")", "==", "dto", ".", "MetricType_SUMMARY", "{", "mf", ".", "Metrics", "[", "i", "]", "=", "Summary", "{", "Labels", ":", "makeLabels", "(", "m", ")", ",", "Quantiles", ":", "makeQuantiles", "(", "m", ")", ",", "Count", ":", "fmt", ".", "Sprint", "(", "m", ".", "GetSummary", "(", ")", ".", "GetSampleCount", "(", ")", ")", ",", "Sum", ":", "fmt", ".", "Sprint", "(", "m", ".", "GetSummary", "(", ")", ".", "GetSampleSum", "(", ")", ")", ",", "}", "\n", "}", "else", "if", "dtoMF", ".", "GetType", "(", ")", "==", "dto", ".", "MetricType_HISTOGRAM", "{", "mf", ".", "Metrics", "[", "i", "]", "=", "Histogram", "{", "Labels", ":", "makeLabels", "(", "m", ")", ",", "Buckets", ":", "makeBuckets", "(", "m", ")", ",", "Count", ":", "fmt", ".", "Sprint", "(", "m", ".", "GetHistogram", "(", ")", ".", "GetSampleCount", "(", ")", ")", ",", "Sum", ":", "fmt", ".", "Sprint", "(", "m", ".", "GetSummary", "(", ")", ".", "GetSampleSum", "(", ")", ")", ",", "}", "\n", "}", "else", "{", "mf", ".", "Metrics", "[", "i", "]", "=", "Metric", "{", "Labels", ":", "makeLabels", "(", "m", ")", ",", "Value", ":", "fmt", ".", "Sprint", "(", "getValue", "(", "m", ")", ")", ",", "}", "\n", "}", "\n", "}", "\n", "return", "mf", "\n", "}" ]
// NewFamily consumes a MetricFamily and transforms it to the local Family type.
[ "NewFamily", "consumes", "a", "MetricFamily", "and", "transforms", "it", "to", "the", "local", "Family", "type", "." ]
9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03
https://github.com/prometheus/prom2json/blob/9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03/prom2json.go#L63-L94
11,267
prometheus/prom2json
prom2json.go
FetchMetricFamilies
func FetchMetricFamilies( url string, ch chan<- *dto.MetricFamily, certificate string, key string, skipServerCertCheck bool, ) error { var transport *http.Transport if certificate != "" && key != "" { cert, err := tls.LoadX509KeyPair(certificate, key) if err != nil { return err } tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, InsecureSkipVerify: skipServerCertCheck, } tlsConfig.BuildNameToCertificate() transport = &http.Transport{TLSClientConfig: tlsConfig} } else { transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: skipServerCertCheck}, } } client := &http.Client{Transport: transport} return decodeContent(client, url, ch) }
go
func FetchMetricFamilies( url string, ch chan<- *dto.MetricFamily, certificate string, key string, skipServerCertCheck bool, ) error { var transport *http.Transport if certificate != "" && key != "" { cert, err := tls.LoadX509KeyPair(certificate, key) if err != nil { return err } tlsConfig := &tls.Config{ Certificates: []tls.Certificate{cert}, InsecureSkipVerify: skipServerCertCheck, } tlsConfig.BuildNameToCertificate() transport = &http.Transport{TLSClientConfig: tlsConfig} } else { transport = &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: skipServerCertCheck}, } } client := &http.Client{Transport: transport} return decodeContent(client, url, ch) }
[ "func", "FetchMetricFamilies", "(", "url", "string", ",", "ch", "chan", "<-", "*", "dto", ".", "MetricFamily", ",", "certificate", "string", ",", "key", "string", ",", "skipServerCertCheck", "bool", ",", ")", "error", "{", "var", "transport", "*", "http", ".", "Transport", "\n", "if", "certificate", "!=", "\"", "\"", "&&", "key", "!=", "\"", "\"", "{", "cert", ",", "err", ":=", "tls", ".", "LoadX509KeyPair", "(", "certificate", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tlsConfig", ":=", "&", "tls", ".", "Config", "{", "Certificates", ":", "[", "]", "tls", ".", "Certificate", "{", "cert", "}", ",", "InsecureSkipVerify", ":", "skipServerCertCheck", ",", "}", "\n", "tlsConfig", ".", "BuildNameToCertificate", "(", ")", "\n", "transport", "=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "tlsConfig", "}", "\n", "}", "else", "{", "transport", "=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "skipServerCertCheck", "}", ",", "}", "\n", "}", "\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "transport", "}", "\n", "return", "decodeContent", "(", "client", ",", "url", ",", "ch", ")", "\n", "}" ]
// FetchMetricFamilies retrieves metrics from the provided URL, decodes them // into MetricFamily proto messages, and sends them to the provided channel. It // returns after all MetricFamilies have been sent.
[ "FetchMetricFamilies", "retrieves", "metrics", "from", "the", "provided", "URL", "decodes", "them", "into", "MetricFamily", "proto", "messages", "and", "sends", "them", "to", "the", "provided", "channel", ".", "It", "returns", "after", "all", "MetricFamilies", "have", "been", "sent", "." ]
9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03
https://github.com/prometheus/prom2json/blob/9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03/prom2json.go#L136-L160
11,268
prometheus/prom2json
prom2json.go
ParseResponse
func ParseResponse(resp *http.Response, ch chan<- *dto.MetricFamily) error { mediatype, params, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) if err == nil && mediatype == "application/vnd.google.protobuf" && params["encoding"] == "delimited" && params["proto"] == "io.prometheus.client.MetricFamily" { defer close(ch) for { mf := &dto.MetricFamily{} if _, err = pbutil.ReadDelimited(resp.Body, mf); err != nil { if err == io.EOF { break } return fmt.Errorf("reading metric family protocol buffer failed: %v", err) } ch <- mf } } else { if err := ParseReader(resp.Body, ch); err != nil { return err } } return nil }
go
func ParseResponse(resp *http.Response, ch chan<- *dto.MetricFamily) error { mediatype, params, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) if err == nil && mediatype == "application/vnd.google.protobuf" && params["encoding"] == "delimited" && params["proto"] == "io.prometheus.client.MetricFamily" { defer close(ch) for { mf := &dto.MetricFamily{} if _, err = pbutil.ReadDelimited(resp.Body, mf); err != nil { if err == io.EOF { break } return fmt.Errorf("reading metric family protocol buffer failed: %v", err) } ch <- mf } } else { if err := ParseReader(resp.Body, ch); err != nil { return err } } return nil }
[ "func", "ParseResponse", "(", "resp", "*", "http", ".", "Response", ",", "ch", "chan", "<-", "*", "dto", ".", "MetricFamily", ")", "error", "{", "mediatype", ",", "params", ",", "err", ":=", "mime", ".", "ParseMediaType", "(", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "==", "nil", "&&", "mediatype", "==", "\"", "\"", "&&", "params", "[", "\"", "\"", "]", "==", "\"", "\"", "&&", "params", "[", "\"", "\"", "]", "==", "\"", "\"", "{", "defer", "close", "(", "ch", ")", "\n", "for", "{", "mf", ":=", "&", "dto", ".", "MetricFamily", "{", "}", "\n", "if", "_", ",", "err", "=", "pbutil", ".", "ReadDelimited", "(", "resp", ".", "Body", ",", "mf", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "ch", "<-", "mf", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "ParseReader", "(", "resp", ".", "Body", ",", "ch", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParseResponse consumes an http.Response and pushes it to the MetricFamily // channel. It returns when all MetricFamilies are parsed and put on the // channel.
[ "ParseResponse", "consumes", "an", "http", ".", "Response", "and", "pushes", "it", "to", "the", "MetricFamily", "channel", ".", "It", "returns", "when", "all", "MetricFamilies", "are", "parsed", "and", "put", "on", "the", "channel", "." ]
9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03
https://github.com/prometheus/prom2json/blob/9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03/prom2json.go#L182-L204
11,269
prometheus/prom2json
prom2json.go
ParseReader
func ParseReader(in io.Reader, ch chan<- *dto.MetricFamily) error { defer close(ch) // We could do further content-type checks here, but the // fallback for now will anyway be the text format // version 0.0.4, so just go for it and see if it works. var parser expfmt.TextParser metricFamilies, err := parser.TextToMetricFamilies(in) if err != nil { return fmt.Errorf("reading text format failed: %v", err) } for _, mf := range metricFamilies { ch <- mf } return nil }
go
func ParseReader(in io.Reader, ch chan<- *dto.MetricFamily) error { defer close(ch) // We could do further content-type checks here, but the // fallback for now will anyway be the text format // version 0.0.4, so just go for it and see if it works. var parser expfmt.TextParser metricFamilies, err := parser.TextToMetricFamilies(in) if err != nil { return fmt.Errorf("reading text format failed: %v", err) } for _, mf := range metricFamilies { ch <- mf } return nil }
[ "func", "ParseReader", "(", "in", "io", ".", "Reader", ",", "ch", "chan", "<-", "*", "dto", ".", "MetricFamily", ")", "error", "{", "defer", "close", "(", "ch", ")", "\n", "// We could do further content-type checks here, but the", "// fallback for now will anyway be the text format", "// version 0.0.4, so just go for it and see if it works.", "var", "parser", "expfmt", ".", "TextParser", "\n", "metricFamilies", ",", "err", ":=", "parser", ".", "TextToMetricFamilies", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "mf", ":=", "range", "metricFamilies", "{", "ch", "<-", "mf", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParseReader consumes an io.Reader and pushes it to the MetricFamily // channel. It returns when all MetricFamilies are parsed and put on the // channel.
[ "ParseReader", "consumes", "an", "io", ".", "Reader", "and", "pushes", "it", "to", "the", "MetricFamily", "channel", ".", "It", "returns", "when", "all", "MetricFamilies", "are", "parsed", "and", "put", "on", "the", "channel", "." ]
9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03
https://github.com/prometheus/prom2json/blob/9fdfeb5d1bb50cd6b17cd81cb3dd2b98c68b9b03/prom2json.go#L209-L223
11,270
AliyunContainerService/docker-machine-driver-aliyunecs
aliyunecs/ecs.go
fixRoutingRules
func (d *Driver) fixRoutingRules(sshClient ssh.Client) { output, err := sshClient.Output("route del -net 172.16.0.0/12") log.Debugf("%s | Delete route command err, output: %v: %s", d.MachineName, err, output) output, err = sshClient.Output("if [ -e /etc/network/interfaces ]; then sed -i '/^up route add -net 172.16.0.0 netmask 255.240.0.0 gw/d' /etc/network/interfaces; fi") log.Debugf("%s | Fix route in /etc/network/interfaces command err, output: %v: %s", d.MachineName, err, output) output, err = sshClient.Output("if [ -e /etc/sysconfig/network-scripts/route-eth0 ]; then sed -i '/^172.16.0.0\\/12 via /d' /etc/sysconfig/network-scripts/route-eth0; fi") log.Debugf("%s | Fix route in /etc/sysconfig/network-scripts/route-eth0 command err, output: %v: %s", d.MachineName, err, output) }
go
func (d *Driver) fixRoutingRules(sshClient ssh.Client) { output, err := sshClient.Output("route del -net 172.16.0.0/12") log.Debugf("%s | Delete route command err, output: %v: %s", d.MachineName, err, output) output, err = sshClient.Output("if [ -e /etc/network/interfaces ]; then sed -i '/^up route add -net 172.16.0.0 netmask 255.240.0.0 gw/d' /etc/network/interfaces; fi") log.Debugf("%s | Fix route in /etc/network/interfaces command err, output: %v: %s", d.MachineName, err, output) output, err = sshClient.Output("if [ -e /etc/sysconfig/network-scripts/route-eth0 ]; then sed -i '/^172.16.0.0\\/12 via /d' /etc/sysconfig/network-scripts/route-eth0; fi") log.Debugf("%s | Fix route in /etc/sysconfig/network-scripts/route-eth0 command err, output: %v: %s", d.MachineName, err, output) }
[ "func", "(", "d", "*", "Driver", ")", "fixRoutingRules", "(", "sshClient", "ssh", ".", "Client", ")", "{", "output", ",", "err", ":=", "sshClient", ".", "Output", "(", "\"", "\"", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "d", ".", "MachineName", ",", "err", ",", "output", ")", "\n\n", "output", ",", "err", "=", "sshClient", ".", "Output", "(", "\"", "\"", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "d", ".", "MachineName", ",", "err", ",", "output", ")", "\n\n", "output", ",", "err", "=", "sshClient", ".", "Output", "(", "\"", "\\\\", "\"", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "d", ".", "MachineName", ",", "err", ",", "output", ")", "\n", "}" ]
// Fix the routing rules
[ "Fix", "the", "routing", "rules" ]
5cfb48294846d7966eeb00fc9148d6be74bc2c45
https://github.com/AliyunContainerService/docker-machine-driver-aliyunecs/blob/5cfb48294846d7966eeb00fc9148d6be74bc2c45/aliyunecs/ecs.go#L1352-L1361
11,271
AliyunContainerService/docker-machine-driver-aliyunecs
aliyunecs/ecs.go
autoFdisk
func (d *Driver) autoFdisk(sshClient ssh.Client) { s := autoFdiskScriptExt4 if d.DiskFS == "xfs" { s = autoFdiskScriptXFS } script := fmt.Sprintf("cat > ~/machine_autofdisk.sh <<MACHINE_EOF\n%s\nMACHINE_EOF\n", s) output, err := sshClient.Output(script) output, err = sshClient.Output("bash ~/machine_autofdisk.sh") log.Debugf("%s | Auto Fdisk command err, output: %v: %s", d.MachineName, err, output) }
go
func (d *Driver) autoFdisk(sshClient ssh.Client) { s := autoFdiskScriptExt4 if d.DiskFS == "xfs" { s = autoFdiskScriptXFS } script := fmt.Sprintf("cat > ~/machine_autofdisk.sh <<MACHINE_EOF\n%s\nMACHINE_EOF\n", s) output, err := sshClient.Output(script) output, err = sshClient.Output("bash ~/machine_autofdisk.sh") log.Debugf("%s | Auto Fdisk command err, output: %v: %s", d.MachineName, err, output) }
[ "func", "(", "d", "*", "Driver", ")", "autoFdisk", "(", "sshClient", "ssh", ".", "Client", ")", "{", "s", ":=", "autoFdiskScriptExt4", "\n\n", "if", "d", ".", "DiskFS", "==", "\"", "\"", "{", "s", "=", "autoFdiskScriptXFS", "\n", "}", "\n\n", "script", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "s", ")", "\n", "output", ",", "err", ":=", "sshClient", ".", "Output", "(", "script", ")", "\n", "output", ",", "err", "=", "sshClient", ".", "Output", "(", "\"", "\"", ")", "\n", "log", ".", "Debugf", "(", "\"", "\"", ",", "d", ".", "MachineName", ",", "err", ",", "output", ")", "\n", "}" ]
// Mount the addtional disk
[ "Mount", "the", "addtional", "disk" ]
5cfb48294846d7966eeb00fc9148d6be74bc2c45
https://github.com/AliyunContainerService/docker-machine-driver-aliyunecs/blob/5cfb48294846d7966eeb00fc9148d6be74bc2c45/aliyunecs/ecs.go#L1364-L1376
11,272
docker/libchan
spdy/streams.go
NewSpdyStreamProvider
func NewSpdyStreamProvider(conn net.Conn, server bool) (StreamProvider, error) { spdyConn, spdyErr := spdystream.NewConnection(conn, server) if spdyErr != nil { return nil, spdyErr } provider := &spdyStreamProvider{ conn: spdyConn, closeChan: make(chan struct{}), listenChan: make(chan *spdyStream), } go spdyConn.Serve(provider.newStreamHandler) return provider, nil }
go
func NewSpdyStreamProvider(conn net.Conn, server bool) (StreamProvider, error) { spdyConn, spdyErr := spdystream.NewConnection(conn, server) if spdyErr != nil { return nil, spdyErr } provider := &spdyStreamProvider{ conn: spdyConn, closeChan: make(chan struct{}), listenChan: make(chan *spdyStream), } go spdyConn.Serve(provider.newStreamHandler) return provider, nil }
[ "func", "NewSpdyStreamProvider", "(", "conn", "net", ".", "Conn", ",", "server", "bool", ")", "(", "StreamProvider", ",", "error", ")", "{", "spdyConn", ",", "spdyErr", ":=", "spdystream", ".", "NewConnection", "(", "conn", ",", "server", ")", "\n", "if", "spdyErr", "!=", "nil", "{", "return", "nil", ",", "spdyErr", "\n", "}", "\n", "provider", ":=", "&", "spdyStreamProvider", "{", "conn", ":", "spdyConn", ",", "closeChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "listenChan", ":", "make", "(", "chan", "*", "spdyStream", ")", ",", "}", "\n", "go", "spdyConn", ".", "Serve", "(", "provider", ".", "newStreamHandler", ")", "\n\n", "return", "provider", ",", "nil", "\n", "}" ]
// NewSpdyStreamProvider creates a stream provider by starting a spdy // session on the given connection. The server argument is used to // determine whether the spdy connection is the client or server side.
[ "NewSpdyStreamProvider", "creates", "a", "stream", "provider", "by", "starting", "a", "spdy", "session", "on", "the", "given", "connection", ".", "The", "server", "argument", "is", "used", "to", "determine", "whether", "the", "spdy", "connection", "is", "the", "client", "or", "server", "side", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/streams.go#L55-L68
11,273
docker/libchan
spdy/session.go
NewTransport
func NewTransport(provider StreamProvider) libchan.Transport { session := &Transport{ provider: provider, referenceCounter: 1, receiverChan: make(chan *receiver), streamC: sync.NewCond(new(sync.Mutex)), streams: make(map[uint64]*stream), } go session.handleStreams() return session }
go
func NewTransport(provider StreamProvider) libchan.Transport { session := &Transport{ provider: provider, referenceCounter: 1, receiverChan: make(chan *receiver), streamC: sync.NewCond(new(sync.Mutex)), streams: make(map[uint64]*stream), } go session.handleStreams() return session }
[ "func", "NewTransport", "(", "provider", "StreamProvider", ")", "libchan", ".", "Transport", "{", "session", ":=", "&", "Transport", "{", "provider", ":", "provider", ",", "referenceCounter", ":", "1", ",", "receiverChan", ":", "make", "(", "chan", "*", "receiver", ")", ",", "streamC", ":", "sync", ".", "NewCond", "(", "new", "(", "sync", ".", "Mutex", ")", ")", ",", "streams", ":", "make", "(", "map", "[", "uint64", "]", "*", "stream", ")", ",", "}", "\n\n", "go", "session", ".", "handleStreams", "(", ")", "\n\n", "return", "session", "\n", "}" ]
// NewTransport returns an object implementing the // libchan Transport interface using a stream provider.
[ "NewTransport", "returns", "an", "object", "implementing", "the", "libchan", "Transport", "interface", "using", "a", "stream", "provider", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/session.go#L62-L74
11,274
docker/libchan
spdy/session.go
NewSendChannel
func (s *Transport) NewSendChannel() (libchan.Sender, error) { stream, err := s.createSubStream(0) if err != nil { return nil, err } // TODO check synchronized return &sender{stream: stream}, nil }
go
func (s *Transport) NewSendChannel() (libchan.Sender, error) { stream, err := s.createSubStream(0) if err != nil { return nil, err } // TODO check synchronized return &sender{stream: stream}, nil }
[ "func", "(", "s", "*", "Transport", ")", "NewSendChannel", "(", ")", "(", "libchan", ".", "Sender", ",", "error", ")", "{", "stream", ",", "err", ":=", "s", ".", "createSubStream", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// TODO check synchronized", "return", "&", "sender", "{", "stream", ":", "stream", "}", ",", "nil", "\n", "}" ]
// NewSendChannel creates and returns a new send channel. The receive // end will get picked up on the remote end through the remote calling // WaitReceiveChannel.
[ "NewSendChannel", "creates", "and", "returns", "a", "new", "send", "channel", ".", "The", "receive", "end", "will", "get", "picked", "up", "on", "the", "remote", "end", "through", "the", "remote", "calling", "WaitReceiveChannel", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/session.go#L177-L185
11,275
docker/libchan
spdy/session.go
WaitReceiveChannel
func (s *Transport) WaitReceiveChannel() (libchan.Receiver, error) { r, ok := <-s.receiverChan if !ok { return nil, io.EOF } return r, nil }
go
func (s *Transport) WaitReceiveChannel() (libchan.Receiver, error) { r, ok := <-s.receiverChan if !ok { return nil, io.EOF } return r, nil }
[ "func", "(", "s", "*", "Transport", ")", "WaitReceiveChannel", "(", ")", "(", "libchan", ".", "Receiver", ",", "error", ")", "{", "r", ",", "ok", ":=", "<-", "s", ".", "receiverChan", "\n", "if", "!", "ok", "{", "return", "nil", ",", "io", ".", "EOF", "\n", "}", "\n\n", "return", "r", ",", "nil", "\n", "}" ]
// WaitReceiveChannel waits for a new channel be created by a remote // call to NewSendChannel.
[ "WaitReceiveChannel", "waits", "for", "a", "new", "channel", "be", "created", "by", "a", "remote", "call", "to", "NewSendChannel", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/session.go#L189-L196
11,276
docker/libchan
spdy/session.go
CreateNestedReceiver
func (s *stream) CreateNestedReceiver() (libchan.Receiver, libchan.Sender, error) { stream, err := s.session.createSubStream(s.referenceID) if err != nil { return nil, nil, err } return &receiver{stream: stream}, &nopSender{stream: stream}, err }
go
func (s *stream) CreateNestedReceiver() (libchan.Receiver, libchan.Sender, error) { stream, err := s.session.createSubStream(s.referenceID) if err != nil { return nil, nil, err } return &receiver{stream: stream}, &nopSender{stream: stream}, err }
[ "func", "(", "s", "*", "stream", ")", "CreateNestedReceiver", "(", ")", "(", "libchan", ".", "Receiver", ",", "libchan", ".", "Sender", ",", "error", ")", "{", "stream", ",", "err", ":=", "s", ".", "session", ".", "createSubStream", "(", "s", ".", "referenceID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "receiver", "{", "stream", ":", "stream", "}", ",", "&", "nopSender", "{", "stream", ":", "stream", "}", ",", "err", "\n", "}" ]
// CreateNestedReceiver creates a new channel returning the local // receiver and the remote sender. The remote sender needs to be // sent across the channel before being utilized.
[ "CreateNestedReceiver", "creates", "a", "new", "channel", "returning", "the", "local", "receiver", "and", "the", "remote", "sender", ".", "The", "remote", "sender", "needs", "to", "be", "sent", "across", "the", "channel", "before", "being", "utilized", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/session.go#L201-L208
11,277
docker/libchan
spdy/session.go
CreateNestedSender
func (s *stream) CreateNestedSender() (libchan.Sender, libchan.Receiver, error) { stream, err := s.session.createSubStream(s.referenceID) if err != nil { return nil, nil, err } return &sender{stream: stream}, &nopReceiver{stream: stream}, err }
go
func (s *stream) CreateNestedSender() (libchan.Sender, libchan.Receiver, error) { stream, err := s.session.createSubStream(s.referenceID) if err != nil { return nil, nil, err } return &sender{stream: stream}, &nopReceiver{stream: stream}, err }
[ "func", "(", "s", "*", "stream", ")", "CreateNestedSender", "(", ")", "(", "libchan", ".", "Sender", ",", "libchan", ".", "Receiver", ",", "error", ")", "{", "stream", ",", "err", ":=", "s", ".", "session", ".", "createSubStream", "(", "s", ".", "referenceID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "sender", "{", "stream", ":", "stream", "}", ",", "&", "nopReceiver", "{", "stream", ":", "stream", "}", ",", "err", "\n", "}" ]
// CreateNestedReceiver creates a new channel returning the local // sender and the remote receiver. The remote receiver needs to be // sent across the channel before being utilized.
[ "CreateNestedReceiver", "creates", "a", "new", "channel", "returning", "the", "local", "sender", "and", "the", "remote", "receiver", ".", "The", "remote", "receiver", "needs", "to", "be", "sent", "across", "the", "channel", "before", "being", "utilized", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/session.go#L213-L220
11,278
docker/libchan
spdy/session.go
Send
func (s *sender) Send(message interface{}) error { s.encodeLock.Lock() defer s.encodeLock.Unlock() if s.encoder == nil { s.buffer = bufio.NewWriter(s.stream) s.encoder = msgpack.NewEncoder(s.buffer) s.encoder.AddExtensions(s.stream.initializeExtensions()) } if err := s.encoder.Encode(message); err != nil { return err } return s.buffer.Flush() }
go
func (s *sender) Send(message interface{}) error { s.encodeLock.Lock() defer s.encodeLock.Unlock() if s.encoder == nil { s.buffer = bufio.NewWriter(s.stream) s.encoder = msgpack.NewEncoder(s.buffer) s.encoder.AddExtensions(s.stream.initializeExtensions()) } if err := s.encoder.Encode(message); err != nil { return err } return s.buffer.Flush() }
[ "func", "(", "s", "*", "sender", ")", "Send", "(", "message", "interface", "{", "}", ")", "error", "{", "s", ".", "encodeLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "encodeLock", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "encoder", "==", "nil", "{", "s", ".", "buffer", "=", "bufio", ".", "NewWriter", "(", "s", ".", "stream", ")", "\n", "s", ".", "encoder", "=", "msgpack", ".", "NewEncoder", "(", "s", ".", "buffer", ")", "\n", "s", ".", "encoder", ".", "AddExtensions", "(", "s", ".", "stream", ".", "initializeExtensions", "(", ")", ")", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "encoder", ".", "Encode", "(", "message", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "s", ".", "buffer", ".", "Flush", "(", ")", "\n", "}" ]
// Send sends a message across the channel to a receiver on the // other side of the transport.
[ "Send", "sends", "a", "message", "across", "the", "channel", "to", "a", "receiver", "on", "the", "other", "side", "of", "the", "transport", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/session.go#L224-L238
11,279
docker/libchan
spdy/session.go
Receive
func (r *receiver) Receive(message interface{}) error { r.decodeLock.Lock() defer r.decodeLock.Unlock() if r.decoder == nil { r.decoder = msgpack.NewDecoder(r.stream) r.decoder.AddExtensions(r.stream.initializeExtensions()) } decodeErr := r.decoder.Decode(message) if decodeErr == io.EOF { r.stream.Close() r.decoder = nil } return decodeErr }
go
func (r *receiver) Receive(message interface{}) error { r.decodeLock.Lock() defer r.decodeLock.Unlock() if r.decoder == nil { r.decoder = msgpack.NewDecoder(r.stream) r.decoder.AddExtensions(r.stream.initializeExtensions()) } decodeErr := r.decoder.Decode(message) if decodeErr == io.EOF { r.stream.Close() r.decoder = nil } return decodeErr }
[ "func", "(", "r", "*", "receiver", ")", "Receive", "(", "message", "interface", "{", "}", ")", "error", "{", "r", ".", "decodeLock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "decodeLock", ".", "Unlock", "(", ")", "\n", "if", "r", ".", "decoder", "==", "nil", "{", "r", ".", "decoder", "=", "msgpack", ".", "NewDecoder", "(", "r", ".", "stream", ")", "\n", "r", ".", "decoder", ".", "AddExtensions", "(", "r", ".", "stream", ".", "initializeExtensions", "(", ")", ")", "\n", "}", "\n\n", "decodeErr", ":=", "r", ".", "decoder", ".", "Decode", "(", "message", ")", "\n", "if", "decodeErr", "==", "io", ".", "EOF", "{", "r", ".", "stream", ".", "Close", "(", ")", "\n", "r", ".", "decoder", "=", "nil", "\n", "}", "\n", "return", "decodeErr", "\n", "}" ]
// Receive receives a message sent across the channel from // a sender on the other side of the transport.
[ "Receive", "receives", "a", "message", "sent", "across", "the", "channel", "from", "a", "sender", "on", "the", "other", "side", "of", "the", "transport", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/session.go#L248-L262
11,280
docker/libchan
inmem.go
BufferedPipe
func BufferedPipe(n int) (Receiver, Sender) { c := make(chan interface{}, n) return pReceiver(c), pSender(c) }
go
func BufferedPipe(n int) (Receiver, Sender) { c := make(chan interface{}, n) return pReceiver(c), pSender(c) }
[ "func", "BufferedPipe", "(", "n", "int", ")", "(", "Receiver", ",", "Sender", ")", "{", "c", ":=", "make", "(", "chan", "interface", "{", "}", ",", "n", ")", "\n", "return", "pReceiver", "(", "c", ")", ",", "pSender", "(", "c", ")", "\n", "}" ]
// BufferedPipe returns an inmemory buffered pipe.
[ "BufferedPipe", "returns", "an", "inmemory", "buffered", "pipe", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/inmem.go#L80-L83
11,281
docker/libchan
spdy/pipe.go
Pipe
func Pipe() (libchan.Receiver, libchan.Sender, error) { c1, c2 := net.Pipe() s1, err := NewSpdyStreamProvider(c1, false) if err != nil { return nil, nil, err } t1 := NewTransport(s1) s2, err := NewSpdyStreamProvider(c2, true) if err != nil { return nil, nil, err } t2 := NewTransport(s2) var recv libchan.Receiver waitError := make(chan error) go func() { var err error recv, err = t2.WaitReceiveChannel() waitError <- err }() send, senderErr := t1.NewSendChannel() if senderErr != nil { c1.Close() c2.Close() return nil, nil, senderErr } receiveErr := <-waitError if receiveErr != nil { c1.Close() c2.Close() return nil, nil, receiveErr } return &pipeReceiver{t2, recv.(*receiver)}, &pipeSender{t1, send.(*sender)}, nil }
go
func Pipe() (libchan.Receiver, libchan.Sender, error) { c1, c2 := net.Pipe() s1, err := NewSpdyStreamProvider(c1, false) if err != nil { return nil, nil, err } t1 := NewTransport(s1) s2, err := NewSpdyStreamProvider(c2, true) if err != nil { return nil, nil, err } t2 := NewTransport(s2) var recv libchan.Receiver waitError := make(chan error) go func() { var err error recv, err = t2.WaitReceiveChannel() waitError <- err }() send, senderErr := t1.NewSendChannel() if senderErr != nil { c1.Close() c2.Close() return nil, nil, senderErr } receiveErr := <-waitError if receiveErr != nil { c1.Close() c2.Close() return nil, nil, receiveErr } return &pipeReceiver{t2, recv.(*receiver)}, &pipeSender{t1, send.(*sender)}, nil }
[ "func", "Pipe", "(", ")", "(", "libchan", ".", "Receiver", ",", "libchan", ".", "Sender", ",", "error", ")", "{", "c1", ",", "c2", ":=", "net", ".", "Pipe", "(", ")", "\n\n", "s1", ",", "err", ":=", "NewSpdyStreamProvider", "(", "c1", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "t1", ":=", "NewTransport", "(", "s1", ")", "\n\n", "s2", ",", "err", ":=", "NewSpdyStreamProvider", "(", "c2", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "t2", ":=", "NewTransport", "(", "s2", ")", "\n\n", "var", "recv", "libchan", ".", "Receiver", "\n", "waitError", ":=", "make", "(", "chan", "error", ")", "\n\n", "go", "func", "(", ")", "{", "var", "err", "error", "\n", "recv", ",", "err", "=", "t2", ".", "WaitReceiveChannel", "(", ")", "\n", "waitError", "<-", "err", "\n", "}", "(", ")", "\n\n", "send", ",", "senderErr", ":=", "t1", ".", "NewSendChannel", "(", ")", "\n", "if", "senderErr", "!=", "nil", "{", "c1", ".", "Close", "(", ")", "\n", "c2", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "senderErr", "\n", "}", "\n\n", "receiveErr", ":=", "<-", "waitError", "\n", "if", "receiveErr", "!=", "nil", "{", "c1", ".", "Close", "(", ")", "\n", "c2", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "receiveErr", "\n", "}", "\n", "return", "&", "pipeReceiver", "{", "t2", ",", "recv", ".", "(", "*", "receiver", ")", "}", ",", "&", "pipeSender", "{", "t1", ",", "send", ".", "(", "*", "sender", ")", "}", ",", "nil", "\n", "}" ]
// Pipe creates a top-level channel pipe using an in memory transport.
[ "Pipe", "creates", "a", "top", "-", "level", "channel", "pipe", "using", "an", "in", "memory", "transport", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/spdy/pipe.go#L21-L59
11,282
docker/libchan
copy.go
Copy
func Copy(w Sender, r Receiver) (int, error) { if senderTo, ok := r.(SenderTo); ok { if n, err := senderTo.SendTo(w); err != ErrIncompatibleSender { return n, err } } if receiverFrom, ok := w.(ReceiverFrom); ok { if n, err := receiverFrom.ReceiveFrom(r); err != ErrIncompatibleReceiver { return n, err } } var n int for { var m interface{} err := r.Receive(&m) if err != nil { if err == io.EOF { break } else { return n, err } } err = w.Send(m) if err != nil { return n, err } n++ } return n, nil }
go
func Copy(w Sender, r Receiver) (int, error) { if senderTo, ok := r.(SenderTo); ok { if n, err := senderTo.SendTo(w); err != ErrIncompatibleSender { return n, err } } if receiverFrom, ok := w.(ReceiverFrom); ok { if n, err := receiverFrom.ReceiveFrom(r); err != ErrIncompatibleReceiver { return n, err } } var n int for { var m interface{} err := r.Receive(&m) if err != nil { if err == io.EOF { break } else { return n, err } } err = w.Send(m) if err != nil { return n, err } n++ } return n, nil }
[ "func", "Copy", "(", "w", "Sender", ",", "r", "Receiver", ")", "(", "int", ",", "error", ")", "{", "if", "senderTo", ",", "ok", ":=", "r", ".", "(", "SenderTo", ")", ";", "ok", "{", "if", "n", ",", "err", ":=", "senderTo", ".", "SendTo", "(", "w", ")", ";", "err", "!=", "ErrIncompatibleSender", "{", "return", "n", ",", "err", "\n", "}", "\n", "}", "\n", "if", "receiverFrom", ",", "ok", ":=", "w", ".", "(", "ReceiverFrom", ")", ";", "ok", "{", "if", "n", ",", "err", ":=", "receiverFrom", ".", "ReceiveFrom", "(", "r", ")", ";", "err", "!=", "ErrIncompatibleReceiver", "{", "return", "n", ",", "err", "\n", "}", "\n", "}", "\n\n", "var", "n", "int", "\n", "for", "{", "var", "m", "interface", "{", "}", "\n", "err", ":=", "r", ".", "Receive", "(", "&", "m", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "else", "{", "return", "n", ",", "err", "\n", "}", "\n", "}", "\n\n", "err", "=", "w", ".", "Send", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "n", ",", "err", "\n", "}", "\n", "n", "++", "\n", "}", "\n", "return", "n", ",", "nil", "\n", "}" ]
// Copy copies from a receiver to a sender until an EOF is // received. The number of copies made is returned along // with any error that may have halted copying prior to an EOF.
[ "Copy", "copies", "from", "a", "receiver", "to", "a", "sender", "until", "an", "EOF", "is", "received", ".", "The", "number", "of", "copies", "made", "is", "returned", "along", "with", "any", "error", "that", "may", "have", "halted", "copying", "prior", "to", "an", "EOF", "." ]
0328dcec840a0659448faf08af087135fffb7fde
https://github.com/docker/libchan/blob/0328dcec840a0659448faf08af087135fffb7fde/copy.go#L38-L69
11,283
terraform-providers/terraform-provider-template
template/datasource_template_file.go
execute
func execute(s string, vars map[string]interface{}) (string, error) { expr, diags := hclsyntax.ParseTemplate([]byte(s), "<template_file>", hcl.Pos{Line: 1, Column: 1}) if diags.HasErrors() { return "", diags } ctx := &hcl.EvalContext{ Variables: map[string]cty.Value{}, } for k, v := range vars { // In practice today this is always a string due to limitations of // the schema system. In future we'd like to support other types here. s, ok := v.(string) if !ok { return "", fmt.Errorf("unexpected type for variable %q: %T", k, v) } ctx.Variables[k] = cty.StringVal(s) } // We borrow the functions from Terraform itself here. This is convenient // but note that this is coming from whatever version of Terraform we // have vendored in to this codebase, not from the version of Terraform // the user is running, and so the set of functions won't always match // between Terraform itself and this provider. // (Over time users will hopefully transition over to Terraform's built-in // templatefile function instead and we can phase this provider out.) scope := &tflang.Scope{ BaseDir: ".", } ctx.Functions = scope.Functions() result, diags := expr.Value(ctx) if diags.HasErrors() { return "", diags } // Our result must always be a string, so we'll try to convert it. var err error result, err = ctyconvert.Convert(result, cty.String) if err != nil { return "", fmt.Errorf("invalid template result: %s", err) } return result.AsString(), nil }
go
func execute(s string, vars map[string]interface{}) (string, error) { expr, diags := hclsyntax.ParseTemplate([]byte(s), "<template_file>", hcl.Pos{Line: 1, Column: 1}) if diags.HasErrors() { return "", diags } ctx := &hcl.EvalContext{ Variables: map[string]cty.Value{}, } for k, v := range vars { // In practice today this is always a string due to limitations of // the schema system. In future we'd like to support other types here. s, ok := v.(string) if !ok { return "", fmt.Errorf("unexpected type for variable %q: %T", k, v) } ctx.Variables[k] = cty.StringVal(s) } // We borrow the functions from Terraform itself here. This is convenient // but note that this is coming from whatever version of Terraform we // have vendored in to this codebase, not from the version of Terraform // the user is running, and so the set of functions won't always match // between Terraform itself and this provider. // (Over time users will hopefully transition over to Terraform's built-in // templatefile function instead and we can phase this provider out.) scope := &tflang.Scope{ BaseDir: ".", } ctx.Functions = scope.Functions() result, diags := expr.Value(ctx) if diags.HasErrors() { return "", diags } // Our result must always be a string, so we'll try to convert it. var err error result, err = ctyconvert.Convert(result, cty.String) if err != nil { return "", fmt.Errorf("invalid template result: %s", err) } return result.AsString(), nil }
[ "func", "execute", "(", "s", "string", ",", "vars", "map", "[", "string", "]", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "expr", ",", "diags", ":=", "hclsyntax", ".", "ParseTemplate", "(", "[", "]", "byte", "(", "s", ")", ",", "\"", "\"", ",", "hcl", ".", "Pos", "{", "Line", ":", "1", ",", "Column", ":", "1", "}", ")", "\n", "if", "diags", ".", "HasErrors", "(", ")", "{", "return", "\"", "\"", ",", "diags", "\n", "}", "\n\n", "ctx", ":=", "&", "hcl", ".", "EvalContext", "{", "Variables", ":", "map", "[", "string", "]", "cty", ".", "Value", "{", "}", ",", "}", "\n", "for", "k", ",", "v", ":=", "range", "vars", "{", "// In practice today this is always a string due to limitations of", "// the schema system. In future we'd like to support other types here.", "s", ",", "ok", ":=", "v", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "ctx", ".", "Variables", "[", "k", "]", "=", "cty", ".", "StringVal", "(", "s", ")", "\n", "}", "\n\n", "// We borrow the functions from Terraform itself here. This is convenient", "// but note that this is coming from whatever version of Terraform we", "// have vendored in to this codebase, not from the version of Terraform", "// the user is running, and so the set of functions won't always match", "// between Terraform itself and this provider.", "// (Over time users will hopefully transition over to Terraform's built-in", "// templatefile function instead and we can phase this provider out.)", "scope", ":=", "&", "tflang", ".", "Scope", "{", "BaseDir", ":", "\"", "\"", ",", "}", "\n", "ctx", ".", "Functions", "=", "scope", ".", "Functions", "(", ")", "\n\n", "result", ",", "diags", ":=", "expr", ".", "Value", "(", "ctx", ")", "\n", "if", "diags", ".", "HasErrors", "(", ")", "{", "return", "\"", "\"", ",", "diags", "\n", "}", "\n\n", "// Our result must always be a string, so we'll try to convert it.", "var", "err", "error", "\n", "result", ",", "err", "=", "ctyconvert", ".", "Convert", "(", "result", ",", "cty", ".", "String", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "result", ".", "AsString", "(", ")", ",", "nil", "\n", "}" ]
// execute parses and executes a template using vars.
[ "execute", "parses", "and", "executes", "a", "template", "using", "vars", "." ]
d3fc0f06fe9edfa61ffe80de0d4d3ecc5475012b
https://github.com/terraform-providers/terraform-provider-template/blob/d3fc0f06fe9edfa61ffe80de0d4d3ecc5475012b/template/datasource_template_file.go#L106-L150
11,284
jeremywohl/flatten
flatten.go
FlattenString
func FlattenString(nestedstr, prefix string, style SeparatorStyle) (string, error) { var nested map[string]interface{} err := json.Unmarshal([]byte(nestedstr), &nested) if err != nil { return "", err } flatmap, err := Flatten(nested, prefix, style) if err != nil { return "", err } flatb, err := json.Marshal(&flatmap) if err != nil { return "", err } return string(flatb), nil }
go
func FlattenString(nestedstr, prefix string, style SeparatorStyle) (string, error) { var nested map[string]interface{} err := json.Unmarshal([]byte(nestedstr), &nested) if err != nil { return "", err } flatmap, err := Flatten(nested, prefix, style) if err != nil { return "", err } flatb, err := json.Marshal(&flatmap) if err != nil { return "", err } return string(flatb), nil }
[ "func", "FlattenString", "(", "nestedstr", ",", "prefix", "string", ",", "style", "SeparatorStyle", ")", "(", "string", ",", "error", ")", "{", "var", "nested", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "nestedstr", ")", ",", "&", "nested", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "flatmap", ",", "err", ":=", "Flatten", "(", "nested", ",", "prefix", ",", "style", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "flatb", ",", "err", ":=", "json", ".", "Marshal", "(", "&", "flatmap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "string", "(", "flatb", ")", ",", "nil", "\n", "}" ]
// FlattenString generates a flat JSON map from a nested one. Keys in the flat map will be a compound of // descending map keys and slice iterations. The presentation of keys is set by style. A prefix is joined // to each key.
[ "FlattenString", "generates", "a", "flat", "JSON", "map", "from", "a", "nested", "one", ".", "Keys", "in", "the", "flat", "map", "will", "be", "a", "compound", "of", "descending", "map", "keys", "and", "slice", "iterations", ".", "The", "presentation", "of", "keys", "is", "set", "by", "style", ".", "A", "prefix", "is", "joined", "to", "each", "key", "." ]
588fe0d4c603f5dc8b3854ff3f7f16e570618ef7
https://github.com/jeremywohl/flatten/blob/588fe0d4c603f5dc8b3854ff3f7f16e570618ef7/flatten.go#L91-L109
11,285
vulcand/vulcand
plugin/ratelimit/ratelimit.go
GetSpec
func GetSpec() *plugin.MiddlewareSpec { cliFlags := []cli.Flag{ cli.IntFlag{Name: "period", Value: 1, Usage: "rate limit period in seconds"}, cli.IntFlag{Name: "requests", Value: 1, Usage: "amount of requests"}, cli.IntFlag{Name: "burst", Value: 1, Usage: "allowed burst"}, cli.StringFlag{Name: "variable, var", Value: "client.ip", Usage: "variable to rate against, e.g. client.ip, request.host or request.header.X-Header"}, cli.StringFlag{Name: "rateVar", Value: "", Usage: "variable to retrieve rates from, e.g. request.header.X-Rates"}, } return &plugin.MiddlewareSpec{ Type: "ratelimit", FromOther: FromOther, FromCli: FromCli, CliFlags: cliFlags, } }
go
func GetSpec() *plugin.MiddlewareSpec { cliFlags := []cli.Flag{ cli.IntFlag{Name: "period", Value: 1, Usage: "rate limit period in seconds"}, cli.IntFlag{Name: "requests", Value: 1, Usage: "amount of requests"}, cli.IntFlag{Name: "burst", Value: 1, Usage: "allowed burst"}, cli.StringFlag{Name: "variable, var", Value: "client.ip", Usage: "variable to rate against, e.g. client.ip, request.host or request.header.X-Header"}, cli.StringFlag{Name: "rateVar", Value: "", Usage: "variable to retrieve rates from, e.g. request.header.X-Rates"}, } return &plugin.MiddlewareSpec{ Type: "ratelimit", FromOther: FromOther, FromCli: FromCli, CliFlags: cliFlags, } }
[ "func", "GetSpec", "(", ")", "*", "plugin", ".", "MiddlewareSpec", "{", "cliFlags", ":=", "[", "]", "cli", ".", "Flag", "{", "cli", ".", "IntFlag", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "1", ",", "Usage", ":", "\"", "\"", "}", ",", "cli", ".", "IntFlag", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "1", ",", "Usage", ":", "\"", "\"", "}", ",", "cli", ".", "IntFlag", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "1", ",", "Usage", ":", "\"", "\"", "}", ",", "cli", ".", "StringFlag", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "\"", "\"", ",", "Usage", ":", "\"", "\"", "}", ",", "cli", ".", "StringFlag", "{", "Name", ":", "\"", "\"", ",", "Value", ":", "\"", "\"", ",", "Usage", ":", "\"", "\"", "}", ",", "}", "\n", "return", "&", "plugin", ".", "MiddlewareSpec", "{", "Type", ":", "\"", "\"", ",", "FromOther", ":", "FromOther", ",", "FromCli", ":", "FromCli", ",", "CliFlags", ":", "cliFlags", ",", "}", "\n", "}" ]
// Spec is an entry point of a plugin and will be called to register this middleware plugin withing vulcand
[ "Spec", "is", "an", "entry", "point", "of", "a", "plugin", "and", "will", "be", "called", "to", "register", "this", "middleware", "plugin", "withing", "vulcand" ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/plugin/ratelimit/ratelimit.go#L18-L32
11,286
vulcand/vulcand
plugin/ratelimit/ratelimit.go
FromCli
func FromCli(c *cli.Context) (plugin.Middleware, error) { return FromOther( RateLimit{ PeriodSeconds: int64(c.Int("period")), Requests: int64(c.Int("requests")), Burst: int64(c.Int("burst")), Variable: c.String("var"), RateVar: c.String("rateVar")}) }
go
func FromCli(c *cli.Context) (plugin.Middleware, error) { return FromOther( RateLimit{ PeriodSeconds: int64(c.Int("period")), Requests: int64(c.Int("requests")), Burst: int64(c.Int("burst")), Variable: c.String("var"), RateVar: c.String("rateVar")}) }
[ "func", "FromCli", "(", "c", "*", "cli", ".", "Context", ")", "(", "plugin", ".", "Middleware", ",", "error", ")", "{", "return", "FromOther", "(", "RateLimit", "{", "PeriodSeconds", ":", "int64", "(", "c", ".", "Int", "(", "\"", "\"", ")", ")", ",", "Requests", ":", "int64", "(", "c", ".", "Int", "(", "\"", "\"", ")", ")", ",", "Burst", ":", "int64", "(", "c", ".", "Int", "(", "\"", "\"", ")", ")", ",", "Variable", ":", "c", ".", "String", "(", "\"", "\"", ")", ",", "RateVar", ":", "c", ".", "String", "(", "\"", "\"", ")", "}", ")", "\n", "}" ]
// FromCli constructs a middleware instance from the command line parameters.
[ "FromCli", "constructs", "a", "middleware", "instance", "from", "the", "command", "line", "parameters", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/plugin/ratelimit/ratelimit.go#L59-L67
11,287
vulcand/vulcand
api/api.go
getHeapProfile
func getHeapProfile(w http.ResponseWriter, r *http.Request) { // Ensure up-to-date data. runtime.GC() w.Header().Set("Content-Type", "application/octet-stream") if err := pprof.Lookup("heap").WriteTo(w, 0); err != nil { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not get heap profile: %s\n", err) } }
go
func getHeapProfile(w http.ResponseWriter, r *http.Request) { // Ensure up-to-date data. runtime.GC() w.Header().Set("Content-Type", "application/octet-stream") if err := pprof.Lookup("heap").WriteTo(w, 0); err != nil { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Could not get heap profile: %s\n", err) } }
[ "func", "getHeapProfile", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "// Ensure up-to-date data.", "runtime", ".", "GC", "(", ")", "\n", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "pprof", ".", "Lookup", "(", "\"", "\"", ")", ".", "WriteTo", "(", "w", ",", "0", ")", ";", "err", "!=", "nil", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// getHeapProfile responds with a pprof-formatted heap profile.
[ "getHeapProfile", "responds", "with", "a", "pprof", "-", "formatted", "heap", "profile", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/api/api.go#L517-L526
11,288
vulcand/vulcand
api/api.go
parseForm
func parseForm(r *http.Request) error { contentType := r.Header.Get("Content-Type") if strings.HasPrefix(contentType, "multipart/form-data") == true { return r.ParseMultipartForm(0) } return r.ParseForm() }
go
func parseForm(r *http.Request) error { contentType := r.Header.Get("Content-Type") if strings.HasPrefix(contentType, "multipart/form-data") == true { return r.ParseMultipartForm(0) } return r.ParseForm() }
[ "func", "parseForm", "(", "r", "*", "http", ".", "Request", ")", "error", "{", "contentType", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "strings", ".", "HasPrefix", "(", "contentType", ",", "\"", "\"", ")", "==", "true", "{", "return", "r", ".", "ParseMultipartForm", "(", "0", ")", "\n", "}", "\n", "return", "r", ".", "ParseForm", "(", ")", "\n", "}" ]
// parseForm the request data based on its content type.
[ "parseForm", "the", "request", "data", "based", "on", "its", "content", "type", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/api/api.go#L584-L590
11,289
vulcand/vulcand
plugin/connlimit/connlimit.go
FromCli
func FromCli(c *cli.Context) (plugin.Middleware, error) { return NewConnLimit(int64(c.Int("connections")), c.String("var")) }
go
func FromCli(c *cli.Context) (plugin.Middleware, error) { return NewConnLimit(int64(c.Int("connections")), c.String("var")) }
[ "func", "FromCli", "(", "c", "*", "cli", ".", "Context", ")", "(", "plugin", ".", "Middleware", ",", "error", ")", "{", "return", "NewConnLimit", "(", "int64", "(", "c", ".", "Int", "(", "\"", "\"", ")", ")", ",", "c", ".", "String", "(", "\"", "\"", ")", ")", "\n", "}" ]
// Constructs the middleware from the command line
[ "Constructs", "the", "middleware", "from", "the", "command", "line" ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/plugin/connlimit/connlimit.go#L61-L63
11,290
vulcand/vulcand
supervisor/supervisor.go
run
func (s *Supervisor) run() { defer s.stopWg.Done() for { select { case <-s.watcherErrorC: s.watcherWg.Wait() s.watcherErrorC = nil case <-s.stopC: close(s.watcherCancelC) s.engine.Close() s.watcherWg.Wait() if s.proxy != nil { s.proxy.Stop(true) } return } err := s.init() // In case of an error keep trying to initialize making pauses between // attempts. for err != nil { log.Errorf("sup failed to reinit, err=%v", err) select { case <-time.After(retryPeriod): case <-s.stopC: return } err = s.init() } } }
go
func (s *Supervisor) run() { defer s.stopWg.Done() for { select { case <-s.watcherErrorC: s.watcherWg.Wait() s.watcherErrorC = nil case <-s.stopC: close(s.watcherCancelC) s.engine.Close() s.watcherWg.Wait() if s.proxy != nil { s.proxy.Stop(true) } return } err := s.init() // In case of an error keep trying to initialize making pauses between // attempts. for err != nil { log.Errorf("sup failed to reinit, err=%v", err) select { case <-time.After(retryPeriod): case <-s.stopC: return } err = s.init() } } }
[ "func", "(", "s", "*", "Supervisor", ")", "run", "(", ")", "{", "defer", "s", ".", "stopWg", ".", "Done", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "s", ".", "watcherErrorC", ":", "s", ".", "watcherWg", ".", "Wait", "(", ")", "\n", "s", ".", "watcherErrorC", "=", "nil", "\n", "case", "<-", "s", ".", "stopC", ":", "close", "(", "s", ".", "watcherCancelC", ")", "\n", "s", ".", "engine", ".", "Close", "(", ")", "\n", "s", ".", "watcherWg", ".", "Wait", "(", ")", "\n", "if", "s", ".", "proxy", "!=", "nil", "{", "s", ".", "proxy", ".", "Stop", "(", "true", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "err", ":=", "s", ".", "init", "(", ")", "\n", "// In case of an error keep trying to initialize making pauses between", "// attempts.", "for", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "select", "{", "case", "<-", "time", ".", "After", "(", "retryPeriod", ")", ":", "case", "<-", "s", ".", "stopC", ":", "return", "\n", "}", "\n", "err", "=", "s", ".", "init", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// supervise listens for error notifications and triggers graceful restart.
[ "supervise", "listens", "for", "error", "notifications", "and", "triggers", "graceful", "restart", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/supervisor/supervisor.go#L255-L285
11,291
vulcand/vulcand
supervisor/supervisor.go
processChange
func processChange(p proxy.Proxy, ch interface{}) error { switch change := ch.(type) { case *engine.HostUpserted: return p.UpsertHost(change.Host) case *engine.HostDeleted: return p.DeleteHost(change.HostKey) case *engine.ListenerUpserted: return p.UpsertListener(change.Listener) case *engine.ListenerDeleted: return p.DeleteListener(change.ListenerKey) case *engine.FrontendUpserted: return p.UpsertFrontend(change.Frontend) case *engine.FrontendDeleted: return p.DeleteFrontend(change.FrontendKey) case *engine.MiddlewareUpserted: return p.UpsertMiddleware(change.FrontendKey, change.Middleware) case *engine.MiddlewareDeleted: return p.DeleteMiddleware(change.MiddlewareKey) case *engine.BackendUpserted: return p.UpsertBackend(change.Backend) case *engine.BackendDeleted: return p.DeleteBackend(change.BackendKey) case *engine.ServerUpserted: return p.UpsertServer(change.BackendKey, change.Server) case *engine.ServerDeleted: return p.DeleteServer(change.ServerKey) } return fmt.Errorf("unsupported change: %#v", ch) }
go
func processChange(p proxy.Proxy, ch interface{}) error { switch change := ch.(type) { case *engine.HostUpserted: return p.UpsertHost(change.Host) case *engine.HostDeleted: return p.DeleteHost(change.HostKey) case *engine.ListenerUpserted: return p.UpsertListener(change.Listener) case *engine.ListenerDeleted: return p.DeleteListener(change.ListenerKey) case *engine.FrontendUpserted: return p.UpsertFrontend(change.Frontend) case *engine.FrontendDeleted: return p.DeleteFrontend(change.FrontendKey) case *engine.MiddlewareUpserted: return p.UpsertMiddleware(change.FrontendKey, change.Middleware) case *engine.MiddlewareDeleted: return p.DeleteMiddleware(change.MiddlewareKey) case *engine.BackendUpserted: return p.UpsertBackend(change.Backend) case *engine.BackendDeleted: return p.DeleteBackend(change.BackendKey) case *engine.ServerUpserted: return p.UpsertServer(change.BackendKey, change.Server) case *engine.ServerDeleted: return p.DeleteServer(change.ServerKey) } return fmt.Errorf("unsupported change: %#v", ch) }
[ "func", "processChange", "(", "p", "proxy", ".", "Proxy", ",", "ch", "interface", "{", "}", ")", "error", "{", "switch", "change", ":=", "ch", ".", "(", "type", ")", "{", "case", "*", "engine", ".", "HostUpserted", ":", "return", "p", ".", "UpsertHost", "(", "change", ".", "Host", ")", "\n", "case", "*", "engine", ".", "HostDeleted", ":", "return", "p", ".", "DeleteHost", "(", "change", ".", "HostKey", ")", "\n\n", "case", "*", "engine", ".", "ListenerUpserted", ":", "return", "p", ".", "UpsertListener", "(", "change", ".", "Listener", ")", "\n\n", "case", "*", "engine", ".", "ListenerDeleted", ":", "return", "p", ".", "DeleteListener", "(", "change", ".", "ListenerKey", ")", "\n\n", "case", "*", "engine", ".", "FrontendUpserted", ":", "return", "p", ".", "UpsertFrontend", "(", "change", ".", "Frontend", ")", "\n", "case", "*", "engine", ".", "FrontendDeleted", ":", "return", "p", ".", "DeleteFrontend", "(", "change", ".", "FrontendKey", ")", "\n\n", "case", "*", "engine", ".", "MiddlewareUpserted", ":", "return", "p", ".", "UpsertMiddleware", "(", "change", ".", "FrontendKey", ",", "change", ".", "Middleware", ")", "\n\n", "case", "*", "engine", ".", "MiddlewareDeleted", ":", "return", "p", ".", "DeleteMiddleware", "(", "change", ".", "MiddlewareKey", ")", "\n\n", "case", "*", "engine", ".", "BackendUpserted", ":", "return", "p", ".", "UpsertBackend", "(", "change", ".", "Backend", ")", "\n", "case", "*", "engine", ".", "BackendDeleted", ":", "return", "p", ".", "DeleteBackend", "(", "change", ".", "BackendKey", ")", "\n\n", "case", "*", "engine", ".", "ServerUpserted", ":", "return", "p", ".", "UpsertServer", "(", "change", ".", "BackendKey", ",", "change", ".", "Server", ")", "\n", "case", "*", "engine", ".", "ServerDeleted", ":", "return", "p", ".", "DeleteServer", "(", "change", ".", "ServerKey", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ch", ")", "\n", "}" ]
// processChange takes the backend change notification emitted by the backend // and applies it to the server.
[ "processChange", "takes", "the", "backend", "change", "notification", "emitted", "by", "the", "backend", "and", "applies", "it", "to", "the", "server", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/supervisor/supervisor.go#L296-L331
11,292
vulcand/vulcand
anomaly/anomaly.go
MarkServerAnomalies
func MarkServerAnomalies(servers []engine.Server) error { if len(servers) == 0 { return nil } stats := make([]engine.RoundTripStats, len(servers)) for i := range servers { stats[i] = *servers[i].Stats } if err := MarkAnomalies(stats); err != nil { return err } for i := range stats { servers[i].Stats = &stats[i] } return nil }
go
func MarkServerAnomalies(servers []engine.Server) error { if len(servers) == 0 { return nil } stats := make([]engine.RoundTripStats, len(servers)) for i := range servers { stats[i] = *servers[i].Stats } if err := MarkAnomalies(stats); err != nil { return err } for i := range stats { servers[i].Stats = &stats[i] } return nil }
[ "func", "MarkServerAnomalies", "(", "servers", "[", "]", "engine", ".", "Server", ")", "error", "{", "if", "len", "(", "servers", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "stats", ":=", "make", "(", "[", "]", "engine", ".", "RoundTripStats", ",", "len", "(", "servers", ")", ")", "\n", "for", "i", ":=", "range", "servers", "{", "stats", "[", "i", "]", "=", "*", "servers", "[", "i", "]", ".", "Stats", "\n", "}", "\n\n", "if", "err", ":=", "MarkAnomalies", "(", "stats", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "for", "i", ":=", "range", "stats", "{", "servers", "[", "i", "]", ".", "Stats", "=", "&", "stats", "[", "i", "]", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MarkServerAnomalies takes the list of servers and marks anomalies detected within this set // by modifying the inner Verdict property.
[ "MarkServerAnomalies", "takes", "the", "list", "of", "servers", "and", "marks", "anomalies", "detected", "within", "this", "set", "by", "modifying", "the", "inner", "Verdict", "property", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/anomaly/anomaly.go#L25-L42
11,293
vulcand/vulcand
anomaly/anomaly.go
MarkAnomalies
func MarkAnomalies(stats []engine.RoundTripStats) error { if len(stats) == 0 { return nil } if err := markLatencies(stats); err != nil { return err } if err := markNetErrorRates(stats); err != nil { return err } return markAppErrorRates(stats) }
go
func MarkAnomalies(stats []engine.RoundTripStats) error { if len(stats) == 0 { return nil } if err := markLatencies(stats); err != nil { return err } if err := markNetErrorRates(stats); err != nil { return err } return markAppErrorRates(stats) }
[ "func", "MarkAnomalies", "(", "stats", "[", "]", "engine", ".", "RoundTripStats", ")", "error", "{", "if", "len", "(", "stats", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "markLatencies", "(", "stats", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "markNetErrorRates", "(", "stats", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "markAppErrorRates", "(", "stats", ")", "\n", "}" ]
// MarkAnomalies takes the list of stats and marks anomalies detected within this group by updating // the Verdict property.
[ "MarkAnomalies", "takes", "the", "list", "of", "stats", "and", "marks", "anomalies", "detected", "within", "this", "group", "by", "updating", "the", "Verdict", "property", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/anomaly/anomaly.go#L46-L57
11,294
vulcand/vulcand
proxy/frontend/frontend.go
New
func New(cfg engine.Frontend, be *backend.T, opts proxy.Options, mwCfgs map[engine.MiddlewareKey]engine.Middleware, listeners plugin.FrontendListeners, ) *T { if mwCfgs == nil { mwCfgs = make(map[engine.MiddlewareKey]engine.Middleware) } fe := T{ cfg: cfg, trustXFDH: opts.TrustForwardHeader, mwCfgs: mwCfgs, backend: be, listeners: listeners, } return &fe }
go
func New(cfg engine.Frontend, be *backend.T, opts proxy.Options, mwCfgs map[engine.MiddlewareKey]engine.Middleware, listeners plugin.FrontendListeners, ) *T { if mwCfgs == nil { mwCfgs = make(map[engine.MiddlewareKey]engine.Middleware) } fe := T{ cfg: cfg, trustXFDH: opts.TrustForwardHeader, mwCfgs: mwCfgs, backend: be, listeners: listeners, } return &fe }
[ "func", "New", "(", "cfg", "engine", ".", "Frontend", ",", "be", "*", "backend", ".", "T", ",", "opts", "proxy", ".", "Options", ",", "mwCfgs", "map", "[", "engine", ".", "MiddlewareKey", "]", "engine", ".", "Middleware", ",", "listeners", "plugin", ".", "FrontendListeners", ",", ")", "*", "T", "{", "if", "mwCfgs", "==", "nil", "{", "mwCfgs", "=", "make", "(", "map", "[", "engine", ".", "MiddlewareKey", "]", "engine", ".", "Middleware", ")", "\n", "}", "\n", "fe", ":=", "T", "{", "cfg", ":", "cfg", ",", "trustXFDH", ":", "opts", ".", "TrustForwardHeader", ",", "mwCfgs", ":", "mwCfgs", ",", "backend", ":", "be", ",", "listeners", ":", "listeners", ",", "}", "\n", "return", "&", "fe", "\n", "}" ]
// New returns a new frontend instance.
[ "New", "returns", "a", "new", "frontend", "instance", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/proxy/frontend/frontend.go#L41-L56
11,295
vulcand/vulcand
proxy/frontend/frontend.go
BackendKey
func (fe *T) BackendKey() engine.BackendKey { fe.mu.Lock() beKey := fe.backend.Key() fe.mu.Unlock() return beKey }
go
func (fe *T) BackendKey() engine.BackendKey { fe.mu.Lock() beKey := fe.backend.Key() fe.mu.Unlock() return beKey }
[ "func", "(", "fe", "*", "T", ")", "BackendKey", "(", ")", "engine", ".", "BackendKey", "{", "fe", ".", "mu", ".", "Lock", "(", ")", "\n", "beKey", ":=", "fe", ".", "backend", ".", "Key", "(", ")", "\n", "fe", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "beKey", "\n", "}" ]
// BackendKey returns the storage key of an associated backend.
[ "BackendKey", "returns", "the", "storage", "key", "of", "an", "associated", "backend", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/proxy/frontend/frontend.go#L64-L69
11,296
vulcand/vulcand
proxy/frontend/frontend.go
Route
func (fe *T) Route() string { fe.mu.Lock() route := fe.cfg.Route fe.mu.Unlock() return route }
go
func (fe *T) Route() string { fe.mu.Lock() route := fe.cfg.Route fe.mu.Unlock() return route }
[ "func", "(", "fe", "*", "T", ")", "Route", "(", ")", "string", "{", "fe", ".", "mu", ".", "Lock", "(", ")", "\n", "route", ":=", "fe", ".", "cfg", ".", "Route", "\n", "fe", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "route", "\n", "}" ]
// Route returns HTTP path. It should be used to configure an HTTP router to // forward requests coming to the path to this frontend instance.
[ "Route", "returns", "HTTP", "path", ".", "It", "should", "be", "used", "to", "configure", "an", "HTTP", "router", "to", "forward", "requests", "coming", "to", "the", "path", "to", "this", "frontend", "instance", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/proxy/frontend/frontend.go#L73-L78
11,297
vulcand/vulcand
proxy/frontend/frontend.go
UpsertMiddleware
func (fe *T) UpsertMiddleware(mwCfg engine.Middleware) { fe.mu.Lock() defer fe.mu.Unlock() mwKey := engine.MiddlewareKey{FrontendKey: engine.FrontendKey{Id: fe.cfg.Id}, Id: mwCfg.Id} fe.mwCfgs[mwKey] = mwCfg fe.ready = false }
go
func (fe *T) UpsertMiddleware(mwCfg engine.Middleware) { fe.mu.Lock() defer fe.mu.Unlock() mwKey := engine.MiddlewareKey{FrontendKey: engine.FrontendKey{Id: fe.cfg.Id}, Id: mwCfg.Id} fe.mwCfgs[mwKey] = mwCfg fe.ready = false }
[ "func", "(", "fe", "*", "T", ")", "UpsertMiddleware", "(", "mwCfg", "engine", ".", "Middleware", ")", "{", "fe", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "fe", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "mwKey", ":=", "engine", ".", "MiddlewareKey", "{", "FrontendKey", ":", "engine", ".", "FrontendKey", "{", "Id", ":", "fe", ".", "cfg", ".", "Id", "}", ",", "Id", ":", "mwCfg", ".", "Id", "}", "\n", "fe", ".", "mwCfgs", "[", "mwKey", "]", "=", "mwCfg", "\n", "fe", ".", "ready", "=", "false", "\n", "}" ]
// UpsertMiddleware upserts a middleware.
[ "UpsertMiddleware", "upserts", "a", "middleware", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/proxy/frontend/frontend.go#L106-L113
11,298
vulcand/vulcand
proxy/frontend/frontend.go
DeleteMiddleware
func (fe *T) DeleteMiddleware(mwKey engine.MiddlewareKey) { fe.mu.Lock() defer fe.mu.Unlock() if _, ok := fe.mwCfgs[mwKey]; !ok { return } delete(fe.mwCfgs, mwKey) fe.ready = false }
go
func (fe *T) DeleteMiddleware(mwKey engine.MiddlewareKey) { fe.mu.Lock() defer fe.mu.Unlock() if _, ok := fe.mwCfgs[mwKey]; !ok { return } delete(fe.mwCfgs, mwKey) fe.ready = false }
[ "func", "(", "fe", "*", "T", ")", "DeleteMiddleware", "(", "mwKey", "engine", ".", "MiddlewareKey", ")", "{", "fe", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "fe", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "fe", ".", "mwCfgs", "[", "mwKey", "]", ";", "!", "ok", "{", "return", "\n", "}", "\n", "delete", "(", "fe", ".", "mwCfgs", ",", "mwKey", ")", "\n", "fe", ".", "ready", "=", "false", "\n", "}" ]
// DeleteMiddleware deletes a middleware if there is one with the specified // storage key or does nothing otherwise.
[ "DeleteMiddleware", "deletes", "a", "middleware", "if", "there", "is", "one", "with", "the", "specified", "storage", "key", "or", "does", "nothing", "otherwise", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/proxy/frontend/frontend.go#L117-L126
11,299
vulcand/vulcand
proxy/frontend/frontend.go
CfgWithStats
func (fe *T) CfgWithStats() (engine.Frontend, bool, error) { fe.mu.Lock() rtmCollect := fe.rtmCollect feCfg := fe.cfg fe.mu.Unlock() if rtmCollect == nil { return engine.Frontend{}, false, nil } var err error if feCfg.Stats, err = rtmCollect.RTStats(); err != nil { return engine.Frontend{}, false, errors.Wrap(err, "failed to get stats") } return feCfg, true, nil }
go
func (fe *T) CfgWithStats() (engine.Frontend, bool, error) { fe.mu.Lock() rtmCollect := fe.rtmCollect feCfg := fe.cfg fe.mu.Unlock() if rtmCollect == nil { return engine.Frontend{}, false, nil } var err error if feCfg.Stats, err = rtmCollect.RTStats(); err != nil { return engine.Frontend{}, false, errors.Wrap(err, "failed to get stats") } return feCfg, true, nil }
[ "func", "(", "fe", "*", "T", ")", "CfgWithStats", "(", ")", "(", "engine", ".", "Frontend", ",", "bool", ",", "error", ")", "{", "fe", ".", "mu", ".", "Lock", "(", ")", "\n", "rtmCollect", ":=", "fe", ".", "rtmCollect", "\n", "feCfg", ":=", "fe", ".", "cfg", "\n", "fe", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "rtmCollect", "==", "nil", "{", "return", "engine", ".", "Frontend", "{", "}", ",", "false", ",", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "if", "feCfg", ".", "Stats", ",", "err", "=", "rtmCollect", ".", "RTStats", "(", ")", ";", "err", "!=", "nil", "{", "return", "engine", ".", "Frontend", "{", "}", ",", "false", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "feCfg", ",", "true", ",", "nil", "\n", "}" ]
// CfgWithStats returns the frontend storage config with associated round trip // stats.
[ "CfgWithStats", "returns", "the", "frontend", "storage", "config", "with", "associated", "round", "trip", "stats", "." ]
5fb2302c78e2db24de076c2b2c6276bf6f48ebf0
https://github.com/vulcand/vulcand/blob/5fb2302c78e2db24de076c2b2c6276bf6f48ebf0/proxy/frontend/frontend.go#L138-L152