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
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
164,900
sjwhitworth/golearn
clustering/em.go
estimateLogProb
func estimateLogProb(X *mat.Dense, p Params, n_comps int) mat.Vector { n_obs, n_feats := X.Dims() // Cache the component Gaussians var N = make([]*distmv.Normal, n_comps) for k := 0; k < n_comps; k++ { dst := make([]float64, n_feats) means := mat.Row(dst, k, p.Means) dist, ok := distmv.NewNormal(means, p.Covs[k], nil) if !ok { panic("Cannot create Normal!") } N[k] = dist } // Compute the component probabilities y_new := mat.NewVecDense(n_obs, nil) for i := 0; i < n_obs; i++ { max_ix := 0 max_pr := math.Inf(-1) x := X.RawRowView(i) for k := 0; k < n_comps; k++ { pr := N[k].LogProb(x) if pr > max_pr { max_ix = k max_pr = pr } } y_new.SetVec(i, float64(max_ix)) } return y_new }
go
func estimateLogProb(X *mat.Dense, p Params, n_comps int) mat.Vector { n_obs, n_feats := X.Dims() // Cache the component Gaussians var N = make([]*distmv.Normal, n_comps) for k := 0; k < n_comps; k++ { dst := make([]float64, n_feats) means := mat.Row(dst, k, p.Means) dist, ok := distmv.NewNormal(means, p.Covs[k], nil) if !ok { panic("Cannot create Normal!") } N[k] = dist } // Compute the component probabilities y_new := mat.NewVecDense(n_obs, nil) for i := 0; i < n_obs; i++ { max_ix := 0 max_pr := math.Inf(-1) x := X.RawRowView(i) for k := 0; k < n_comps; k++ { pr := N[k].LogProb(x) if pr > max_pr { max_ix = k max_pr = pr } } y_new.SetVec(i, float64(max_ix)) } return y_new }
[ "func", "estimateLogProb", "(", "X", "*", "mat", ".", "Dense", ",", "p", "Params", ",", "n_comps", "int", ")", "mat", ".", "Vector", "{", "n_obs", ",", "n_feats", ":=", "X", ".", "Dims", "(", ")", "\n\n", "// Cache the component Gaussians", "var", "N", "=", "make", "(", "[", "]", "*", "distmv", ".", "Normal", ",", "n_comps", ")", "\n", "for", "k", ":=", "0", ";", "k", "<", "n_comps", ";", "k", "++", "{", "dst", ":=", "make", "(", "[", "]", "float64", ",", "n_feats", ")", "\n", "means", ":=", "mat", ".", "Row", "(", "dst", ",", "k", ",", "p", ".", "Means", ")", "\n", "dist", ",", "ok", ":=", "distmv", ".", "NewNormal", "(", "means", ",", "p", ".", "Covs", "[", "k", "]", ",", "nil", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "N", "[", "k", "]", "=", "dist", "\n", "}", "\n\n", "// Compute the component probabilities", "y_new", ":=", "mat", ".", "NewVecDense", "(", "n_obs", ",", "nil", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "max_ix", ":=", "0", "\n", "max_pr", ":=", "math", ".", "Inf", "(", "-", "1", ")", "\n", "x", ":=", "X", ".", "RawRowView", "(", "i", ")", "\n", "for", "k", ":=", "0", ";", "k", "<", "n_comps", ";", "k", "++", "{", "pr", ":=", "N", "[", "k", "]", ".", "LogProb", "(", "x", ")", "\n", "if", "pr", ">", "max_pr", "{", "max_ix", "=", "k", "\n", "max_pr", "=", "pr", "\n", "}", "\n", "}", "\n", "y_new", ".", "SetVec", "(", "i", ",", "float64", "(", "max_ix", ")", ")", "\n", "}", "\n\n", "return", "y_new", "\n", "}" ]
// Creates mat.Vector of most likely component for each observation
[ "Creates", "mat", ".", "Vector", "of", "most", "likely", "component", "for", "each", "observation" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L162-L194
164,901
sjwhitworth/golearn
clustering/em.go
shrunkCovariance
func shrunkCovariance(X *mat.Dense) *mat.SymDense { n_obs, n_feats := X.Dims() size := int(math.Pow(float64(n_feats), 2)) covs := mat.NewSymDense(n_feats, make([]float64, size, size)) for j := 0; j < n_feats; j++ { // compute the variance for the jth feature var points []float64 for i := 0; i < n_obs; i++ { points = append(points, X.At(i, j)) } variance := stat.Variance(points, nil) // set the jth diagonal entry to the variance covs.SetSym(j, j, variance) } return covs }
go
func shrunkCovariance(X *mat.Dense) *mat.SymDense { n_obs, n_feats := X.Dims() size := int(math.Pow(float64(n_feats), 2)) covs := mat.NewSymDense(n_feats, make([]float64, size, size)) for j := 0; j < n_feats; j++ { // compute the variance for the jth feature var points []float64 for i := 0; i < n_obs; i++ { points = append(points, X.At(i, j)) } variance := stat.Variance(points, nil) // set the jth diagonal entry to the variance covs.SetSym(j, j, variance) } return covs }
[ "func", "shrunkCovariance", "(", "X", "*", "mat", ".", "Dense", ")", "*", "mat", ".", "SymDense", "{", "n_obs", ",", "n_feats", ":=", "X", ".", "Dims", "(", ")", "\n", "size", ":=", "int", "(", "math", ".", "Pow", "(", "float64", "(", "n_feats", ")", ",", "2", ")", ")", "\n", "covs", ":=", "mat", ".", "NewSymDense", "(", "n_feats", ",", "make", "(", "[", "]", "float64", ",", "size", ",", "size", ")", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "n_feats", ";", "j", "++", "{", "// compute the variance for the jth feature", "var", "points", "[", "]", "float64", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "points", "=", "append", "(", "points", ",", "X", ".", "At", "(", "i", ",", "j", ")", ")", "\n", "}", "\n", "variance", ":=", "stat", ".", "Variance", "(", "points", ",", "nil", ")", "\n", "// set the jth diagonal entry to the variance", "covs", ".", "SetSym", "(", "j", ",", "j", ",", "variance", ")", "\n", "}", "\n", "return", "covs", "\n", "}" ]
// Returns a symmetric matrix with variance on the diagonal
[ "Returns", "a", "symmetric", "matrix", "with", "variance", "on", "the", "diagonal" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L197-L212
164,902
sjwhitworth/golearn
clustering/em.go
initMeans
func initMeans(X *mat.Dense, n_comps, n_feats int) *mat.Dense { var results []float64 for k := 0; k < n_comps; k++ { for j := 0; j < n_feats; j++ { v := X.ColView(j) min := vectorMin(v) max := vectorMax(v) r := min + rand.Float64()*(max-min) results = append(results, r) } } means := mat.NewDense(n_comps, n_feats, results) return means }
go
func initMeans(X *mat.Dense, n_comps, n_feats int) *mat.Dense { var results []float64 for k := 0; k < n_comps; k++ { for j := 0; j < n_feats; j++ { v := X.ColView(j) min := vectorMin(v) max := vectorMax(v) r := min + rand.Float64()*(max-min) results = append(results, r) } } means := mat.NewDense(n_comps, n_feats, results) return means }
[ "func", "initMeans", "(", "X", "*", "mat", ".", "Dense", ",", "n_comps", ",", "n_feats", "int", ")", "*", "mat", ".", "Dense", "{", "var", "results", "[", "]", "float64", "\n", "for", "k", ":=", "0", ";", "k", "<", "n_comps", ";", "k", "++", "{", "for", "j", ":=", "0", ";", "j", "<", "n_feats", ";", "j", "++", "{", "v", ":=", "X", ".", "ColView", "(", "j", ")", "\n", "min", ":=", "vectorMin", "(", "v", ")", "\n", "max", ":=", "vectorMax", "(", "v", ")", "\n", "r", ":=", "min", "+", "rand", ".", "Float64", "(", ")", "*", "(", "max", "-", "min", ")", "\n", "results", "=", "append", "(", "results", ",", "r", ")", "\n", "}", "\n", "}", "\n", "means", ":=", "mat", ".", "NewDense", "(", "n_comps", ",", "n_feats", ",", "results", ")", "\n", "return", "means", "\n", "}" ]
// Creates an n_comps x n_feats array of means
[ "Creates", "an", "n_comps", "x", "n_feats", "array", "of", "means" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L215-L228
164,903
sjwhitworth/golearn
clustering/em.go
initCovariance
func initCovariance(n_comps, n_feats int) []mat.Symmetric { var result []mat.Symmetric floats := identity(n_feats) for k := 0; k < n_comps; k++ { matrix := mat.NewSymDense(n_feats, floats) result = append(result, matrix) } return result }
go
func initCovariance(n_comps, n_feats int) []mat.Symmetric { var result []mat.Symmetric floats := identity(n_feats) for k := 0; k < n_comps; k++ { matrix := mat.NewSymDense(n_feats, floats) result = append(result, matrix) } return result }
[ "func", "initCovariance", "(", "n_comps", ",", "n_feats", "int", ")", "[", "]", "mat", ".", "Symmetric", "{", "var", "result", "[", "]", "mat", ".", "Symmetric", "\n", "floats", ":=", "identity", "(", "n_feats", ")", "\n", "for", "k", ":=", "0", ";", "k", "<", "n_comps", ";", "k", "++", "{", "matrix", ":=", "mat", ".", "NewSymDense", "(", "n_feats", ",", "floats", ")", "\n", "result", "=", "append", "(", "result", ",", "matrix", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Creates a n_comps array of n_feats x n_feats mat.Symmetrics
[ "Creates", "a", "n_comps", "array", "of", "n_feats", "x", "n_feats", "mat", ".", "Symmetrics" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L231-L239
164,904
sjwhitworth/golearn
clustering/em.go
distance
func distance(p Params, p_new Params) float64 { dist := 0.0 n_obs, n_feats := p.Means.Dims() for i := 0; i < n_obs; i++ { means_i := p.Means.RawRowView(i) means_new_i := p_new.Means.RawRowView(i) for j := 0; j < n_feats; j++ { dist += math.Pow((means_i[j] - means_new_i[j]), 2) } } return math.Sqrt(dist) }
go
func distance(p Params, p_new Params) float64 { dist := 0.0 n_obs, n_feats := p.Means.Dims() for i := 0; i < n_obs; i++ { means_i := p.Means.RawRowView(i) means_new_i := p_new.Means.RawRowView(i) for j := 0; j < n_feats; j++ { dist += math.Pow((means_i[j] - means_new_i[j]), 2) } } return math.Sqrt(dist) }
[ "func", "distance", "(", "p", "Params", ",", "p_new", "Params", ")", "float64", "{", "dist", ":=", "0.0", "\n", "n_obs", ",", "n_feats", ":=", "p", ".", "Means", ".", "Dims", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "means_i", ":=", "p", ".", "Means", ".", "RawRowView", "(", "i", ")", "\n", "means_new_i", ":=", "p_new", ".", "Means", ".", "RawRowView", "(", "i", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "n_feats", ";", "j", "++", "{", "dist", "+=", "math", ".", "Pow", "(", "(", "means_i", "[", "j", "]", "-", "means_new_i", "[", "j", "]", ")", ",", "2", ")", "\n", "}", "\n", "}", "\n", "return", "math", ".", "Sqrt", "(", "dist", ")", "\n", "}" ]
// Compues the euclidian distance between two parameters
[ "Compues", "the", "euclidian", "distance", "between", "two", "parameters" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L242-L253
164,905
sjwhitworth/golearn
clustering/em.go
vectorMin
func vectorMin(v mat.Vector) float64 { n_obs, _ := v.Dims() min := v.At(0, 0) for i := 0; i < n_obs; i++ { if v.At(i, 0) < min { min = v.At(i, 0) } } return min }
go
func vectorMin(v mat.Vector) float64 { n_obs, _ := v.Dims() min := v.At(0, 0) for i := 0; i < n_obs; i++ { if v.At(i, 0) < min { min = v.At(i, 0) } } return min }
[ "func", "vectorMin", "(", "v", "mat", ".", "Vector", ")", "float64", "{", "n_obs", ",", "_", ":=", "v", ".", "Dims", "(", ")", "\n", "min", ":=", "v", ".", "At", "(", "0", ",", "0", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "if", "v", ".", "At", "(", "i", ",", "0", ")", "<", "min", "{", "min", "=", "v", ".", "At", "(", "i", ",", "0", ")", "\n", "}", "\n", "}", "\n", "return", "min", "\n", "}" ]
// Helper functions // Finds the min value of a mat.Vector
[ "Helper", "functions", "Finds", "the", "min", "value", "of", "a", "mat", ".", "Vector" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L257-L266
164,906
sjwhitworth/golearn
clustering/em.go
vectorMax
func vectorMax(v mat.Vector) float64 { n_obs, _ := v.Dims() max := v.At(0, 0) for i := 0; i < n_obs; i++ { if v.At(i, 0) > max { max = v.At(i, 0) } } return max }
go
func vectorMax(v mat.Vector) float64 { n_obs, _ := v.Dims() max := v.At(0, 0) for i := 0; i < n_obs; i++ { if v.At(i, 0) > max { max = v.At(i, 0) } } return max }
[ "func", "vectorMax", "(", "v", "mat", ".", "Vector", ")", "float64", "{", "n_obs", ",", "_", ":=", "v", ".", "Dims", "(", ")", "\n", "max", ":=", "v", ".", "At", "(", "0", ",", "0", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "if", "v", ".", "At", "(", "i", ",", "0", ")", ">", "max", "{", "max", "=", "v", ".", "At", "(", "i", ",", "0", ")", "\n", "}", "\n", "}", "\n", "return", "max", "\n", "}" ]
// Find the max value of a mat.Vector
[ "Find", "the", "max", "value", "of", "a", "mat", ".", "Vector" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L269-L278
164,907
sjwhitworth/golearn
clustering/em.go
vecToInts
func vecToInts(v mat.Vector) []int { n_obs, _ := v.Dims() var ints = make([]int, n_obs) for i := 0; i < n_obs; i++ { ints[i] = int(v.At(i, 0)) } return ints }
go
func vecToInts(v mat.Vector) []int { n_obs, _ := v.Dims() var ints = make([]int, n_obs) for i := 0; i < n_obs; i++ { ints[i] = int(v.At(i, 0)) } return ints }
[ "func", "vecToInts", "(", "v", "mat", ".", "Vector", ")", "[", "]", "int", "{", "n_obs", ",", "_", ":=", "v", ".", "Dims", "(", ")", "\n", "var", "ints", "=", "make", "(", "[", "]", "int", ",", "n_obs", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "ints", "[", "i", "]", "=", "int", "(", "v", ".", "At", "(", "i", ",", "0", ")", ")", "\n", "}", "\n", "return", "ints", "\n", "}" ]
// Converts a mat.Vector to an array of ints
[ "Converts", "a", "mat", ".", "Vector", "to", "an", "array", "of", "ints" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L281-L288
164,908
sjwhitworth/golearn
clustering/em.go
means
func means(X *mat.Dense) []float64 { n_obs, n_feats := X.Dims() var result []float64 for j := 0; j < n_feats; j++ { sum_j := 0.0 for i := 0; i < n_obs; i++ { sum_j = sum_j + X.At(i, j) } mean := (sum_j / float64(n_obs)) result = append(result, mean) } return result }
go
func means(X *mat.Dense) []float64 { n_obs, n_feats := X.Dims() var result []float64 for j := 0; j < n_feats; j++ { sum_j := 0.0 for i := 0; i < n_obs; i++ { sum_j = sum_j + X.At(i, j) } mean := (sum_j / float64(n_obs)) result = append(result, mean) } return result }
[ "func", "means", "(", "X", "*", "mat", ".", "Dense", ")", "[", "]", "float64", "{", "n_obs", ",", "n_feats", ":=", "X", ".", "Dims", "(", ")", "\n", "var", "result", "[", "]", "float64", "\n", "for", "j", ":=", "0", ";", "j", "<", "n_feats", ";", "j", "++", "{", "sum_j", ":=", "0.0", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "sum_j", "=", "sum_j", "+", "X", ".", "At", "(", "i", ",", "j", ")", "\n", "}", "\n", "mean", ":=", "(", "sum_j", "/", "float64", "(", "n_obs", ")", ")", "\n", "result", "=", "append", "(", "result", ",", "mean", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Computes column Means of a mat.Dense
[ "Computes", "column", "Means", "of", "a", "mat", ".", "Dense" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L291-L303
164,909
sjwhitworth/golearn
clustering/em.go
where
func where(X *mat.Dense, y mat.Vector, target int) *mat.Dense { n_obs, n_feats := X.Dims() var result []float64 rows := 0 for i := 0; i < n_obs; i++ { if int(y.At(i, 0)) == target { for j := 0; j < n_feats; j++ { result = append(result, X.At(i, j)) } rows++ } } X_i := mat.NewDense(rows, n_feats, result) return X_i }
go
func where(X *mat.Dense, y mat.Vector, target int) *mat.Dense { n_obs, n_feats := X.Dims() var result []float64 rows := 0 for i := 0; i < n_obs; i++ { if int(y.At(i, 0)) == target { for j := 0; j < n_feats; j++ { result = append(result, X.At(i, j)) } rows++ } } X_i := mat.NewDense(rows, n_feats, result) return X_i }
[ "func", "where", "(", "X", "*", "mat", ".", "Dense", ",", "y", "mat", ".", "Vector", ",", "target", "int", ")", "*", "mat", ".", "Dense", "{", "n_obs", ",", "n_feats", ":=", "X", ".", "Dims", "(", ")", "\n", "var", "result", "[", "]", "float64", "\n", "rows", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "n_obs", ";", "i", "++", "{", "if", "int", "(", "y", ".", "At", "(", "i", ",", "0", ")", ")", "==", "target", "{", "for", "j", ":=", "0", ";", "j", "<", "n_feats", ";", "j", "++", "{", "result", "=", "append", "(", "result", ",", "X", ".", "At", "(", "i", ",", "j", ")", ")", "\n", "}", "\n", "rows", "++", "\n", "}", "\n", "}", "\n", "X_i", ":=", "mat", ".", "NewDense", "(", "rows", ",", "n_feats", ",", "result", ")", "\n", "return", "X_i", "\n", "}" ]
// Subest a mat.Dense with rows matching a target value
[ "Subest", "a", "mat", ".", "Dense", "with", "rows", "matching", "a", "target", "value" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L306-L320
164,910
sjwhitworth/golearn
clustering/em.go
identity
func identity(N int) []float64 { var results []float64 for i := 0; i < N; i++ { for j := 0; j < N; j++ { if j == i { results = append(results, 1) } else { results = append(results, 0) } } } return results }
go
func identity(N int) []float64 { var results []float64 for i := 0; i < N; i++ { for j := 0; j < N; j++ { if j == i { results = append(results, 1) } else { results = append(results, 0) } } } return results }
[ "func", "identity", "(", "N", "int", ")", "[", "]", "float64", "{", "var", "results", "[", "]", "float64", "\n", "for", "i", ":=", "0", ";", "i", "<", "N", ";", "i", "++", "{", "for", "j", ":=", "0", ";", "j", "<", "N", ";", "j", "++", "{", "if", "j", "==", "i", "{", "results", "=", "append", "(", "results", ",", "1", ")", "\n", "}", "else", "{", "results", "=", "append", "(", "results", ",", "0", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "results", "\n", "}" ]
// Returns values for a square array with ones on the main diagonal
[ "Returns", "values", "for", "a", "square", "array", "with", "ones", "on", "the", "main", "diagonal" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L323-L335
164,911
sjwhitworth/golearn
clustering/em.go
symVals
func symVals(M int, v float64) []float64 { var results []float64 for i := 0; i < M*M; i++ { results = append(results, v) } return results }
go
func symVals(M int, v float64) []float64 { var results []float64 for i := 0; i < M*M; i++ { results = append(results, v) } return results }
[ "func", "symVals", "(", "M", "int", ",", "v", "float64", ")", "[", "]", "float64", "{", "var", "results", "[", "]", "float64", "\n", "for", "i", ":=", "0", ";", "i", "<", "M", "*", "M", ";", "i", "++", "{", "results", "=", "append", "(", "results", ",", "v", ")", "\n", "}", "\n", "return", "results", "\n", "}" ]
// Generates an array of values for symmetric matrix
[ "Generates", "an", "array", "of", "values", "for", "symmetric", "matrix" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/em.go#L338-L344
164,912
sjwhitworth/golearn
base/arff.go
SerializeInstancesToDenseARFF
func SerializeInstancesToDenseARFF(inst FixedDataGrid, path, relation string) error { // Get all of the Attributes in a reasonable order attrs := NonClassAttributes(inst) cAttrs := inst.AllClassAttributes() for _, c := range cAttrs { attrs = append(attrs, c) } return SerializeInstancesToDenseARFFWithAttributes(inst, attrs, path, relation) }
go
func SerializeInstancesToDenseARFF(inst FixedDataGrid, path, relation string) error { // Get all of the Attributes in a reasonable order attrs := NonClassAttributes(inst) cAttrs := inst.AllClassAttributes() for _, c := range cAttrs { attrs = append(attrs, c) } return SerializeInstancesToDenseARFFWithAttributes(inst, attrs, path, relation) }
[ "func", "SerializeInstancesToDenseARFF", "(", "inst", "FixedDataGrid", ",", "path", ",", "relation", "string", ")", "error", "{", "// Get all of the Attributes in a reasonable order", "attrs", ":=", "NonClassAttributes", "(", "inst", ")", "\n", "cAttrs", ":=", "inst", ".", "AllClassAttributes", "(", ")", "\n", "for", "_", ",", "c", ":=", "range", "cAttrs", "{", "attrs", "=", "append", "(", "attrs", ",", "c", ")", "\n", "}", "\n\n", "return", "SerializeInstancesToDenseARFFWithAttributes", "(", "inst", ",", "attrs", ",", "path", ",", "relation", ")", "\n\n", "}" ]
// SerializeInstancesToDenseARFF writes the given FixedDataGrid to a // densely-formatted ARFF file.
[ "SerializeInstancesToDenseARFF", "writes", "the", "given", "FixedDataGrid", "to", "a", "densely", "-", "formatted", "ARFF", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/arff.go#L16-L27
164,913
sjwhitworth/golearn
base/arff.go
SerializeInstancesToDenseARFFWithAttributes
func SerializeInstancesToDenseARFFWithAttributes(inst FixedDataGrid, rawAttrs []Attribute, path, relation string) error { // Open output file f, err := os.OpenFile(path, os.O_RDWR, 0600) if err != nil { return err } defer f.Close() return SerializeInstancesToWriterDenseARFFWithAttributes(f, inst, rawAttrs, relation) }
go
func SerializeInstancesToDenseARFFWithAttributes(inst FixedDataGrid, rawAttrs []Attribute, path, relation string) error { // Open output file f, err := os.OpenFile(path, os.O_RDWR, 0600) if err != nil { return err } defer f.Close() return SerializeInstancesToWriterDenseARFFWithAttributes(f, inst, rawAttrs, relation) }
[ "func", "SerializeInstancesToDenseARFFWithAttributes", "(", "inst", "FixedDataGrid", ",", "rawAttrs", "[", "]", "Attribute", ",", "path", ",", "relation", "string", ")", "error", "{", "// Open output file", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_RDWR", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "SerializeInstancesToWriterDenseARFFWithAttributes", "(", "f", ",", "inst", ",", "rawAttrs", ",", "relation", ")", "\n\n", "}" ]
// SerializeInstancesToDenseARFFWithAttributes writes the given FixedDataGrid to a // densely-formatted ARFF file with the header Attributes in the order given.
[ "SerializeInstancesToDenseARFFWithAttributes", "writes", "the", "given", "FixedDataGrid", "to", "a", "densely", "-", "formatted", "ARFF", "file", "with", "the", "header", "Attributes", "in", "the", "order", "given", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/arff.go#L31-L42
164,914
sjwhitworth/golearn
base/arff.go
ParseARFFGetRows
func ParseARFFGetRows(filepath string) (int, error) { f, err := os.Open(filepath) if err != nil { return 0, err } defer f.Close() counting := false count := 0 scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() if len(line) == 0 { continue } if counting { if line[0] == '@' { continue } if line[0] == '%' { continue } count++ continue } if line[0] == '@' { line = strings.ToLower(line) if line == "@data" { counting = true } } } return count, nil }
go
func ParseARFFGetRows(filepath string) (int, error) { f, err := os.Open(filepath) if err != nil { return 0, err } defer f.Close() counting := false count := 0 scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() if len(line) == 0 { continue } if counting { if line[0] == '@' { continue } if line[0] == '%' { continue } count++ continue } if line[0] == '@' { line = strings.ToLower(line) if line == "@data" { counting = true } } } return count, nil }
[ "func", "ParseARFFGetRows", "(", "filepath", "string", ")", "(", "int", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "counting", ":=", "false", "\n", "count", ":=", "0", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "f", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "line", ":=", "scanner", ".", "Text", "(", ")", "\n", "if", "len", "(", "line", ")", "==", "0", "{", "continue", "\n", "}", "\n", "if", "counting", "{", "if", "line", "[", "0", "]", "==", "'@'", "{", "continue", "\n", "}", "\n", "if", "line", "[", "0", "]", "==", "'%'", "{", "continue", "\n", "}", "\n", "count", "++", "\n", "continue", "\n", "}", "\n", "if", "line", "[", "0", "]", "==", "'@'", "{", "line", "=", "strings", ".", "ToLower", "(", "line", ")", "\n", "if", "line", "==", "\"", "\"", "{", "counting", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "count", ",", "nil", "\n", "}" ]
// ParseARFFGetRows returns the number of data rows in an ARFF file.
[ "ParseARFFGetRows", "returns", "the", "number", "of", "data", "rows", "in", "an", "ARFF", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/arff.go#L77-L111
164,915
sjwhitworth/golearn
base/arff.go
ParseDenseARFFToInstances
func ParseDenseARFFToInstances(filepath string) (ret *DenseInstances, err error) { defer func() { if r := recover(); r != nil { if _, ok := r.(runtime.Error); ok { panic(r) } err = r.(error) } }() // Find the number of rows in the file rows, err := ParseARFFGetRows(filepath) if err != nil { return nil, err } // Get the Attributes we want attrs := ParseARFFGetAttributes(filepath) // Allocate return value ret = NewDenseInstances() // Add all the Attributes for _, a := range attrs { ret.AddAttribute(a) } // Set the last Attribute as the class ret.AddClassAttribute(attrs[len(attrs)-1]) ret.Extend(rows) f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() // Read the data // Seek past the header err = ParseDenseARFFBuildInstancesFromReader(f, attrs, ret) if err != nil { ret = nil } return ret, err }
go
func ParseDenseARFFToInstances(filepath string) (ret *DenseInstances, err error) { defer func() { if r := recover(); r != nil { if _, ok := r.(runtime.Error); ok { panic(r) } err = r.(error) } }() // Find the number of rows in the file rows, err := ParseARFFGetRows(filepath) if err != nil { return nil, err } // Get the Attributes we want attrs := ParseARFFGetAttributes(filepath) // Allocate return value ret = NewDenseInstances() // Add all the Attributes for _, a := range attrs { ret.AddAttribute(a) } // Set the last Attribute as the class ret.AddClassAttribute(attrs[len(attrs)-1]) ret.Extend(rows) f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() // Read the data // Seek past the header err = ParseDenseARFFBuildInstancesFromReader(f, attrs, ret) if err != nil { ret = nil } return ret, err }
[ "func", "ParseDenseARFFToInstances", "(", "filepath", "string", ")", "(", "ret", "*", "DenseInstances", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "r", ".", "(", "runtime", ".", "Error", ")", ";", "ok", "{", "panic", "(", "r", ")", "\n", "}", "\n", "err", "=", "r", ".", "(", "error", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Find the number of rows in the file", "rows", ",", "err", ":=", "ParseARFFGetRows", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Get the Attributes we want", "attrs", ":=", "ParseARFFGetAttributes", "(", "filepath", ")", "\n\n", "// Allocate return value", "ret", "=", "NewDenseInstances", "(", ")", "\n\n", "// Add all the Attributes", "for", "_", ",", "a", ":=", "range", "attrs", "{", "ret", ".", "AddAttribute", "(", "a", ")", "\n", "}", "\n\n", "// Set the last Attribute as the class", "ret", ".", "AddClassAttribute", "(", "attrs", "[", "len", "(", "attrs", ")", "-", "1", "]", ")", "\n", "ret", ".", "Extend", "(", "rows", ")", "\n\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "// Read the data", "// Seek past the header", "err", "=", "ParseDenseARFFBuildInstancesFromReader", "(", "f", ",", "attrs", ",", "ret", ")", "\n", "if", "err", "!=", "nil", "{", "ret", "=", "nil", "\n", "}", "\n", "return", "ret", ",", "err", "\n", "}" ]
// ParseDenseARFFToInstances parses the dense ARFF File into a FixedDataGrid
[ "ParseDenseARFFToInstances", "parses", "the", "dense", "ARFF", "File", "into", "a", "FixedDataGrid" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/arff.go#L253-L297
164,916
sjwhitworth/golearn
meta/one_v_all.go
NewOneVsAllModel
func NewOneVsAllModel(f func(string) base.Classifier) *OneVsAllModel { return &OneVsAllModel{ f, nil, nil, 0, nil, nil, } }
go
func NewOneVsAllModel(f func(string) base.Classifier) *OneVsAllModel { return &OneVsAllModel{ f, nil, nil, 0, nil, nil, } }
[ "func", "NewOneVsAllModel", "(", "f", "func", "(", "string", ")", "base", ".", "Classifier", ")", "*", "OneVsAllModel", "{", "return", "&", "OneVsAllModel", "{", "f", ",", "nil", ",", "nil", ",", "0", ",", "nil", ",", "nil", ",", "}", "\n", "}" ]
// NewOneVsAllModel creates a new OneVsAllModel. The argument // must be a function which returns a base.Classifier ready for training.
[ "NewOneVsAllModel", "creates", "a", "new", "OneVsAllModel", ".", "The", "argument", "must", "be", "a", "function", "which", "returns", "a", "base", ".", "Classifier", "ready", "for", "training", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/meta/one_v_all.go#L23-L32
164,917
sjwhitworth/golearn
kdtree/kdtree.go
Build
func (t *Tree) Build(data [][]float64) error { if len(data) == 0 { return errors.New("no input data") } size := len(data[0]) for _, v := range data { if len(v) != size { return errors.New("amounts of features are not the same") } } t.data = data newData := make([]int, len(data)) for k, _ := range newData { newData[k] = k } if len(data) == 1 { t.firstDiv = &node{feature: -1, srcRowNo: 0} t.firstDiv.value = make([]float64, len(data[0])) copy(t.firstDiv.value, data[0]) } else { t.firstDiv = t.buildHandle(newData, 0) } return nil }
go
func (t *Tree) Build(data [][]float64) error { if len(data) == 0 { return errors.New("no input data") } size := len(data[0]) for _, v := range data { if len(v) != size { return errors.New("amounts of features are not the same") } } t.data = data newData := make([]int, len(data)) for k, _ := range newData { newData[k] = k } if len(data) == 1 { t.firstDiv = &node{feature: -1, srcRowNo: 0} t.firstDiv.value = make([]float64, len(data[0])) copy(t.firstDiv.value, data[0]) } else { t.firstDiv = t.buildHandle(newData, 0) } return nil }
[ "func", "(", "t", "*", "Tree", ")", "Build", "(", "data", "[", "]", "[", "]", "float64", ")", "error", "{", "if", "len", "(", "data", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "size", ":=", "len", "(", "data", "[", "0", "]", ")", "\n", "for", "_", ",", "v", ":=", "range", "data", "{", "if", "len", "(", "v", ")", "!=", "size", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "t", ".", "data", "=", "data", "\n\n", "newData", ":=", "make", "(", "[", "]", "int", ",", "len", "(", "data", ")", ")", "\n", "for", "k", ",", "_", ":=", "range", "newData", "{", "newData", "[", "k", "]", "=", "k", "\n", "}", "\n\n", "if", "len", "(", "data", ")", "==", "1", "{", "t", ".", "firstDiv", "=", "&", "node", "{", "feature", ":", "-", "1", ",", "srcRowNo", ":", "0", "}", "\n", "t", ".", "firstDiv", ".", "value", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "data", "[", "0", "]", ")", ")", "\n", "copy", "(", "t", ".", "firstDiv", ".", "value", ",", "data", "[", "0", "]", ")", "\n", "}", "else", "{", "t", ".", "firstDiv", "=", "t", ".", "buildHandle", "(", "newData", ",", "0", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Build builds the kdtree with specific data.
[ "Build", "builds", "the", "kdtree", "with", "specific", "data", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/kdtree/kdtree.go#L42-L69
164,918
sjwhitworth/golearn
kdtree/kdtree.go
buildHandle
func (t *Tree) buildHandle(data []int, featureIndex int) *node { n := &node{feature: featureIndex} tmp := SortData{RowData: t.data, Data: data, Feature: featureIndex} sort.Sort(tmp) middle := len(data) / 2 divPoint := middle for i := middle + 1; i < len(data); i++ { if t.data[data[i]][featureIndex] == t.data[data[middle]][featureIndex] { divPoint = i } else { break } } n.srcRowNo = data[divPoint] n.value = make([]float64, len(t.data[data[divPoint]])) copy(n.value, t.data[data[divPoint]]) if divPoint == 1 { n.left = &node{feature: -1} n.left.value = make([]float64, len(t.data[data[0]])) copy(n.left.value, t.data[data[0]]) n.left.srcRowNo = data[0] } else { n.left = t.buildHandle(data[:divPoint], (featureIndex+1)%len(t.data[data[0]])) } if divPoint == (len(data) - 2) { n.right = &node{feature: -1} n.right.value = make([]float64, len(t.data[data[divPoint+1]])) copy(n.right.value, t.data[data[divPoint+1]]) n.right.srcRowNo = data[divPoint+1] } else if divPoint != (len(data) - 1) { n.right = t.buildHandle(data[divPoint+1:], (featureIndex+1)%len(t.data[data[0]])) } else { n.right = &node{feature: -2} } return n }
go
func (t *Tree) buildHandle(data []int, featureIndex int) *node { n := &node{feature: featureIndex} tmp := SortData{RowData: t.data, Data: data, Feature: featureIndex} sort.Sort(tmp) middle := len(data) / 2 divPoint := middle for i := middle + 1; i < len(data); i++ { if t.data[data[i]][featureIndex] == t.data[data[middle]][featureIndex] { divPoint = i } else { break } } n.srcRowNo = data[divPoint] n.value = make([]float64, len(t.data[data[divPoint]])) copy(n.value, t.data[data[divPoint]]) if divPoint == 1 { n.left = &node{feature: -1} n.left.value = make([]float64, len(t.data[data[0]])) copy(n.left.value, t.data[data[0]]) n.left.srcRowNo = data[0] } else { n.left = t.buildHandle(data[:divPoint], (featureIndex+1)%len(t.data[data[0]])) } if divPoint == (len(data) - 2) { n.right = &node{feature: -1} n.right.value = make([]float64, len(t.data[data[divPoint+1]])) copy(n.right.value, t.data[data[divPoint+1]]) n.right.srcRowNo = data[divPoint+1] } else if divPoint != (len(data) - 1) { n.right = t.buildHandle(data[divPoint+1:], (featureIndex+1)%len(t.data[data[0]])) } else { n.right = &node{feature: -2} } return n }
[ "func", "(", "t", "*", "Tree", ")", "buildHandle", "(", "data", "[", "]", "int", ",", "featureIndex", "int", ")", "*", "node", "{", "n", ":=", "&", "node", "{", "feature", ":", "featureIndex", "}", "\n\n", "tmp", ":=", "SortData", "{", "RowData", ":", "t", ".", "data", ",", "Data", ":", "data", ",", "Feature", ":", "featureIndex", "}", "\n", "sort", ".", "Sort", "(", "tmp", ")", "\n", "middle", ":=", "len", "(", "data", ")", "/", "2", "\n\n", "divPoint", ":=", "middle", "\n", "for", "i", ":=", "middle", "+", "1", ";", "i", "<", "len", "(", "data", ")", ";", "i", "++", "{", "if", "t", ".", "data", "[", "data", "[", "i", "]", "]", "[", "featureIndex", "]", "==", "t", ".", "data", "[", "data", "[", "middle", "]", "]", "[", "featureIndex", "]", "{", "divPoint", "=", "i", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n\n", "n", ".", "srcRowNo", "=", "data", "[", "divPoint", "]", "\n", "n", ".", "value", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "t", ".", "data", "[", "data", "[", "divPoint", "]", "]", ")", ")", "\n", "copy", "(", "n", ".", "value", ",", "t", ".", "data", "[", "data", "[", "divPoint", "]", "]", ")", "\n\n", "if", "divPoint", "==", "1", "{", "n", ".", "left", "=", "&", "node", "{", "feature", ":", "-", "1", "}", "\n", "n", ".", "left", ".", "value", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "t", ".", "data", "[", "data", "[", "0", "]", "]", ")", ")", "\n", "copy", "(", "n", ".", "left", ".", "value", ",", "t", ".", "data", "[", "data", "[", "0", "]", "]", ")", "\n", "n", ".", "left", ".", "srcRowNo", "=", "data", "[", "0", "]", "\n", "}", "else", "{", "n", ".", "left", "=", "t", ".", "buildHandle", "(", "data", "[", ":", "divPoint", "]", ",", "(", "featureIndex", "+", "1", ")", "%", "len", "(", "t", ".", "data", "[", "data", "[", "0", "]", "]", ")", ")", "\n", "}", "\n\n", "if", "divPoint", "==", "(", "len", "(", "data", ")", "-", "2", ")", "{", "n", ".", "right", "=", "&", "node", "{", "feature", ":", "-", "1", "}", "\n", "n", ".", "right", ".", "value", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "t", ".", "data", "[", "data", "[", "divPoint", "+", "1", "]", "]", ")", ")", "\n", "copy", "(", "n", ".", "right", ".", "value", ",", "t", ".", "data", "[", "data", "[", "divPoint", "+", "1", "]", "]", ")", "\n", "n", ".", "right", ".", "srcRowNo", "=", "data", "[", "divPoint", "+", "1", "]", "\n", "}", "else", "if", "divPoint", "!=", "(", "len", "(", "data", ")", "-", "1", ")", "{", "n", ".", "right", "=", "t", ".", "buildHandle", "(", "data", "[", "divPoint", "+", "1", ":", "]", ",", "(", "featureIndex", "+", "1", ")", "%", "len", "(", "t", ".", "data", "[", "data", "[", "0", "]", "]", ")", ")", "\n", "}", "else", "{", "n", ".", "right", "=", "&", "node", "{", "feature", ":", "-", "2", "}", "\n", "}", "\n", "return", "n", "\n", "}" ]
// buildHandle builds the kdtree recursively.
[ "buildHandle", "builds", "the", "kdtree", "recursively", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/kdtree/kdtree.go#L72-L112
164,919
sjwhitworth/golearn
base/view.go
NewInstancesViewFromVisible
func NewInstancesViewFromVisible(src FixedDataGrid, rows []int, attrs []Attribute) *InstancesView { ret := &InstancesView{ src, ResolveAttributes(src, attrs), make(map[int]int), make(map[Attribute]bool), true, } for i, a := range rows { ret.rows[i] = a } ret.addClassAttrsFromSrc(src) return ret }
go
func NewInstancesViewFromVisible(src FixedDataGrid, rows []int, attrs []Attribute) *InstancesView { ret := &InstancesView{ src, ResolveAttributes(src, attrs), make(map[int]int), make(map[Attribute]bool), true, } for i, a := range rows { ret.rows[i] = a } ret.addClassAttrsFromSrc(src) return ret }
[ "func", "NewInstancesViewFromVisible", "(", "src", "FixedDataGrid", ",", "rows", "[", "]", "int", ",", "attrs", "[", "]", "Attribute", ")", "*", "InstancesView", "{", "ret", ":=", "&", "InstancesView", "{", "src", ",", "ResolveAttributes", "(", "src", ",", "attrs", ")", ",", "make", "(", "map", "[", "int", "]", "int", ")", ",", "make", "(", "map", "[", "Attribute", "]", "bool", ")", ",", "true", ",", "}", "\n\n", "for", "i", ",", "a", ":=", "range", "rows", "{", "ret", ".", "rows", "[", "i", "]", "=", "a", "\n", "}", "\n\n", "ret", ".", "addClassAttrsFromSrc", "(", "src", ")", "\n", "return", "ret", "\n", "}" ]
// NewInstancesViewFromVisible creates a new InstancesView from a source // FixedDataGrid, a slice of row numbers and a slice of Attributes. // // Only the rows specified will appear in this InstancesView, and they will // appear in the same order they appear within the rows array. // // Only the Attributes specified will appear in this InstancesView. Retrieving // Attribute specifications from this InstancesView will maintain their order.
[ "NewInstancesViewFromVisible", "creates", "a", "new", "InstancesView", "from", "a", "source", "FixedDataGrid", "a", "slice", "of", "row", "numbers", "and", "a", "slice", "of", "Attributes", ".", "Only", "the", "rows", "specified", "will", "appear", "in", "this", "InstancesView", "and", "they", "will", "appear", "in", "the", "same", "order", "they", "appear", "within", "the", "rows", "array", ".", "Only", "the", "Attributes", "specified", "will", "appear", "in", "this", "InstancesView", ".", "Retrieving", "Attribute", "specifications", "from", "this", "InstancesView", "will", "maintain", "their", "order", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L78-L93
164,920
sjwhitworth/golearn
base/view.go
NewInstancesViewFromAttrs
func NewInstancesViewFromAttrs(src FixedDataGrid, attrs []Attribute) *InstancesView { ret := &InstancesView{ src, ResolveAttributes(src, attrs), nil, make(map[Attribute]bool), false, } ret.addClassAttrsFromSrc(src) return ret }
go
func NewInstancesViewFromAttrs(src FixedDataGrid, attrs []Attribute) *InstancesView { ret := &InstancesView{ src, ResolveAttributes(src, attrs), nil, make(map[Attribute]bool), false, } ret.addClassAttrsFromSrc(src) return ret }
[ "func", "NewInstancesViewFromAttrs", "(", "src", "FixedDataGrid", ",", "attrs", "[", "]", "Attribute", ")", "*", "InstancesView", "{", "ret", ":=", "&", "InstancesView", "{", "src", ",", "ResolveAttributes", "(", "src", ",", "attrs", ")", ",", "nil", ",", "make", "(", "map", "[", "Attribute", "]", "bool", ")", ",", "false", ",", "}", "\n\n", "ret", ".", "addClassAttrsFromSrc", "(", "src", ")", "\n", "return", "ret", "\n", "}" ]
// NewInstancesViewFromAttrs creates a new InstancesView from a source // FixedDataGrid and a slice of Attributes. // // Only the Attributes specified will appear in this InstancesView.
[ "NewInstancesViewFromAttrs", "creates", "a", "new", "InstancesView", "from", "a", "source", "FixedDataGrid", "and", "a", "slice", "of", "Attributes", ".", "Only", "the", "Attributes", "specified", "will", "appear", "in", "this", "InstancesView", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L99-L110
164,921
sjwhitworth/golearn
base/view.go
GetAttribute
func (v *InstancesView) GetAttribute(a Attribute) (AttributeSpec, error) { if a == nil { return AttributeSpec{}, fmt.Errorf("Attribute can't be nil") } // Pass-through on nil if v.attrs == nil { return v.src.GetAttribute(a) } // Otherwise for _, r := range v.attrs { // If the attribute matches... if r.GetAttribute().Equals(a) { return r, nil } } return AttributeSpec{}, fmt.Errorf("Requested Attribute has been filtered") }
go
func (v *InstancesView) GetAttribute(a Attribute) (AttributeSpec, error) { if a == nil { return AttributeSpec{}, fmt.Errorf("Attribute can't be nil") } // Pass-through on nil if v.attrs == nil { return v.src.GetAttribute(a) } // Otherwise for _, r := range v.attrs { // If the attribute matches... if r.GetAttribute().Equals(a) { return r, nil } } return AttributeSpec{}, fmt.Errorf("Requested Attribute has been filtered") }
[ "func", "(", "v", "*", "InstancesView", ")", "GetAttribute", "(", "a", "Attribute", ")", "(", "AttributeSpec", ",", "error", ")", "{", "if", "a", "==", "nil", "{", "return", "AttributeSpec", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// Pass-through on nil", "if", "v", ".", "attrs", "==", "nil", "{", "return", "v", ".", "src", ".", "GetAttribute", "(", "a", ")", "\n", "}", "\n", "// Otherwise", "for", "_", ",", "r", ":=", "range", "v", ".", "attrs", "{", "// If the attribute matches...", "if", "r", ".", "GetAttribute", "(", ")", ".", "Equals", "(", "a", ")", "{", "return", "r", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "AttributeSpec", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// GetAttribute returns an Attribute specification matching an Attribute // if it has not been filtered. // // The AttributeSpecs returned are the same as those returned by the // source FixedDataGrid.
[ "GetAttribute", "returns", "an", "Attribute", "specification", "matching", "an", "Attribute", "if", "it", "has", "not", "been", "filtered", ".", "The", "AttributeSpecs", "returned", "are", "the", "same", "as", "those", "returned", "by", "the", "source", "FixedDataGrid", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L117-L133
164,922
sjwhitworth/golearn
base/view.go
AllAttributes
func (v *InstancesView) AllAttributes() []Attribute { if v.attrs == nil { return v.src.AllAttributes() } ret := make([]Attribute, len(v.attrs)) for i, a := range v.attrs { ret[i] = a.GetAttribute() } return ret }
go
func (v *InstancesView) AllAttributes() []Attribute { if v.attrs == nil { return v.src.AllAttributes() } ret := make([]Attribute, len(v.attrs)) for i, a := range v.attrs { ret[i] = a.GetAttribute() } return ret }
[ "func", "(", "v", "*", "InstancesView", ")", "AllAttributes", "(", ")", "[", "]", "Attribute", "{", "if", "v", ".", "attrs", "==", "nil", "{", "return", "v", ".", "src", ".", "AllAttributes", "(", ")", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "len", "(", "v", ".", "attrs", ")", ")", "\n\n", "for", "i", ",", "a", ":=", "range", "v", ".", "attrs", "{", "ret", "[", "i", "]", "=", "a", ".", "GetAttribute", "(", ")", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// AllAttributes returns every Attribute which hasn't been filtered.
[ "AllAttributes", "returns", "every", "Attribute", "which", "hasn", "t", "been", "filtered", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L136-L149
164,923
sjwhitworth/golearn
base/view.go
AddClassAttribute
func (v *InstancesView) AddClassAttribute(a Attribute) error { // Check that this Attribute is defined matched := false for _, r := range v.AllAttributes() { if r.Equals(a) { matched = true } } if !matched { return fmt.Errorf("Attribute has been filtered") } v.classAttrs[a] = true return nil }
go
func (v *InstancesView) AddClassAttribute(a Attribute) error { // Check that this Attribute is defined matched := false for _, r := range v.AllAttributes() { if r.Equals(a) { matched = true } } if !matched { return fmt.Errorf("Attribute has been filtered") } v.classAttrs[a] = true return nil }
[ "func", "(", "v", "*", "InstancesView", ")", "AddClassAttribute", "(", "a", "Attribute", ")", "error", "{", "// Check that this Attribute is defined", "matched", ":=", "false", "\n", "for", "_", ",", "r", ":=", "range", "v", ".", "AllAttributes", "(", ")", "{", "if", "r", ".", "Equals", "(", "a", ")", "{", "matched", "=", "true", "\n", "}", "\n", "}", "\n", "if", "!", "matched", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "v", ".", "classAttrs", "[", "a", "]", "=", "true", "\n", "return", "nil", "\n", "}" ]
// AddClassAttribute adds the given Attribute to the set of defined // class Attributes, if it hasn't been filtered.
[ "AddClassAttribute", "adds", "the", "given", "Attribute", "to", "the", "set", "of", "defined", "class", "Attributes", "if", "it", "hasn", "t", "been", "filtered", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L153-L167
164,924
sjwhitworth/golearn
base/view.go
RemoveClassAttribute
func (v *InstancesView) RemoveClassAttribute(a Attribute) error { v.classAttrs[a] = false return nil }
go
func (v *InstancesView) RemoveClassAttribute(a Attribute) error { v.classAttrs[a] = false return nil }
[ "func", "(", "v", "*", "InstancesView", ")", "RemoveClassAttribute", "(", "a", "Attribute", ")", "error", "{", "v", ".", "classAttrs", "[", "a", "]", "=", "false", "\n", "return", "nil", "\n", "}" ]
// RemoveClassAttribute removes the given Attribute from the set of // class Attributes.
[ "RemoveClassAttribute", "removes", "the", "given", "Attribute", "from", "the", "set", "of", "class", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L171-L174
164,925
sjwhitworth/golearn
base/view.go
AllClassAttributes
func (v *InstancesView) AllClassAttributes() []Attribute { ret := make([]Attribute, 0) for a := range v.classAttrs { if v.classAttrs[a] { ret = append(ret, a) } } return ret }
go
func (v *InstancesView) AllClassAttributes() []Attribute { ret := make([]Attribute, 0) for a := range v.classAttrs { if v.classAttrs[a] { ret = append(ret, a) } } return ret }
[ "func", "(", "v", "*", "InstancesView", ")", "AllClassAttributes", "(", ")", "[", "]", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "0", ")", "\n", "for", "a", ":=", "range", "v", ".", "classAttrs", "{", "if", "v", ".", "classAttrs", "[", "a", "]", "{", "ret", "=", "append", "(", "ret", ",", "a", ")", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// AllClassAttributes returns all the Attributes currently defined // as being class Attributes.
[ "AllClassAttributes", "returns", "all", "the", "Attributes", "currently", "defined", "as", "being", "class", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L178-L186
164,926
sjwhitworth/golearn
base/view.go
Size
func (v *InstancesView) Size() (int, int) { // Get the original size hSize, vSize := v.src.Size() // Adjust to the number of defined Attributes if v.attrs != nil { hSize = len(v.attrs) } // Adjust to the number of defined rows if v.rows != nil { if v.maskRows { vSize = len(v.rows) } else if len(v.rows) > vSize { vSize = len(v.rows) } } return hSize, vSize }
go
func (v *InstancesView) Size() (int, int) { // Get the original size hSize, vSize := v.src.Size() // Adjust to the number of defined Attributes if v.attrs != nil { hSize = len(v.attrs) } // Adjust to the number of defined rows if v.rows != nil { if v.maskRows { vSize = len(v.rows) } else if len(v.rows) > vSize { vSize = len(v.rows) } } return hSize, vSize }
[ "func", "(", "v", "*", "InstancesView", ")", "Size", "(", ")", "(", "int", ",", "int", ")", "{", "// Get the original size", "hSize", ",", "vSize", ":=", "v", ".", "src", ".", "Size", "(", ")", "\n", "// Adjust to the number of defined Attributes", "if", "v", ".", "attrs", "!=", "nil", "{", "hSize", "=", "len", "(", "v", ".", "attrs", ")", "\n", "}", "\n", "// Adjust to the number of defined rows", "if", "v", ".", "rows", "!=", "nil", "{", "if", "v", ".", "maskRows", "{", "vSize", "=", "len", "(", "v", ".", "rows", ")", "\n", "}", "else", "if", "len", "(", "v", ".", "rows", ")", ">", "vSize", "{", "vSize", "=", "len", "(", "v", ".", "rows", ")", "\n", "}", "\n", "}", "\n", "return", "hSize", ",", "vSize", "\n", "}" ]
// Size Returns the number of Attributes and rows this InstancesView // contains.
[ "Size", "Returns", "the", "number", "of", "Attributes", "and", "rows", "this", "InstancesView", "contains", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L231-L247
164,927
sjwhitworth/golearn
base/view.go
String
func (v *InstancesView) String() string { var buffer bytes.Buffer maxRows := 30 // Get all Attribute information as := ResolveAllAttributes(v) // Print header cols, rows := v.Size() buffer.WriteString("InstancesView with ") buffer.WriteString(fmt.Sprintf("%d row(s) ", rows)) buffer.WriteString(fmt.Sprintf("%d attribute(s)\n", cols)) if v.attrs != nil { buffer.WriteString(fmt.Sprintf("With defined Attribute view\n")) } if v.rows != nil { buffer.WriteString(fmt.Sprintf("With defined Row view\n")) } if v.maskRows { buffer.WriteString("Row masking on.\n") } buffer.WriteString(fmt.Sprintf("Attributes:\n")) for _, a := range as { prefix := "\t" if v.classAttrs[a.attr] { prefix = "*\t" } buffer.WriteString(fmt.Sprintf("%s%s\n", prefix, a.attr)) } // Print data if rows < maxRows { maxRows = rows } buffer.WriteString("Data:") for i := 0; i < maxRows; i++ { buffer.WriteString("\t") for _, a := range as { val := v.Get(a, i) buffer.WriteString(fmt.Sprintf("%s ", a.attr.GetStringFromSysVal(val))) } buffer.WriteString("\n") } missingRows := rows - maxRows if missingRows != 0 { buffer.WriteString(fmt.Sprintf("\t...\n%d row(s) undisplayed", missingRows)) } else { buffer.WriteString("All rows displayed") } return buffer.String() }
go
func (v *InstancesView) String() string { var buffer bytes.Buffer maxRows := 30 // Get all Attribute information as := ResolveAllAttributes(v) // Print header cols, rows := v.Size() buffer.WriteString("InstancesView with ") buffer.WriteString(fmt.Sprintf("%d row(s) ", rows)) buffer.WriteString(fmt.Sprintf("%d attribute(s)\n", cols)) if v.attrs != nil { buffer.WriteString(fmt.Sprintf("With defined Attribute view\n")) } if v.rows != nil { buffer.WriteString(fmt.Sprintf("With defined Row view\n")) } if v.maskRows { buffer.WriteString("Row masking on.\n") } buffer.WriteString(fmt.Sprintf("Attributes:\n")) for _, a := range as { prefix := "\t" if v.classAttrs[a.attr] { prefix = "*\t" } buffer.WriteString(fmt.Sprintf("%s%s\n", prefix, a.attr)) } // Print data if rows < maxRows { maxRows = rows } buffer.WriteString("Data:") for i := 0; i < maxRows; i++ { buffer.WriteString("\t") for _, a := range as { val := v.Get(a, i) buffer.WriteString(fmt.Sprintf("%s ", a.attr.GetStringFromSysVal(val))) } buffer.WriteString("\n") } missingRows := rows - maxRows if missingRows != 0 { buffer.WriteString(fmt.Sprintf("\t...\n%d row(s) undisplayed", missingRows)) } else { buffer.WriteString("All rows displayed") } return buffer.String() }
[ "func", "(", "v", "*", "InstancesView", ")", "String", "(", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "maxRows", ":=", "30", "\n\n", "// Get all Attribute information", "as", ":=", "ResolveAllAttributes", "(", "v", ")", "\n\n", "// Print header", "cols", ",", "rows", ":=", "v", ".", "Size", "(", ")", "\n", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rows", ")", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "cols", ")", ")", "\n", "if", "v", ".", "attrs", "!=", "nil", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ")", ")", "\n", "}", "\n", "if", "v", ".", "rows", "!=", "nil", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ")", ")", "\n", "}", "\n", "if", "v", ".", "maskRows", "{", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ")", ")", "\n\n", "for", "_", ",", "a", ":=", "range", "as", "{", "prefix", ":=", "\"", "\\t", "\"", "\n", "if", "v", ".", "classAttrs", "[", "a", ".", "attr", "]", "{", "prefix", "=", "\"", "\\t", "\"", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "prefix", ",", "a", ".", "attr", ")", ")", "\n", "}", "\n\n", "// Print data", "if", "rows", "<", "maxRows", "{", "maxRows", "=", "rows", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "maxRows", ";", "i", "++", "{", "buffer", ".", "WriteString", "(", "\"", "\\t", "\"", ")", "\n", "for", "_", ",", "a", ":=", "range", "as", "{", "val", ":=", "v", ".", "Get", "(", "a", ",", "i", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ".", "attr", ".", "GetStringFromSysVal", "(", "val", ")", ")", ")", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "missingRows", ":=", "rows", "-", "maxRows", "\n", "if", "missingRows", "!=", "0", "{", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\\n", "\"", ",", "missingRows", ")", ")", "\n", "}", "else", "{", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// String returns a human-readable summary of this InstancesView.
[ "String", "returns", "a", "human", "-", "readable", "summary", "of", "this", "InstancesView", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/view.go#L250-L303
164,928
sjwhitworth/golearn
base/fixed.go
Attributes
func (f *FixedAttributeGroup) Attributes() []Attribute { ret := make([]Attribute, len(f.attributes)) // Add Attributes for i, a := range f.attributes { ret[i] = a } return ret }
go
func (f *FixedAttributeGroup) Attributes() []Attribute { ret := make([]Attribute, len(f.attributes)) // Add Attributes for i, a := range f.attributes { ret[i] = a } return ret }
[ "func", "(", "f", "*", "FixedAttributeGroup", ")", "Attributes", "(", ")", "[", "]", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "len", "(", "f", ".", "attributes", ")", ")", "\n", "// Add Attributes", "for", "i", ",", "a", ":=", "range", "f", ".", "attributes", "{", "ret", "[", "i", "]", "=", "a", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Attributes returns a slice of Attributes in this FixedAttributeGroup
[ "Attributes", "returns", "a", "slice", "of", "Attributes", "in", "this", "FixedAttributeGroup" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/fixed.go#L29-L36
164,929
sjwhitworth/golearn
base/fixed.go
AddAttribute
func (f *FixedAttributeGroup) AddAttribute(a Attribute) error { f.attributes = append(f.attributes, a) return nil }
go
func (f *FixedAttributeGroup) AddAttribute(a Attribute) error { f.attributes = append(f.attributes, a) return nil }
[ "func", "(", "f", "*", "FixedAttributeGroup", ")", "AddAttribute", "(", "a", "Attribute", ")", "error", "{", "f", ".", "attributes", "=", "append", "(", "f", ".", "attributes", ",", "a", ")", "\n", "return", "nil", "\n", "}" ]
// AddAttribute adds an attribute to this FixedAttributeGroup
[ "AddAttribute", "adds", "an", "attribute", "to", "this", "FixedAttributeGroup" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/fixed.go#L39-L42
164,930
sjwhitworth/golearn
knn/knn.go
NewKnnClassifier
func NewKnnClassifier(distfunc, algorithm string, neighbours int) *KNNClassifier { KNN := KNNClassifier{} KNN.DistanceFunc = distfunc KNN.Algorithm = algorithm KNN.NearestNeighbours = neighbours KNN.Weighted = false KNN.AllowOptimisations = true return &KNN }
go
func NewKnnClassifier(distfunc, algorithm string, neighbours int) *KNNClassifier { KNN := KNNClassifier{} KNN.DistanceFunc = distfunc KNN.Algorithm = algorithm KNN.NearestNeighbours = neighbours KNN.Weighted = false KNN.AllowOptimisations = true return &KNN }
[ "func", "NewKnnClassifier", "(", "distfunc", ",", "algorithm", "string", ",", "neighbours", "int", ")", "*", "KNNClassifier", "{", "KNN", ":=", "KNNClassifier", "{", "}", "\n", "KNN", ".", "DistanceFunc", "=", "distfunc", "\n", "KNN", ".", "Algorithm", "=", "algorithm", "\n", "KNN", ".", "NearestNeighbours", "=", "neighbours", "\n", "KNN", ".", "Weighted", "=", "false", "\n", "KNN", ".", "AllowOptimisations", "=", "true", "\n", "return", "&", "KNN", "\n", "}" ]
// NewKnnClassifier returns a new classifier
[ "NewKnnClassifier", "returns", "a", "new", "classifier" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L35-L43
164,931
sjwhitworth/golearn
knn/knn.go
Fit
func (KNN *KNNClassifier) Fit(trainingData base.FixedDataGrid) error { KNN.TrainingData = trainingData return nil }
go
func (KNN *KNNClassifier) Fit(trainingData base.FixedDataGrid) error { KNN.TrainingData = trainingData return nil }
[ "func", "(", "KNN", "*", "KNNClassifier", ")", "Fit", "(", "trainingData", "base", ".", "FixedDataGrid", ")", "error", "{", "KNN", ".", "TrainingData", "=", "trainingData", "\n", "return", "nil", "\n", "}" ]
// Fit stores the training data for later
[ "Fit", "stores", "the", "training", "data", "for", "later" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L46-L49
164,932
sjwhitworth/golearn
knn/knn.go
Save
func (KNN *KNNClassifier) Save(filePath string) error { writer, err := base.CreateSerializedClassifierStub(filePath, KNN.GetMetadata()) if err != nil { return err } fmt.Printf("writer: %v", writer) return KNN.SaveWithPrefix(writer, "") }
go
func (KNN *KNNClassifier) Save(filePath string) error { writer, err := base.CreateSerializedClassifierStub(filePath, KNN.GetMetadata()) if err != nil { return err } fmt.Printf("writer: %v", writer) return KNN.SaveWithPrefix(writer, "") }
[ "func", "(", "KNN", "*", "KNNClassifier", ")", "Save", "(", "filePath", "string", ")", "error", "{", "writer", ",", "err", ":=", "base", ".", "CreateSerializedClassifierStub", "(", "filePath", ",", "KNN", ".", "GetMetadata", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fmt", ".", "Printf", "(", "\"", "\"", ",", "writer", ")", "\n", "return", "KNN", ".", "SaveWithPrefix", "(", "writer", ",", "\"", "\"", ")", "\n", "}" ]
// Save outputs a given KNN classifier.
[ "Save", "outputs", "a", "given", "KNN", "classifier", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L347-L354
164,933
sjwhitworth/golearn
knn/knn.go
SaveWithPrefix
func (KNN *KNNClassifier) SaveWithPrefix(writer *base.ClassifierSerializer, prefix string) error { err := writer.WriteInstancesForKey(writer.Prefix(prefix, "TrainingInstances"), KNN.TrainingData, true) if err != nil { return err } err = writer.Close() return err }
go
func (KNN *KNNClassifier) SaveWithPrefix(writer *base.ClassifierSerializer, prefix string) error { err := writer.WriteInstancesForKey(writer.Prefix(prefix, "TrainingInstances"), KNN.TrainingData, true) if err != nil { return err } err = writer.Close() return err }
[ "func", "(", "KNN", "*", "KNNClassifier", ")", "SaveWithPrefix", "(", "writer", "*", "base", ".", "ClassifierSerializer", ",", "prefix", "string", ")", "error", "{", "err", ":=", "writer", ".", "WriteInstancesForKey", "(", "writer", ".", "Prefix", "(", "prefix", ",", "\"", "\"", ")", ",", "KNN", ".", "TrainingData", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "writer", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}" ]
// SaveWithPrefix outputs KNN as part of another file.
[ "SaveWithPrefix", "outputs", "KNN", "as", "part", "of", "another", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L357-L364
164,934
sjwhitworth/golearn
knn/knn.go
Load
func (KNN *KNNClassifier) Load(filePath string) error { reader, err := base.ReadSerializedClassifierStub(filePath) if err != nil { return err } return KNN.LoadWithPrefix(reader, "") }
go
func (KNN *KNNClassifier) Load(filePath string) error { reader, err := base.ReadSerializedClassifierStub(filePath) if err != nil { return err } return KNN.LoadWithPrefix(reader, "") }
[ "func", "(", "KNN", "*", "KNNClassifier", ")", "Load", "(", "filePath", "string", ")", "error", "{", "reader", ",", "err", ":=", "base", ".", "ReadSerializedClassifierStub", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "KNN", ".", "LoadWithPrefix", "(", "reader", ",", "\"", "\"", ")", "\n", "}" ]
// Load reloads a given KNN classifier when it's the only thing in the output file.
[ "Load", "reloads", "a", "given", "KNN", "classifier", "when", "it", "s", "the", "only", "thing", "in", "the", "output", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L367-L374
164,935
sjwhitworth/golearn
knn/knn.go
LoadWithPrefix
func (KNN *KNNClassifier) LoadWithPrefix(reader *base.ClassifierDeserializer, prefix string) error { clsMetadata, err := reader.ReadMetadataAtPrefix(prefix) if err != nil { return err } if clsMetadata.ClassifierName != "KNN" { return fmt.Errorf("This file doesn't contain a KNN classifier") } if clsMetadata.ClassifierVersion != "1.0" { return fmt.Errorf("Can't understand this file format") } metadata := clsMetadata.ClassifierMetadata KNN.DistanceFunc = metadata["distance_func"].(string) KNN.Algorithm = metadata["algorithm"].(string) //KNN.NearestNeighbours = metadata["neighbours"].(int) KNN.Weighted = metadata["weighted"].(bool) KNN.AllowOptimisations = metadata["allow_optimizations"].(bool) // 101 on why JSON is a bad serialization format floatNeighbours := metadata["neighbours"].(float64) KNN.NearestNeighbours = int(floatNeighbours) KNN.TrainingData, err = reader.GetInstancesForKey(reader.Prefix(prefix, "TrainingInstances")) return err }
go
func (KNN *KNNClassifier) LoadWithPrefix(reader *base.ClassifierDeserializer, prefix string) error { clsMetadata, err := reader.ReadMetadataAtPrefix(prefix) if err != nil { return err } if clsMetadata.ClassifierName != "KNN" { return fmt.Errorf("This file doesn't contain a KNN classifier") } if clsMetadata.ClassifierVersion != "1.0" { return fmt.Errorf("Can't understand this file format") } metadata := clsMetadata.ClassifierMetadata KNN.DistanceFunc = metadata["distance_func"].(string) KNN.Algorithm = metadata["algorithm"].(string) //KNN.NearestNeighbours = metadata["neighbours"].(int) KNN.Weighted = metadata["weighted"].(bool) KNN.AllowOptimisations = metadata["allow_optimizations"].(bool) // 101 on why JSON is a bad serialization format floatNeighbours := metadata["neighbours"].(float64) KNN.NearestNeighbours = int(floatNeighbours) KNN.TrainingData, err = reader.GetInstancesForKey(reader.Prefix(prefix, "TrainingInstances")) return err }
[ "func", "(", "KNN", "*", "KNNClassifier", ")", "LoadWithPrefix", "(", "reader", "*", "base", ".", "ClassifierDeserializer", ",", "prefix", "string", ")", "error", "{", "clsMetadata", ",", "err", ":=", "reader", ".", "ReadMetadataAtPrefix", "(", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "clsMetadata", ".", "ClassifierName", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "clsMetadata", ".", "ClassifierVersion", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "metadata", ":=", "clsMetadata", ".", "ClassifierMetadata", "\n", "KNN", ".", "DistanceFunc", "=", "metadata", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "KNN", ".", "Algorithm", "=", "metadata", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "//KNN.NearestNeighbours = metadata[\"neighbours\"].(int)", "KNN", ".", "Weighted", "=", "metadata", "[", "\"", "\"", "]", ".", "(", "bool", ")", "\n", "KNN", ".", "AllowOptimisations", "=", "metadata", "[", "\"", "\"", "]", ".", "(", "bool", ")", "\n\n", "// 101 on why JSON is a bad serialization format", "floatNeighbours", ":=", "metadata", "[", "\"", "\"", "]", ".", "(", "float64", ")", "\n", "KNN", ".", "NearestNeighbours", "=", "int", "(", "floatNeighbours", ")", "\n\n", "KNN", ".", "TrainingData", ",", "err", "=", "reader", ".", "GetInstancesForKey", "(", "reader", ".", "Prefix", "(", "prefix", ",", "\"", "\"", ")", ")", "\n\n", "return", "err", "\n", "}" ]
// LoadWithPrefix reloads a given KNN classifier when it's part of another file.
[ "LoadWithPrefix", "reloads", "a", "given", "KNN", "classifier", "when", "it", "s", "part", "of", "another", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L377-L405
164,936
sjwhitworth/golearn
knn/knn.go
ReloadKNNClassifier
func ReloadKNNClassifier(filePath string) (*KNNClassifier, error) { stub := &KNNClassifier{} err := stub.Load(filePath) if err != nil { return nil, err } return stub, nil }
go
func ReloadKNNClassifier(filePath string) (*KNNClassifier, error) { stub := &KNNClassifier{} err := stub.Load(filePath) if err != nil { return nil, err } return stub, nil }
[ "func", "ReloadKNNClassifier", "(", "filePath", "string", ")", "(", "*", "KNNClassifier", ",", "error", ")", "{", "stub", ":=", "&", "KNNClassifier", "{", "}", "\n", "err", ":=", "stub", ".", "Load", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "stub", ",", "nil", "\n", "}" ]
// ReloadKNNClassifier reloads a KNNClassifier when it's the only thing in an output file.
[ "ReloadKNNClassifier", "reloads", "a", "KNNClassifier", "when", "it", "s", "the", "only", "thing", "in", "an", "output", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L408-L415
164,937
sjwhitworth/golearn
knn/knn.go
NewKnnRegressor
func NewKnnRegressor(distfunc string) *KNNRegressor { KNN := KNNRegressor{} KNN.DistanceFunc = distfunc return &KNN }
go
func NewKnnRegressor(distfunc string) *KNNRegressor { KNN := KNNRegressor{} KNN.DistanceFunc = distfunc return &KNN }
[ "func", "NewKnnRegressor", "(", "distfunc", "string", ")", "*", "KNNRegressor", "{", "KNN", ":=", "KNNRegressor", "{", "}", "\n", "KNN", ".", "DistanceFunc", "=", "distfunc", "\n", "return", "&", "KNN", "\n", "}" ]
// NewKnnRegressor mints a new classifier.
[ "NewKnnRegressor", "mints", "a", "new", "classifier", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/knn/knn.go#L425-L429
164,938
sjwhitworth/golearn
neural/layered.go
NewMultiLayerNet
func NewMultiLayerNet(layers []int) *MultiLayerNet { return &MultiLayerNet{ nil, make(map[base.Attribute]int), layers, 0, 0, 0.001, 500, 0.90, } }
go
func NewMultiLayerNet(layers []int) *MultiLayerNet { return &MultiLayerNet{ nil, make(map[base.Attribute]int), layers, 0, 0, 0.001, 500, 0.90, } }
[ "func", "NewMultiLayerNet", "(", "layers", "[", "]", "int", ")", "*", "MultiLayerNet", "{", "return", "&", "MultiLayerNet", "{", "nil", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "int", ")", ",", "layers", ",", "0", ",", "0", ",", "0.001", ",", "500", ",", "0.90", ",", "}", "\n", "}" ]
// NewMultiLayerNet returns an underlying // Network conceptuallyorganised into layers // // Layers variable = slice of integers representing // node count at each layer.
[ "NewMultiLayerNet", "returns", "an", "underlying", "Network", "conceptuallyorganised", "into", "layers", "Layers", "variable", "=", "slice", "of", "integers", "representing", "node", "count", "at", "each", "layer", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/neural/layered.go#L37-L48
164,939
sjwhitworth/golearn
neural/layered.go
String
func (m *MultiLayerNet) String() string { return fmt.Sprintf("MultiLayerNet(%v, %v, %f, %f, %d", m.layers, m.network, m.Convergence, m.LearningRate, m.MaxIterations) }
go
func (m *MultiLayerNet) String() string { return fmt.Sprintf("MultiLayerNet(%v, %v, %f, %f, %d", m.layers, m.network, m.Convergence, m.LearningRate, m.MaxIterations) }
[ "func", "(", "m", "*", "MultiLayerNet", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "layers", ",", "m", ".", "network", ",", "m", ".", "Convergence", ",", "m", ".", "LearningRate", ",", "m", ".", "MaxIterations", ")", "\n", "}" ]
// String returns a human-readable summary of this network.
[ "String", "returns", "a", "human", "-", "readable", "summary", "of", "this", "network", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/neural/layered.go#L51-L53
164,940
sjwhitworth/golearn
neural/layered.go
Predict
func (m *MultiLayerNet) Predict(X base.FixedDataGrid) base.FixedDataGrid { // Create the return vector ret := base.GeneratePredictionVector(X) // Make sure everything's a FloatAttribute insts := m.convertToFloatInsts(X) // Get the input/output Attributes inputAttrs := base.NonClassAttributes(insts) outputAttrs := ret.AllClassAttributes() // Compute layers layers := 2 + len(m.layers) // Check that we're operating in a singular mode floatMode := 0 categoricalMode := 0 for _, a := range outputAttrs { if _, ok := a.(*base.CategoricalAttribute); ok { categoricalMode++ } else if _, ok := a.(*base.FloatAttribute); ok { floatMode++ } else { panic("Unsupported output Attribute type!") } } if floatMode > 0 && categoricalMode > 0 { panic("Can't predict a mix of float and categorical Attributes") } else if categoricalMode > 1 { panic("Can't predict more than one categorical class Attribute") } // Create the activation vector a := mat.NewDense(m.network.size, 1, make([]float64, m.network.size)) // Resolve the input AttributeSpecs inputAs := base.ResolveAttributes(insts, inputAttrs) // Resolve the output Attributespecs outputAs := base.ResolveAttributes(ret, outputAttrs) // Map over each input row insts.MapOverRows(inputAs, func(row [][]byte, rc int) (bool, error) { // Clear the activation vector for i := 0; i < m.network.size; i++ { a.Set(i, 0, 0.0) } // Build the activation vector for i, vb := range row { if cIndex, ok := m.attrs[inputAs[i].GetAttribute()]; !ok { panic("Can't resolve the Attribute!") } else { a.Set(cIndex, 0, base.UnpackBytesToFloat(vb)) } } // Robots, activate! m.network.Activate(a, layers) // Decide which class to set if floatMode > 0 { for _, as := range outputAs { cIndex := m.attrs[as.GetAttribute()] ret.Set(as, rc, base.PackFloatToBytes(a.At(cIndex, 0))) } } else { maxIndex := 0 maxVal := 0.0 for i := m.classAttrOffset; i < m.classAttrOffset+m.classAttrCount; i++ { val := a.At(i, 0) if val > maxVal { maxIndex = i maxVal = val } } maxIndex -= m.classAttrOffset ret.Set(outputAs[0], rc, base.PackU64ToBytes(uint64(maxIndex))) } return true, nil }) return ret }
go
func (m *MultiLayerNet) Predict(X base.FixedDataGrid) base.FixedDataGrid { // Create the return vector ret := base.GeneratePredictionVector(X) // Make sure everything's a FloatAttribute insts := m.convertToFloatInsts(X) // Get the input/output Attributes inputAttrs := base.NonClassAttributes(insts) outputAttrs := ret.AllClassAttributes() // Compute layers layers := 2 + len(m.layers) // Check that we're operating in a singular mode floatMode := 0 categoricalMode := 0 for _, a := range outputAttrs { if _, ok := a.(*base.CategoricalAttribute); ok { categoricalMode++ } else if _, ok := a.(*base.FloatAttribute); ok { floatMode++ } else { panic("Unsupported output Attribute type!") } } if floatMode > 0 && categoricalMode > 0 { panic("Can't predict a mix of float and categorical Attributes") } else if categoricalMode > 1 { panic("Can't predict more than one categorical class Attribute") } // Create the activation vector a := mat.NewDense(m.network.size, 1, make([]float64, m.network.size)) // Resolve the input AttributeSpecs inputAs := base.ResolveAttributes(insts, inputAttrs) // Resolve the output Attributespecs outputAs := base.ResolveAttributes(ret, outputAttrs) // Map over each input row insts.MapOverRows(inputAs, func(row [][]byte, rc int) (bool, error) { // Clear the activation vector for i := 0; i < m.network.size; i++ { a.Set(i, 0, 0.0) } // Build the activation vector for i, vb := range row { if cIndex, ok := m.attrs[inputAs[i].GetAttribute()]; !ok { panic("Can't resolve the Attribute!") } else { a.Set(cIndex, 0, base.UnpackBytesToFloat(vb)) } } // Robots, activate! m.network.Activate(a, layers) // Decide which class to set if floatMode > 0 { for _, as := range outputAs { cIndex := m.attrs[as.GetAttribute()] ret.Set(as, rc, base.PackFloatToBytes(a.At(cIndex, 0))) } } else { maxIndex := 0 maxVal := 0.0 for i := m.classAttrOffset; i < m.classAttrOffset+m.classAttrCount; i++ { val := a.At(i, 0) if val > maxVal { maxIndex = i maxVal = val } } maxIndex -= m.classAttrOffset ret.Set(outputAs[0], rc, base.PackU64ToBytes(uint64(maxIndex))) } return true, nil }) return ret }
[ "func", "(", "m", "*", "MultiLayerNet", ")", "Predict", "(", "X", "base", ".", "FixedDataGrid", ")", "base", ".", "FixedDataGrid", "{", "// Create the return vector", "ret", ":=", "base", ".", "GeneratePredictionVector", "(", "X", ")", "\n\n", "// Make sure everything's a FloatAttribute", "insts", ":=", "m", ".", "convertToFloatInsts", "(", "X", ")", "\n\n", "// Get the input/output Attributes", "inputAttrs", ":=", "base", ".", "NonClassAttributes", "(", "insts", ")", "\n", "outputAttrs", ":=", "ret", ".", "AllClassAttributes", "(", ")", "\n\n", "// Compute layers", "layers", ":=", "2", "+", "len", "(", "m", ".", "layers", ")", "\n\n", "// Check that we're operating in a singular mode", "floatMode", ":=", "0", "\n", "categoricalMode", ":=", "0", "\n", "for", "_", ",", "a", ":=", "range", "outputAttrs", "{", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "CategoricalAttribute", ")", ";", "ok", "{", "categoricalMode", "++", "\n", "}", "else", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "FloatAttribute", ")", ";", "ok", "{", "floatMode", "++", "\n", "}", "else", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "floatMode", ">", "0", "&&", "categoricalMode", ">", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "else", "if", "categoricalMode", ">", "1", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Create the activation vector", "a", ":=", "mat", ".", "NewDense", "(", "m", ".", "network", ".", "size", ",", "1", ",", "make", "(", "[", "]", "float64", ",", "m", ".", "network", ".", "size", ")", ")", "\n\n", "// Resolve the input AttributeSpecs", "inputAs", ":=", "base", ".", "ResolveAttributes", "(", "insts", ",", "inputAttrs", ")", "\n\n", "// Resolve the output Attributespecs", "outputAs", ":=", "base", ".", "ResolveAttributes", "(", "ret", ",", "outputAttrs", ")", "\n\n", "// Map over each input row", "insts", ".", "MapOverRows", "(", "inputAs", ",", "func", "(", "row", "[", "]", "[", "]", "byte", ",", "rc", "int", ")", "(", "bool", ",", "error", ")", "{", "// Clear the activation vector", "for", "i", ":=", "0", ";", "i", "<", "m", ".", "network", ".", "size", ";", "i", "++", "{", "a", ".", "Set", "(", "i", ",", "0", ",", "0.0", ")", "\n", "}", "\n", "// Build the activation vector", "for", "i", ",", "vb", ":=", "range", "row", "{", "if", "cIndex", ",", "ok", ":=", "m", ".", "attrs", "[", "inputAs", "[", "i", "]", ".", "GetAttribute", "(", ")", "]", ";", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "else", "{", "a", ".", "Set", "(", "cIndex", ",", "0", ",", "base", ".", "UnpackBytesToFloat", "(", "vb", ")", ")", "\n", "}", "\n", "}", "\n", "// Robots, activate!", "m", ".", "network", ".", "Activate", "(", "a", ",", "layers", ")", "\n\n", "// Decide which class to set", "if", "floatMode", ">", "0", "{", "for", "_", ",", "as", ":=", "range", "outputAs", "{", "cIndex", ":=", "m", ".", "attrs", "[", "as", ".", "GetAttribute", "(", ")", "]", "\n", "ret", ".", "Set", "(", "as", ",", "rc", ",", "base", ".", "PackFloatToBytes", "(", "a", ".", "At", "(", "cIndex", ",", "0", ")", ")", ")", "\n", "}", "\n", "}", "else", "{", "maxIndex", ":=", "0", "\n", "maxVal", ":=", "0.0", "\n", "for", "i", ":=", "m", ".", "classAttrOffset", ";", "i", "<", "m", ".", "classAttrOffset", "+", "m", ".", "classAttrCount", ";", "i", "++", "{", "val", ":=", "a", ".", "At", "(", "i", ",", "0", ")", "\n", "if", "val", ">", "maxVal", "{", "maxIndex", "=", "i", "\n", "maxVal", "=", "val", "\n", "}", "\n", "}", "\n", "maxIndex", "-=", "m", ".", "classAttrOffset", "\n", "ret", ".", "Set", "(", "outputAs", "[", "0", "]", ",", "rc", ",", "base", ".", "PackU64ToBytes", "(", "uint64", "(", "maxIndex", ")", ")", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n\n", "return", "ret", "\n\n", "}" ]
// Predict uses the underlying network to produce predictions for the // class variables of X. // // Can only predict one CategoricalAttribute at a time, or up to n // FloatAttributes. Set or unset ClassAttributes to work around this // limitation.
[ "Predict", "uses", "the", "underlying", "network", "to", "produce", "predictions", "for", "the", "class", "variables", "of", "X", ".", "Can", "only", "predict", "one", "CategoricalAttribute", "at", "a", "time", "or", "up", "to", "n", "FloatAttributes", ".", "Set", "or", "unset", "ClassAttributes", "to", "work", "around", "this", "limitation", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/neural/layered.go#L73-L157
164,941
sjwhitworth/golearn
base/mat.go
InstancesFromMat64
func InstancesFromMat64(rows, cols int, data *mat.Dense) *Mat64Instances { var ret Mat64Instances for i := 0; i < cols; i++ { ret.attributes = append(ret.attributes, NewFloatAttribute(fmt.Sprintf("%d", i))) } ret.classAttrs = make(map[int]bool) ret.Data = data ret.rows = rows return &ret }
go
func InstancesFromMat64(rows, cols int, data *mat.Dense) *Mat64Instances { var ret Mat64Instances for i := 0; i < cols; i++ { ret.attributes = append(ret.attributes, NewFloatAttribute(fmt.Sprintf("%d", i))) } ret.classAttrs = make(map[int]bool) ret.Data = data ret.rows = rows return &ret }
[ "func", "InstancesFromMat64", "(", "rows", ",", "cols", "int", ",", "data", "*", "mat", ".", "Dense", ")", "*", "Mat64Instances", "{", "var", "ret", "Mat64Instances", "\n", "for", "i", ":=", "0", ";", "i", "<", "cols", ";", "i", "++", "{", "ret", ".", "attributes", "=", "append", "(", "ret", ".", "attributes", ",", "NewFloatAttribute", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ")", ")", ")", "\n", "}", "\n\n", "ret", ".", "classAttrs", "=", "make", "(", "map", "[", "int", "]", "bool", ")", "\n", "ret", ".", "Data", "=", "data", "\n", "ret", ".", "rows", "=", "rows", "\n\n", "return", "&", "ret", "\n", "}" ]
// InstancesFromMat64 returns a new Mat64Instances from a literal provided.
[ "InstancesFromMat64", "returns", "a", "new", "Mat64Instances", "from", "a", "literal", "provided", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L17-L29
164,942
sjwhitworth/golearn
base/mat.go
GetAttribute
func (m *Mat64Instances) GetAttribute(a Attribute) (AttributeSpec, error) { for i, at := range m.attributes { if at.Equals(a) { return AttributeSpec{0, i, at}, nil } } return AttributeSpec{}, fmt.Errorf("Couldn't find a matching attribute") }
go
func (m *Mat64Instances) GetAttribute(a Attribute) (AttributeSpec, error) { for i, at := range m.attributes { if at.Equals(a) { return AttributeSpec{0, i, at}, nil } } return AttributeSpec{}, fmt.Errorf("Couldn't find a matching attribute") }
[ "func", "(", "m", "*", "Mat64Instances", ")", "GetAttribute", "(", "a", "Attribute", ")", "(", "AttributeSpec", ",", "error", ")", "{", "for", "i", ",", "at", ":=", "range", "m", ".", "attributes", "{", "if", "at", ".", "Equals", "(", "a", ")", "{", "return", "AttributeSpec", "{", "0", ",", "i", ",", "at", "}", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "AttributeSpec", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// GetAttribute returns an AttributeSpec from an Attribute field.
[ "GetAttribute", "returns", "an", "AttributeSpec", "from", "an", "Attribute", "field", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L32-L39
164,943
sjwhitworth/golearn
base/mat.go
AllAttributes
func (m *Mat64Instances) AllAttributes() []Attribute { ret := make([]Attribute, len(m.attributes)) for i, a := range m.attributes { ret[i] = a } return ret }
go
func (m *Mat64Instances) AllAttributes() []Attribute { ret := make([]Attribute, len(m.attributes)) for i, a := range m.attributes { ret[i] = a } return ret }
[ "func", "(", "m", "*", "Mat64Instances", ")", "AllAttributes", "(", ")", "[", "]", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "len", "(", "m", ".", "attributes", ")", ")", "\n", "for", "i", ",", "a", ":=", "range", "m", ".", "attributes", "{", "ret", "[", "i", "]", "=", "a", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// AllAttributes returns every defined Attribute.
[ "AllAttributes", "returns", "every", "defined", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L42-L48
164,944
sjwhitworth/golearn
base/mat.go
AddClassAttribute
func (m *Mat64Instances) AddClassAttribute(a Attribute) error { as, err := m.GetAttribute(a) if err != nil { return err } m.classAttrs[as.position] = true return nil }
go
func (m *Mat64Instances) AddClassAttribute(a Attribute) error { as, err := m.GetAttribute(a) if err != nil { return err } m.classAttrs[as.position] = true return nil }
[ "func", "(", "m", "*", "Mat64Instances", ")", "AddClassAttribute", "(", "a", "Attribute", ")", "error", "{", "as", ",", "err", ":=", "m", ".", "GetAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "classAttrs", "[", "as", ".", "position", "]", "=", "true", "\n", "return", "nil", "\n", "}" ]
// AddClassAttribute adds an attribute to the class set.
[ "AddClassAttribute", "adds", "an", "attribute", "to", "the", "class", "set", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L51-L59
164,945
sjwhitworth/golearn
base/mat.go
RemoveClassAttribute
func (m *Mat64Instances) RemoveClassAttribute(a Attribute) error { as, err := m.GetAttribute(a) if err != nil { return err } m.classAttrs[as.position] = false return nil }
go
func (m *Mat64Instances) RemoveClassAttribute(a Attribute) error { as, err := m.GetAttribute(a) if err != nil { return err } m.classAttrs[as.position] = false return nil }
[ "func", "(", "m", "*", "Mat64Instances", ")", "RemoveClassAttribute", "(", "a", "Attribute", ")", "error", "{", "as", ",", "err", ":=", "m", ".", "GetAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "classAttrs", "[", "as", ".", "position", "]", "=", "false", "\n", "return", "nil", "\n", "}" ]
// RemoveClassAttribute removes an attribute to the class set.
[ "RemoveClassAttribute", "removes", "an", "attribute", "to", "the", "class", "set", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L62-L70
164,946
sjwhitworth/golearn
base/mat.go
AllClassAttributes
func (m *Mat64Instances) AllClassAttributes() []Attribute { ret := make([]Attribute, 0) for i := range m.classAttrs { if m.classAttrs[i] { ret = append(ret, m.attributes[i]) } } return ret }
go
func (m *Mat64Instances) AllClassAttributes() []Attribute { ret := make([]Attribute, 0) for i := range m.classAttrs { if m.classAttrs[i] { ret = append(ret, m.attributes[i]) } } return ret }
[ "func", "(", "m", "*", "Mat64Instances", ")", "AllClassAttributes", "(", ")", "[", "]", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "0", ")", "\n", "for", "i", ":=", "range", "m", ".", "classAttrs", "{", "if", "m", ".", "classAttrs", "[", "i", "]", "{", "ret", "=", "append", "(", "ret", ",", "m", ".", "attributes", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// AllClassAttributes returns every class attribute.
[ "AllClassAttributes", "returns", "every", "class", "attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L73-L82
164,947
sjwhitworth/golearn
base/mat.go
Get
func (m *Mat64Instances) Get(as AttributeSpec, row int) []byte { val := m.Data.At(row, as.position) return PackFloatToBytes(val) }
go
func (m *Mat64Instances) Get(as AttributeSpec, row int) []byte { val := m.Data.At(row, as.position) return PackFloatToBytes(val) }
[ "func", "(", "m", "*", "Mat64Instances", ")", "Get", "(", "as", "AttributeSpec", ",", "row", "int", ")", "[", "]", "byte", "{", "val", ":=", "m", ".", "Data", ".", "At", "(", "row", ",", "as", ".", "position", ")", "\n", "return", "PackFloatToBytes", "(", "val", ")", "\n", "}" ]
// Get returns the bytes at a given position
[ "Get", "returns", "the", "bytes", "at", "a", "given", "position" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L85-L88
164,948
sjwhitworth/golearn
base/mat.go
MapOverRows
func (m *Mat64Instances) MapOverRows(as []AttributeSpec, f func([][]byte, int) (bool, error)) error { rowData := make([][]byte, len(as)) for j, _ := range as { rowData[j] = make([]byte, 8) } for i := 0; i < m.rows; i++ { for j, as := range as { PackFloatToBytesInline(m.Data.At(i, as.position), rowData[j]) } stat, err := f(rowData, i) if !stat { return err } } return nil }
go
func (m *Mat64Instances) MapOverRows(as []AttributeSpec, f func([][]byte, int) (bool, error)) error { rowData := make([][]byte, len(as)) for j, _ := range as { rowData[j] = make([]byte, 8) } for i := 0; i < m.rows; i++ { for j, as := range as { PackFloatToBytesInline(m.Data.At(i, as.position), rowData[j]) } stat, err := f(rowData, i) if !stat { return err } } return nil }
[ "func", "(", "m", "*", "Mat64Instances", ")", "MapOverRows", "(", "as", "[", "]", "AttributeSpec", ",", "f", "func", "(", "[", "]", "[", "]", "byte", ",", "int", ")", "(", "bool", ",", "error", ")", ")", "error", "{", "rowData", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "as", ")", ")", "\n", "for", "j", ",", "_", ":=", "range", "as", "{", "rowData", "[", "j", "]", "=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "m", ".", "rows", ";", "i", "++", "{", "for", "j", ",", "as", ":=", "range", "as", "{", "PackFloatToBytesInline", "(", "m", ".", "Data", ".", "At", "(", "i", ",", "as", ".", "position", ")", ",", "rowData", "[", "j", "]", ")", "\n", "}", "\n", "stat", ",", "err", ":=", "f", "(", "rowData", ",", "i", ")", "\n", "if", "!", "stat", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MapOverRows is a convenience function for iteration
[ "MapOverRows", "is", "a", "convenience", "function", "for", "iteration" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L91-L107
164,949
sjwhitworth/golearn
base/mat.go
Size
func (m *Mat64Instances) Size() (int, int) { return len(m.attributes), m.rows }
go
func (m *Mat64Instances) Size() (int, int) { return len(m.attributes), m.rows }
[ "func", "(", "m", "*", "Mat64Instances", ")", "Size", "(", ")", "(", "int", ",", "int", ")", "{", "return", "len", "(", "m", ".", "attributes", ")", ",", "m", ".", "rows", "\n", "}" ]
// Size returns the number of Attributes, then the number of rows
[ "Size", "returns", "the", "number", "of", "Attributes", "then", "the", "number", "of", "rows" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/mat.go#L116-L118
164,950
sjwhitworth/golearn
trees/entropy.go
getSplitEntropyFast
func getSplitEntropyFast(s [2][]int) float64 { ret := 0.0 count := 0 for a := range s { for c := range s[a] { count += s[a][c] } } for a := range s { total := 0.0 for c := range s[a] { total += float64(s[a][c]) } for c := range s[a] { if s[a][c] != 0 { ret -= float64(s[a][c]) / float64(count) * math.Log(float64(s[a][c])/float64(count)) / math.Log(2) } } ret += total / float64(count) * math.Log(total/float64(count)) / math.Log(2) } return ret }
go
func getSplitEntropyFast(s [2][]int) float64 { ret := 0.0 count := 0 for a := range s { for c := range s[a] { count += s[a][c] } } for a := range s { total := 0.0 for c := range s[a] { total += float64(s[a][c]) } for c := range s[a] { if s[a][c] != 0 { ret -= float64(s[a][c]) / float64(count) * math.Log(float64(s[a][c])/float64(count)) / math.Log(2) } } ret += total / float64(count) * math.Log(total/float64(count)) / math.Log(2) } return ret }
[ "func", "getSplitEntropyFast", "(", "s", "[", "2", "]", "[", "]", "int", ")", "float64", "{", "ret", ":=", "0.0", "\n", "count", ":=", "0", "\n", "for", "a", ":=", "range", "s", "{", "for", "c", ":=", "range", "s", "[", "a", "]", "{", "count", "+=", "s", "[", "a", "]", "[", "c", "]", "\n", "}", "\n", "}", "\n", "for", "a", ":=", "range", "s", "{", "total", ":=", "0.0", "\n", "for", "c", ":=", "range", "s", "[", "a", "]", "{", "total", "+=", "float64", "(", "s", "[", "a", "]", "[", "c", "]", ")", "\n", "}", "\n", "for", "c", ":=", "range", "s", "[", "a", "]", "{", "if", "s", "[", "a", "]", "[", "c", "]", "!=", "0", "{", "ret", "-=", "float64", "(", "s", "[", "a", "]", "[", "c", "]", ")", "/", "float64", "(", "count", ")", "*", "math", ".", "Log", "(", "float64", "(", "s", "[", "a", "]", "[", "c", "]", ")", "/", "float64", "(", "count", ")", ")", "/", "math", ".", "Log", "(", "2", ")", "\n", "}", "\n", "}", "\n", "ret", "+=", "total", "/", "float64", "(", "count", ")", "*", "math", ".", "Log", "(", "total", "/", "float64", "(", "count", ")", ")", "/", "math", ".", "Log", "(", "2", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// getSplitEntropyFast determines the entropy of the target // class distribution after splitting on an base.Attribute. // It is similar to getSplitEntropy, but accepts array of slices, // to avoid map access overhead.
[ "getSplitEntropyFast", "determines", "the", "entropy", "of", "the", "target", "class", "distribution", "after", "splitting", "on", "an", "base", ".", "Attribute", ".", "It", "is", "similar", "to", "getSplitEntropy", "but", "accepts", "array", "of", "slices", "to", "avoid", "map", "access", "overhead", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/entropy.go#L165-L186
164,951
sjwhitworth/golearn
trees/entropy.go
getSplitEntropy
func getSplitEntropy(s map[string]map[string]int) float64 { ret := 0.0 count := 0 for a := range s { for c := range s[a] { count += s[a][c] } } for a := range s { total := 0.0 for c := range s[a] { total += float64(s[a][c]) } for c := range s[a] { ret -= float64(s[a][c]) / float64(count) * math.Log(float64(s[a][c])/float64(count)) / math.Log(2) } ret += total / float64(count) * math.Log(total/float64(count)) / math.Log(2) } return ret }
go
func getSplitEntropy(s map[string]map[string]int) float64 { ret := 0.0 count := 0 for a := range s { for c := range s[a] { count += s[a][c] } } for a := range s { total := 0.0 for c := range s[a] { total += float64(s[a][c]) } for c := range s[a] { ret -= float64(s[a][c]) / float64(count) * math.Log(float64(s[a][c])/float64(count)) / math.Log(2) } ret += total / float64(count) * math.Log(total/float64(count)) / math.Log(2) } return ret }
[ "func", "getSplitEntropy", "(", "s", "map", "[", "string", "]", "map", "[", "string", "]", "int", ")", "float64", "{", "ret", ":=", "0.0", "\n", "count", ":=", "0", "\n", "for", "a", ":=", "range", "s", "{", "for", "c", ":=", "range", "s", "[", "a", "]", "{", "count", "+=", "s", "[", "a", "]", "[", "c", "]", "\n", "}", "\n", "}", "\n", "for", "a", ":=", "range", "s", "{", "total", ":=", "0.0", "\n", "for", "c", ":=", "range", "s", "[", "a", "]", "{", "total", "+=", "float64", "(", "s", "[", "a", "]", "[", "c", "]", ")", "\n", "}", "\n", "for", "c", ":=", "range", "s", "[", "a", "]", "{", "ret", "-=", "float64", "(", "s", "[", "a", "]", "[", "c", "]", ")", "/", "float64", "(", "count", ")", "*", "math", ".", "Log", "(", "float64", "(", "s", "[", "a", "]", "[", "c", "]", ")", "/", "float64", "(", "count", ")", ")", "/", "math", ".", "Log", "(", "2", ")", "\n", "}", "\n", "ret", "+=", "total", "/", "float64", "(", "count", ")", "*", "math", ".", "Log", "(", "total", "/", "float64", "(", "count", ")", ")", "/", "math", ".", "Log", "(", "2", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// getSplitEntropy determines the entropy of the target // class distribution after splitting on an base.Attribute
[ "getSplitEntropy", "determines", "the", "entropy", "of", "the", "target", "class", "distribution", "after", "splitting", "on", "an", "base", ".", "Attribute" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/entropy.go#L190-L209
164,952
sjwhitworth/golearn
trees/entropy.go
getBaseEntropy
func getBaseEntropy(s map[string]int) float64 { ret := 0.0 count := 0 for k := range s { count += s[k] } for k := range s { ret -= float64(s[k]) / float64(count) * math.Log(float64(s[k])/float64(count)) / math.Log(2) } return ret }
go
func getBaseEntropy(s map[string]int) float64 { ret := 0.0 count := 0 for k := range s { count += s[k] } for k := range s { ret -= float64(s[k]) / float64(count) * math.Log(float64(s[k])/float64(count)) / math.Log(2) } return ret }
[ "func", "getBaseEntropy", "(", "s", "map", "[", "string", "]", "int", ")", "float64", "{", "ret", ":=", "0.0", "\n", "count", ":=", "0", "\n", "for", "k", ":=", "range", "s", "{", "count", "+=", "s", "[", "k", "]", "\n", "}", "\n", "for", "k", ":=", "range", "s", "{", "ret", "-=", "float64", "(", "s", "[", "k", "]", ")", "/", "float64", "(", "count", ")", "*", "math", ".", "Log", "(", "float64", "(", "s", "[", "k", "]", ")", "/", "float64", "(", "count", ")", ")", "/", "math", ".", "Log", "(", "2", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// getBaseEntropy determines the entropy of the target // class distribution before splitting on an base.Attribute
[ "getBaseEntropy", "determines", "the", "entropy", "of", "the", "target", "class", "distribution", "before", "splitting", "on", "an", "base", ".", "Attribute" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/entropy.go#L213-L223
164,953
hashicorp/packer
common/terminal_windows.go
getConsoleScreenBufferInfo
func getConsoleScreenBufferInfo(csbi *_CONSOLE_SCREEN_BUFFER_INFO) (err error) { var ( bi _CONSOLE_SCREEN_BUFFER_INFO fd syscall.Handle ) // Re-open CONOUT$ as in some instances, stdout may be closed and guaranteed an stdout if fd, err = syscall.Open("CONOUT$", syscall.O_RDWR, 0); err != nil { return err } defer syscall.Close(fd) // grab the dimensions for the console if err = kernel32_GetConsoleScreenBufferInfo(fd, &bi); err != nil { return err } *csbi = bi return nil }
go
func getConsoleScreenBufferInfo(csbi *_CONSOLE_SCREEN_BUFFER_INFO) (err error) { var ( bi _CONSOLE_SCREEN_BUFFER_INFO fd syscall.Handle ) // Re-open CONOUT$ as in some instances, stdout may be closed and guaranteed an stdout if fd, err = syscall.Open("CONOUT$", syscall.O_RDWR, 0); err != nil { return err } defer syscall.Close(fd) // grab the dimensions for the console if err = kernel32_GetConsoleScreenBufferInfo(fd, &bi); err != nil { return err } *csbi = bi return nil }
[ "func", "getConsoleScreenBufferInfo", "(", "csbi", "*", "_CONSOLE_SCREEN_BUFFER_INFO", ")", "(", "err", "error", ")", "{", "var", "(", "bi", "_CONSOLE_SCREEN_BUFFER_INFO", "\n", "fd", "syscall", ".", "Handle", "\n", ")", "\n\n", "// Re-open CONOUT$ as in some instances, stdout may be closed and guaranteed an stdout", "if", "fd", ",", "err", "=", "syscall", ".", "Open", "(", "\"", "\"", ",", "syscall", ".", "O_RDWR", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "syscall", ".", "Close", "(", "fd", ")", "\n\n", "// grab the dimensions for the console", "if", "err", "=", "kernel32_GetConsoleScreenBufferInfo", "(", "fd", ",", "&", "bi", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "*", "csbi", "=", "bi", "\n", "return", "nil", "\n", "}" ]
// windows api to get the console screen buffer info
[ "windows", "api", "to", "get", "the", "console", "screen", "buffer", "info" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/terminal_windows.go#L57-L76
164,954
hashicorp/packer
builder/googlecompute/step_create_image.go
Run
func (s *StepCreateImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { config := state.Get("config").(*Config) driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) if config.PackerForce && config.imageAlreadyExists { ui.Say("Deleting previous image...") errCh := driver.DeleteImage(config.ImageName) err := <-errCh if err != nil { err := fmt.Errorf("Error deleting image: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } } ui.Say("Creating image...") imageCh, errCh := driver.CreateImage( config.ImageName, config.ImageDescription, config.ImageFamily, config.Zone, config.DiskName, config.ImageLabels, config.ImageLicenses) var err error select { case err = <-errCh: case <-time.After(config.stateTimeout): err = errors.New("time out while waiting for image to register") } if err != nil { err := fmt.Errorf("Error waiting for image: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("image", <-imageCh) return multistep.ActionContinue }
go
func (s *StepCreateImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { config := state.Get("config").(*Config) driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) if config.PackerForce && config.imageAlreadyExists { ui.Say("Deleting previous image...") errCh := driver.DeleteImage(config.ImageName) err := <-errCh if err != nil { err := fmt.Errorf("Error deleting image: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } } ui.Say("Creating image...") imageCh, errCh := driver.CreateImage( config.ImageName, config.ImageDescription, config.ImageFamily, config.Zone, config.DiskName, config.ImageLabels, config.ImageLicenses) var err error select { case err = <-errCh: case <-time.After(config.stateTimeout): err = errors.New("time out while waiting for image to register") } if err != nil { err := fmt.Errorf("Error waiting for image: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("image", <-imageCh) return multistep.ActionContinue }
[ "func", "(", "s", "*", "StepCreateImage", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "state", "multistep", ".", "StateBag", ")", "multistep", ".", "StepAction", "{", "config", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "*", "Config", ")", "\n", "driver", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "Driver", ")", "\n", "ui", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Ui", ")", "\n\n", "if", "config", ".", "PackerForce", "&&", "config", ".", "imageAlreadyExists", "{", "ui", ".", "Say", "(", "\"", "\"", ")", "\n\n", "errCh", ":=", "driver", ".", "DeleteImage", "(", "config", ".", "ImageName", ")", "\n", "err", ":=", "<-", "errCh", "\n", "if", "err", "!=", "nil", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "state", ".", "Put", "(", "\"", "\"", ",", "err", ")", "\n", "ui", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n", "}", "\n\n", "ui", ".", "Say", "(", "\"", "\"", ")", "\n\n", "imageCh", ",", "errCh", ":=", "driver", ".", "CreateImage", "(", "config", ".", "ImageName", ",", "config", ".", "ImageDescription", ",", "config", ".", "ImageFamily", ",", "config", ".", "Zone", ",", "config", ".", "DiskName", ",", "config", ".", "ImageLabels", ",", "config", ".", "ImageLicenses", ")", "\n", "var", "err", "error", "\n", "select", "{", "case", "err", "=", "<-", "errCh", ":", "case", "<-", "time", ".", "After", "(", "config", ".", "stateTimeout", ")", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "state", ".", "Put", "(", "\"", "\"", ",", "err", ")", "\n", "ui", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "state", ".", "Put", "(", "\"", "\"", ",", "<-", "imageCh", ")", "\n", "return", "multistep", ".", "ActionContinue", "\n", "}" ]
// Run executes the Packer build step that creates a GCE machine image. // // The image is created from the persistent disk used by the instance. The // instance must be deleted and the disk retained before doing this step.
[ "Run", "executes", "the", "Packer", "build", "step", "that", "creates", "a", "GCE", "machine", "image", ".", "The", "image", "is", "created", "from", "the", "persistent", "disk", "used", "by", "the", "instance", ".", "The", "instance", "must", "be", "deleted", "and", "the", "disk", "retained", "before", "doing", "this", "step", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/step_create_image.go#L21-L60
164,955
hashicorp/packer
template/interpolate/render.go
RenderInterface
func RenderInterface(v interface{}, ctx *Context) (interface{}, error) { f := func(v string) (string, error) { return Render(v, ctx) } walker := &renderWalker{ F: f, Replace: true, } err := reflectwalk.Walk(v, walker) if err != nil { return nil, err } if walker.Top != nil { v = walker.Top } return v, nil }
go
func RenderInterface(v interface{}, ctx *Context) (interface{}, error) { f := func(v string) (string, error) { return Render(v, ctx) } walker := &renderWalker{ F: f, Replace: true, } err := reflectwalk.Walk(v, walker) if err != nil { return nil, err } if walker.Top != nil { v = walker.Top } return v, nil }
[ "func", "RenderInterface", "(", "v", "interface", "{", "}", ",", "ctx", "*", "Context", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "f", ":=", "func", "(", "v", "string", ")", "(", "string", ",", "error", ")", "{", "return", "Render", "(", "v", ",", "ctx", ")", "\n", "}", "\n\n", "walker", ":=", "&", "renderWalker", "{", "F", ":", "f", ",", "Replace", ":", "true", ",", "}", "\n", "err", ":=", "reflectwalk", ".", "Walk", "(", "v", ",", "walker", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "walker", ".", "Top", "!=", "nil", "{", "v", "=", "walker", ".", "Top", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}" ]
// RenderInterface renders any value and returns the resulting value.
[ "RenderInterface", "renders", "any", "value", "and", "returns", "the", "resulting", "value", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/render.go#L58-L76
164,956
hashicorp/packer
template/interpolate/render.go
ValidateInterface
func ValidateInterface(v interface{}, ctx *Context) error { f := func(v string) (string, error) { return v, Validate(v, ctx) } walker := &renderWalker{ F: f, Replace: false, } err := reflectwalk.Walk(v, walker) if err != nil { return err } return nil }
go
func ValidateInterface(v interface{}, ctx *Context) error { f := func(v string) (string, error) { return v, Validate(v, ctx) } walker := &renderWalker{ F: f, Replace: false, } err := reflectwalk.Walk(v, walker) if err != nil { return err } return nil }
[ "func", "ValidateInterface", "(", "v", "interface", "{", "}", ",", "ctx", "*", "Context", ")", "error", "{", "f", ":=", "func", "(", "v", "string", ")", "(", "string", ",", "error", ")", "{", "return", "v", ",", "Validate", "(", "v", ",", "ctx", ")", "\n", "}", "\n\n", "walker", ":=", "&", "renderWalker", "{", "F", ":", "f", ",", "Replace", ":", "false", ",", "}", "\n", "err", ":=", "reflectwalk", ".", "Walk", "(", "v", ",", "walker", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ValidateInterface renders any value and returns the resulting value.
[ "ValidateInterface", "renders", "any", "value", "and", "returns", "the", "resulting", "value", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/render.go#L79-L94
164,957
hashicorp/packer
template/interpolate/render.go
include
func (f *RenderFilter) include(k string) bool { if f == nil { return true } k = strings.ToLower(k) f.once.Do(f.init) if len(f.includeSet) > 0 { _, ok := f.includeSet[k] return ok } if len(f.excludeSet) > 0 { _, ok := f.excludeSet[k] return !ok } return true }
go
func (f *RenderFilter) include(k string) bool { if f == nil { return true } k = strings.ToLower(k) f.once.Do(f.init) if len(f.includeSet) > 0 { _, ok := f.includeSet[k] return ok } if len(f.excludeSet) > 0 { _, ok := f.excludeSet[k] return !ok } return true }
[ "func", "(", "f", "*", "RenderFilter", ")", "include", "(", "k", "string", ")", "bool", "{", "if", "f", "==", "nil", "{", "return", "true", "\n", "}", "\n\n", "k", "=", "strings", ".", "ToLower", "(", "k", ")", "\n\n", "f", ".", "once", ".", "Do", "(", "f", ".", "init", ")", "\n", "if", "len", "(", "f", ".", "includeSet", ")", ">", "0", "{", "_", ",", "ok", ":=", "f", ".", "includeSet", "[", "k", "]", "\n", "return", "ok", "\n", "}", "\n", "if", "len", "(", "f", ".", "excludeSet", ")", ">", "0", "{", "_", ",", "ok", ":=", "f", ".", "excludeSet", "[", "k", "]", "\n", "return", "!", "ok", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Include checks whether a key should be included.
[ "Include", "checks", "whether", "a", "key", "should", "be", "included", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/render.go#L97-L115
164,958
hashicorp/packer
builder/openstack/networks.go
CheckFloatingIP
func CheckFloatingIP(client *gophercloud.ServiceClient, id string) (*floatingips.FloatingIP, error) { floatingIP, err := floatingips.Get(client, id).Extract() if err != nil { return nil, err } if floatingIP.PortID != "" { return nil, fmt.Errorf("provided floating IP '%s' is already associated with port '%s'", id, floatingIP.PortID) } return floatingIP, nil }
go
func CheckFloatingIP(client *gophercloud.ServiceClient, id string) (*floatingips.FloatingIP, error) { floatingIP, err := floatingips.Get(client, id).Extract() if err != nil { return nil, err } if floatingIP.PortID != "" { return nil, fmt.Errorf("provided floating IP '%s' is already associated with port '%s'", id, floatingIP.PortID) } return floatingIP, nil }
[ "func", "CheckFloatingIP", "(", "client", "*", "gophercloud", ".", "ServiceClient", ",", "id", "string", ")", "(", "*", "floatingips", ".", "FloatingIP", ",", "error", ")", "{", "floatingIP", ",", "err", ":=", "floatingips", ".", "Get", "(", "client", ",", "id", ")", ".", "Extract", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "floatingIP", ".", "PortID", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ",", "floatingIP", ".", "PortID", ")", "\n", "}", "\n\n", "return", "floatingIP", ",", "nil", "\n", "}" ]
// CheckFloatingIP gets a floating IP by its ID and checks if it is already // associated with any internal interface. // It returns floating IP if it can be used.
[ "CheckFloatingIP", "gets", "a", "floating", "IP", "by", "its", "ID", "and", "checks", "if", "it", "is", "already", "associated", "with", "any", "internal", "interface", ".", "It", "returns", "floating", "IP", "if", "it", "can", "be", "used", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/networks.go#L18-L29
164,959
hashicorp/packer
builder/openstack/networks.go
FindFreeFloatingIP
func FindFreeFloatingIP(client *gophercloud.ServiceClient) (*floatingips.FloatingIP, error) { var freeFloatingIP *floatingips.FloatingIP pager := floatingips.List(client, floatingips.ListOpts{ Status: "DOWN", }) err := pager.EachPage(func(page pagination.Page) (bool, error) { candidates, err := floatingips.ExtractFloatingIPs(page) if err != nil { return false, err // stop and throw error out } for _, candidate := range candidates { if candidate.PortID != "" { continue // this floating IP is associated with port, move to next in list } // Floating IP is able to be allocated. freeFloatingIP = &candidate return false, nil // stop iterating over pages } return true, nil // try the next page }) if err != nil { return nil, err } if freeFloatingIP == nil { return nil, fmt.Errorf("no free floating IPs found") } return freeFloatingIP, nil }
go
func FindFreeFloatingIP(client *gophercloud.ServiceClient) (*floatingips.FloatingIP, error) { var freeFloatingIP *floatingips.FloatingIP pager := floatingips.List(client, floatingips.ListOpts{ Status: "DOWN", }) err := pager.EachPage(func(page pagination.Page) (bool, error) { candidates, err := floatingips.ExtractFloatingIPs(page) if err != nil { return false, err // stop and throw error out } for _, candidate := range candidates { if candidate.PortID != "" { continue // this floating IP is associated with port, move to next in list } // Floating IP is able to be allocated. freeFloatingIP = &candidate return false, nil // stop iterating over pages } return true, nil // try the next page }) if err != nil { return nil, err } if freeFloatingIP == nil { return nil, fmt.Errorf("no free floating IPs found") } return freeFloatingIP, nil }
[ "func", "FindFreeFloatingIP", "(", "client", "*", "gophercloud", ".", "ServiceClient", ")", "(", "*", "floatingips", ".", "FloatingIP", ",", "error", ")", "{", "var", "freeFloatingIP", "*", "floatingips", ".", "FloatingIP", "\n\n", "pager", ":=", "floatingips", ".", "List", "(", "client", ",", "floatingips", ".", "ListOpts", "{", "Status", ":", "\"", "\"", ",", "}", ")", "\n", "err", ":=", "pager", ".", "EachPage", "(", "func", "(", "page", "pagination", ".", "Page", ")", "(", "bool", ",", "error", ")", "{", "candidates", ",", "err", ":=", "floatingips", ".", "ExtractFloatingIPs", "(", "page", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "// stop and throw error out", "\n", "}", "\n\n", "for", "_", ",", "candidate", ":=", "range", "candidates", "{", "if", "candidate", ".", "PortID", "!=", "\"", "\"", "{", "continue", "// this floating IP is associated with port, move to next in list", "\n", "}", "\n\n", "// Floating IP is able to be allocated.", "freeFloatingIP", "=", "&", "candidate", "\n", "return", "false", ",", "nil", "// stop iterating over pages", "\n", "}", "\n", "return", "true", ",", "nil", "// try the next page", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "freeFloatingIP", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "freeFloatingIP", ",", "nil", "\n", "}" ]
// FindFreeFloatingIP returns free unassociated floating IP. // It will return first floating IP if there are many.
[ "FindFreeFloatingIP", "returns", "free", "unassociated", "floating", "IP", ".", "It", "will", "return", "first", "floating", "IP", "if", "there", "are", "many", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/networks.go#L33-L64
164,960
hashicorp/packer
builder/openstack/networks.go
GetInstancePortID
func GetInstancePortID(client *gophercloud.ServiceClient, id string) (string, error) { interfacesPage, err := attachinterfaces.List(client, id).AllPages() if err != nil { return "", err } interfaces, err := attachinterfaces.ExtractInterfaces(interfacesPage) if err != nil { return "", err } if len(interfaces) == 0 { return "", fmt.Errorf("instance '%s' has no interfaces", id) } return interfaces[0].PortID, nil }
go
func GetInstancePortID(client *gophercloud.ServiceClient, id string) (string, error) { interfacesPage, err := attachinterfaces.List(client, id).AllPages() if err != nil { return "", err } interfaces, err := attachinterfaces.ExtractInterfaces(interfacesPage) if err != nil { return "", err } if len(interfaces) == 0 { return "", fmt.Errorf("instance '%s' has no interfaces", id) } return interfaces[0].PortID, nil }
[ "func", "GetInstancePortID", "(", "client", "*", "gophercloud", ".", "ServiceClient", ",", "id", "string", ")", "(", "string", ",", "error", ")", "{", "interfacesPage", ",", "err", ":=", "attachinterfaces", ".", "List", "(", "client", ",", "id", ")", ".", "AllPages", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "interfaces", ",", "err", ":=", "attachinterfaces", ".", "ExtractInterfaces", "(", "interfacesPage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "len", "(", "interfaces", ")", "==", "0", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "id", ")", "\n", "}", "\n\n", "return", "interfaces", "[", "0", "]", ".", "PortID", ",", "nil", "\n", "}" ]
// GetInstancePortID returns internal port of the instance that can be used for // the association of a floating IP. // It will return an ID of a first port if there are many.
[ "GetInstancePortID", "returns", "internal", "port", "of", "the", "instance", "that", "can", "be", "used", "for", "the", "association", "of", "a", "floating", "IP", ".", "It", "will", "return", "an", "ID", "of", "a", "first", "port", "if", "there", "are", "many", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/networks.go#L69-L83
164,961
hashicorp/packer
builder/openstack/networks.go
CheckFloatingIPNetwork
func CheckFloatingIPNetwork(client *gophercloud.ServiceClient, networkRef string) (string, error) { if _, err := uuid.Parse(networkRef); err != nil { return GetFloatingIPNetworkIDByName(client, networkRef) } return networkRef, nil }
go
func CheckFloatingIPNetwork(client *gophercloud.ServiceClient, networkRef string) (string, error) { if _, err := uuid.Parse(networkRef); err != nil { return GetFloatingIPNetworkIDByName(client, networkRef) } return networkRef, nil }
[ "func", "CheckFloatingIPNetwork", "(", "client", "*", "gophercloud", ".", "ServiceClient", ",", "networkRef", "string", ")", "(", "string", ",", "error", ")", "{", "if", "_", ",", "err", ":=", "uuid", ".", "Parse", "(", "networkRef", ")", ";", "err", "!=", "nil", "{", "return", "GetFloatingIPNetworkIDByName", "(", "client", ",", "networkRef", ")", "\n", "}", "\n\n", "return", "networkRef", ",", "nil", "\n", "}" ]
// CheckFloatingIPNetwork checks provided network reference and returns a valid // Networking service ID.
[ "CheckFloatingIPNetwork", "checks", "provided", "network", "reference", "and", "returns", "a", "valid", "Networking", "service", "ID", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/networks.go#L87-L93
164,962
hashicorp/packer
builder/openstack/networks.go
GetFloatingIPNetworkIDByName
func GetFloatingIPNetworkIDByName(client *gophercloud.ServiceClient, networkName string) (string, error) { var externalNetworks []ExternalNetwork allPages, err := networks.List(client, networks.ListOpts{ Name: networkName, }).AllPages() if err != nil { return "", err } if err := networks.ExtractNetworksInto(allPages, &externalNetworks); err != nil { return "", err } if len(externalNetworks) == 0 { return "", fmt.Errorf("can't find external network %s", networkName) } // Check and return the first external network. if !externalNetworks[0].External { return "", fmt.Errorf("network %s is not external", networkName) } return externalNetworks[0].ID, nil }
go
func GetFloatingIPNetworkIDByName(client *gophercloud.ServiceClient, networkName string) (string, error) { var externalNetworks []ExternalNetwork allPages, err := networks.List(client, networks.ListOpts{ Name: networkName, }).AllPages() if err != nil { return "", err } if err := networks.ExtractNetworksInto(allPages, &externalNetworks); err != nil { return "", err } if len(externalNetworks) == 0 { return "", fmt.Errorf("can't find external network %s", networkName) } // Check and return the first external network. if !externalNetworks[0].External { return "", fmt.Errorf("network %s is not external", networkName) } return externalNetworks[0].ID, nil }
[ "func", "GetFloatingIPNetworkIDByName", "(", "client", "*", "gophercloud", ".", "ServiceClient", ",", "networkName", "string", ")", "(", "string", ",", "error", ")", "{", "var", "externalNetworks", "[", "]", "ExternalNetwork", "\n\n", "allPages", ",", "err", ":=", "networks", ".", "List", "(", "client", ",", "networks", ".", "ListOpts", "{", "Name", ":", "networkName", ",", "}", ")", ".", "AllPages", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "networks", ".", "ExtractNetworksInto", "(", "allPages", ",", "&", "externalNetworks", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "externalNetworks", ")", "==", "0", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "networkName", ")", "\n", "}", "\n", "// Check and return the first external network.", "if", "!", "externalNetworks", "[", "0", "]", ".", "External", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "networkName", ")", "\n", "}", "\n\n", "return", "externalNetworks", "[", "0", "]", ".", "ID", ",", "nil", "\n", "}" ]
// GetFloatingIPNetworkIDByName searches for the external network ID by the provided name.
[ "GetFloatingIPNetworkIDByName", "searches", "for", "the", "external", "network", "ID", "by", "the", "provided", "name", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/networks.go#L102-L125
164,963
hashicorp/packer
builder/googlecompute/driver_gce.go
waitForState
func waitForState(errCh chan<- error, target string, refresh stateRefreshFunc) error { ctx := context.TODO() err := retry.Config{ RetryDelay: (&retry.Backoff{InitialBackoff: 2 * time.Second, MaxBackoff: 2 * time.Second, Multiplier: 2}).Linear, }.Run(ctx, func(ctx context.Context) error { state, err := refresh() if err != nil { return err } if state == target { return nil } return fmt.Errorf("retrying for state %s, got %s", target, state) }) errCh <- err return err }
go
func waitForState(errCh chan<- error, target string, refresh stateRefreshFunc) error { ctx := context.TODO() err := retry.Config{ RetryDelay: (&retry.Backoff{InitialBackoff: 2 * time.Second, MaxBackoff: 2 * time.Second, Multiplier: 2}).Linear, }.Run(ctx, func(ctx context.Context) error { state, err := refresh() if err != nil { return err } if state == target { return nil } return fmt.Errorf("retrying for state %s, got %s", target, state) }) errCh <- err return err }
[ "func", "waitForState", "(", "errCh", "chan", "<-", "error", ",", "target", "string", ",", "refresh", "stateRefreshFunc", ")", "error", "{", "ctx", ":=", "context", ".", "TODO", "(", ")", "\n", "err", ":=", "retry", ".", "Config", "{", "RetryDelay", ":", "(", "&", "retry", ".", "Backoff", "{", "InitialBackoff", ":", "2", "*", "time", ".", "Second", ",", "MaxBackoff", ":", "2", "*", "time", ".", "Second", ",", "Multiplier", ":", "2", "}", ")", ".", "Linear", ",", "}", ".", "Run", "(", "ctx", ",", "func", "(", "ctx", "context", ".", "Context", ")", "error", "{", "state", ",", "err", ":=", "refresh", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "state", "==", "target", "{", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "target", ",", "state", ")", "\n", "}", ")", "\n", "errCh", "<-", "err", "\n", "return", "err", "\n", "}" ]
// waitForState will spin in a loop forever waiting for state to // reach a certain target.
[ "waitForState", "will", "spin", "in", "a", "loop", "forever", "waiting", "for", "state", "to", "reach", "a", "certain", "target", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/driver_gce.go#L611-L627
164,964
hashicorp/packer
common/multistep_debug.go
MultistepDebugFn
func MultistepDebugFn(ui packer.Ui) multistep.DebugPauseFn { return func(loc multistep.DebugLocation, name string, state multistep.StateBag) { var locationString string switch loc { case multistep.DebugLocationAfterRun: locationString = "after run of" case multistep.DebugLocationBeforeCleanup: locationString = "before cleanup of" default: locationString = "at" } message := fmt.Sprintf( "Pausing %s step '%s'. Press enter to continue.", locationString, name) result := make(chan string, 1) go func() { line, err := ui.Ask(message) if err != nil { log.Printf("Error asking for input: %s", err) } result <- line }() for { select { case <-result: return case <-time.After(100 * time.Millisecond): if _, ok := state.GetOk(multistep.StateCancelled); ok { return } } } } }
go
func MultistepDebugFn(ui packer.Ui) multistep.DebugPauseFn { return func(loc multistep.DebugLocation, name string, state multistep.StateBag) { var locationString string switch loc { case multistep.DebugLocationAfterRun: locationString = "after run of" case multistep.DebugLocationBeforeCleanup: locationString = "before cleanup of" default: locationString = "at" } message := fmt.Sprintf( "Pausing %s step '%s'. Press enter to continue.", locationString, name) result := make(chan string, 1) go func() { line, err := ui.Ask(message) if err != nil { log.Printf("Error asking for input: %s", err) } result <- line }() for { select { case <-result: return case <-time.After(100 * time.Millisecond): if _, ok := state.GetOk(multistep.StateCancelled); ok { return } } } } }
[ "func", "MultistepDebugFn", "(", "ui", "packer", ".", "Ui", ")", "multistep", ".", "DebugPauseFn", "{", "return", "func", "(", "loc", "multistep", ".", "DebugLocation", ",", "name", "string", ",", "state", "multistep", ".", "StateBag", ")", "{", "var", "locationString", "string", "\n", "switch", "loc", "{", "case", "multistep", ".", "DebugLocationAfterRun", ":", "locationString", "=", "\"", "\"", "\n", "case", "multistep", ".", "DebugLocationBeforeCleanup", ":", "locationString", "=", "\"", "\"", "\n", "default", ":", "locationString", "=", "\"", "\"", "\n", "}", "\n\n", "message", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "locationString", ",", "name", ")", "\n\n", "result", ":=", "make", "(", "chan", "string", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "line", ",", "err", ":=", "ui", ".", "Ask", "(", "message", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "result", "<-", "line", "\n", "}", "(", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "result", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "100", "*", "time", ".", "Millisecond", ")", ":", "if", "_", ",", "ok", ":=", "state", ".", "GetOk", "(", "multistep", ".", "StateCancelled", ")", ";", "ok", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// MultistepDebugFn will return a proper multistep.DebugPauseFn to // use for debugging if you're using multistep in your builder.
[ "MultistepDebugFn", "will", "return", "a", "proper", "multistep", ".", "DebugPauseFn", "to", "use", "for", "debugging", "if", "you", "re", "using", "multistep", "in", "your", "builder", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/multistep_debug.go#L14-L51
164,965
hashicorp/packer
builder/hyperv/common/step_create_build_dir.go
Run
func (s *StepCreateBuildDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) ui.Say("Creating build directory...") var err error if s.TempPath == "" { s.buildDir, err = tmp.Dir("hyperv") } else { s.buildDir, err = ioutil.TempDir(s.TempPath, "hyperv") } if err != nil { err = fmt.Errorf("Error creating build directory: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } log.Printf("Created build directory: %s", s.buildDir) // Record the build directory location for later steps state.Put("build_dir", s.buildDir) return multistep.ActionContinue }
go
func (s *StepCreateBuildDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) ui.Say("Creating build directory...") var err error if s.TempPath == "" { s.buildDir, err = tmp.Dir("hyperv") } else { s.buildDir, err = ioutil.TempDir(s.TempPath, "hyperv") } if err != nil { err = fmt.Errorf("Error creating build directory: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } log.Printf("Created build directory: %s", s.buildDir) // Record the build directory location for later steps state.Put("build_dir", s.buildDir) return multistep.ActionContinue }
[ "func", "(", "s", "*", "StepCreateBuildDir", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "state", "multistep", ".", "StateBag", ")", "multistep", ".", "StepAction", "{", "ui", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Ui", ")", "\n\n", "ui", ".", "Say", "(", "\"", "\"", ")", "\n\n", "var", "err", "error", "\n", "if", "s", ".", "TempPath", "==", "\"", "\"", "{", "s", ".", "buildDir", ",", "err", "=", "tmp", ".", "Dir", "(", "\"", "\"", ")", "\n", "}", "else", "{", "s", ".", "buildDir", ",", "err", "=", "ioutil", ".", "TempDir", "(", "s", ".", "TempPath", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "state", ".", "Put", "(", "\"", "\"", ",", "err", ")", "\n", "ui", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "s", ".", "buildDir", ")", "\n\n", "// Record the build directory location for later steps", "state", ".", "Put", "(", "\"", "\"", ",", "s", ".", "buildDir", ")", "\n\n", "return", "multistep", ".", "ActionContinue", "\n", "}" ]
// Creates the main directory used to house the VMs files and folders // during the build
[ "Creates", "the", "main", "directory", "used", "to", "house", "the", "VMs", "files", "and", "folders", "during", "the", "build" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/step_create_build_dir.go#L28-L53
164,966
hashicorp/packer
builder/hyperv/common/step_create_build_dir.go
Cleanup
func (s *StepCreateBuildDir) Cleanup(state multistep.StateBag) { if s.buildDir == "" { return } ui := state.Get("ui").(packer.Ui) ui.Say("Deleting build directory...") err := os.RemoveAll(s.buildDir) if err != nil { ui.Error(fmt.Sprintf("Error deleting build directory: %s", err)) } }
go
func (s *StepCreateBuildDir) Cleanup(state multistep.StateBag) { if s.buildDir == "" { return } ui := state.Get("ui").(packer.Ui) ui.Say("Deleting build directory...") err := os.RemoveAll(s.buildDir) if err != nil { ui.Error(fmt.Sprintf("Error deleting build directory: %s", err)) } }
[ "func", "(", "s", "*", "StepCreateBuildDir", ")", "Cleanup", "(", "state", "multistep", ".", "StateBag", ")", "{", "if", "s", ".", "buildDir", "==", "\"", "\"", "{", "return", "\n", "}", "\n\n", "ui", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Ui", ")", "\n", "ui", ".", "Say", "(", "\"", "\"", ")", "\n\n", "err", ":=", "os", ".", "RemoveAll", "(", "s", ".", "buildDir", ")", "\n", "if", "err", "!=", "nil", "{", "ui", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "}" ]
// Cleanup removes the build directory
[ "Cleanup", "removes", "the", "build", "directory" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/step_create_build_dir.go#L56-L68
164,967
hashicorp/packer
helper/enumflag/flag.go
New
func New(target *string, options ...string) *enumFlag { return &enumFlag{target: target, options: options} }
go
func New(target *string, options ...string) *enumFlag { return &enumFlag{target: target, options: options} }
[ "func", "New", "(", "target", "*", "string", ",", "options", "...", "string", ")", "*", "enumFlag", "{", "return", "&", "enumFlag", "{", "target", ":", "target", ",", "options", ":", "options", "}", "\n", "}" ]
// New returns a flag.Value implementation for parsing flags with a one-of-a-set value
[ "New", "returns", "a", "flag", ".", "Value", "implementation", "for", "parsing", "flags", "with", "a", "one", "-", "of", "-", "a", "-", "set", "value" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/enumflag/flag.go#L11-L13
164,968
hashicorp/packer
packer/provisioner.go
Run
func (h *ProvisionHook) Run(ctx context.Context, name string, ui Ui, comm Communicator, data interface{}) error { // Shortcut if len(h.Provisioners) == 0 { return nil } if comm == nil { return fmt.Errorf( "No communicator found for provisioners! This is usually because the\n" + "`communicator` config was set to \"none\". If you have any provisioners\n" + "then a communicator is required. Please fix this to continue.") } for _, p := range h.Provisioners { ts := CheckpointReporter.AddSpan(p.TypeName, "provisioner", p.Config) err := p.Provisioner.Provision(ctx, ui, comm) ts.End(err) if err != nil { return err } } return nil }
go
func (h *ProvisionHook) Run(ctx context.Context, name string, ui Ui, comm Communicator, data interface{}) error { // Shortcut if len(h.Provisioners) == 0 { return nil } if comm == nil { return fmt.Errorf( "No communicator found for provisioners! This is usually because the\n" + "`communicator` config was set to \"none\". If you have any provisioners\n" + "then a communicator is required. Please fix this to continue.") } for _, p := range h.Provisioners { ts := CheckpointReporter.AddSpan(p.TypeName, "provisioner", p.Config) err := p.Provisioner.Provision(ctx, ui, comm) ts.End(err) if err != nil { return err } } return nil }
[ "func", "(", "h", "*", "ProvisionHook", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "ui", "Ui", ",", "comm", "Communicator", ",", "data", "interface", "{", "}", ")", "error", "{", "// Shortcut", "if", "len", "(", "h", ".", "Provisioners", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "if", "comm", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", "+", "\"", "\\\"", "\\\"", "\\n", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "for", "_", ",", "p", ":=", "range", "h", ".", "Provisioners", "{", "ts", ":=", "CheckpointReporter", ".", "AddSpan", "(", "p", ".", "TypeName", ",", "\"", "\"", ",", "p", ".", "Config", ")", "\n\n", "err", ":=", "p", ".", "Provisioner", ".", "Provision", "(", "ctx", ",", "ui", ",", "comm", ")", "\n\n", "ts", ".", "End", "(", "err", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Runs the provisioners in order.
[ "Runs", "the", "provisioners", "in", "order", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/provisioner.go#L41-L66
164,969
hashicorp/packer
builder/parallels/common/step_prepare_parallels_tools.go
Run
func (s *StepPrepareParallelsTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(Driver) if s.ParallelsToolsMode == ParallelsToolsModeDisable { return multistep.ActionContinue } path, err := driver.ToolsISOPath(s.ParallelsToolsFlavor) if err != nil { state.Put("error", err) return multistep.ActionHalt } if _, err := os.Stat(path); err != nil { state.Put("error", fmt.Errorf( "Couldn't find Parallels Tools for the '%s' flavor! Please, check the\n"+ "value of 'parallels_tools_flavor'. Valid flavors are: 'win', 'lin',\n"+ "'mac', 'os2' and 'other'", s.ParallelsToolsFlavor)) return multistep.ActionHalt } state.Put("parallels_tools_path", path) return multistep.ActionContinue }
go
func (s *StepPrepareParallelsTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(Driver) if s.ParallelsToolsMode == ParallelsToolsModeDisable { return multistep.ActionContinue } path, err := driver.ToolsISOPath(s.ParallelsToolsFlavor) if err != nil { state.Put("error", err) return multistep.ActionHalt } if _, err := os.Stat(path); err != nil { state.Put("error", fmt.Errorf( "Couldn't find Parallels Tools for the '%s' flavor! Please, check the\n"+ "value of 'parallels_tools_flavor'. Valid flavors are: 'win', 'lin',\n"+ "'mac', 'os2' and 'other'", s.ParallelsToolsFlavor)) return multistep.ActionHalt } state.Put("parallels_tools_path", path) return multistep.ActionContinue }
[ "func", "(", "s", "*", "StepPrepareParallelsTools", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "state", "multistep", ".", "StateBag", ")", "multistep", ".", "StepAction", "{", "driver", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "Driver", ")", "\n\n", "if", "s", ".", "ParallelsToolsMode", "==", "ParallelsToolsModeDisable", "{", "return", "multistep", ".", "ActionContinue", "\n", "}", "\n\n", "path", ",", "err", ":=", "driver", ".", "ToolsISOPath", "(", "s", ".", "ParallelsToolsFlavor", ")", "\n\n", "if", "err", "!=", "nil", "{", "state", ".", "Put", "(", "\"", "\"", ",", "err", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "!=", "nil", "{", "state", ".", "Put", "(", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", "+", "\"", "\\n", "\"", "+", "\"", "\"", ",", "s", ".", "ParallelsToolsFlavor", ")", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "state", ".", "Put", "(", "\"", "\"", ",", "path", ")", "\n", "return", "multistep", ".", "ActionContinue", "\n", "}" ]
// Run sets the value of "parallels_tools_path".
[ "Run", "sets", "the", "value", "of", "parallels_tools_path", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_prepare_parallels_tools.go#L25-L49
164,970
hashicorp/packer
builder/parallels/common/step_output_dir.go
Run
func (s *StepOutputDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) if _, err := os.Stat(s.Path); err == nil && s.Force { ui.Say("Deleting previous output directory...") os.RemoveAll(s.Path) } // Create the directory if err := os.MkdirAll(s.Path, 0755); err != nil { state.Put("error", err) return multistep.ActionHalt } // Make sure we can write in the directory f, err := os.Create(filepath.Join(s.Path, "_packer_perm_check")) if err != nil { err = fmt.Errorf("Couldn't write to output directory: %s", err) state.Put("error", err) return multistep.ActionHalt } f.Close() os.Remove(f.Name()) s.success = true return multistep.ActionContinue }
go
func (s *StepOutputDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) if _, err := os.Stat(s.Path); err == nil && s.Force { ui.Say("Deleting previous output directory...") os.RemoveAll(s.Path) } // Create the directory if err := os.MkdirAll(s.Path, 0755); err != nil { state.Put("error", err) return multistep.ActionHalt } // Make sure we can write in the directory f, err := os.Create(filepath.Join(s.Path, "_packer_perm_check")) if err != nil { err = fmt.Errorf("Couldn't write to output directory: %s", err) state.Put("error", err) return multistep.ActionHalt } f.Close() os.Remove(f.Name()) s.success = true return multistep.ActionContinue }
[ "func", "(", "s", "*", "StepOutputDir", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "state", "multistep", ".", "StateBag", ")", "multistep", ".", "StepAction", "{", "ui", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Ui", ")", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "s", ".", "Path", ")", ";", "err", "==", "nil", "&&", "s", ".", "Force", "{", "ui", ".", "Say", "(", "\"", "\"", ")", "\n", "os", ".", "RemoveAll", "(", "s", ".", "Path", ")", "\n", "}", "\n\n", "// Create the directory", "if", "err", ":=", "os", ".", "MkdirAll", "(", "s", ".", "Path", ",", "0755", ")", ";", "err", "!=", "nil", "{", "state", ".", "Put", "(", "\"", "\"", ",", "err", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "// Make sure we can write in the directory", "f", ",", "err", ":=", "os", ".", "Create", "(", "filepath", ".", "Join", "(", "s", ".", "Path", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "state", ".", "Put", "(", "\"", "\"", ",", "err", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n", "f", ".", "Close", "(", ")", "\n", "os", ".", "Remove", "(", "f", ".", "Name", "(", ")", ")", "\n\n", "s", ".", "success", "=", "true", "\n", "return", "multistep", ".", "ActionContinue", "\n", "}" ]
// Run sets up the output directory.
[ "Run", "sets", "up", "the", "output", "directory", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_output_dir.go#L25-L51
164,971
hashicorp/packer
command/meta.go
Core
func (m *Meta) Core(tpl *template.Template) (*packer.Core, error) { // Copy the config so we don't modify it config := *m.CoreConfig config.Template = tpl config.Variables = m.flagVars // Init the core core, err := packer.NewCore(&config) if err != nil { return nil, fmt.Errorf("Error initializing core: %s", err) } return core, nil }
go
func (m *Meta) Core(tpl *template.Template) (*packer.Core, error) { // Copy the config so we don't modify it config := *m.CoreConfig config.Template = tpl config.Variables = m.flagVars // Init the core core, err := packer.NewCore(&config) if err != nil { return nil, fmt.Errorf("Error initializing core: %s", err) } return core, nil }
[ "func", "(", "m", "*", "Meta", ")", "Core", "(", "tpl", "*", "template", ".", "Template", ")", "(", "*", "packer", ".", "Core", ",", "error", ")", "{", "// Copy the config so we don't modify it", "config", ":=", "*", "m", ".", "CoreConfig", "\n", "config", ".", "Template", "=", "tpl", "\n", "config", ".", "Variables", "=", "m", ".", "flagVars", "\n\n", "// Init the core", "core", ",", "err", ":=", "packer", ".", "NewCore", "(", "&", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "core", ",", "nil", "\n", "}" ]
// Core returns the core for the given template given the configured // CoreConfig and user variables on this Meta.
[ "Core", "returns", "the", "core", "for", "the", "given", "template", "given", "the", "configured", "CoreConfig", "and", "user", "variables", "on", "this", "Meta", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/command/meta.go#L38-L51
164,972
hashicorp/packer
command/meta.go
BuildNames
func (m *Meta) BuildNames(c *packer.Core) []string { // TODO: test // Filter the "only" if len(m.CoreConfig.Only) > 0 { // Build a set of all the available names nameSet := make(map[string]struct{}) for _, n := range c.BuildNames() { nameSet[n] = struct{}{} } // Build our result set which we pre-allocate some sane number result := make([]string, 0, len(m.CoreConfig.Only)) for _, n := range m.CoreConfig.Only { if _, ok := nameSet[n]; ok { result = append(result, n) } } return result } // Filter the "except" if len(m.CoreConfig.Except) > 0 { // Build a set of the things we don't want nameSet := make(map[string]struct{}) for _, n := range m.CoreConfig.Except { nameSet[n] = struct{}{} } // Build our result set which is the names of all builds except // those in the given set. names := c.BuildNames() result := make([]string, 0, len(names)) for _, n := range names { if _, ok := nameSet[n]; !ok { result = append(result, n) } } return result } // We care about everything return c.BuildNames() }
go
func (m *Meta) BuildNames(c *packer.Core) []string { // TODO: test // Filter the "only" if len(m.CoreConfig.Only) > 0 { // Build a set of all the available names nameSet := make(map[string]struct{}) for _, n := range c.BuildNames() { nameSet[n] = struct{}{} } // Build our result set which we pre-allocate some sane number result := make([]string, 0, len(m.CoreConfig.Only)) for _, n := range m.CoreConfig.Only { if _, ok := nameSet[n]; ok { result = append(result, n) } } return result } // Filter the "except" if len(m.CoreConfig.Except) > 0 { // Build a set of the things we don't want nameSet := make(map[string]struct{}) for _, n := range m.CoreConfig.Except { nameSet[n] = struct{}{} } // Build our result set which is the names of all builds except // those in the given set. names := c.BuildNames() result := make([]string, 0, len(names)) for _, n := range names { if _, ok := nameSet[n]; !ok { result = append(result, n) } } return result } // We care about everything return c.BuildNames() }
[ "func", "(", "m", "*", "Meta", ")", "BuildNames", "(", "c", "*", "packer", ".", "Core", ")", "[", "]", "string", "{", "// TODO: test", "// Filter the \"only\"", "if", "len", "(", "m", ".", "CoreConfig", ".", "Only", ")", ">", "0", "{", "// Build a set of all the available names", "nameSet", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "n", ":=", "range", "c", ".", "BuildNames", "(", ")", "{", "nameSet", "[", "n", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// Build our result set which we pre-allocate some sane number", "result", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "m", ".", "CoreConfig", ".", "Only", ")", ")", "\n", "for", "_", ",", "n", ":=", "range", "m", ".", "CoreConfig", ".", "Only", "{", "if", "_", ",", "ok", ":=", "nameSet", "[", "n", "]", ";", "ok", "{", "result", "=", "append", "(", "result", ",", "n", ")", "\n", "}", "\n", "}", "\n\n", "return", "result", "\n", "}", "\n\n", "// Filter the \"except\"", "if", "len", "(", "m", ".", "CoreConfig", ".", "Except", ")", ">", "0", "{", "// Build a set of the things we don't want", "nameSet", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "n", ":=", "range", "m", ".", "CoreConfig", ".", "Except", "{", "nameSet", "[", "n", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "// Build our result set which is the names of all builds except", "// those in the given set.", "names", ":=", "c", ".", "BuildNames", "(", ")", "\n", "result", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "names", ")", ")", "\n", "for", "_", ",", "n", ":=", "range", "names", "{", "if", "_", ",", "ok", ":=", "nameSet", "[", "n", "]", ";", "!", "ok", "{", "result", "=", "append", "(", "result", ",", "n", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}", "\n\n", "// We care about everything", "return", "c", ".", "BuildNames", "(", ")", "\n", "}" ]
// BuildNames returns the list of builds that are in the given core // that we care about taking into account the only and except flags.
[ "BuildNames", "returns", "the", "list", "of", "builds", "that", "are", "in", "the", "given", "core", "that", "we", "care", "about", "taking", "into", "account", "the", "only", "and", "except", "flags", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/command/meta.go#L55-L99
164,973
hashicorp/packer
command/meta.go
FlagSet
func (m *Meta) FlagSet(n string, fs FlagSetFlags) *flag.FlagSet { f := flag.NewFlagSet(n, flag.ContinueOnError) // FlagSetBuildFilter tells us to enable the settings for selecting // builds we care about. if fs&FlagSetBuildFilter != 0 { f.Var((*sliceflag.StringFlag)(&m.CoreConfig.Except), "except", "") f.Var((*sliceflag.StringFlag)(&m.CoreConfig.Only), "only", "") } // FlagSetVars tells us what variables to use if fs&FlagSetVars != 0 { f.Var((*kvflag.Flag)(&m.flagVars), "var", "") f.Var((*kvflag.FlagJSON)(&m.flagVars), "var-file", "") } // Create an io.Writer that writes to our Ui properly for errors. // This is kind of a hack, but it does the job. Basically: create // a pipe, use a scanner to break it into lines, and output each line // to the UI. Do this forever. errR, errW := io.Pipe() errScanner := bufio.NewScanner(errR) go func() { for errScanner.Scan() { m.Ui.Error(errScanner.Text()) } }() f.SetOutput(errW) return f }
go
func (m *Meta) FlagSet(n string, fs FlagSetFlags) *flag.FlagSet { f := flag.NewFlagSet(n, flag.ContinueOnError) // FlagSetBuildFilter tells us to enable the settings for selecting // builds we care about. if fs&FlagSetBuildFilter != 0 { f.Var((*sliceflag.StringFlag)(&m.CoreConfig.Except), "except", "") f.Var((*sliceflag.StringFlag)(&m.CoreConfig.Only), "only", "") } // FlagSetVars tells us what variables to use if fs&FlagSetVars != 0 { f.Var((*kvflag.Flag)(&m.flagVars), "var", "") f.Var((*kvflag.FlagJSON)(&m.flagVars), "var-file", "") } // Create an io.Writer that writes to our Ui properly for errors. // This is kind of a hack, but it does the job. Basically: create // a pipe, use a scanner to break it into lines, and output each line // to the UI. Do this forever. errR, errW := io.Pipe() errScanner := bufio.NewScanner(errR) go func() { for errScanner.Scan() { m.Ui.Error(errScanner.Text()) } }() f.SetOutput(errW) return f }
[ "func", "(", "m", "*", "Meta", ")", "FlagSet", "(", "n", "string", ",", "fs", "FlagSetFlags", ")", "*", "flag", ".", "FlagSet", "{", "f", ":=", "flag", ".", "NewFlagSet", "(", "n", ",", "flag", ".", "ContinueOnError", ")", "\n\n", "// FlagSetBuildFilter tells us to enable the settings for selecting", "// builds we care about.", "if", "fs", "&", "FlagSetBuildFilter", "!=", "0", "{", "f", ".", "Var", "(", "(", "*", "sliceflag", ".", "StringFlag", ")", "(", "&", "m", ".", "CoreConfig", ".", "Except", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "f", ".", "Var", "(", "(", "*", "sliceflag", ".", "StringFlag", ")", "(", "&", "m", ".", "CoreConfig", ".", "Only", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// FlagSetVars tells us what variables to use", "if", "fs", "&", "FlagSetVars", "!=", "0", "{", "f", ".", "Var", "(", "(", "*", "kvflag", ".", "Flag", ")", "(", "&", "m", ".", "flagVars", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "f", ".", "Var", "(", "(", "*", "kvflag", ".", "FlagJSON", ")", "(", "&", "m", ".", "flagVars", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Create an io.Writer that writes to our Ui properly for errors.", "// This is kind of a hack, but it does the job. Basically: create", "// a pipe, use a scanner to break it into lines, and output each line", "// to the UI. Do this forever.", "errR", ",", "errW", ":=", "io", ".", "Pipe", "(", ")", "\n", "errScanner", ":=", "bufio", ".", "NewScanner", "(", "errR", ")", "\n", "go", "func", "(", ")", "{", "for", "errScanner", ".", "Scan", "(", ")", "{", "m", ".", "Ui", ".", "Error", "(", "errScanner", ".", "Text", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "f", ".", "SetOutput", "(", "errW", ")", "\n\n", "return", "f", "\n", "}" ]
// FlagSet returns a FlagSet with the common flags that every // command implements. The exact behavior of FlagSet can be configured // using the flags as the second parameter, for example to disable // build settings on the commands that don't handle builds.
[ "FlagSet", "returns", "a", "FlagSet", "with", "the", "common", "flags", "that", "every", "command", "implements", ".", "The", "exact", "behavior", "of", "FlagSet", "can", "be", "configured", "using", "the", "flags", "as", "the", "second", "parameter", "for", "example", "to", "disable", "build", "settings", "on", "the", "commands", "that", "don", "t", "handle", "builds", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/command/meta.go#L105-L135
164,974
hashicorp/packer
builder/parallels/common/step_upload_version.go
Run
func (s *StepUploadVersion) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { comm := state.Get("communicator").(packer.Communicator) driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) if s.Path == "" { log.Println("ParallelsVersionFile is empty. Not uploading.") return multistep.ActionContinue } version, err := driver.Version() if err != nil { state.Put("error", fmt.Errorf("Error reading version for metadata upload: %s", err)) return multistep.ActionHalt } ui.Say(fmt.Sprintf("Uploading Parallels version info (%s)", version)) var data bytes.Buffer data.WriteString(version) if err := comm.Upload(s.Path, &data, nil); err != nil { state.Put("error", fmt.Errorf("Error uploading Parallels version: %s", err)) return multistep.ActionHalt } return multistep.ActionContinue }
go
func (s *StepUploadVersion) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { comm := state.Get("communicator").(packer.Communicator) driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) if s.Path == "" { log.Println("ParallelsVersionFile is empty. Not uploading.") return multistep.ActionContinue } version, err := driver.Version() if err != nil { state.Put("error", fmt.Errorf("Error reading version for metadata upload: %s", err)) return multistep.ActionHalt } ui.Say(fmt.Sprintf("Uploading Parallels version info (%s)", version)) var data bytes.Buffer data.WriteString(version) if err := comm.Upload(s.Path, &data, nil); err != nil { state.Put("error", fmt.Errorf("Error uploading Parallels version: %s", err)) return multistep.ActionHalt } return multistep.ActionContinue }
[ "func", "(", "s", "*", "StepUploadVersion", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "state", "multistep", ".", "StateBag", ")", "multistep", ".", "StepAction", "{", "comm", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Communicator", ")", "\n", "driver", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "Driver", ")", "\n", "ui", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Ui", ")", "\n\n", "if", "s", ".", "Path", "==", "\"", "\"", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "multistep", ".", "ActionContinue", "\n", "}", "\n\n", "version", ",", "err", ":=", "driver", ".", "Version", "(", ")", "\n", "if", "err", "!=", "nil", "{", "state", ".", "Put", "(", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "ui", ".", "Say", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "version", ")", ")", "\n", "var", "data", "bytes", ".", "Buffer", "\n", "data", ".", "WriteString", "(", "version", ")", "\n", "if", "err", ":=", "comm", ".", "Upload", "(", "s", ".", "Path", ",", "&", "data", ",", "nil", ")", ";", "err", "!=", "nil", "{", "state", ".", "Put", "(", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "return", "multistep", ".", "ActionContinue", "\n", "}" ]
// Run uploads a file containing the version of Parallels Desktop.
[ "Run", "uploads", "a", "file", "containing", "the", "version", "of", "Parallels", "Desktop", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_upload_version.go#L25-L50
164,975
hashicorp/packer
builder/triton/target_image_config.go
Prepare
func (c *TargetImageConfig) Prepare(ctx *interpolate.Context) []error { var errs []error if c.ImageName == "" { errs = append(errs, fmt.Errorf("An image_name must be specified")) } if c.ImageVersion == "" { errs = append(errs, fmt.Errorf("An image_version must be specified")) } if len(errs) > 0 { return errs } return nil }
go
func (c *TargetImageConfig) Prepare(ctx *interpolate.Context) []error { var errs []error if c.ImageName == "" { errs = append(errs, fmt.Errorf("An image_name must be specified")) } if c.ImageVersion == "" { errs = append(errs, fmt.Errorf("An image_version must be specified")) } if len(errs) > 0 { return errs } return nil }
[ "func", "(", "c", "*", "TargetImageConfig", ")", "Prepare", "(", "ctx", "*", "interpolate", ".", "Context", ")", "[", "]", "error", "{", "var", "errs", "[", "]", "error", "\n\n", "if", "c", ".", "ImageName", "==", "\"", "\"", "{", "errs", "=", "append", "(", "errs", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "c", ".", "ImageVersion", "==", "\"", "\"", "{", "errs", "=", "append", "(", "errs", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "if", "len", "(", "errs", ")", ">", "0", "{", "return", "errs", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Prepare performs basic validation on a TargetImageConfig struct.
[ "Prepare", "performs", "basic", "validation", "on", "a", "TargetImageConfig", "struct", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/triton/target_image_config.go#L22-L38
164,976
hashicorp/packer
builder/parallels/common/step_attach_parallels_tools.go
Run
func (s *StepAttachParallelsTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) vmName := state.Get("vmName").(string) // If we're not attaching the guest additions then just return if s.ParallelsToolsMode != ParallelsToolsModeAttach { log.Println("Not attaching parallels tools since we're uploading.") return multistep.ActionContinue } // Get the Parallels Tools path on the host machine parallelsToolsPath := state.Get("parallels_tools_path").(string) // Attach the guest additions to the computer ui.Say("Attaching Parallels Tools ISO to the new CD/DVD drive...") cdrom, err := driver.DeviceAddCDROM(vmName, parallelsToolsPath) if err != nil { err = fmt.Errorf("Error attaching Parallels Tools ISO: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Track the device name so that we can can delete later s.cdromDevice = cdrom return multistep.ActionContinue }
go
func (s *StepAttachParallelsTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) vmName := state.Get("vmName").(string) // If we're not attaching the guest additions then just return if s.ParallelsToolsMode != ParallelsToolsModeAttach { log.Println("Not attaching parallels tools since we're uploading.") return multistep.ActionContinue } // Get the Parallels Tools path on the host machine parallelsToolsPath := state.Get("parallels_tools_path").(string) // Attach the guest additions to the computer ui.Say("Attaching Parallels Tools ISO to the new CD/DVD drive...") cdrom, err := driver.DeviceAddCDROM(vmName, parallelsToolsPath) if err != nil { err = fmt.Errorf("Error attaching Parallels Tools ISO: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Track the device name so that we can can delete later s.cdromDevice = cdrom return multistep.ActionContinue }
[ "func", "(", "s", "*", "StepAttachParallelsTools", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "state", "multistep", ".", "StateBag", ")", "multistep", ".", "StepAction", "{", "driver", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "Driver", ")", "\n", "ui", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Ui", ")", "\n", "vmName", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "string", ")", "\n\n", "// If we're not attaching the guest additions then just return", "if", "s", ".", "ParallelsToolsMode", "!=", "ParallelsToolsModeAttach", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "return", "multistep", ".", "ActionContinue", "\n", "}", "\n\n", "// Get the Parallels Tools path on the host machine", "parallelsToolsPath", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "string", ")", "\n\n", "// Attach the guest additions to the computer", "ui", ".", "Say", "(", "\"", "\"", ")", "\n\n", "cdrom", ",", "err", ":=", "driver", ".", "DeviceAddCDROM", "(", "vmName", ",", "parallelsToolsPath", ")", "\n\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "state", ".", "Put", "(", "\"", "\"", ",", "err", ")", "\n", "ui", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "multistep", ".", "ActionHalt", "\n", "}", "\n\n", "// Track the device name so that we can can delete later", "s", ".", "cdromDevice", "=", "cdrom", "\n\n", "return", "multistep", ".", "ActionContinue", "\n", "}" ]
// Run adds a virtual CD-ROM device to the VM and attaches Parallels Tools ISO image. // If ISO image is not specified, then this step will be skipped.
[ "Run", "adds", "a", "virtual", "CD", "-", "ROM", "device", "to", "the", "VM", "and", "attaches", "Parallels", "Tools", "ISO", "image", ".", "If", "ISO", "image", "is", "not", "specified", "then", "this", "step", "will", "be", "skipped", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_attach_parallels_tools.go#L29-L59
164,977
hashicorp/packer
builder/parallels/common/step_attach_parallels_tools.go
Cleanup
func (s *StepAttachParallelsTools) Cleanup(state multistep.StateBag) { if s.cdromDevice == "" { return } driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) vmName := state.Get("vmName").(string) log.Println("Detaching Parallels Tools ISO...") command := []string{ "set", vmName, "--device-del", s.cdromDevice, } if err := driver.Prlctl(command...); err != nil { ui.Error(fmt.Sprintf("Error detaching Parallels Tools ISO: %s", err)) } }
go
func (s *StepAttachParallelsTools) Cleanup(state multistep.StateBag) { if s.cdromDevice == "" { return } driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) vmName := state.Get("vmName").(string) log.Println("Detaching Parallels Tools ISO...") command := []string{ "set", vmName, "--device-del", s.cdromDevice, } if err := driver.Prlctl(command...); err != nil { ui.Error(fmt.Sprintf("Error detaching Parallels Tools ISO: %s", err)) } }
[ "func", "(", "s", "*", "StepAttachParallelsTools", ")", "Cleanup", "(", "state", "multistep", ".", "StateBag", ")", "{", "if", "s", ".", "cdromDevice", "==", "\"", "\"", "{", "return", "\n", "}", "\n\n", "driver", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "Driver", ")", "\n", "ui", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "packer", ".", "Ui", ")", "\n", "vmName", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "string", ")", "\n\n", "log", ".", "Println", "(", "\"", "\"", ")", "\n\n", "command", ":=", "[", "]", "string", "{", "\"", "\"", ",", "vmName", ",", "\"", "\"", ",", "s", ".", "cdromDevice", ",", "}", "\n\n", "if", "err", ":=", "driver", ".", "Prlctl", "(", "command", "...", ")", ";", "err", "!=", "nil", "{", "ui", ".", "Error", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "}" ]
// Cleanup removes the virtual CD-ROM device attached to the VM.
[ "Cleanup", "removes", "the", "virtual", "CD", "-", "ROM", "device", "attached", "to", "the", "VM", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_attach_parallels_tools.go#L62-L81
164,978
hashicorp/packer
builder/parallels/common/artifact.go
NewArtifact
func NewArtifact(dir string) (packer.Artifact, error) { files := make([]string, 0, 5) visit := func(path string, info os.FileInfo, err error) error { if err != nil { if os.IsNotExist(err) { // It's possible that the path in question existed prior to visit being invoked, but has // since been deleted. This happens, for example, if you have the VM console open while // building. Opening the console creates a <vm name>.app directory which is gone by the time // visit is invoked, resulting in err being a "file not found" error. In this case, skip the // entire path and continue to the next one. return filepath.SkipDir } return err } for _, unnecessaryFile := range unnecessaryFiles { if unnecessary, _ := regexp.MatchString(unnecessaryFile, path); unnecessary { return os.RemoveAll(path) } } if !info.IsDir() { files = append(files, path) } return nil } if err := filepath.Walk(dir, visit); err != nil { return nil, err } return &artifact{ dir: dir, f: files, }, nil }
go
func NewArtifact(dir string) (packer.Artifact, error) { files := make([]string, 0, 5) visit := func(path string, info os.FileInfo, err error) error { if err != nil { if os.IsNotExist(err) { // It's possible that the path in question existed prior to visit being invoked, but has // since been deleted. This happens, for example, if you have the VM console open while // building. Opening the console creates a <vm name>.app directory which is gone by the time // visit is invoked, resulting in err being a "file not found" error. In this case, skip the // entire path and continue to the next one. return filepath.SkipDir } return err } for _, unnecessaryFile := range unnecessaryFiles { if unnecessary, _ := regexp.MatchString(unnecessaryFile, path); unnecessary { return os.RemoveAll(path) } } if !info.IsDir() { files = append(files, path) } return nil } if err := filepath.Walk(dir, visit); err != nil { return nil, err } return &artifact{ dir: dir, f: files, }, nil }
[ "func", "NewArtifact", "(", "dir", "string", ")", "(", "packer", ".", "Artifact", ",", "error", ")", "{", "files", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "5", ")", "\n", "visit", ":=", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "// It's possible that the path in question existed prior to visit being invoked, but has", "// since been deleted. This happens, for example, if you have the VM console open while", "// building. Opening the console creates a <vm name>.app directory which is gone by the time", "// visit is invoked, resulting in err being a \"file not found\" error. In this case, skip the", "// entire path and continue to the next one.", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "for", "_", ",", "unnecessaryFile", ":=", "range", "unnecessaryFiles", "{", "if", "unnecessary", ",", "_", ":=", "regexp", ".", "MatchString", "(", "unnecessaryFile", ",", "path", ")", ";", "unnecessary", "{", "return", "os", ".", "RemoveAll", "(", "path", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "info", ".", "IsDir", "(", ")", "{", "files", "=", "append", "(", "files", ",", "path", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "filepath", ".", "Walk", "(", "dir", ",", "visit", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "artifact", "{", "dir", ":", "dir", ",", "f", ":", "files", ",", "}", ",", "nil", "\n", "}" ]
// NewArtifact returns a Parallels artifact containing the files // in the given directory.
[ "NewArtifact", "returns", "a", "Parallels", "artifact", "containing", "the", "files", "in", "the", "given", "directory", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/artifact.go#L28-L63
164,979
hashicorp/packer
helper/multistep/debug_runner.go
DebugPauseDefault
func DebugPauseDefault(loc DebugLocation, name string, state StateBag) { var locationString string switch loc { case DebugLocationAfterRun: locationString = "after run of" case DebugLocationBeforeCleanup: locationString = "before cleanup of" } fmt.Printf("Pausing %s step '%s'. Press any key to continue.\n", locationString, name) var line string fmt.Scanln(&line) }
go
func DebugPauseDefault(loc DebugLocation, name string, state StateBag) { var locationString string switch loc { case DebugLocationAfterRun: locationString = "after run of" case DebugLocationBeforeCleanup: locationString = "before cleanup of" } fmt.Printf("Pausing %s step '%s'. Press any key to continue.\n", locationString, name) var line string fmt.Scanln(&line) }
[ "func", "DebugPauseDefault", "(", "loc", "DebugLocation", ",", "name", "string", ",", "state", "StateBag", ")", "{", "var", "locationString", "string", "\n", "switch", "loc", "{", "case", "DebugLocationAfterRun", ":", "locationString", "=", "\"", "\"", "\n", "case", "DebugLocationBeforeCleanup", ":", "locationString", "=", "\"", "\"", "\n", "}", "\n\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "locationString", ",", "name", ")", "\n\n", "var", "line", "string", "\n", "fmt", ".", "Scanln", "(", "&", "line", ")", "\n", "}" ]
// DebugPauseDefault is the default pause function when using the // DebugRunner if no PauseFn is specified. It outputs some information // to stderr about the step and waits for keyboard input on stdin before // continuing.
[ "DebugPauseDefault", "is", "the", "default", "pause", "function", "when", "using", "the", "DebugRunner", "if", "no", "PauseFn", "is", "specified", ".", "It", "outputs", "some", "information", "to", "stderr", "about", "the", "step", "and", "waits", "for", "keyboard", "input", "on", "stdin", "before", "continuing", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/multistep/debug_runner.go#L88-L101
164,980
hashicorp/packer
packer/communicator.go
SetExited
func (r *RemoteCmd) SetExited(status int) { r.initchan() r.Lock() r.exitStatus = status r.Unlock() close(r.exitCh) }
go
func (r *RemoteCmd) SetExited(status int) { r.initchan() r.Lock() r.exitStatus = status r.Unlock() close(r.exitCh) }
[ "func", "(", "r", "*", "RemoteCmd", ")", "SetExited", "(", "status", "int", ")", "{", "r", ".", "initchan", "(", ")", "\n\n", "r", ".", "Lock", "(", ")", "\n", "r", ".", "exitStatus", "=", "status", "\n", "r", ".", "Unlock", "(", ")", "\n\n", "close", "(", "r", ".", "exitCh", ")", "\n", "}" ]
// SetExited is a helper for setting that this process is exited. This // should be called by communicators who are running a remote command in // order to set that the command is done.
[ "SetExited", "is", "a", "helper", "for", "setting", "that", "this", "process", "is", "exited", ".", "This", "should", "be", "called", "by", "communicators", "who", "are", "running", "a", "remote", "command", "in", "order", "to", "set", "that", "the", "command", "is", "done", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/communicator.go#L169-L177
164,981
hashicorp/packer
packer/communicator.go
Wait
func (r *RemoteCmd) Wait() int { r.initchan() <-r.exitCh r.Lock() defer r.Unlock() return r.exitStatus }
go
func (r *RemoteCmd) Wait() int { r.initchan() <-r.exitCh r.Lock() defer r.Unlock() return r.exitStatus }
[ "func", "(", "r", "*", "RemoteCmd", ")", "Wait", "(", ")", "int", "{", "r", ".", "initchan", "(", ")", "\n", "<-", "r", ".", "exitCh", "\n", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "return", "r", ".", "exitStatus", "\n", "}" ]
// Wait for command exit and return exit status
[ "Wait", "for", "command", "exit", "and", "return", "exit", "status" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/communicator.go#L180-L186
164,982
hashicorp/packer
builder/parallels/common/ssh.go
CommHost
func CommHost(state multistep.StateBag) (string, error) { vmName := state.Get("vmName").(string) driver := state.Get("driver").(Driver) mac, err := driver.MAC(vmName) if err != nil { return "", err } ip, err := driver.IPAddress(mac) if err != nil { return "", err } return ip, nil }
go
func CommHost(state multistep.StateBag) (string, error) { vmName := state.Get("vmName").(string) driver := state.Get("driver").(Driver) mac, err := driver.MAC(vmName) if err != nil { return "", err } ip, err := driver.IPAddress(mac) if err != nil { return "", err } return ip, nil }
[ "func", "CommHost", "(", "state", "multistep", ".", "StateBag", ")", "(", "string", ",", "error", ")", "{", "vmName", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "string", ")", "\n", "driver", ":=", "state", ".", "Get", "(", "\"", "\"", ")", ".", "(", "Driver", ")", "\n\n", "mac", ",", "err", ":=", "driver", ".", "MAC", "(", "vmName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "ip", ",", "err", ":=", "driver", ".", "IPAddress", "(", "mac", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "ip", ",", "nil", "\n", "}" ]
// CommHost returns the VM's IP address which should be used to access it by SSH.
[ "CommHost", "returns", "the", "VM", "s", "IP", "address", "which", "should", "be", "used", "to", "access", "it", "by", "SSH", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/ssh.go#L8-L23
164,983
hashicorp/packer
common/json/unmarshal.go
Unmarshal
func Unmarshal(data []byte, i interface{}) error { err := json.Unmarshal(data, i) if err != nil { syntaxErr, ok := err.(*json.SyntaxError) if !ok { return err } // We have a syntax error. Extract out the line number and friends. // https://groups.google.com/forum/#!topic/golang-nuts/fizimmXtVfc newline := []byte{'\x0a'} // Calculate the start/end position of the line where the error is start := bytes.LastIndex(data[:syntaxErr.Offset], newline) + 1 end := len(data) if idx := bytes.Index(data[start:], newline); idx >= 0 { end = start + idx } // Count the line number we're on plus the offset in the line line := bytes.Count(data[:start], newline) + 1 pos := int(syntaxErr.Offset) - start - 1 err = fmt.Errorf("Error in line %d, char %d: %s\n%s", line, pos, syntaxErr, data[start:end]) return err } return nil }
go
func Unmarshal(data []byte, i interface{}) error { err := json.Unmarshal(data, i) if err != nil { syntaxErr, ok := err.(*json.SyntaxError) if !ok { return err } // We have a syntax error. Extract out the line number and friends. // https://groups.google.com/forum/#!topic/golang-nuts/fizimmXtVfc newline := []byte{'\x0a'} // Calculate the start/end position of the line where the error is start := bytes.LastIndex(data[:syntaxErr.Offset], newline) + 1 end := len(data) if idx := bytes.Index(data[start:], newline); idx >= 0 { end = start + idx } // Count the line number we're on plus the offset in the line line := bytes.Count(data[:start], newline) + 1 pos := int(syntaxErr.Offset) - start - 1 err = fmt.Errorf("Error in line %d, char %d: %s\n%s", line, pos, syntaxErr, data[start:end]) return err } return nil }
[ "func", "Unmarshal", "(", "data", "[", "]", "byte", ",", "i", "interface", "{", "}", ")", "error", "{", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "i", ")", "\n", "if", "err", "!=", "nil", "{", "syntaxErr", ",", "ok", ":=", "err", ".", "(", "*", "json", ".", "SyntaxError", ")", "\n", "if", "!", "ok", "{", "return", "err", "\n", "}", "\n\n", "// We have a syntax error. Extract out the line number and friends.", "// https://groups.google.com/forum/#!topic/golang-nuts/fizimmXtVfc", "newline", ":=", "[", "]", "byte", "{", "'\\x0a'", "}", "\n\n", "// Calculate the start/end position of the line where the error is", "start", ":=", "bytes", ".", "LastIndex", "(", "data", "[", ":", "syntaxErr", ".", "Offset", "]", ",", "newline", ")", "+", "1", "\n", "end", ":=", "len", "(", "data", ")", "\n", "if", "idx", ":=", "bytes", ".", "Index", "(", "data", "[", "start", ":", "]", ",", "newline", ")", ";", "idx", ">=", "0", "{", "end", "=", "start", "+", "idx", "\n", "}", "\n\n", "// Count the line number we're on plus the offset in the line", "line", ":=", "bytes", ".", "Count", "(", "data", "[", ":", "start", "]", ",", "newline", ")", "+", "1", "\n", "pos", ":=", "int", "(", "syntaxErr", ".", "Offset", ")", "-", "start", "-", "1", "\n\n", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "line", ",", "pos", ",", "syntaxErr", ",", "data", "[", "start", ":", "end", "]", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Unmarshal is wrapper around json.Unmarshal that returns user-friendly // errors when there are syntax errors.
[ "Unmarshal", "is", "wrapper", "around", "json", ".", "Unmarshal", "that", "returns", "user", "-", "friendly", "errors", "when", "there", "are", "syntax", "errors", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/json/unmarshal.go#L11-L40
164,984
hashicorp/packer
builder/cloudstack/step_create_instance.go
generateUserData
func (s *stepCreateInstance) generateUserData(userData string, httpGETOnly bool) (string, error) { renderedUserData, err := interpolate.Render(userData, &s.Ctx) if err != nil { return "", fmt.Errorf("Error rendering user_data: %s", err) } ud := base64.StdEncoding.EncodeToString([]byte(renderedUserData)) // DeployVirtualMachine uses POST by default which allows 32K of // userdata. If using GET instead the userdata is limited to 2K. maxUD := 32768 if httpGETOnly { maxUD = 2048 } if len(ud) > maxUD { return "", fmt.Errorf( "The supplied user_data contains %d bytes after encoding, "+ "this exceeds the limit of %d bytes", len(ud), maxUD) } return ud, nil }
go
func (s *stepCreateInstance) generateUserData(userData string, httpGETOnly bool) (string, error) { renderedUserData, err := interpolate.Render(userData, &s.Ctx) if err != nil { return "", fmt.Errorf("Error rendering user_data: %s", err) } ud := base64.StdEncoding.EncodeToString([]byte(renderedUserData)) // DeployVirtualMachine uses POST by default which allows 32K of // userdata. If using GET instead the userdata is limited to 2K. maxUD := 32768 if httpGETOnly { maxUD = 2048 } if len(ud) > maxUD { return "", fmt.Errorf( "The supplied user_data contains %d bytes after encoding, "+ "this exceeds the limit of %d bytes", len(ud), maxUD) } return ud, nil }
[ "func", "(", "s", "*", "stepCreateInstance", ")", "generateUserData", "(", "userData", "string", ",", "httpGETOnly", "bool", ")", "(", "string", ",", "error", ")", "{", "renderedUserData", ",", "err", ":=", "interpolate", ".", "Render", "(", "userData", ",", "&", "s", ".", "Ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "ud", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "renderedUserData", ")", ")", "\n\n", "// DeployVirtualMachine uses POST by default which allows 32K of", "// userdata. If using GET instead the userdata is limited to 2K.", "maxUD", ":=", "32768", "\n", "if", "httpGETOnly", "{", "maxUD", "=", "2048", "\n", "}", "\n\n", "if", "len", "(", "ud", ")", ">", "maxUD", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "\"", "\"", ",", "len", "(", "ud", ")", ",", "maxUD", ")", "\n", "}", "\n\n", "return", "ud", ",", "nil", "\n", "}" ]
// generateUserData returns the user data as a base64 encoded string.
[ "generateUserData", "returns", "the", "user", "data", "as", "a", "base64", "encoded", "string", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/cloudstack/step_create_instance.go#L213-L235
164,985
hashicorp/packer
helper/config/decode.go
Decode
func Decode(target interface{}, config *DecodeOpts, raws ...interface{}) error { if config == nil { config = &DecodeOpts{Interpolate: true} } // Interpolate first if config.Interpolate { // Detect user variables from the raws and merge them into our context ctx, err := DetectContext(raws...) if err != nil { return err } if config.InterpolateContext == nil { config.InterpolateContext = ctx } else { config.InterpolateContext.BuildName = ctx.BuildName config.InterpolateContext.BuildType = ctx.BuildType config.InterpolateContext.TemplatePath = ctx.TemplatePath config.InterpolateContext.UserVariables = ctx.UserVariables } ctx = config.InterpolateContext // Render everything for i, raw := range raws { m, err := interpolate.RenderMap(raw, ctx, config.InterpolateFilter) if err != nil { return err } raws[i] = m } } // Build our decoder var md mapstructure.Metadata decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ Result: target, Metadata: &md, WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc( uint8ToStringHook, mapstructure.StringToSliceHookFunc(","), mapstructure.StringToTimeDurationHookFunc(), ), }) if err != nil { return err } for _, raw := range raws { if err := decoder.Decode(raw); err != nil { return err } } // Set the metadata if it is set if config.Metadata != nil { *config.Metadata = md } // If we have unused keys, it is an error if len(md.Unused) > 0 { var err error sort.Strings(md.Unused) for _, unused := range md.Unused { if unused != "type" && !strings.HasPrefix(unused, "packer_") { err = multierror.Append(err, fmt.Errorf( "unknown configuration key: %q", unused)) } } if err != nil { return err } } return nil }
go
func Decode(target interface{}, config *DecodeOpts, raws ...interface{}) error { if config == nil { config = &DecodeOpts{Interpolate: true} } // Interpolate first if config.Interpolate { // Detect user variables from the raws and merge them into our context ctx, err := DetectContext(raws...) if err != nil { return err } if config.InterpolateContext == nil { config.InterpolateContext = ctx } else { config.InterpolateContext.BuildName = ctx.BuildName config.InterpolateContext.BuildType = ctx.BuildType config.InterpolateContext.TemplatePath = ctx.TemplatePath config.InterpolateContext.UserVariables = ctx.UserVariables } ctx = config.InterpolateContext // Render everything for i, raw := range raws { m, err := interpolate.RenderMap(raw, ctx, config.InterpolateFilter) if err != nil { return err } raws[i] = m } } // Build our decoder var md mapstructure.Metadata decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ Result: target, Metadata: &md, WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc( uint8ToStringHook, mapstructure.StringToSliceHookFunc(","), mapstructure.StringToTimeDurationHookFunc(), ), }) if err != nil { return err } for _, raw := range raws { if err := decoder.Decode(raw); err != nil { return err } } // Set the metadata if it is set if config.Metadata != nil { *config.Metadata = md } // If we have unused keys, it is an error if len(md.Unused) > 0 { var err error sort.Strings(md.Unused) for _, unused := range md.Unused { if unused != "type" && !strings.HasPrefix(unused, "packer_") { err = multierror.Append(err, fmt.Errorf( "unknown configuration key: %q", unused)) } } if err != nil { return err } } return nil }
[ "func", "Decode", "(", "target", "interface", "{", "}", ",", "config", "*", "DecodeOpts", ",", "raws", "...", "interface", "{", "}", ")", "error", "{", "if", "config", "==", "nil", "{", "config", "=", "&", "DecodeOpts", "{", "Interpolate", ":", "true", "}", "\n", "}", "\n\n", "// Interpolate first", "if", "config", ".", "Interpolate", "{", "// Detect user variables from the raws and merge them into our context", "ctx", ",", "err", ":=", "DetectContext", "(", "raws", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "config", ".", "InterpolateContext", "==", "nil", "{", "config", ".", "InterpolateContext", "=", "ctx", "\n", "}", "else", "{", "config", ".", "InterpolateContext", ".", "BuildName", "=", "ctx", ".", "BuildName", "\n", "config", ".", "InterpolateContext", ".", "BuildType", "=", "ctx", ".", "BuildType", "\n", "config", ".", "InterpolateContext", ".", "TemplatePath", "=", "ctx", ".", "TemplatePath", "\n", "config", ".", "InterpolateContext", ".", "UserVariables", "=", "ctx", ".", "UserVariables", "\n", "}", "\n", "ctx", "=", "config", ".", "InterpolateContext", "\n\n", "// Render everything", "for", "i", ",", "raw", ":=", "range", "raws", "{", "m", ",", "err", ":=", "interpolate", ".", "RenderMap", "(", "raw", ",", "ctx", ",", "config", ".", "InterpolateFilter", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "raws", "[", "i", "]", "=", "m", "\n", "}", "\n", "}", "\n\n", "// Build our decoder", "var", "md", "mapstructure", ".", "Metadata", "\n", "decoder", ",", "err", ":=", "mapstructure", ".", "NewDecoder", "(", "&", "mapstructure", ".", "DecoderConfig", "{", "Result", ":", "target", ",", "Metadata", ":", "&", "md", ",", "WeaklyTypedInput", ":", "true", ",", "DecodeHook", ":", "mapstructure", ".", "ComposeDecodeHookFunc", "(", "uint8ToStringHook", ",", "mapstructure", ".", "StringToSliceHookFunc", "(", "\"", "\"", ")", ",", "mapstructure", ".", "StringToTimeDurationHookFunc", "(", ")", ",", ")", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "raw", ":=", "range", "raws", "{", "if", "err", ":=", "decoder", ".", "Decode", "(", "raw", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Set the metadata if it is set", "if", "config", ".", "Metadata", "!=", "nil", "{", "*", "config", ".", "Metadata", "=", "md", "\n", "}", "\n\n", "// If we have unused keys, it is an error", "if", "len", "(", "md", ".", "Unused", ")", ">", "0", "{", "var", "err", "error", "\n", "sort", ".", "Strings", "(", "md", ".", "Unused", ")", "\n", "for", "_", ",", "unused", ":=", "range", "md", ".", "Unused", "{", "if", "unused", "!=", "\"", "\"", "&&", "!", "strings", ".", "HasPrefix", "(", "unused", ",", "\"", "\"", ")", "{", "err", "=", "multierror", ".", "Append", "(", "err", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "unused", ")", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Decode decodes the configuration into the target and optionally // automatically interpolates all the configuration as it goes.
[ "Decode", "decodes", "the", "configuration", "into", "the", "target", "and", "optionally", "automatically", "interpolates", "all", "the", "configuration", "as", "it", "goes", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/config/decode.go#L30-L105
164,986
hashicorp/packer
helper/config/decode.go
DetectContext
func DetectContext(raws ...interface{}) (*interpolate.Context, error) { var s struct { BuildName string `mapstructure:"packer_build_name"` BuildType string `mapstructure:"packer_builder_type"` TemplatePath string `mapstructure:"packer_template_path"` Vars map[string]string `mapstructure:"packer_user_variables"` SensitiveVars []string `mapstructure:"packer_sensitive_variables"` } for _, r := range raws { if err := mapstructure.Decode(r, &s); err != nil { return nil, err } } return &interpolate.Context{ BuildName: s.BuildName, BuildType: s.BuildType, TemplatePath: s.TemplatePath, UserVariables: s.Vars, SensitiveVariables: s.SensitiveVars, }, nil }
go
func DetectContext(raws ...interface{}) (*interpolate.Context, error) { var s struct { BuildName string `mapstructure:"packer_build_name"` BuildType string `mapstructure:"packer_builder_type"` TemplatePath string `mapstructure:"packer_template_path"` Vars map[string]string `mapstructure:"packer_user_variables"` SensitiveVars []string `mapstructure:"packer_sensitive_variables"` } for _, r := range raws { if err := mapstructure.Decode(r, &s); err != nil { return nil, err } } return &interpolate.Context{ BuildName: s.BuildName, BuildType: s.BuildType, TemplatePath: s.TemplatePath, UserVariables: s.Vars, SensitiveVariables: s.SensitiveVars, }, nil }
[ "func", "DetectContext", "(", "raws", "...", "interface", "{", "}", ")", "(", "*", "interpolate", ".", "Context", ",", "error", ")", "{", "var", "s", "struct", "{", "BuildName", "string", "`mapstructure:\"packer_build_name\"`", "\n", "BuildType", "string", "`mapstructure:\"packer_builder_type\"`", "\n", "TemplatePath", "string", "`mapstructure:\"packer_template_path\"`", "\n", "Vars", "map", "[", "string", "]", "string", "`mapstructure:\"packer_user_variables\"`", "\n", "SensitiveVars", "[", "]", "string", "`mapstructure:\"packer_sensitive_variables\"`", "\n", "}", "\n\n", "for", "_", ",", "r", ":=", "range", "raws", "{", "if", "err", ":=", "mapstructure", ".", "Decode", "(", "r", ",", "&", "s", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "&", "interpolate", ".", "Context", "{", "BuildName", ":", "s", ".", "BuildName", ",", "BuildType", ":", "s", ".", "BuildType", ",", "TemplatePath", ":", "s", ".", "TemplatePath", ",", "UserVariables", ":", "s", ".", "Vars", ",", "SensitiveVariables", ":", "s", ".", "SensitiveVars", ",", "}", ",", "nil", "\n", "}" ]
// DetectContext builds a base interpolate.Context, automatically // detecting things like user variables from the raw configuration params.
[ "DetectContext", "builds", "a", "base", "interpolate", ".", "Context", "automatically", "detecting", "things", "like", "user", "variables", "from", "the", "raw", "configuration", "params", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/config/decode.go#L109-L131
164,987
hashicorp/packer
packer/multi_error.go
MultiErrorAppend
func MultiErrorAppend(err error, errs ...error) *MultiError { if err == nil { err = new(MultiError) } switch err := err.(type) { case *MultiError: if err == nil { err = new(MultiError) } for _, verr := range errs { switch rhsErr := verr.(type) { case *MultiError: if rhsErr != nil { err.Errors = append(err.Errors, rhsErr.Errors...) } default: err.Errors = append(err.Errors, verr) } } return err default: newErrs := make([]error, len(errs)+1) newErrs[0] = err copy(newErrs[1:], errs) return &MultiError{ Errors: newErrs, } } }
go
func MultiErrorAppend(err error, errs ...error) *MultiError { if err == nil { err = new(MultiError) } switch err := err.(type) { case *MultiError: if err == nil { err = new(MultiError) } for _, verr := range errs { switch rhsErr := verr.(type) { case *MultiError: if rhsErr != nil { err.Errors = append(err.Errors, rhsErr.Errors...) } default: err.Errors = append(err.Errors, verr) } } return err default: newErrs := make([]error, len(errs)+1) newErrs[0] = err copy(newErrs[1:], errs) return &MultiError{ Errors: newErrs, } } }
[ "func", "MultiErrorAppend", "(", "err", "error", ",", "errs", "...", "error", ")", "*", "MultiError", "{", "if", "err", "==", "nil", "{", "err", "=", "new", "(", "MultiError", ")", "\n", "}", "\n\n", "switch", "err", ":=", "err", ".", "(", "type", ")", "{", "case", "*", "MultiError", ":", "if", "err", "==", "nil", "{", "err", "=", "new", "(", "MultiError", ")", "\n", "}", "\n\n", "for", "_", ",", "verr", ":=", "range", "errs", "{", "switch", "rhsErr", ":=", "verr", ".", "(", "type", ")", "{", "case", "*", "MultiError", ":", "if", "rhsErr", "!=", "nil", "{", "err", ".", "Errors", "=", "append", "(", "err", ".", "Errors", ",", "rhsErr", ".", "Errors", "...", ")", "\n", "}", "\n", "default", ":", "err", ".", "Errors", "=", "append", "(", "err", ".", "Errors", ",", "verr", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "default", ":", "newErrs", ":=", "make", "(", "[", "]", "error", ",", "len", "(", "errs", ")", "+", "1", ")", "\n", "newErrs", "[", "0", "]", "=", "err", "\n", "copy", "(", "newErrs", "[", "1", ":", "]", ",", "errs", ")", "\n", "return", "&", "MultiError", "{", "Errors", ":", "newErrs", ",", "}", "\n", "}", "\n", "}" ]
// MultiErrorAppend is a helper function that will append more errors // onto a MultiError in order to create a larger multi-error. If the // original error is not a MultiError, it will be turned into one.
[ "MultiErrorAppend", "is", "a", "helper", "function", "that", "will", "append", "more", "errors", "onto", "a", "MultiError", "in", "order", "to", "create", "a", "larger", "multi", "-", "error", ".", "If", "the", "original", "error", "is", "not", "a", "MultiError", "it", "will", "be", "turned", "into", "one", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/multi_error.go#L29-L59
164,988
hashicorp/packer
builder/openstack/server.go
ServerStateRefreshFunc
func ServerStateRefreshFunc( client *gophercloud.ServiceClient, s *servers.Server) StateRefreshFunc { return func() (interface{}, string, int, error) { serverNew, err := servers.Get(client, s.ID).Extract() if err != nil { if _, ok := err.(gophercloud.ErrDefault404); ok { log.Printf("[INFO] 404 on ServerStateRefresh, returning DELETED") return nil, "DELETED", 0, nil } log.Printf("[ERROR] Error on ServerStateRefresh: %s", err) return nil, "", 0, err } return serverNew, serverNew.Status, serverNew.Progress, nil } }
go
func ServerStateRefreshFunc( client *gophercloud.ServiceClient, s *servers.Server) StateRefreshFunc { return func() (interface{}, string, int, error) { serverNew, err := servers.Get(client, s.ID).Extract() if err != nil { if _, ok := err.(gophercloud.ErrDefault404); ok { log.Printf("[INFO] 404 on ServerStateRefresh, returning DELETED") return nil, "DELETED", 0, nil } log.Printf("[ERROR] Error on ServerStateRefresh: %s", err) return nil, "", 0, err } return serverNew, serverNew.Status, serverNew.Progress, nil } }
[ "func", "ServerStateRefreshFunc", "(", "client", "*", "gophercloud", ".", "ServiceClient", ",", "s", "*", "servers", ".", "Server", ")", "StateRefreshFunc", "{", "return", "func", "(", ")", "(", "interface", "{", "}", ",", "string", ",", "int", ",", "error", ")", "{", "serverNew", ",", "err", ":=", "servers", ".", "Get", "(", "client", ",", "s", ".", "ID", ")", ".", "Extract", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "gophercloud", ".", "ErrDefault404", ")", ";", "ok", "{", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "\"", "\"", ",", "0", ",", "nil", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "\"", "\"", ",", "0", ",", "err", "\n", "}", "\n\n", "return", "serverNew", ",", "serverNew", ".", "Status", ",", "serverNew", ".", "Progress", ",", "nil", "\n", "}", "\n", "}" ]
// ServerStateRefreshFunc returns a StateRefreshFunc that is used to watch // an openstack server.
[ "ServerStateRefreshFunc", "returns", "a", "StateRefreshFunc", "that", "is", "used", "to", "watch", "an", "openstack", "server", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/server.go#L36-L51
164,989
hashicorp/packer
builder/openstack/server.go
WaitForState
func WaitForState(conf *StateChangeConf) (i interface{}, err error) { log.Printf("Waiting for state to become: %s", conf.Target) for { var currentProgress int var currentState string i, currentState, currentProgress, err = conf.Refresh() if err != nil { return } for _, t := range conf.Target { if currentState == t { return } } if conf.StepState != nil { if _, ok := conf.StepState.GetOk(multistep.StateCancelled); ok { return nil, errors.New("interrupted") } } found := false for _, allowed := range conf.Pending { if currentState == allowed { found = true break } } if !found { return nil, fmt.Errorf("unexpected state '%s', wanted target '%s'", currentState, conf.Target) } log.Printf("Waiting for state to become: %s currently %s (%d%%)", conf.Target, currentState, currentProgress) time.Sleep(2 * time.Second) } }
go
func WaitForState(conf *StateChangeConf) (i interface{}, err error) { log.Printf("Waiting for state to become: %s", conf.Target) for { var currentProgress int var currentState string i, currentState, currentProgress, err = conf.Refresh() if err != nil { return } for _, t := range conf.Target { if currentState == t { return } } if conf.StepState != nil { if _, ok := conf.StepState.GetOk(multistep.StateCancelled); ok { return nil, errors.New("interrupted") } } found := false for _, allowed := range conf.Pending { if currentState == allowed { found = true break } } if !found { return nil, fmt.Errorf("unexpected state '%s', wanted target '%s'", currentState, conf.Target) } log.Printf("Waiting for state to become: %s currently %s (%d%%)", conf.Target, currentState, currentProgress) time.Sleep(2 * time.Second) } }
[ "func", "WaitForState", "(", "conf", "*", "StateChangeConf", ")", "(", "i", "interface", "{", "}", ",", "err", "error", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "conf", ".", "Target", ")", "\n\n", "for", "{", "var", "currentProgress", "int", "\n", "var", "currentState", "string", "\n", "i", ",", "currentState", ",", "currentProgress", ",", "err", "=", "conf", ".", "Refresh", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "for", "_", ",", "t", ":=", "range", "conf", ".", "Target", "{", "if", "currentState", "==", "t", "{", "return", "\n", "}", "\n", "}", "\n\n", "if", "conf", ".", "StepState", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "conf", ".", "StepState", ".", "GetOk", "(", "multistep", ".", "StateCancelled", ")", ";", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "found", ":=", "false", "\n", "for", "_", ",", "allowed", ":=", "range", "conf", ".", "Pending", "{", "if", "currentState", "==", "allowed", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "found", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "currentState", ",", "conf", ".", "Target", ")", "\n", "}", "\n\n", "log", ".", "Printf", "(", "\"", "\"", ",", "conf", ".", "Target", ",", "currentState", ",", "currentProgress", ")", "\n", "time", ".", "Sleep", "(", "2", "*", "time", ".", "Second", ")", "\n", "}", "\n", "}" ]
// WaitForState watches an object and waits for it to achieve a certain // state.
[ "WaitForState", "watches", "an", "object", "and", "waits", "for", "it", "to", "achieve", "a", "certain", "state", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/openstack/server.go#L55-L93
164,990
hashicorp/packer
packer/plugin/client.go
Exited
func (c *Client) Exited() bool { c.l.Lock() defer c.l.Unlock() return c.exited }
go
func (c *Client) Exited() bool { c.l.Lock() defer c.l.Unlock() return c.exited }
[ "func", "(", "c", "*", "Client", ")", "Exited", "(", ")", "bool", "{", "c", ".", "l", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "l", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "exited", "\n", "}" ]
// Tells whether or not the underlying process has exited.
[ "Tells", "whether", "or", "not", "the", "underlying", "process", "has", "exited", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/plugin/client.go#L125-L129
164,991
hashicorp/packer
packer/plugin/client.go
Builder
func (c *Client) Builder() (packer.Builder, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdBuilder{client.Builder(), c}, nil }
go
func (c *Client) Builder() (packer.Builder, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdBuilder{client.Builder(), c}, nil }
[ "func", "(", "c", "*", "Client", ")", "Builder", "(", ")", "(", "packer", ".", "Builder", ",", "error", ")", "{", "client", ",", "err", ":=", "c", ".", "packrpcClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "cmdBuilder", "{", "client", ".", "Builder", "(", ")", ",", "c", "}", ",", "nil", "\n", "}" ]
// Returns a builder implementation that is communicating over this // client. If the client hasn't been started, this will start it.
[ "Returns", "a", "builder", "implementation", "that", "is", "communicating", "over", "this", "client", ".", "If", "the", "client", "hasn", "t", "been", "started", "this", "will", "start", "it", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/plugin/client.go#L133-L140
164,992
hashicorp/packer
packer/plugin/client.go
Hook
func (c *Client) Hook() (packer.Hook, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdHook{client.Hook(), c}, nil }
go
func (c *Client) Hook() (packer.Hook, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdHook{client.Hook(), c}, nil }
[ "func", "(", "c", "*", "Client", ")", "Hook", "(", ")", "(", "packer", ".", "Hook", ",", "error", ")", "{", "client", ",", "err", ":=", "c", ".", "packrpcClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "cmdHook", "{", "client", ".", "Hook", "(", ")", ",", "c", "}", ",", "nil", "\n", "}" ]
// Returns a hook implementation that is communicating over this // client. If the client hasn't been started, this will start it.
[ "Returns", "a", "hook", "implementation", "that", "is", "communicating", "over", "this", "client", ".", "If", "the", "client", "hasn", "t", "been", "started", "this", "will", "start", "it", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/plugin/client.go#L144-L151
164,993
hashicorp/packer
packer/plugin/client.go
PostProcessor
func (c *Client) PostProcessor() (packer.PostProcessor, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdPostProcessor{client.PostProcessor(), c}, nil }
go
func (c *Client) PostProcessor() (packer.PostProcessor, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdPostProcessor{client.PostProcessor(), c}, nil }
[ "func", "(", "c", "*", "Client", ")", "PostProcessor", "(", ")", "(", "packer", ".", "PostProcessor", ",", "error", ")", "{", "client", ",", "err", ":=", "c", ".", "packrpcClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "cmdPostProcessor", "{", "client", ".", "PostProcessor", "(", ")", ",", "c", "}", ",", "nil", "\n", "}" ]
// Returns a post-processor implementation that is communicating over // this client. If the client hasn't been started, this will start it.
[ "Returns", "a", "post", "-", "processor", "implementation", "that", "is", "communicating", "over", "this", "client", ".", "If", "the", "client", "hasn", "t", "been", "started", "this", "will", "start", "it", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/plugin/client.go#L155-L162
164,994
hashicorp/packer
packer/plugin/client.go
Provisioner
func (c *Client) Provisioner() (packer.Provisioner, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdProvisioner{client.Provisioner(), c}, nil }
go
func (c *Client) Provisioner() (packer.Provisioner, error) { client, err := c.packrpcClient() if err != nil { return nil, err } return &cmdProvisioner{client.Provisioner(), c}, nil }
[ "func", "(", "c", "*", "Client", ")", "Provisioner", "(", ")", "(", "packer", ".", "Provisioner", ",", "error", ")", "{", "client", ",", "err", ":=", "c", ".", "packrpcClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "cmdProvisioner", "{", "client", ".", "Provisioner", "(", ")", ",", "c", "}", ",", "nil", "\n", "}" ]
// Returns a provisioner implementation that is communicating over this // client. If the client hasn't been started, this will start it.
[ "Returns", "a", "provisioner", "implementation", "that", "is", "communicating", "over", "this", "client", ".", "If", "the", "client", "hasn", "t", "been", "started", "this", "will", "start", "it", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/plugin/client.go#L166-L173
164,995
hashicorp/packer
builder/hyperv/common/driver_ps_4.go
Mac
func (d *HypervPS4Driver) Mac(vmName string) (string, error) { res, err := hyperv.Mac(vmName) if err != nil { return res, err } if res == "" { err := fmt.Errorf("%s", "No mac address.") return res, err } return res, err }
go
func (d *HypervPS4Driver) Mac(vmName string) (string, error) { res, err := hyperv.Mac(vmName) if err != nil { return res, err } if res == "" { err := fmt.Errorf("%s", "No mac address.") return res, err } return res, err }
[ "func", "(", "d", "*", "HypervPS4Driver", ")", "Mac", "(", "vmName", "string", ")", "(", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "hyperv", ".", "Mac", "(", "vmName", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "if", "res", "==", "\"", "\"", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "res", ",", "err", "\n", "}", "\n\n", "return", "res", ",", "err", "\n", "}" ]
// Get mac address for VM.
[ "Get", "mac", "address", "for", "VM", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L76-L89
164,996
hashicorp/packer
builder/hyperv/common/driver_ps_4.go
IpAddress
func (d *HypervPS4Driver) IpAddress(mac string) (string, error) { res, err := hyperv.IpAddress(mac) if err != nil { return res, err } if res == "" { err := fmt.Errorf("%s", "No ip address.") return res, err } return res, err }
go
func (d *HypervPS4Driver) IpAddress(mac string) (string, error) { res, err := hyperv.IpAddress(mac) if err != nil { return res, err } if res == "" { err := fmt.Errorf("%s", "No ip address.") return res, err } return res, err }
[ "func", "(", "d", "*", "HypervPS4Driver", ")", "IpAddress", "(", "mac", "string", ")", "(", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "hyperv", ".", "IpAddress", "(", "mac", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "if", "res", "==", "\"", "\"", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "res", ",", "err", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// Get ip address for mac address.
[ "Get", "ip", "address", "for", "mac", "address", "." ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L92-L104
164,997
hashicorp/packer
builder/hyperv/common/driver_ps_4.go
GetHostName
func (d *HypervPS4Driver) GetHostName(ip string) (string, error) { return powershell.GetHostName(ip) }
go
func (d *HypervPS4Driver) GetHostName(ip string) (string, error) { return powershell.GetHostName(ip) }
[ "func", "(", "d", "*", "HypervPS4Driver", ")", "GetHostName", "(", "ip", "string", ")", "(", "string", ",", "error", ")", "{", "return", "powershell", ".", "GetHostName", "(", "ip", ")", "\n", "}" ]
// Get host name from ip address
[ "Get", "host", "name", "from", "ip", "address" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L107-L109
164,998
hashicorp/packer
builder/hyperv/common/driver_ps_4.go
GetHostAdapterIpAddressForSwitch
func (d *HypervPS4Driver) GetHostAdapterIpAddressForSwitch(switchName string) (string, error) { res, err := hyperv.GetHostAdapterIpAddressForSwitch(switchName) if err != nil { return res, err } if res == "" { err := fmt.Errorf("%s", "No ip address.") return res, err } return res, err }
go
func (d *HypervPS4Driver) GetHostAdapterIpAddressForSwitch(switchName string) (string, error) { res, err := hyperv.GetHostAdapterIpAddressForSwitch(switchName) if err != nil { return res, err } if res == "" { err := fmt.Errorf("%s", "No ip address.") return res, err } return res, err }
[ "func", "(", "d", "*", "HypervPS4Driver", ")", "GetHostAdapterIpAddressForSwitch", "(", "switchName", "string", ")", "(", "string", ",", "error", ")", "{", "res", ",", "err", ":=", "hyperv", ".", "GetHostAdapterIpAddressForSwitch", "(", "switchName", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n\n", "if", "res", "==", "\"", "\"", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "res", ",", "err", "\n", "}", "\n", "return", "res", ",", "err", "\n", "}" ]
// Finds the IP address of a host adapter connected to switch
[ "Finds", "the", "IP", "address", "of", "a", "host", "adapter", "connected", "to", "switch" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L116-L128
164,999
hashicorp/packer
builder/hyperv/common/driver_ps_4.go
TypeScanCodes
func (d *HypervPS4Driver) TypeScanCodes(vmName string, scanCodes string) error { return hyperv.TypeScanCodes(vmName, scanCodes) }
go
func (d *HypervPS4Driver) TypeScanCodes(vmName string, scanCodes string) error { return hyperv.TypeScanCodes(vmName, scanCodes) }
[ "func", "(", "d", "*", "HypervPS4Driver", ")", "TypeScanCodes", "(", "vmName", "string", ",", "scanCodes", "string", ")", "error", "{", "return", "hyperv", ".", "TypeScanCodes", "(", "vmName", ",", "scanCodes", ")", "\n", "}" ]
// Type scan codes to virtual keyboard of vm
[ "Type", "scan", "codes", "to", "virtual", "keyboard", "of", "vm" ]
d343852c15da050ee3ad039cc4cadfbf7f9b1759
https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/driver_ps_4.go#L131-L133