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,700
dexidp/dex
server/handlers.go
newHealthChecker
func (s *Server) newHealthChecker(ctx context.Context) http.Handler { h := &healthChecker{s: s} // Perform one health check synchronously so the returned handler returns // valid data immediately. h.runHealthCheck() go func() { for { select { case <-ctx.Done(): return case <-time.After(time.Second * 15): } h.runHealthCheck() } }() return h }
go
func (s *Server) newHealthChecker(ctx context.Context) http.Handler { h := &healthChecker{s: s} // Perform one health check synchronously so the returned handler returns // valid data immediately. h.runHealthCheck() go func() { for { select { case <-ctx.Done(): return case <-time.After(time.Second * 15): } h.runHealthCheck() } }() return h }
[ "func", "(", "s", "*", "Server", ")", "newHealthChecker", "(", "ctx", "context", ".", "Context", ")", "http", ".", "Handler", "{", "h", ":=", "&", "healthChecker", "{", "s", ":", "s", "}", "\n\n", "// Perform one health check synchronously so the returned handler returns", "// valid data immediately.", "h", ".", "runHealthCheck", "(", ")", "\n\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "time", ".", "Second", "*", "15", ")", ":", "}", "\n", "h", ".", "runHealthCheck", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "return", "h", "\n", "}" ]
// newHealthChecker returns the healthz handler. The handler runs until the // provided context is canceled.
[ "newHealthChecker", "returns", "the", "healthz", "handler", ".", "The", "handler", "runs", "until", "the", "provided", "context", "is", "canceled", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/handlers.go#L27-L45
164,701
dexidp/dex
server/handlers.go
runHealthCheck
func (h *healthChecker) runHealthCheck() { t := h.s.now() err := checkStorageHealth(h.s.storage, h.s.now) passed := h.s.now().Sub(t) if err != nil { h.s.logger.Errorf("Storage health check failed: %v", err) } // Make sure to only hold the mutex to access the fields, and not while // we're querying the storage object. h.mu.Lock() h.err = err h.passed = passed h.mu.Unlock() }
go
func (h *healthChecker) runHealthCheck() { t := h.s.now() err := checkStorageHealth(h.s.storage, h.s.now) passed := h.s.now().Sub(t) if err != nil { h.s.logger.Errorf("Storage health check failed: %v", err) } // Make sure to only hold the mutex to access the fields, and not while // we're querying the storage object. h.mu.Lock() h.err = err h.passed = passed h.mu.Unlock() }
[ "func", "(", "h", "*", "healthChecker", ")", "runHealthCheck", "(", ")", "{", "t", ":=", "h", ".", "s", ".", "now", "(", ")", "\n", "err", ":=", "checkStorageHealth", "(", "h", ".", "s", ".", "storage", ",", "h", ".", "s", ".", "now", ")", "\n", "passed", ":=", "h", ".", "s", ".", "now", "(", ")", ".", "Sub", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "h", ".", "s", ".", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Make sure to only hold the mutex to access the fields, and not while", "// we're querying the storage object.", "h", ".", "mu", ".", "Lock", "(", ")", "\n", "h", ".", "err", "=", "err", "\n", "h", ".", "passed", "=", "passed", "\n", "h", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// runHealthCheck performs a single health check and makes the result available // for any clients performing and HTTP request against the healthChecker.
[ "runHealthCheck", "performs", "a", "single", "health", "check", "and", "makes", "the", "result", "available", "for", "any", "clients", "performing", "and", "HTTP", "request", "against", "the", "healthChecker", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/handlers.go#L62-L76
164,702
dexidp/dex
server/handlers.go
handleAuthorization
func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) { authReq, err := s.parseAuthorizationRequest(r) if err != nil { s.logger.Errorf("Failed to parse authorization request: %v", err) if handler, ok := err.Handle(); ok { // client_id and redirect_uri checked out and we can redirect back to // the client with the error. handler.ServeHTTP(w, r) return } // Otherwise render the error to the user. // // TODO(ericchiang): Should we just always render the error? s.renderError(w, err.Status(), err.Error()) return } // TODO(ericchiang): Create this authorization request later in the login flow // so users don't hit "not found" database errors if they wait at the login // screen too long. // // See: https://github.com/dexidp/dex/issues/646 authReq.Expiry = s.now().Add(s.authRequestsValidFor) if err := s.storage.CreateAuthRequest(authReq); err != nil { s.logger.Errorf("Failed to create authorization request: %v", err) s.renderError(w, http.StatusInternalServerError, "Failed to connect to the database.") return } connectors, e := s.storage.ListConnectors() if e != nil { s.logger.Errorf("Failed to get list of connectors: %v", err) s.renderError(w, http.StatusInternalServerError, "Failed to retrieve connector list.") return } if len(connectors) == 1 { for _, c := range connectors { // TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter // on create the auth request. http.Redirect(w, r, s.absPath("/auth", c.ID)+"?req="+authReq.ID, http.StatusFound) return } } connectorInfos := make([]connectorInfo, len(connectors)) i := 0 for _, conn := range connectors { connectorInfos[i] = connectorInfo{ ID: conn.ID, Name: conn.Name, // TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter // on create the auth request. URL: s.absPath("/auth", conn.ID) + "?req=" + authReq.ID, } i++ } if err := s.templates.login(w, connectorInfos); err != nil { s.logger.Errorf("Server template error: %v", err) } }
go
func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) { authReq, err := s.parseAuthorizationRequest(r) if err != nil { s.logger.Errorf("Failed to parse authorization request: %v", err) if handler, ok := err.Handle(); ok { // client_id and redirect_uri checked out and we can redirect back to // the client with the error. handler.ServeHTTP(w, r) return } // Otherwise render the error to the user. // // TODO(ericchiang): Should we just always render the error? s.renderError(w, err.Status(), err.Error()) return } // TODO(ericchiang): Create this authorization request later in the login flow // so users don't hit "not found" database errors if they wait at the login // screen too long. // // See: https://github.com/dexidp/dex/issues/646 authReq.Expiry = s.now().Add(s.authRequestsValidFor) if err := s.storage.CreateAuthRequest(authReq); err != nil { s.logger.Errorf("Failed to create authorization request: %v", err) s.renderError(w, http.StatusInternalServerError, "Failed to connect to the database.") return } connectors, e := s.storage.ListConnectors() if e != nil { s.logger.Errorf("Failed to get list of connectors: %v", err) s.renderError(w, http.StatusInternalServerError, "Failed to retrieve connector list.") return } if len(connectors) == 1 { for _, c := range connectors { // TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter // on create the auth request. http.Redirect(w, r, s.absPath("/auth", c.ID)+"?req="+authReq.ID, http.StatusFound) return } } connectorInfos := make([]connectorInfo, len(connectors)) i := 0 for _, conn := range connectors { connectorInfos[i] = connectorInfo{ ID: conn.ID, Name: conn.Name, // TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter // on create the auth request. URL: s.absPath("/auth", conn.ID) + "?req=" + authReq.ID, } i++ } if err := s.templates.login(w, connectorInfos); err != nil { s.logger.Errorf("Server template error: %v", err) } }
[ "func", "(", "s", "*", "Server", ")", "handleAuthorization", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "authReq", ",", "err", ":=", "s", ".", "parseAuthorizationRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "if", "handler", ",", "ok", ":=", "err", ".", "Handle", "(", ")", ";", "ok", "{", "// client_id and redirect_uri checked out and we can redirect back to", "// the client with the error.", "handler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "return", "\n", "}", "\n\n", "// Otherwise render the error to the user.", "//", "// TODO(ericchiang): Should we just always render the error?", "s", ".", "renderError", "(", "w", ",", "err", ".", "Status", "(", ")", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "// TODO(ericchiang): Create this authorization request later in the login flow", "// so users don't hit \"not found\" database errors if they wait at the login", "// screen too long.", "//", "// See: https://github.com/dexidp/dex/issues/646", "authReq", ".", "Expiry", "=", "s", ".", "now", "(", ")", ".", "Add", "(", "s", ".", "authRequestsValidFor", ")", "\n", "if", "err", ":=", "s", ".", "storage", ".", "CreateAuthRequest", "(", "authReq", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "s", ".", "renderError", "(", "w", ",", "http", ".", "StatusInternalServerError", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "connectors", ",", "e", ":=", "s", ".", "storage", ".", "ListConnectors", "(", ")", "\n", "if", "e", "!=", "nil", "{", "s", ".", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "s", ".", "renderError", "(", "w", ",", "http", ".", "StatusInternalServerError", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "len", "(", "connectors", ")", "==", "1", "{", "for", "_", ",", "c", ":=", "range", "connectors", "{", "// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter", "// on create the auth request.", "http", ".", "Redirect", "(", "w", ",", "r", ",", "s", ".", "absPath", "(", "\"", "\"", ",", "c", ".", "ID", ")", "+", "\"", "\"", "+", "authReq", ".", "ID", ",", "http", ".", "StatusFound", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "connectorInfos", ":=", "make", "(", "[", "]", "connectorInfo", ",", "len", "(", "connectors", ")", ")", "\n", "i", ":=", "0", "\n", "for", "_", ",", "conn", ":=", "range", "connectors", "{", "connectorInfos", "[", "i", "]", "=", "connectorInfo", "{", "ID", ":", "conn", ".", "ID", ",", "Name", ":", "conn", ".", "Name", ",", "// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter", "// on create the auth request.", "URL", ":", "s", ".", "absPath", "(", "\"", "\"", ",", "conn", ".", "ID", ")", "+", "\"", "\"", "+", "authReq", ".", "ID", ",", "}", "\n", "i", "++", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "templates", ".", "login", "(", "w", ",", "connectorInfos", ")", ";", "err", "!=", "nil", "{", "s", ".", "logger", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// handleAuthorization handles the OAuth2 auth endpoint.
[ "handleAuthorization", "handles", "the", "OAuth2", "auth", "endpoint", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/handlers.go#L196-L258
164,703
dexidp/dex
server/handlers.go
finalizeLogin
func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.AuthRequest, conn connector.Connector) (string, error) { claims := storage.Claims{ UserID: identity.UserID, Username: identity.Username, Email: identity.Email, EmailVerified: identity.EmailVerified, Groups: identity.Groups, } updater := func(a storage.AuthRequest) (storage.AuthRequest, error) { a.LoggedIn = true a.Claims = claims a.ConnectorData = identity.ConnectorData return a, nil } if err := s.storage.UpdateAuthRequest(authReq.ID, updater); err != nil { return "", fmt.Errorf("failed to update auth request: %v", err) } email := claims.Email if !claims.EmailVerified { email = email + " (unverified)" } s.logger.Infof("login successful: connector %q, username=%q, email=%q, groups=%q", authReq.ConnectorID, claims.Username, email, claims.Groups) return path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID, nil }
go
func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.AuthRequest, conn connector.Connector) (string, error) { claims := storage.Claims{ UserID: identity.UserID, Username: identity.Username, Email: identity.Email, EmailVerified: identity.EmailVerified, Groups: identity.Groups, } updater := func(a storage.AuthRequest) (storage.AuthRequest, error) { a.LoggedIn = true a.Claims = claims a.ConnectorData = identity.ConnectorData return a, nil } if err := s.storage.UpdateAuthRequest(authReq.ID, updater); err != nil { return "", fmt.Errorf("failed to update auth request: %v", err) } email := claims.Email if !claims.EmailVerified { email = email + " (unverified)" } s.logger.Infof("login successful: connector %q, username=%q, email=%q, groups=%q", authReq.ConnectorID, claims.Username, email, claims.Groups) return path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID, nil }
[ "func", "(", "s", "*", "Server", ")", "finalizeLogin", "(", "identity", "connector", ".", "Identity", ",", "authReq", "storage", ".", "AuthRequest", ",", "conn", "connector", ".", "Connector", ")", "(", "string", ",", "error", ")", "{", "claims", ":=", "storage", ".", "Claims", "{", "UserID", ":", "identity", ".", "UserID", ",", "Username", ":", "identity", ".", "Username", ",", "Email", ":", "identity", ".", "Email", ",", "EmailVerified", ":", "identity", ".", "EmailVerified", ",", "Groups", ":", "identity", ".", "Groups", ",", "}", "\n\n", "updater", ":=", "func", "(", "a", "storage", ".", "AuthRequest", ")", "(", "storage", ".", "AuthRequest", ",", "error", ")", "{", "a", ".", "LoggedIn", "=", "true", "\n", "a", ".", "Claims", "=", "claims", "\n", "a", ".", "ConnectorData", "=", "identity", ".", "ConnectorData", "\n", "return", "a", ",", "nil", "\n", "}", "\n", "if", "err", ":=", "s", ".", "storage", ".", "UpdateAuthRequest", "(", "authReq", ".", "ID", ",", "updater", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "email", ":=", "claims", ".", "Email", "\n", "if", "!", "claims", ".", "EmailVerified", "{", "email", "=", "email", "+", "\"", "\"", "\n", "}", "\n\n", "s", ".", "logger", ".", "Infof", "(", "\"", "\"", ",", "authReq", ".", "ConnectorID", ",", "claims", ".", "Username", ",", "email", ",", "claims", ".", "Groups", ")", "\n\n", "return", "path", ".", "Join", "(", "s", ".", "issuerURL", ".", "Path", ",", "\"", "\"", ")", "+", "\"", "\"", "+", "authReq", ".", "ID", ",", "nil", "\n", "}" ]
// finalizeLogin associates the user's identity with the current AuthRequest, then returns // the approval page's path.
[ "finalizeLogin", "associates", "the", "user", "s", "identity", "with", "the", "current", "AuthRequest", "then", "returns", "the", "approval", "page", "s", "path", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/handlers.go#L461-L489
164,704
dexidp/dex
server/handlers.go
usernamePrompt
func usernamePrompt(conn connector.PasswordConnector) string { if attr := conn.Prompt(); attr != "" { return attr } return "Username" }
go
func usernamePrompt(conn connector.PasswordConnector) string { if attr := conn.Prompt(); attr != "" { return attr } return "Username" }
[ "func", "usernamePrompt", "(", "conn", "connector", ".", "PasswordConnector", ")", "string", "{", "if", "attr", ":=", "conn", ".", "Prompt", "(", ")", ";", "attr", "!=", "\"", "\"", "{", "return", "attr", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// Check for username prompt override from connector. Defaults to "Username".
[ "Check", "for", "username", "prompt", "override", "from", "connector", ".", "Defaults", "to", "Username", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/handlers.go#L1070-L1075
164,705
dexidp/dex
server/server.go
NewServer
func NewServer(ctx context.Context, c Config) (*Server, error) { return newServer(ctx, c, defaultRotationStrategy( value(c.RotateKeysAfter, 6*time.Hour), value(c.IDTokensValidFor, 24*time.Hour), )) }
go
func NewServer(ctx context.Context, c Config) (*Server, error) { return newServer(ctx, c, defaultRotationStrategy( value(c.RotateKeysAfter, 6*time.Hour), value(c.IDTokensValidFor, 24*time.Hour), )) }
[ "func", "NewServer", "(", "ctx", "context", ".", "Context", ",", "c", "Config", ")", "(", "*", "Server", ",", "error", ")", "{", "return", "newServer", "(", "ctx", ",", "c", ",", "defaultRotationStrategy", "(", "value", "(", "c", ".", "RotateKeysAfter", ",", "6", "*", "time", ".", "Hour", ")", ",", "value", "(", "c", ".", "IDTokensValidFor", ",", "24", "*", "time", ".", "Hour", ")", ",", ")", ")", "\n", "}" ]
// NewServer constructs a server from the provided config.
[ "NewServer", "constructs", "a", "server", "from", "the", "provided", "config", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/server.go#L148-L153
164,706
dexidp/dex
server/server.go
newKeyCacher
func newKeyCacher(s storage.Storage, now func() time.Time) storage.Storage { if now == nil { now = time.Now } return &keyCacher{Storage: s, now: now} }
go
func newKeyCacher(s storage.Storage, now func() time.Time) storage.Storage { if now == nil { now = time.Now } return &keyCacher{Storage: s, now: now} }
[ "func", "newKeyCacher", "(", "s", "storage", ".", "Storage", ",", "now", "func", "(", ")", "time", ".", "Time", ")", "storage", ".", "Storage", "{", "if", "now", "==", "nil", "{", "now", "=", "time", ".", "Now", "\n", "}", "\n", "return", "&", "keyCacher", "{", "Storage", ":", "s", ",", "now", ":", "now", "}", "\n", "}" ]
// newKeyCacher returns a storage which caches keys so long as the next
[ "newKeyCacher", "returns", "a", "storage", "which", "caches", "keys", "so", "long", "as", "the", "next" ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/server.go#L382-L387
164,707
dexidp/dex
server/server.go
openConnector
func openConnector(logger log.Logger, conn storage.Connector) (connector.Connector, error) { var c connector.Connector f, ok := ConnectorsConfig[conn.Type] if !ok { return c, fmt.Errorf("unknown connector type %q", conn.Type) } connConfig := f() if len(conn.Config) != 0 { data := []byte(string(conn.Config)) if err := json.Unmarshal(data, connConfig); err != nil { return c, fmt.Errorf("parse connector config: %v", err) } } c, err := connConfig.Open(conn.ID, logger) if err != nil { return c, fmt.Errorf("failed to create connector %s: %v", conn.ID, err) } return c, nil }
go
func openConnector(logger log.Logger, conn storage.Connector) (connector.Connector, error) { var c connector.Connector f, ok := ConnectorsConfig[conn.Type] if !ok { return c, fmt.Errorf("unknown connector type %q", conn.Type) } connConfig := f() if len(conn.Config) != 0 { data := []byte(string(conn.Config)) if err := json.Unmarshal(data, connConfig); err != nil { return c, fmt.Errorf("parse connector config: %v", err) } } c, err := connConfig.Open(conn.ID, logger) if err != nil { return c, fmt.Errorf("failed to create connector %s: %v", conn.ID, err) } return c, nil }
[ "func", "openConnector", "(", "logger", "log", ".", "Logger", ",", "conn", "storage", ".", "Connector", ")", "(", "connector", ".", "Connector", ",", "error", ")", "{", "var", "c", "connector", ".", "Connector", "\n\n", "f", ",", "ok", ":=", "ConnectorsConfig", "[", "conn", ".", "Type", "]", "\n", "if", "!", "ok", "{", "return", "c", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "conn", ".", "Type", ")", "\n", "}", "\n\n", "connConfig", ":=", "f", "(", ")", "\n", "if", "len", "(", "conn", ".", "Config", ")", "!=", "0", "{", "data", ":=", "[", "]", "byte", "(", "string", "(", "conn", ".", "Config", ")", ")", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "connConfig", ")", ";", "err", "!=", "nil", "{", "return", "c", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "c", ",", "err", ":=", "connConfig", ".", "Open", "(", "conn", ".", "ID", ",", "logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "c", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "conn", ".", "ID", ",", "err", ")", "\n", "}", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// openConnector will parse the connector config and open the connector.
[ "openConnector", "will", "parse", "the", "connector", "config", "and", "open", "the", "connector", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/server.go#L456-L478
164,708
dexidp/dex
server/server.go
OpenConnector
func (s *Server) OpenConnector(conn storage.Connector) (Connector, error) { var c connector.Connector if conn.Type == LocalConnector { c = newPasswordDB(s.storage) } else { var err error c, err = openConnector(s.logger, conn) if err != nil { return Connector{}, fmt.Errorf("failed to open connector: %v", err) } } connector := Connector{ ResourceVersion: conn.ResourceVersion, Connector: c, } s.mu.Lock() s.connectors[conn.ID] = connector s.mu.Unlock() return connector, nil }
go
func (s *Server) OpenConnector(conn storage.Connector) (Connector, error) { var c connector.Connector if conn.Type == LocalConnector { c = newPasswordDB(s.storage) } else { var err error c, err = openConnector(s.logger, conn) if err != nil { return Connector{}, fmt.Errorf("failed to open connector: %v", err) } } connector := Connector{ ResourceVersion: conn.ResourceVersion, Connector: c, } s.mu.Lock() s.connectors[conn.ID] = connector s.mu.Unlock() return connector, nil }
[ "func", "(", "s", "*", "Server", ")", "OpenConnector", "(", "conn", "storage", ".", "Connector", ")", "(", "Connector", ",", "error", ")", "{", "var", "c", "connector", ".", "Connector", "\n\n", "if", "conn", ".", "Type", "==", "LocalConnector", "{", "c", "=", "newPasswordDB", "(", "s", ".", "storage", ")", "\n", "}", "else", "{", "var", "err", "error", "\n", "c", ",", "err", "=", "openConnector", "(", "s", ".", "logger", ",", "conn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Connector", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "connector", ":=", "Connector", "{", "ResourceVersion", ":", "conn", ".", "ResourceVersion", ",", "Connector", ":", "c", ",", "}", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "connectors", "[", "conn", ".", "ID", "]", "=", "connector", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "return", "connector", ",", "nil", "\n", "}" ]
// OpenConnector updates server connector map with specified connector object.
[ "OpenConnector", "updates", "server", "connector", "map", "with", "specified", "connector", "object", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/server.go#L481-L503
164,709
dexidp/dex
server/server.go
getConnector
func (s *Server) getConnector(id string) (Connector, error) { storageConnector, err := s.storage.GetConnector(id) if err != nil { return Connector{}, fmt.Errorf("failed to get connector object from storage: %v", err) } var conn Connector var ok bool s.mu.Lock() conn, ok = s.connectors[id] s.mu.Unlock() if !ok || storageConnector.ResourceVersion != conn.ResourceVersion { // Connector object does not exist in server connectors map or // has been updated in the storage. Need to get latest. conn, err := s.OpenConnector(storageConnector) if err != nil { return Connector{}, fmt.Errorf("failed to open connector: %v", err) } return conn, nil } return conn, nil }
go
func (s *Server) getConnector(id string) (Connector, error) { storageConnector, err := s.storage.GetConnector(id) if err != nil { return Connector{}, fmt.Errorf("failed to get connector object from storage: %v", err) } var conn Connector var ok bool s.mu.Lock() conn, ok = s.connectors[id] s.mu.Unlock() if !ok || storageConnector.ResourceVersion != conn.ResourceVersion { // Connector object does not exist in server connectors map or // has been updated in the storage. Need to get latest. conn, err := s.OpenConnector(storageConnector) if err != nil { return Connector{}, fmt.Errorf("failed to open connector: %v", err) } return conn, nil } return conn, nil }
[ "func", "(", "s", "*", "Server", ")", "getConnector", "(", "id", "string", ")", "(", "Connector", ",", "error", ")", "{", "storageConnector", ",", "err", ":=", "s", ".", "storage", ".", "GetConnector", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Connector", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "var", "conn", "Connector", "\n", "var", "ok", "bool", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "conn", ",", "ok", "=", "s", ".", "connectors", "[", "id", "]", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "!", "ok", "||", "storageConnector", ".", "ResourceVersion", "!=", "conn", ".", "ResourceVersion", "{", "// Connector object does not exist in server connectors map or", "// has been updated in the storage. Need to get latest.", "conn", ",", "err", ":=", "s", ".", "OpenConnector", "(", "storageConnector", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Connector", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}", "\n\n", "return", "conn", ",", "nil", "\n", "}" ]
// getConnector retrieves the connector object with the given id from the storage // and updates the connector list for server if necessary.
[ "getConnector", "retrieves", "the", "connector", "object", "with", "the", "given", "id", "from", "the", "storage", "and", "updates", "the", "connector", "list", "for", "server", "if", "necessary", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/server/server.go#L507-L530
164,710
dexidp/dex
connector/keystone/keystone.go
Open
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { return &conn{ c.Domain, c.Host, c.AdminUsername, c.AdminPassword, logger}, nil }
go
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { return &conn{ c.Domain, c.Host, c.AdminUsername, c.AdminPassword, logger}, nil }
[ "func", "(", "c", "*", "Config", ")", "Open", "(", "id", "string", ",", "logger", "log", ".", "Logger", ")", "(", "connector", ".", "Connector", ",", "error", ")", "{", "return", "&", "conn", "{", "c", ".", "Domain", ",", "c", ".", "Host", ",", "c", ".", "AdminUsername", ",", "c", ".", "AdminPassword", ",", "logger", "}", ",", "nil", "\n", "}" ]
// Open returns an authentication strategy using Keystone.
[ "Open", "returns", "an", "authentication", "strategy", "using", "Keystone", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/keystone/keystone.go#L104-L111
164,711
dexidp/dex
connector/github/github.go
Open
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { if c.Org != "" { // Return error if both 'org' and 'orgs' fields are used. if len(c.Orgs) > 0 { return nil, errors.New("github: cannot use both 'org' and 'orgs' fields simultaneously") } logger.Warn("github: legacy field 'org' being used. Switch to the newer 'orgs' field structure") } g := githubConnector{ redirectURI: c.RedirectURI, org: c.Org, orgs: c.Orgs, clientID: c.ClientID, clientSecret: c.ClientSecret, apiURL: apiURL, logger: logger, useLoginAsID: c.UseLoginAsID, } if c.HostName != "" { // ensure this is a hostname and not a URL or path. if strings.Contains(c.HostName, "/") { return nil, errors.New("invalid hostname: hostname cannot contain `/`") } g.hostName = c.HostName g.apiURL = "https://" + c.HostName + "/api/v3" } if c.RootCA != "" { if c.HostName == "" { return nil, errors.New("invalid connector config: Host name field required for a root certificate file") } g.rootCA = c.RootCA var err error if g.httpClient, err = newHTTPClient(g.rootCA); err != nil { return nil, fmt.Errorf("failed to create HTTP client: %v", err) } } g.loadAllGroups = c.LoadAllGroups switch c.TeamNameField { case "name", "slug", "both", "": g.teamNameField = c.TeamNameField default: return nil, fmt.Errorf("invalid connector config: unsupported team name field value `%s`", c.TeamNameField) } return &g, nil }
go
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { if c.Org != "" { // Return error if both 'org' and 'orgs' fields are used. if len(c.Orgs) > 0 { return nil, errors.New("github: cannot use both 'org' and 'orgs' fields simultaneously") } logger.Warn("github: legacy field 'org' being used. Switch to the newer 'orgs' field structure") } g := githubConnector{ redirectURI: c.RedirectURI, org: c.Org, orgs: c.Orgs, clientID: c.ClientID, clientSecret: c.ClientSecret, apiURL: apiURL, logger: logger, useLoginAsID: c.UseLoginAsID, } if c.HostName != "" { // ensure this is a hostname and not a URL or path. if strings.Contains(c.HostName, "/") { return nil, errors.New("invalid hostname: hostname cannot contain `/`") } g.hostName = c.HostName g.apiURL = "https://" + c.HostName + "/api/v3" } if c.RootCA != "" { if c.HostName == "" { return nil, errors.New("invalid connector config: Host name field required for a root certificate file") } g.rootCA = c.RootCA var err error if g.httpClient, err = newHTTPClient(g.rootCA); err != nil { return nil, fmt.Errorf("failed to create HTTP client: %v", err) } } g.loadAllGroups = c.LoadAllGroups switch c.TeamNameField { case "name", "slug", "both", "": g.teamNameField = c.TeamNameField default: return nil, fmt.Errorf("invalid connector config: unsupported team name field value `%s`", c.TeamNameField) } return &g, nil }
[ "func", "(", "c", "*", "Config", ")", "Open", "(", "id", "string", ",", "logger", "log", ".", "Logger", ")", "(", "connector", ".", "Connector", ",", "error", ")", "{", "if", "c", ".", "Org", "!=", "\"", "\"", "{", "// Return error if both 'org' and 'orgs' fields are used.", "if", "len", "(", "c", ".", "Orgs", ")", ">", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "logger", ".", "Warn", "(", "\"", "\"", ")", "\n", "}", "\n\n", "g", ":=", "githubConnector", "{", "redirectURI", ":", "c", ".", "RedirectURI", ",", "org", ":", "c", ".", "Org", ",", "orgs", ":", "c", ".", "Orgs", ",", "clientID", ":", "c", ".", "ClientID", ",", "clientSecret", ":", "c", ".", "ClientSecret", ",", "apiURL", ":", "apiURL", ",", "logger", ":", "logger", ",", "useLoginAsID", ":", "c", ".", "UseLoginAsID", ",", "}", "\n\n", "if", "c", ".", "HostName", "!=", "\"", "\"", "{", "// ensure this is a hostname and not a URL or path.", "if", "strings", ".", "Contains", "(", "c", ".", "HostName", ",", "\"", "\"", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "g", ".", "hostName", "=", "c", ".", "HostName", "\n", "g", ".", "apiURL", "=", "\"", "\"", "+", "c", ".", "HostName", "+", "\"", "\"", "\n", "}", "\n\n", "if", "c", ".", "RootCA", "!=", "\"", "\"", "{", "if", "c", ".", "HostName", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "g", ".", "rootCA", "=", "c", ".", "RootCA", "\n\n", "var", "err", "error", "\n", "if", "g", ".", "httpClient", ",", "err", "=", "newHTTPClient", "(", "g", ".", "rootCA", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "}", "\n", "g", ".", "loadAllGroups", "=", "c", ".", "LoadAllGroups", "\n\n", "switch", "c", ".", "TeamNameField", "{", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "g", ".", "teamNameField", "=", "c", ".", "TeamNameField", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "TeamNameField", ")", "\n", "}", "\n\n", "return", "&", "g", ",", "nil", "\n", "}" ]
// Open returns a strategy for logging in through GitHub.
[ "Open", "returns", "a", "strategy", "for", "logging", "in", "through", "GitHub", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/github/github.go#L68-L121
164,712
dexidp/dex
connector/github/github.go
newHTTPClient
func newHTTPClient(rootCA string) (*http.Client, error) { tlsConfig := tls.Config{RootCAs: x509.NewCertPool()} rootCABytes, err := ioutil.ReadFile(rootCA) if err != nil { return nil, fmt.Errorf("failed to read root-ca: %v", err) } if !tlsConfig.RootCAs.AppendCertsFromPEM(rootCABytes) { return nil, fmt.Errorf("no certs found in root CA file %q", rootCA) } return &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tlsConfig, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, }, nil }
go
func newHTTPClient(rootCA string) (*http.Client, error) { tlsConfig := tls.Config{RootCAs: x509.NewCertPool()} rootCABytes, err := ioutil.ReadFile(rootCA) if err != nil { return nil, fmt.Errorf("failed to read root-ca: %v", err) } if !tlsConfig.RootCAs.AppendCertsFromPEM(rootCABytes) { return nil, fmt.Errorf("no certs found in root CA file %q", rootCA) } return &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tlsConfig, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, }, nil }
[ "func", "newHTTPClient", "(", "rootCA", "string", ")", "(", "*", "http", ".", "Client", ",", "error", ")", "{", "tlsConfig", ":=", "tls", ".", "Config", "{", "RootCAs", ":", "x509", ".", "NewCertPool", "(", ")", "}", "\n", "rootCABytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "rootCA", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "tlsConfig", ".", "RootCAs", ".", "AppendCertsFromPEM", "(", "rootCABytes", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rootCA", ")", "\n", "}", "\n\n", "return", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tlsConfig", ",", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "DialContext", ":", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "DualStack", ":", "true", ",", "}", ")", ".", "DialContext", ",", "MaxIdleConns", ":", "100", ",", "IdleConnTimeout", ":", "90", "*", "time", ".", "Second", ",", "TLSHandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "ExpectContinueTimeout", ":", "1", "*", "time", ".", "Second", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// newHTTPClient returns a new HTTP client that trusts the custom delcared rootCA cert.
[ "newHTTPClient", "returns", "a", "new", "HTTP", "client", "that", "trusts", "the", "custom", "delcared", "rootCA", "cert", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/github/github.go#L209-L234
164,713
dexidp/dex
connector/github/github.go
getGroups
func (c *githubConnector) getGroups(ctx context.Context, client *http.Client, groupScope bool, userLogin string) ([]string, error) { if len(c.orgs) > 0 { return c.groupsForOrgs(ctx, client, userLogin) } else if c.org != "" { return c.teamsForOrg(ctx, client, c.org) } else if groupScope && c.loadAllGroups { return c.userGroups(ctx, client) } return nil, nil }
go
func (c *githubConnector) getGroups(ctx context.Context, client *http.Client, groupScope bool, userLogin string) ([]string, error) { if len(c.orgs) > 0 { return c.groupsForOrgs(ctx, client, userLogin) } else if c.org != "" { return c.teamsForOrg(ctx, client, c.org) } else if groupScope && c.loadAllGroups { return c.userGroups(ctx, client) } return nil, nil }
[ "func", "(", "c", "*", "githubConnector", ")", "getGroups", "(", "ctx", "context", ".", "Context", ",", "client", "*", "http", ".", "Client", ",", "groupScope", "bool", ",", "userLogin", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "if", "len", "(", "c", ".", "orgs", ")", ">", "0", "{", "return", "c", ".", "groupsForOrgs", "(", "ctx", ",", "client", ",", "userLogin", ")", "\n", "}", "else", "if", "c", ".", "org", "!=", "\"", "\"", "{", "return", "c", ".", "teamsForOrg", "(", "ctx", ",", "client", ",", "c", ".", "org", ")", "\n", "}", "else", "if", "groupScope", "&&", "c", ".", "loadAllGroups", "{", "return", "c", ".", "userGroups", "(", "ctx", ",", "client", ")", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// getGroups retrieves GitHub orgs and teams a user is in, if any.
[ "getGroups", "retrieves", "GitHub", "orgs", "and", "teams", "a", "user", "is", "in", "if", "any", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/github/github.go#L334-L343
164,714
dexidp/dex
connector/github/github.go
formatTeamName
func formatTeamName(org string, team string) string { return fmt.Sprintf("%s:%s", org, team) }
go
func formatTeamName(org string, team string) string { return fmt.Sprintf("%s:%s", org, team) }
[ "func", "formatTeamName", "(", "org", "string", ",", "team", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "org", ",", "team", ")", "\n", "}" ]
// formatTeamName returns unique team name. // Orgs might have the same team names. To make team name unique it should be prefixed with the org name.
[ "formatTeamName", "returns", "unique", "team", "name", ".", "Orgs", "might", "have", "the", "same", "team", "names", ".", "To", "make", "team", "name", "unique", "it", "should", "be", "prefixed", "with", "the", "org", "name", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/github/github.go#L347-L349
164,715
dexidp/dex
connector/github/github.go
userOrgs
func (c *githubConnector) userOrgs(ctx context.Context, client *http.Client) ([]string, error) { groups := make([]string, 0) apiURL := c.apiURL + "/user/orgs" for { // https://developer.github.com/v3/orgs/#list-your-organizations var ( orgs []org err error ) if apiURL, err = get(ctx, client, apiURL, &orgs); err != nil { return nil, fmt.Errorf("github: get orgs: %v", err) } for _, o := range orgs { groups = append(groups, o.Login) } if apiURL == "" { break } } return groups, nil }
go
func (c *githubConnector) userOrgs(ctx context.Context, client *http.Client) ([]string, error) { groups := make([]string, 0) apiURL := c.apiURL + "/user/orgs" for { // https://developer.github.com/v3/orgs/#list-your-organizations var ( orgs []org err error ) if apiURL, err = get(ctx, client, apiURL, &orgs); err != nil { return nil, fmt.Errorf("github: get orgs: %v", err) } for _, o := range orgs { groups = append(groups, o.Login) } if apiURL == "" { break } } return groups, nil }
[ "func", "(", "c", "*", "githubConnector", ")", "userOrgs", "(", "ctx", "context", ".", "Context", ",", "client", "*", "http", ".", "Client", ")", "(", "[", "]", "string", ",", "error", ")", "{", "groups", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "apiURL", ":=", "c", ".", "apiURL", "+", "\"", "\"", "\n", "for", "{", "// https://developer.github.com/v3/orgs/#list-your-organizations", "var", "(", "orgs", "[", "]", "org", "\n", "err", "error", "\n", ")", "\n", "if", "apiURL", ",", "err", "=", "get", "(", "ctx", ",", "client", ",", "apiURL", ",", "&", "orgs", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "orgs", "{", "groups", "=", "append", "(", "groups", ",", "o", ".", "Login", ")", "\n", "}", "\n\n", "if", "apiURL", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "groups", ",", "nil", "\n", "}" ]
// userOrgs retrieves list of current user orgs
[ "userOrgs", "retrieves", "list", "of", "current", "user", "orgs" ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/github/github.go#L417-L440
164,716
dexidp/dex
connector/github/github.go
userOrgTeams
func (c *githubConnector) userOrgTeams(ctx context.Context, client *http.Client) (map[string][]string, error) { groups := make(map[string][]string, 0) apiURL := c.apiURL + "/user/teams" for { // https://developer.github.com/v3/orgs/teams/#list-user-teams var ( teams []team err error ) if apiURL, err = get(ctx, client, apiURL, &teams); err != nil { return nil, fmt.Errorf("github: get teams: %v", err) } for _, t := range teams { groups[t.Org.Login] = append(groups[t.Org.Login], c.teamGroupClaims(t)...) } if apiURL == "" { break } } return groups, nil }
go
func (c *githubConnector) userOrgTeams(ctx context.Context, client *http.Client) (map[string][]string, error) { groups := make(map[string][]string, 0) apiURL := c.apiURL + "/user/teams" for { // https://developer.github.com/v3/orgs/teams/#list-user-teams var ( teams []team err error ) if apiURL, err = get(ctx, client, apiURL, &teams); err != nil { return nil, fmt.Errorf("github: get teams: %v", err) } for _, t := range teams { groups[t.Org.Login] = append(groups[t.Org.Login], c.teamGroupClaims(t)...) } if apiURL == "" { break } } return groups, nil }
[ "func", "(", "c", "*", "githubConnector", ")", "userOrgTeams", "(", "ctx", "context", ".", "Context", ",", "client", "*", "http", ".", "Client", ")", "(", "map", "[", "string", "]", "[", "]", "string", ",", "error", ")", "{", "groups", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ",", "0", ")", "\n", "apiURL", ":=", "c", ".", "apiURL", "+", "\"", "\"", "\n", "for", "{", "// https://developer.github.com/v3/orgs/teams/#list-user-teams", "var", "(", "teams", "[", "]", "team", "\n", "err", "error", "\n", ")", "\n", "if", "apiURL", ",", "err", "=", "get", "(", "ctx", ",", "client", ",", "apiURL", ",", "&", "teams", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "for", "_", ",", "t", ":=", "range", "teams", "{", "groups", "[", "t", ".", "Org", ".", "Login", "]", "=", "append", "(", "groups", "[", "t", ".", "Org", ".", "Login", "]", ",", "c", ".", "teamGroupClaims", "(", "t", ")", "...", ")", "\n", "}", "\n\n", "if", "apiURL", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "groups", ",", "nil", "\n", "}" ]
// userOrgTeams retrieves teams which current user belongs to. // Method returns a map where key is an org name and value list of teams under the org.
[ "userOrgTeams", "retrieves", "teams", "which", "current", "user", "belongs", "to", ".", "Method", "returns", "a", "map", "where", "key", "is", "an", "org", "name", "and", "value", "list", "of", "teams", "under", "the", "org", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/github/github.go#L444-L467
164,717
dexidp/dex
connector/github/github.go
filterTeams
func filterTeams(userTeams, configTeams []string) (teams []string) { teamFilter := make(map[string]struct{}) for _, team := range configTeams { if _, ok := teamFilter[team]; !ok { teamFilter[team] = struct{}{} } } for _, team := range userTeams { if _, ok := teamFilter[team]; ok { teams = append(teams, team) } } return }
go
func filterTeams(userTeams, configTeams []string) (teams []string) { teamFilter := make(map[string]struct{}) for _, team := range configTeams { if _, ok := teamFilter[team]; !ok { teamFilter[team] = struct{}{} } } for _, team := range userTeams { if _, ok := teamFilter[team]; ok { teams = append(teams, team) } } return }
[ "func", "filterTeams", "(", "userTeams", ",", "configTeams", "[", "]", "string", ")", "(", "teams", "[", "]", "string", ")", "{", "teamFilter", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "team", ":=", "range", "configTeams", "{", "if", "_", ",", "ok", ":=", "teamFilter", "[", "team", "]", ";", "!", "ok", "{", "teamFilter", "[", "team", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "team", ":=", "range", "userTeams", "{", "if", "_", ",", "ok", ":=", "teamFilter", "[", "team", "]", ";", "ok", "{", "teams", "=", "append", "(", "teams", ",", "team", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Filter the users' team memberships by 'teams' from config.
[ "Filter", "the", "users", "team", "memberships", "by", "teams", "from", "config", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/github/github.go#L470-L483
164,718
dexidp/dex
connector/ldap/ldap.go
Open
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { conn, err := c.OpenConnector(logger) if err != nil { return nil, err } return connector.Connector(conn), nil }
go
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { conn, err := c.OpenConnector(logger) if err != nil { return nil, err } return connector.Connector(conn), nil }
[ "func", "(", "c", "*", "Config", ")", "Open", "(", "id", "string", ",", "logger", "log", ".", "Logger", ")", "(", "connector", ".", "Connector", ",", "error", ")", "{", "conn", ",", "err", ":=", "c", ".", "OpenConnector", "(", "logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "connector", ".", "Connector", "(", "conn", ")", ",", "nil", "\n", "}" ]
// Open returns an authentication strategy using LDAP.
[ "Open", "returns", "an", "authentication", "strategy", "using", "LDAP", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/ldap/ldap.go#L167-L173
164,719
dexidp/dex
connector/ldap/ldap.go
OpenConnector
func (c *Config) OpenConnector(logger log.Logger) (interface { connector.Connector connector.PasswordConnector connector.RefreshConnector }, error) { return c.openConnector(logger) }
go
func (c *Config) OpenConnector(logger log.Logger) (interface { connector.Connector connector.PasswordConnector connector.RefreshConnector }, error) { return c.openConnector(logger) }
[ "func", "(", "c", "*", "Config", ")", "OpenConnector", "(", "logger", "log", ".", "Logger", ")", "(", "interface", "{", "connector", ".", "Connector", "\n", "connector", ".", "PasswordConnector", "\n", "connector", ".", "RefreshConnector", "\n", "}", ",", "error", ")", "{", "return", "c", ".", "openConnector", "(", "logger", ")", "\n", "}" ]
// OpenConnector is the same as Open but returns a type with all implemented connector interfaces.
[ "OpenConnector", "is", "the", "same", "as", "Open", "but", "returns", "a", "type", "with", "all", "implemented", "connector", "interfaces", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/ldap/ldap.go#L181-L187
164,720
dexidp/dex
connector/ldap/ldap.go
do
func (c *ldapConnector) do(ctx context.Context, f func(c *ldap.Conn) error) error { // TODO(ericchiang): support context here var ( conn *ldap.Conn err error ) switch { case c.InsecureNoSSL: conn, err = ldap.Dial("tcp", c.Host) case c.StartTLS: conn, err = ldap.Dial("tcp", c.Host) if err != nil { return fmt.Errorf("failed to connect: %v", err) } if err := conn.StartTLS(c.tlsConfig); err != nil { return fmt.Errorf("start TLS failed: %v", err) } default: conn, err = ldap.DialTLS("tcp", c.Host, c.tlsConfig) } if err != nil { return fmt.Errorf("failed to connect: %v", err) } defer conn.Close() // If bindDN and bindPW are empty this will default to an anonymous bind. if err := conn.Bind(c.BindDN, c.BindPW); err != nil { if c.BindDN == "" && c.BindPW == "" { return fmt.Errorf("ldap: initial anonymous bind failed: %v", err) } return fmt.Errorf("ldap: initial bind for user %q failed: %v", c.BindDN, err) } return f(conn) }
go
func (c *ldapConnector) do(ctx context.Context, f func(c *ldap.Conn) error) error { // TODO(ericchiang): support context here var ( conn *ldap.Conn err error ) switch { case c.InsecureNoSSL: conn, err = ldap.Dial("tcp", c.Host) case c.StartTLS: conn, err = ldap.Dial("tcp", c.Host) if err != nil { return fmt.Errorf("failed to connect: %v", err) } if err := conn.StartTLS(c.tlsConfig); err != nil { return fmt.Errorf("start TLS failed: %v", err) } default: conn, err = ldap.DialTLS("tcp", c.Host, c.tlsConfig) } if err != nil { return fmt.Errorf("failed to connect: %v", err) } defer conn.Close() // If bindDN and bindPW are empty this will default to an anonymous bind. if err := conn.Bind(c.BindDN, c.BindPW); err != nil { if c.BindDN == "" && c.BindPW == "" { return fmt.Errorf("ldap: initial anonymous bind failed: %v", err) } return fmt.Errorf("ldap: initial bind for user %q failed: %v", c.BindDN, err) } return f(conn) }
[ "func", "(", "c", "*", "ldapConnector", ")", "do", "(", "ctx", "context", ".", "Context", ",", "f", "func", "(", "c", "*", "ldap", ".", "Conn", ")", "error", ")", "error", "{", "// TODO(ericchiang): support context here", "var", "(", "conn", "*", "ldap", ".", "Conn", "\n", "err", "error", "\n", ")", "\n", "switch", "{", "case", "c", ".", "InsecureNoSSL", ":", "conn", ",", "err", "=", "ldap", ".", "Dial", "(", "\"", "\"", ",", "c", ".", "Host", ")", "\n", "case", "c", ".", "StartTLS", ":", "conn", ",", "err", "=", "ldap", ".", "Dial", "(", "\"", "\"", ",", "c", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "conn", ".", "StartTLS", "(", "c", ".", "tlsConfig", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "default", ":", "conn", ",", "err", "=", "ldap", ".", "DialTLS", "(", "\"", "\"", ",", "c", ".", "Host", ",", "c", ".", "tlsConfig", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "conn", ".", "Close", "(", ")", "\n\n", "// If bindDN and bindPW are empty this will default to an anonymous bind.", "if", "err", ":=", "conn", ".", "Bind", "(", "c", ".", "BindDN", ",", "c", ".", "BindPW", ")", ";", "err", "!=", "nil", "{", "if", "c", ".", "BindDN", "==", "\"", "\"", "&&", "c", ".", "BindPW", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "BindDN", ",", "err", ")", "\n", "}", "\n\n", "return", "f", "(", "conn", ")", "\n", "}" ]
// do initializes a connection to the LDAP directory and passes it to the // provided function. It then performs appropriate teardown or reuse before // returning.
[ "do", "initializes", "a", "connection", "to", "the", "LDAP", "directory", "and", "passes", "it", "to", "the", "provided", "function", ".", "It", "then", "performs", "appropriate", "teardown", "or", "reuse", "before", "returning", "." ]
60f47c4228b7719889eee4ca6c4c6cc60834d910
https://github.com/dexidp/dex/blob/60f47c4228b7719889eee4ca6c4c6cc60834d910/connector/ldap/ldap.go#L272-L306
164,721
sjwhitworth/golearn
evaluation/cross_fold.go
GetCrossValidatedMetric
func GetCrossValidatedMetric(in []ConfusionMatrix, metric func(ConfusionMatrix) float64) (mean, variance float64) { scores := make([]float64, len(in)) for i, c := range in { scores[i] = metric(c) } // Compute mean, variance sum := 0.0 for _, s := range scores { sum += s } sum /= float64(len(scores)) mean = sum sum = 0.0 for _, s := range scores { sum += (s - mean) * (s - mean) } sum /= float64(len(scores)) variance = sum return mean, variance }
go
func GetCrossValidatedMetric(in []ConfusionMatrix, metric func(ConfusionMatrix) float64) (mean, variance float64) { scores := make([]float64, len(in)) for i, c := range in { scores[i] = metric(c) } // Compute mean, variance sum := 0.0 for _, s := range scores { sum += s } sum /= float64(len(scores)) mean = sum sum = 0.0 for _, s := range scores { sum += (s - mean) * (s - mean) } sum /= float64(len(scores)) variance = sum return mean, variance }
[ "func", "GetCrossValidatedMetric", "(", "in", "[", "]", "ConfusionMatrix", ",", "metric", "func", "(", "ConfusionMatrix", ")", "float64", ")", "(", "mean", ",", "variance", "float64", ")", "{", "scores", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "in", ")", ")", "\n", "for", "i", ",", "c", ":=", "range", "in", "{", "scores", "[", "i", "]", "=", "metric", "(", "c", ")", "\n", "}", "\n\n", "// Compute mean, variance", "sum", ":=", "0.0", "\n", "for", "_", ",", "s", ":=", "range", "scores", "{", "sum", "+=", "s", "\n", "}", "\n", "sum", "/=", "float64", "(", "len", "(", "scores", ")", ")", "\n", "mean", "=", "sum", "\n", "sum", "=", "0.0", "\n", "for", "_", ",", "s", ":=", "range", "scores", "{", "sum", "+=", "(", "s", "-", "mean", ")", "*", "(", "s", "-", "mean", ")", "\n", "}", "\n", "sum", "/=", "float64", "(", "len", "(", "scores", ")", ")", "\n", "variance", "=", "sum", "\n", "return", "mean", ",", "variance", "\n", "}" ]
// GetCrossValidatedMetric returns the mean and variance of the confusion-matrix-derived // metric across all folds.
[ "GetCrossValidatedMetric", "returns", "the", "mean", "and", "variance", "of", "the", "confusion", "-", "matrix", "-", "derived", "metric", "across", "all", "folds", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/cross_fold.go#L10-L30
164,722
sjwhitworth/golearn
evaluation/cross_fold.go
GenerateCrossFoldValidationConfusionMatrices
func GenerateCrossFoldValidationConfusionMatrices(data base.FixedDataGrid, cls base.Classifier, folds int) ([]ConfusionMatrix, error) { _, rows := data.Size() // Assign each row to a fold foldMap := make([]int, rows) inverseFoldMap := make(map[int][]int) for i := 0; i < rows; i++ { fold := rand.Intn(folds) foldMap[i] = fold if _, ok := inverseFoldMap[fold]; !ok { inverseFoldMap[fold] = make([]int, 0) } inverseFoldMap[fold] = append(inverseFoldMap[fold], i) } ret := make([]ConfusionMatrix, folds) // Create training/test views for each fold for i := 0; i < folds; i++ { // Fold i is for testing testData := base.NewInstancesViewFromVisible(data, inverseFoldMap[i], data.AllAttributes()) otherRows := make([]int, 0) for j := 0; j < folds; j++ { if i == j { continue } otherRows = append(otherRows, inverseFoldMap[j]...) } trainData := base.NewInstancesViewFromVisible(data, otherRows, data.AllAttributes()) // Train err := cls.Fit(trainData) if err != nil { return nil, err } // Predict pred, err := cls.Predict(testData) if err != nil { return nil, err } // Evaluate cf, err := GetConfusionMatrix(testData, pred) if err != nil { return nil, err } ret[i] = cf } return ret, nil }
go
func GenerateCrossFoldValidationConfusionMatrices(data base.FixedDataGrid, cls base.Classifier, folds int) ([]ConfusionMatrix, error) { _, rows := data.Size() // Assign each row to a fold foldMap := make([]int, rows) inverseFoldMap := make(map[int][]int) for i := 0; i < rows; i++ { fold := rand.Intn(folds) foldMap[i] = fold if _, ok := inverseFoldMap[fold]; !ok { inverseFoldMap[fold] = make([]int, 0) } inverseFoldMap[fold] = append(inverseFoldMap[fold], i) } ret := make([]ConfusionMatrix, folds) // Create training/test views for each fold for i := 0; i < folds; i++ { // Fold i is for testing testData := base.NewInstancesViewFromVisible(data, inverseFoldMap[i], data.AllAttributes()) otherRows := make([]int, 0) for j := 0; j < folds; j++ { if i == j { continue } otherRows = append(otherRows, inverseFoldMap[j]...) } trainData := base.NewInstancesViewFromVisible(data, otherRows, data.AllAttributes()) // Train err := cls.Fit(trainData) if err != nil { return nil, err } // Predict pred, err := cls.Predict(testData) if err != nil { return nil, err } // Evaluate cf, err := GetConfusionMatrix(testData, pred) if err != nil { return nil, err } ret[i] = cf } return ret, nil }
[ "func", "GenerateCrossFoldValidationConfusionMatrices", "(", "data", "base", ".", "FixedDataGrid", ",", "cls", "base", ".", "Classifier", ",", "folds", "int", ")", "(", "[", "]", "ConfusionMatrix", ",", "error", ")", "{", "_", ",", "rows", ":=", "data", ".", "Size", "(", ")", "\n\n", "// Assign each row to a fold", "foldMap", ":=", "make", "(", "[", "]", "int", ",", "rows", ")", "\n", "inverseFoldMap", ":=", "make", "(", "map", "[", "int", "]", "[", "]", "int", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "rows", ";", "i", "++", "{", "fold", ":=", "rand", ".", "Intn", "(", "folds", ")", "\n", "foldMap", "[", "i", "]", "=", "fold", "\n", "if", "_", ",", "ok", ":=", "inverseFoldMap", "[", "fold", "]", ";", "!", "ok", "{", "inverseFoldMap", "[", "fold", "]", "=", "make", "(", "[", "]", "int", ",", "0", ")", "\n", "}", "\n", "inverseFoldMap", "[", "fold", "]", "=", "append", "(", "inverseFoldMap", "[", "fold", "]", ",", "i", ")", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "ConfusionMatrix", ",", "folds", ")", "\n\n", "// Create training/test views for each fold", "for", "i", ":=", "0", ";", "i", "<", "folds", ";", "i", "++", "{", "// Fold i is for testing", "testData", ":=", "base", ".", "NewInstancesViewFromVisible", "(", "data", ",", "inverseFoldMap", "[", "i", "]", ",", "data", ".", "AllAttributes", "(", ")", ")", "\n", "otherRows", ":=", "make", "(", "[", "]", "int", ",", "0", ")", "\n", "for", "j", ":=", "0", ";", "j", "<", "folds", ";", "j", "++", "{", "if", "i", "==", "j", "{", "continue", "\n", "}", "\n", "otherRows", "=", "append", "(", "otherRows", ",", "inverseFoldMap", "[", "j", "]", "...", ")", "\n", "}", "\n", "trainData", ":=", "base", ".", "NewInstancesViewFromVisible", "(", "data", ",", "otherRows", ",", "data", ".", "AllAttributes", "(", ")", ")", "\n", "// Train", "err", ":=", "cls", ".", "Fit", "(", "trainData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Predict", "pred", ",", "err", ":=", "cls", ".", "Predict", "(", "testData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Evaluate", "cf", ",", "err", ":=", "GetConfusionMatrix", "(", "testData", ",", "pred", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ret", "[", "i", "]", "=", "cf", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// GenerateCrossFoldValidationConfusionMatrices divides the data into a number of folds // then trains and evaluates the classifier on each fold, producing a new ConfusionMatrix.
[ "GenerateCrossFoldValidationConfusionMatrices", "divides", "the", "data", "into", "a", "number", "of", "folds", "then", "trains", "and", "evaluates", "the", "classifier", "on", "each", "fold", "producing", "a", "new", "ConfusionMatrix", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/evaluation/cross_fold.go#L34-L81
164,723
sjwhitworth/golearn
base/bag.go
Attributes
func (b *BinaryAttributeGroup) Attributes() []Attribute { ret := make([]Attribute, len(b.attributes)) for i, a := range b.attributes { ret[i] = a } return ret }
go
func (b *BinaryAttributeGroup) Attributes() []Attribute { ret := make([]Attribute, len(b.attributes)) for i, a := range b.attributes { ret[i] = a } return ret }
[ "func", "(", "b", "*", "BinaryAttributeGroup", ")", "Attributes", "(", ")", "[", "]", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "len", "(", "b", ".", "attributes", ")", ")", "\n", "for", "i", ",", "a", ":=", "range", "b", ".", "attributes", "{", "ret", "[", "i", "]", "=", "a", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Attributes returns a slice of Attributes in this BinaryAttributeGroup.
[ "Attributes", "returns", "a", "slice", "of", "Attributes", "in", "this", "BinaryAttributeGroup", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/bag.go#L30-L36
164,724
sjwhitworth/golearn
base/bag.go
AddAttribute
func (b *BinaryAttributeGroup) AddAttribute(a Attribute) error { b.attributes = append(b.attributes, a) return nil }
go
func (b *BinaryAttributeGroup) AddAttribute(a Attribute) error { b.attributes = append(b.attributes, a) return nil }
[ "func", "(", "b", "*", "BinaryAttributeGroup", ")", "AddAttribute", "(", "a", "Attribute", ")", "error", "{", "b", ".", "attributes", "=", "append", "(", "b", ".", "attributes", ",", "a", ")", "\n", "return", "nil", "\n", "}" ]
// AddAttribute adds an Attribute to this BinaryAttributeGroup
[ "AddAttribute", "adds", "an", "Attribute", "to", "this", "BinaryAttributeGroup" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/bag.go#L39-L42
164,725
sjwhitworth/golearn
ensemble/randomforest.go
NewRandomForest
func NewRandomForest(forestSize int, features int) *RandomForest { ret := &RandomForest{ base.BaseClassifier{}, forestSize, features, nil, } return ret }
go
func NewRandomForest(forestSize int, features int) *RandomForest { ret := &RandomForest{ base.BaseClassifier{}, forestSize, features, nil, } return ret }
[ "func", "NewRandomForest", "(", "forestSize", "int", ",", "features", "int", ")", "*", "RandomForest", "{", "ret", ":=", "&", "RandomForest", "{", "base", ".", "BaseClassifier", "{", "}", ",", "forestSize", ",", "features", ",", "nil", ",", "}", "\n", "return", "ret", "\n", "}" ]
// NewRandomForest generates and return a new random forests // forestSize controls the number of trees that get built // features controls the number of features used to build each tree.
[ "NewRandomForest", "generates", "and", "return", "a", "new", "random", "forests", "forestSize", "controls", "the", "number", "of", "trees", "that", "get", "built", "features", "controls", "the", "number", "of", "features", "used", "to", "build", "each", "tree", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/ensemble/randomforest.go#L23-L31
164,726
sjwhitworth/golearn
ensemble/randomforest.go
Fit
func (f *RandomForest) Fit(on base.FixedDataGrid) error { numNonClassAttributes := len(base.NonClassAttributes(on)) if numNonClassAttributes < f.Features { return errors.New(fmt.Sprintf( "Random forest with %d features cannot fit data grid with %d non-class attributes", f.Features, numNonClassAttributes, )) } f.Model = new(meta.BaggedModel) f.Model.RandomFeatures = f.Features for i := 0; i < f.ForestSize; i++ { tree := trees.NewID3DecisionTree(0.00) f.Model.AddModel(tree) } f.Model.Fit(on) return nil }
go
func (f *RandomForest) Fit(on base.FixedDataGrid) error { numNonClassAttributes := len(base.NonClassAttributes(on)) if numNonClassAttributes < f.Features { return errors.New(fmt.Sprintf( "Random forest with %d features cannot fit data grid with %d non-class attributes", f.Features, numNonClassAttributes, )) } f.Model = new(meta.BaggedModel) f.Model.RandomFeatures = f.Features for i := 0; i < f.ForestSize; i++ { tree := trees.NewID3DecisionTree(0.00) f.Model.AddModel(tree) } f.Model.Fit(on) return nil }
[ "func", "(", "f", "*", "RandomForest", ")", "Fit", "(", "on", "base", ".", "FixedDataGrid", ")", "error", "{", "numNonClassAttributes", ":=", "len", "(", "base", ".", "NonClassAttributes", "(", "on", ")", ")", "\n", "if", "numNonClassAttributes", "<", "f", ".", "Features", "{", "return", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Features", ",", "numNonClassAttributes", ",", ")", ")", "\n", "}", "\n\n", "f", ".", "Model", "=", "new", "(", "meta", ".", "BaggedModel", ")", "\n", "f", ".", "Model", ".", "RandomFeatures", "=", "f", ".", "Features", "\n", "for", "i", ":=", "0", ";", "i", "<", "f", ".", "ForestSize", ";", "i", "++", "{", "tree", ":=", "trees", ".", "NewID3DecisionTree", "(", "0.00", ")", "\n", "f", ".", "Model", ".", "AddModel", "(", "tree", ")", "\n", "}", "\n", "f", ".", "Model", ".", "Fit", "(", "on", ")", "\n", "return", "nil", "\n", "}" ]
// Fit builds the RandomForest on the specified instances
[ "Fit", "builds", "the", "RandomForest", "on", "the", "specified", "instances" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/ensemble/randomforest.go#L34-L52
164,727
sjwhitworth/golearn
ensemble/randomforest.go
Predict
func (f *RandomForest) Predict(with base.FixedDataGrid) (base.FixedDataGrid, error) { return f.Model.Predict(with) }
go
func (f *RandomForest) Predict(with base.FixedDataGrid) (base.FixedDataGrid, error) { return f.Model.Predict(with) }
[ "func", "(", "f", "*", "RandomForest", ")", "Predict", "(", "with", "base", ".", "FixedDataGrid", ")", "(", "base", ".", "FixedDataGrid", ",", "error", ")", "{", "return", "f", ".", "Model", ".", "Predict", "(", "with", ")", "\n", "}" ]
// Predict generates predictions from a trained RandomForest.
[ "Predict", "generates", "predictions", "from", "a", "trained", "RandomForest", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/ensemble/randomforest.go#L55-L57
164,728
sjwhitworth/golearn
ensemble/randomforest.go
String
func (f *RandomForest) String() string { return fmt.Sprintf("RandomForest(ForestSize: %d, Features:%d, %s\n)", f.ForestSize, f.Features, f.Model) }
go
func (f *RandomForest) String() string { return fmt.Sprintf("RandomForest(ForestSize: %d, Features:%d, %s\n)", f.ForestSize, f.Features, f.Model) }
[ "func", "(", "f", "*", "RandomForest", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "f", ".", "ForestSize", ",", "f", ".", "Features", ",", "f", ".", "Model", ")", "\n", "}" ]
// String returns a human-readable representation of this tree.
[ "String", "returns", "a", "human", "-", "readable", "representation", "of", "this", "tree", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/ensemble/randomforest.go#L60-L62
164,729
sjwhitworth/golearn
base/util_instances.go
GeneratePredictionVector
func GeneratePredictionVector(from FixedDataGrid) UpdatableDataGrid { classAttrs := from.AllClassAttributes() _, rowCount := from.Size() ret := NewDenseInstances() for _, a := range classAttrs { ret.AddAttribute(a) ret.AddClassAttribute(a) } ret.Extend(rowCount) return ret }
go
func GeneratePredictionVector(from FixedDataGrid) UpdatableDataGrid { classAttrs := from.AllClassAttributes() _, rowCount := from.Size() ret := NewDenseInstances() for _, a := range classAttrs { ret.AddAttribute(a) ret.AddClassAttribute(a) } ret.Extend(rowCount) return ret }
[ "func", "GeneratePredictionVector", "(", "from", "FixedDataGrid", ")", "UpdatableDataGrid", "{", "classAttrs", ":=", "from", ".", "AllClassAttributes", "(", ")", "\n", "_", ",", "rowCount", ":=", "from", ".", "Size", "(", ")", "\n", "ret", ":=", "NewDenseInstances", "(", ")", "\n", "for", "_", ",", "a", ":=", "range", "classAttrs", "{", "ret", ".", "AddAttribute", "(", "a", ")", "\n", "ret", ".", "AddClassAttribute", "(", "a", ")", "\n", "}", "\n", "ret", ".", "Extend", "(", "rowCount", ")", "\n", "return", "ret", "\n", "}" ]
// This file contains utility functions relating to efficiently // generating predictions and instantiating DataGrid implementations. // GeneratePredictionVector selects the class Attributes from a given // FixedDataGrid and returns something which can hold the predictions.
[ "This", "file", "contains", "utility", "functions", "relating", "to", "efficiently", "generating", "predictions", "and", "instantiating", "DataGrid", "implementations", ".", "GeneratePredictionVector", "selects", "the", "class", "Attributes", "from", "a", "given", "FixedDataGrid", "and", "returns", "something", "which", "can", "hold", "the", "predictions", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L13-L23
164,730
sjwhitworth/golearn
base/util_instances.go
GetAttributeByName
func GetAttributeByName(inst FixedDataGrid, name string) Attribute { for _, a := range inst.AllAttributes() { if a.GetName() == name { return a } } return nil }
go
func GetAttributeByName(inst FixedDataGrid, name string) Attribute { for _, a := range inst.AllAttributes() { if a.GetName() == name { return a } } return nil }
[ "func", "GetAttributeByName", "(", "inst", "FixedDataGrid", ",", "name", "string", ")", "Attribute", "{", "for", "_", ",", "a", ":=", "range", "inst", ".", "AllAttributes", "(", ")", "{", "if", "a", ".", "GetName", "(", ")", "==", "name", "{", "return", "a", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetAttributeByName returns an Attribute matching a given name. // Returns nil if one doesn't exist.
[ "GetAttributeByName", "returns", "an", "Attribute", "matching", "a", "given", "name", ".", "Returns", "nil", "if", "one", "doesn", "t", "exist", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L114-L121
164,731
sjwhitworth/golearn
base/util_instances.go
GetClassDistributionByBinaryFloatValue
func GetClassDistributionByBinaryFloatValue(inst FixedDataGrid) []int { // Get the class variable attrs := inst.AllClassAttributes() if len(attrs) != 1 { panic(fmt.Errorf("Wrong number of class variables (has %d, should be 1)", len(attrs))) } if _, ok := attrs[0].(*FloatAttribute); !ok { panic(fmt.Errorf("Class Attribute must be FloatAttribute (is %s)", attrs[0])) } // Get the number of class values ret := make([]int, 2) // Map through everything specs := ResolveAttributes(inst, attrs) inst.MapOverRows(specs, func(vals [][]byte, row int) (bool, error) { index := UnpackBytesToFloat(vals[0]) if index > 0.5 { ret[1]++ } else { ret[0]++ } return false, nil }) return ret }
go
func GetClassDistributionByBinaryFloatValue(inst FixedDataGrid) []int { // Get the class variable attrs := inst.AllClassAttributes() if len(attrs) != 1 { panic(fmt.Errorf("Wrong number of class variables (has %d, should be 1)", len(attrs))) } if _, ok := attrs[0].(*FloatAttribute); !ok { panic(fmt.Errorf("Class Attribute must be FloatAttribute (is %s)", attrs[0])) } // Get the number of class values ret := make([]int, 2) // Map through everything specs := ResolveAttributes(inst, attrs) inst.MapOverRows(specs, func(vals [][]byte, row int) (bool, error) { index := UnpackBytesToFloat(vals[0]) if index > 0.5 { ret[1]++ } else { ret[0]++ } return false, nil }) return ret }
[ "func", "GetClassDistributionByBinaryFloatValue", "(", "inst", "FixedDataGrid", ")", "[", "]", "int", "{", "// Get the class variable", "attrs", ":=", "inst", ".", "AllClassAttributes", "(", ")", "\n", "if", "len", "(", "attrs", ")", "!=", "1", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "attrs", ")", ")", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "attrs", "[", "0", "]", ".", "(", "*", "FloatAttribute", ")", ";", "!", "ok", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "attrs", "[", "0", "]", ")", ")", "\n", "}", "\n\n", "// Get the number of class values", "ret", ":=", "make", "(", "[", "]", "int", ",", "2", ")", "\n\n", "// Map through everything", "specs", ":=", "ResolveAttributes", "(", "inst", ",", "attrs", ")", "\n", "inst", ".", "MapOverRows", "(", "specs", ",", "func", "(", "vals", "[", "]", "[", "]", "byte", ",", "row", "int", ")", "(", "bool", ",", "error", ")", "{", "index", ":=", "UnpackBytesToFloat", "(", "vals", "[", "0", "]", ")", "\n", "if", "index", ">", "0.5", "{", "ret", "[", "1", "]", "++", "\n", "}", "else", "{", "ret", "[", "0", "]", "++", "\n", "}", "\n\n", "return", "false", ",", "nil", "\n", "}", ")", "\n\n", "return", "ret", "\n", "}" ]
// GetClassDistributionByBinaryFloatValue returns the count of each row // which has a float value close to 0.0 or 1.0.
[ "GetClassDistributionByBinaryFloatValue", "returns", "the", "count", "of", "each", "row", "which", "has", "a", "float", "value", "close", "to", "0", ".", "0", "or", "1", ".", "0", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L125-L153
164,732
sjwhitworth/golearn
base/util_instances.go
GetClassDistributionAfterThreshold
func GetClassDistributionAfterThreshold(inst FixedDataGrid, at Attribute, val float64) map[string]map[string]int { ret := make(map[string]map[string]int) // Find the attribute we're decomposing on attrSpec, err := inst.GetAttribute(at) if err != nil { panic(fmt.Sprintf("Invalid attribute %s (%s)", at, err)) } // Validate if _, ok := at.(*FloatAttribute); !ok { panic(fmt.Sprintf("Must be numeric!")) } _, rows := inst.Size() for i := 0; i < rows; i++ { splitVal := UnpackBytesToFloat(inst.Get(attrSpec, i)) > val splitVar := "0" if splitVal { splitVar = "1" } classVar := GetClass(inst, i) if _, ok := ret[splitVar]; !ok { ret[splitVar] = make(map[string]int) i-- continue } ret[splitVar][classVar]++ } return ret }
go
func GetClassDistributionAfterThreshold(inst FixedDataGrid, at Attribute, val float64) map[string]map[string]int { ret := make(map[string]map[string]int) // Find the attribute we're decomposing on attrSpec, err := inst.GetAttribute(at) if err != nil { panic(fmt.Sprintf("Invalid attribute %s (%s)", at, err)) } // Validate if _, ok := at.(*FloatAttribute); !ok { panic(fmt.Sprintf("Must be numeric!")) } _, rows := inst.Size() for i := 0; i < rows; i++ { splitVal := UnpackBytesToFloat(inst.Get(attrSpec, i)) > val splitVar := "0" if splitVal { splitVar = "1" } classVar := GetClass(inst, i) if _, ok := ret[splitVar]; !ok { ret[splitVar] = make(map[string]int) i-- continue } ret[splitVar][classVar]++ } return ret }
[ "func", "GetClassDistributionAfterThreshold", "(", "inst", "FixedDataGrid", ",", "at", "Attribute", ",", "val", "float64", ")", "map", "[", "string", "]", "map", "[", "string", "]", "int", "{", "ret", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "int", ")", "\n\n", "// Find the attribute we're decomposing on", "attrSpec", ",", "err", ":=", "inst", ".", "GetAttribute", "(", "at", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "at", ",", "err", ")", ")", "\n", "}", "\n\n", "// Validate", "if", "_", ",", "ok", ":=", "at", ".", "(", "*", "FloatAttribute", ")", ";", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "_", ",", "rows", ":=", "inst", ".", "Size", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "rows", ";", "i", "++", "{", "splitVal", ":=", "UnpackBytesToFloat", "(", "inst", ".", "Get", "(", "attrSpec", ",", "i", ")", ")", ">", "val", "\n", "splitVar", ":=", "\"", "\"", "\n", "if", "splitVal", "{", "splitVar", "=", "\"", "\"", "\n", "}", "\n", "classVar", ":=", "GetClass", "(", "inst", ",", "i", ")", "\n", "if", "_", ",", "ok", ":=", "ret", "[", "splitVar", "]", ";", "!", "ok", "{", "ret", "[", "splitVar", "]", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "i", "--", "\n", "continue", "\n", "}", "\n", "ret", "[", "splitVar", "]", "[", "classVar", "]", "++", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// GetClassDistributionAfterThreshold returns the class distribution // after a speculative split on a given Attribute using a threshold.
[ "GetClassDistributionAfterThreshold", "returns", "the", "class", "distribution", "after", "a", "speculative", "split", "on", "a", "given", "Attribute", "using", "a", "threshold", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L200-L232
164,733
sjwhitworth/golearn
base/util_instances.go
GetClassDistributionAfterSplit
func GetClassDistributionAfterSplit(inst FixedDataGrid, at Attribute) map[string]map[string]int { ret := make(map[string]map[string]int) // Find the attribute we're decomposing on attrSpec, err := inst.GetAttribute(at) if err != nil { panic(fmt.Sprintf("Invalid attribute %s (%s)", at, err)) } _, rows := inst.Size() for i := 0; i < rows; i++ { splitVar := at.GetStringFromSysVal(inst.Get(attrSpec, i)) classVar := GetClass(inst, i) if _, ok := ret[splitVar]; !ok { ret[splitVar] = make(map[string]int) i-- continue } ret[splitVar][classVar]++ } return ret }
go
func GetClassDistributionAfterSplit(inst FixedDataGrid, at Attribute) map[string]map[string]int { ret := make(map[string]map[string]int) // Find the attribute we're decomposing on attrSpec, err := inst.GetAttribute(at) if err != nil { panic(fmt.Sprintf("Invalid attribute %s (%s)", at, err)) } _, rows := inst.Size() for i := 0; i < rows; i++ { splitVar := at.GetStringFromSysVal(inst.Get(attrSpec, i)) classVar := GetClass(inst, i) if _, ok := ret[splitVar]; !ok { ret[splitVar] = make(map[string]int) i-- continue } ret[splitVar][classVar]++ } return ret }
[ "func", "GetClassDistributionAfterSplit", "(", "inst", "FixedDataGrid", ",", "at", "Attribute", ")", "map", "[", "string", "]", "map", "[", "string", "]", "int", "{", "ret", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "int", ")", "\n\n", "// Find the attribute we're decomposing on", "attrSpec", ",", "err", ":=", "inst", ".", "GetAttribute", "(", "at", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "at", ",", "err", ")", ")", "\n", "}", "\n\n", "_", ",", "rows", ":=", "inst", ".", "Size", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "rows", ";", "i", "++", "{", "splitVar", ":=", "at", ".", "GetStringFromSysVal", "(", "inst", ".", "Get", "(", "attrSpec", ",", "i", ")", ")", "\n", "classVar", ":=", "GetClass", "(", "inst", ",", "i", ")", "\n", "if", "_", ",", "ok", ":=", "ret", "[", "splitVar", "]", ";", "!", "ok", "{", "ret", "[", "splitVar", "]", "=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "i", "--", "\n", "continue", "\n", "}", "\n", "ret", "[", "splitVar", "]", "[", "classVar", "]", "++", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// GetClassDistributionAfterSplit returns the class distribution // after a speculative split on a given Attribute.
[ "GetClassDistributionAfterSplit", "returns", "the", "class", "distribution", "after", "a", "speculative", "split", "on", "a", "given", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L236-L260
164,734
sjwhitworth/golearn
base/util_instances.go
LazyShuffle
func LazyShuffle(from FixedDataGrid) FixedDataGrid { _, rows := from.Size() rowMap := make(map[int]int) for i := 0; i < rows; i++ { j := rand.Intn(i + 1) rowMap[i] = j rowMap[j] = i } return NewInstancesViewFromRows(from, rowMap) }
go
func LazyShuffle(from FixedDataGrid) FixedDataGrid { _, rows := from.Size() rowMap := make(map[int]int) for i := 0; i < rows; i++ { j := rand.Intn(i + 1) rowMap[i] = j rowMap[j] = i } return NewInstancesViewFromRows(from, rowMap) }
[ "func", "LazyShuffle", "(", "from", "FixedDataGrid", ")", "FixedDataGrid", "{", "_", ",", "rows", ":=", "from", ".", "Size", "(", ")", "\n", "rowMap", ":=", "make", "(", "map", "[", "int", "]", "int", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "rows", ";", "i", "++", "{", "j", ":=", "rand", ".", "Intn", "(", "i", "+", "1", ")", "\n", "rowMap", "[", "i", "]", "=", "j", "\n", "rowMap", "[", "j", "]", "=", "i", "\n", "}", "\n", "return", "NewInstancesViewFromRows", "(", "from", ",", "rowMap", ")", "\n", "}" ]
// LazyShuffle randomizes the row order without re-ordering the rows // via an InstancesView.
[ "LazyShuffle", "randomizes", "the", "row", "order", "without", "re", "-", "ordering", "the", "rows", "via", "an", "InstancesView", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L400-L409
164,735
sjwhitworth/golearn
base/util_instances.go
CheckCompatible
func CheckCompatible(s1 FixedDataGrid, s2 FixedDataGrid) []Attribute { s1Attrs := s1.AllAttributes() s2Attrs := s2.AllAttributes() interAttrs := AttributeIntersect(s1Attrs, s2Attrs) if len(interAttrs) != len(s1Attrs) { return nil } else if len(interAttrs) != len(s2Attrs) { return nil } return interAttrs }
go
func CheckCompatible(s1 FixedDataGrid, s2 FixedDataGrid) []Attribute { s1Attrs := s1.AllAttributes() s2Attrs := s2.AllAttributes() interAttrs := AttributeIntersect(s1Attrs, s2Attrs) if len(interAttrs) != len(s1Attrs) { return nil } else if len(interAttrs) != len(s2Attrs) { return nil } return interAttrs }
[ "func", "CheckCompatible", "(", "s1", "FixedDataGrid", ",", "s2", "FixedDataGrid", ")", "[", "]", "Attribute", "{", "s1Attrs", ":=", "s1", ".", "AllAttributes", "(", ")", "\n", "s2Attrs", ":=", "s2", ".", "AllAttributes", "(", ")", "\n", "interAttrs", ":=", "AttributeIntersect", "(", "s1Attrs", ",", "s2Attrs", ")", "\n", "if", "len", "(", "interAttrs", ")", "!=", "len", "(", "s1Attrs", ")", "{", "return", "nil", "\n", "}", "else", "if", "len", "(", "interAttrs", ")", "!=", "len", "(", "s2Attrs", ")", "{", "return", "nil", "\n", "}", "\n", "return", "interAttrs", "\n", "}" ]
// CheckCompatible checks whether two DataGrids have the same Attributes // and if they do, it returns them.
[ "CheckCompatible", "checks", "whether", "two", "DataGrids", "have", "the", "same", "Attributes", "and", "if", "they", "do", "it", "returns", "them", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L443-L453
164,736
sjwhitworth/golearn
base/util_instances.go
CheckStrictlyCompatible
func CheckStrictlyCompatible(s1 FixedDataGrid, s2 FixedDataGrid) bool { // Cast d1, ok1 := s1.(*DenseInstances) d2, ok2 := s2.(*DenseInstances) if !ok1 || !ok2 { return false } // Retrieve AttributeGroups d1ags := d1.AllAttributeGroups() d2ags := d2.AllAttributeGroups() // Check everything in d1 is in d2 for a := range d1ags { _, ok := d2ags[a] if !ok { return false } } // Check everything in d2 is in d1 for a := range d2ags { _, ok := d1ags[a] if !ok { return false } } // Check that everything has the same number // of equivalent Attributes, in the same order for a := range d1ags { ag1 := d1ags[a] ag2 := d2ags[a] a1 := ag1.Attributes() a2 := ag2.Attributes() for i := range a1 { at1 := a1[i] at2 := a2[i] if !at1.Equals(at2) { return false } } } return true }
go
func CheckStrictlyCompatible(s1 FixedDataGrid, s2 FixedDataGrid) bool { // Cast d1, ok1 := s1.(*DenseInstances) d2, ok2 := s2.(*DenseInstances) if !ok1 || !ok2 { return false } // Retrieve AttributeGroups d1ags := d1.AllAttributeGroups() d2ags := d2.AllAttributeGroups() // Check everything in d1 is in d2 for a := range d1ags { _, ok := d2ags[a] if !ok { return false } } // Check everything in d2 is in d1 for a := range d2ags { _, ok := d1ags[a] if !ok { return false } } // Check that everything has the same number // of equivalent Attributes, in the same order for a := range d1ags { ag1 := d1ags[a] ag2 := d2ags[a] a1 := ag1.Attributes() a2 := ag2.Attributes() for i := range a1 { at1 := a1[i] at2 := a2[i] if !at1.Equals(at2) { return false } } } return true }
[ "func", "CheckStrictlyCompatible", "(", "s1", "FixedDataGrid", ",", "s2", "FixedDataGrid", ")", "bool", "{", "// Cast", "d1", ",", "ok1", ":=", "s1", ".", "(", "*", "DenseInstances", ")", "\n", "d2", ",", "ok2", ":=", "s2", ".", "(", "*", "DenseInstances", ")", "\n", "if", "!", "ok1", "||", "!", "ok2", "{", "return", "false", "\n", "}", "\n\n", "// Retrieve AttributeGroups", "d1ags", ":=", "d1", ".", "AllAttributeGroups", "(", ")", "\n", "d2ags", ":=", "d2", ".", "AllAttributeGroups", "(", ")", "\n\n", "// Check everything in d1 is in d2", "for", "a", ":=", "range", "d1ags", "{", "_", ",", "ok", ":=", "d2ags", "[", "a", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// Check everything in d2 is in d1", "for", "a", ":=", "range", "d2ags", "{", "_", ",", "ok", ":=", "d1ags", "[", "a", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// Check that everything has the same number", "// of equivalent Attributes, in the same order", "for", "a", ":=", "range", "d1ags", "{", "ag1", ":=", "d1ags", "[", "a", "]", "\n", "ag2", ":=", "d2ags", "[", "a", "]", "\n", "a1", ":=", "ag1", ".", "Attributes", "(", ")", "\n", "a2", ":=", "ag2", ".", "Attributes", "(", ")", "\n", "for", "i", ":=", "range", "a1", "{", "at1", ":=", "a1", "[", "i", "]", "\n", "at2", ":=", "a2", "[", "i", "]", "\n", "if", "!", "at1", ".", "Equals", "(", "at2", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// CheckStrictlyCompatible checks whether two DenseInstances have // AttributeGroups with the same Attributes, in the same order, // enabling optimisations.
[ "CheckStrictlyCompatible", "checks", "whether", "two", "DenseInstances", "have", "AttributeGroups", "with", "the", "same", "Attributes", "in", "the", "same", "order", "enabling", "optimisations", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/util_instances.go#L458-L503
164,737
sjwhitworth/golearn
filters/binning.go
NewBinningFilter
func NewBinningFilter(d base.FixedDataGrid, bins int) *BinningFilter { return &BinningFilter{ AbstractDiscretizeFilter{ make(map[base.Attribute]bool), false, d, }, bins, make(map[base.Attribute]float64), make(map[base.Attribute]float64), } }
go
func NewBinningFilter(d base.FixedDataGrid, bins int) *BinningFilter { return &BinningFilter{ AbstractDiscretizeFilter{ make(map[base.Attribute]bool), false, d, }, bins, make(map[base.Attribute]float64), make(map[base.Attribute]float64), } }
[ "func", "NewBinningFilter", "(", "d", "base", ".", "FixedDataGrid", ",", "bins", "int", ")", "*", "BinningFilter", "{", "return", "&", "BinningFilter", "{", "AbstractDiscretizeFilter", "{", "make", "(", "map", "[", "base", ".", "Attribute", "]", "bool", ")", ",", "false", ",", "d", ",", "}", ",", "bins", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "float64", ")", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "float64", ")", ",", "}", "\n", "}" ]
// NewBinningFilter creates a BinningFilter structure // with some helpful default initialisations.
[ "NewBinningFilter", "creates", "a", "BinningFilter", "structure", "with", "some", "helpful", "default", "initialisations", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/binning.go#L21-L32
164,738
sjwhitworth/golearn
filters/binning.go
Train
func (b *BinningFilter) Train() error { as := b.getAttributeSpecs() // Set up the AttributeSpecs, and values for attr := range b.attrs { if !b.attrs[attr] { continue } b.minVals[attr] = float64(math.Inf(1)) b.maxVals[attr] = float64(math.Inf(-1)) } err := b.train.MapOverRows(as, func(row [][]byte, rowNo int) (bool, error) { for i, a := range row { attr := as[i].GetAttribute() attrf := attr.(*base.FloatAttribute) val := float64(attrf.GetFloatFromSysVal(a)) if val > b.maxVals[attr] { b.maxVals[attr] = val } if val < b.minVals[attr] { b.minVals[attr] = val } } return true, nil }) if err != nil { return fmt.Errorf("Training error: %s", err) } b.trained = true return nil }
go
func (b *BinningFilter) Train() error { as := b.getAttributeSpecs() // Set up the AttributeSpecs, and values for attr := range b.attrs { if !b.attrs[attr] { continue } b.minVals[attr] = float64(math.Inf(1)) b.maxVals[attr] = float64(math.Inf(-1)) } err := b.train.MapOverRows(as, func(row [][]byte, rowNo int) (bool, error) { for i, a := range row { attr := as[i].GetAttribute() attrf := attr.(*base.FloatAttribute) val := float64(attrf.GetFloatFromSysVal(a)) if val > b.maxVals[attr] { b.maxVals[attr] = val } if val < b.minVals[attr] { b.minVals[attr] = val } } return true, nil }) if err != nil { return fmt.Errorf("Training error: %s", err) } b.trained = true return nil }
[ "func", "(", "b", "*", "BinningFilter", ")", "Train", "(", ")", "error", "{", "as", ":=", "b", ".", "getAttributeSpecs", "(", ")", "\n", "// Set up the AttributeSpecs, and values", "for", "attr", ":=", "range", "b", ".", "attrs", "{", "if", "!", "b", ".", "attrs", "[", "attr", "]", "{", "continue", "\n", "}", "\n", "b", ".", "minVals", "[", "attr", "]", "=", "float64", "(", "math", ".", "Inf", "(", "1", ")", ")", "\n", "b", ".", "maxVals", "[", "attr", "]", "=", "float64", "(", "math", ".", "Inf", "(", "-", "1", ")", ")", "\n", "}", "\n\n", "err", ":=", "b", ".", "train", ".", "MapOverRows", "(", "as", ",", "func", "(", "row", "[", "]", "[", "]", "byte", ",", "rowNo", "int", ")", "(", "bool", ",", "error", ")", "{", "for", "i", ",", "a", ":=", "range", "row", "{", "attr", ":=", "as", "[", "i", "]", ".", "GetAttribute", "(", ")", "\n", "attrf", ":=", "attr", ".", "(", "*", "base", ".", "FloatAttribute", ")", "\n", "val", ":=", "float64", "(", "attrf", ".", "GetFloatFromSysVal", "(", "a", ")", ")", "\n", "if", "val", ">", "b", ".", "maxVals", "[", "attr", "]", "{", "b", ".", "maxVals", "[", "attr", "]", "=", "val", "\n", "}", "\n", "if", "val", "<", "b", ".", "minVals", "[", "attr", "]", "{", "b", ".", "minVals", "[", "attr", "]", "=", "val", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "b", ".", "trained", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Train computes and stores the bin values // for the training instances.
[ "Train", "computes", "and", "stores", "the", "bin", "values", "for", "the", "training", "instances", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/binning.go#L40-L72
164,739
sjwhitworth/golearn
filters/binning.go
Transform
func (b *BinningFilter) Transform(a base.Attribute, n base.Attribute, field []byte) []byte { if !b.attrs[a] { return field } af, ok := a.(*base.FloatAttribute) if !ok { panic("Attribute is the wrong type") } minVal := b.minVals[a] maxVal := b.maxVals[a] disc := 0 // Casts to float64 to replicate a floating point precision error delta := float64(maxVal-minVal) / float64(b.bins) val := float64(af.GetFloatFromSysVal(field)) if val <= minVal { disc = 0 } else { disc = int(math.Floor(float64(float64(val-minVal)/delta + 0.0001))) } return base.PackU64ToBytes(uint64(disc)) }
go
func (b *BinningFilter) Transform(a base.Attribute, n base.Attribute, field []byte) []byte { if !b.attrs[a] { return field } af, ok := a.(*base.FloatAttribute) if !ok { panic("Attribute is the wrong type") } minVal := b.minVals[a] maxVal := b.maxVals[a] disc := 0 // Casts to float64 to replicate a floating point precision error delta := float64(maxVal-minVal) / float64(b.bins) val := float64(af.GetFloatFromSysVal(field)) if val <= minVal { disc = 0 } else { disc = int(math.Floor(float64(float64(val-minVal)/delta + 0.0001))) } return base.PackU64ToBytes(uint64(disc)) }
[ "func", "(", "b", "*", "BinningFilter", ")", "Transform", "(", "a", "base", ".", "Attribute", ",", "n", "base", ".", "Attribute", ",", "field", "[", "]", "byte", ")", "[", "]", "byte", "{", "if", "!", "b", ".", "attrs", "[", "a", "]", "{", "return", "field", "\n", "}", "\n", "af", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "FloatAttribute", ")", "\n", "if", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "minVal", ":=", "b", ".", "minVals", "[", "a", "]", "\n", "maxVal", ":=", "b", ".", "maxVals", "[", "a", "]", "\n", "disc", ":=", "0", "\n", "// Casts to float64 to replicate a floating point precision error", "delta", ":=", "float64", "(", "maxVal", "-", "minVal", ")", "/", "float64", "(", "b", ".", "bins", ")", "\n", "val", ":=", "float64", "(", "af", ".", "GetFloatFromSysVal", "(", "field", ")", ")", "\n", "if", "val", "<=", "minVal", "{", "disc", "=", "0", "\n", "}", "else", "{", "disc", "=", "int", "(", "math", ".", "Floor", "(", "float64", "(", "float64", "(", "val", "-", "minVal", ")", "/", "delta", "+", "0.0001", ")", ")", ")", "\n", "}", "\n", "return", "base", ".", "PackU64ToBytes", "(", "uint64", "(", "disc", ")", ")", "\n", "}" ]
// Transform takes an Attribute and byte sequence and returns // the transformed byte sequence.
[ "Transform", "takes", "an", "Attribute", "and", "byte", "sequence", "and", "returns", "the", "transformed", "byte", "sequence", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/binning.go#L76-L97
164,740
sjwhitworth/golearn
base/serialize_attributes.go
MarshalAttribute
func MarshalAttribute(a Attribute) (map[string]interface{}, error) { ret := make(map[string]interface{}) marshaledAttrRaw, err := a.MarshalJSON() if err != nil { return nil, err } err = json.Unmarshal(marshaledAttrRaw, &ret) if err != nil { return nil, err } return ret, nil }
go
func MarshalAttribute(a Attribute) (map[string]interface{}, error) { ret := make(map[string]interface{}) marshaledAttrRaw, err := a.MarshalJSON() if err != nil { return nil, err } err = json.Unmarshal(marshaledAttrRaw, &ret) if err != nil { return nil, err } return ret, nil }
[ "func", "MarshalAttribute", "(", "a", "Attribute", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "ret", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "marshaledAttrRaw", ",", "err", ":=", "a", ".", "MarshalJSON", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "marshaledAttrRaw", ",", "&", "ret", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// MarshalAttribute converts an Attribute to a JSON map.
[ "MarshalAttribute", "converts", "an", "Attribute", "to", "a", "JSON", "map", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_attributes.go#L34-L45
164,741
sjwhitworth/golearn
base/serialize_attributes.go
DeserializeAttributes
func DeserializeAttributes(data []byte) ([]Attribute, error) { // Define a JSON shim Attribute var attrs []json.RawMessage err := json.Unmarshal(data, &attrs) if err != nil { return nil, fmt.Errorf("Failed to deserialize attributes: %v", err) } ret := make([]Attribute, len(attrs)) for i, v := range attrs { ret[i], err = DeserializeAttribute(v) if err != nil { return nil, err } } return ret, nil }
go
func DeserializeAttributes(data []byte) ([]Attribute, error) { // Define a JSON shim Attribute var attrs []json.RawMessage err := json.Unmarshal(data, &attrs) if err != nil { return nil, fmt.Errorf("Failed to deserialize attributes: %v", err) } ret := make([]Attribute, len(attrs)) for i, v := range attrs { ret[i], err = DeserializeAttribute(v) if err != nil { return nil, err } } return ret, nil }
[ "func", "DeserializeAttributes", "(", "data", "[", "]", "byte", ")", "(", "[", "]", "Attribute", ",", "error", ")", "{", "// Define a JSON shim Attribute", "var", "attrs", "[", "]", "json", ".", "RawMessage", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "attrs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "len", "(", "attrs", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "attrs", "{", "ret", "[", "i", "]", ",", "err", "=", "DeserializeAttribute", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "ret", ",", "nil", "\n", "}" ]
// DeserializeAttributes constructs a ve
[ "DeserializeAttributes", "constructs", "a", "ve" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_attributes.go#L93-L111
164,742
sjwhitworth/golearn
base/serialize_attributes.go
ReplaceDeserializedAttributeWithVersionFromInstances
func ReplaceDeserializedAttributeWithVersionFromInstances(deserialized Attribute, matchingWith FixedDataGrid) (Attribute, error) { for _, a := range matchingWith.AllAttributes() { if a.Equals(deserialized) { return a, nil } } return nil, WrapError(fmt.Errorf("Unable to match %v in %v", deserialized, matchingWith)) }
go
func ReplaceDeserializedAttributeWithVersionFromInstances(deserialized Attribute, matchingWith FixedDataGrid) (Attribute, error) { for _, a := range matchingWith.AllAttributes() { if a.Equals(deserialized) { return a, nil } } return nil, WrapError(fmt.Errorf("Unable to match %v in %v", deserialized, matchingWith)) }
[ "func", "ReplaceDeserializedAttributeWithVersionFromInstances", "(", "deserialized", "Attribute", ",", "matchingWith", "FixedDataGrid", ")", "(", "Attribute", ",", "error", ")", "{", "for", "_", ",", "a", ":=", "range", "matchingWith", ".", "AllAttributes", "(", ")", "{", "if", "a", ".", "Equals", "(", "deserialized", ")", "{", "return", "a", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "WrapError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "deserialized", ",", "matchingWith", ")", ")", "\n", "}" ]
// ReplaceDeserializedAttributeWithVersionFromInstances takes an independently deserialized Attribute and matches it // if possible with one from a candidate FixedDataGrid.
[ "ReplaceDeserializedAttributeWithVersionFromInstances", "takes", "an", "independently", "deserialized", "Attribute", "and", "matches", "it", "if", "possible", "with", "one", "from", "a", "candidate", "FixedDataGrid", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_attributes.go#L115-L122
164,743
sjwhitworth/golearn
base/serialize_attributes.go
ReplaceDeserializedAttributesWithVersionsFromInstances
func ReplaceDeserializedAttributesWithVersionsFromInstances(deserialized []Attribute, matchingWith FixedDataGrid) ([]Attribute, error) { ret := make([]Attribute, len(deserialized)) for i, a := range deserialized { match, err := ReplaceDeserializedAttributeWithVersionFromInstances(a, matchingWith) if err != nil { return nil, WrapError(err) } ret[i] = match } return ret, nil }
go
func ReplaceDeserializedAttributesWithVersionsFromInstances(deserialized []Attribute, matchingWith FixedDataGrid) ([]Attribute, error) { ret := make([]Attribute, len(deserialized)) for i, a := range deserialized { match, err := ReplaceDeserializedAttributeWithVersionFromInstances(a, matchingWith) if err != nil { return nil, WrapError(err) } ret[i] = match } return ret, nil }
[ "func", "ReplaceDeserializedAttributesWithVersionsFromInstances", "(", "deserialized", "[", "]", "Attribute", ",", "matchingWith", "FixedDataGrid", ")", "(", "[", "]", "Attribute", ",", "error", ")", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "len", "(", "deserialized", ")", ")", "\n", "for", "i", ",", "a", ":=", "range", "deserialized", "{", "match", ",", "err", ":=", "ReplaceDeserializedAttributeWithVersionFromInstances", "(", "a", ",", "matchingWith", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "WrapError", "(", "err", ")", "\n", "}", "\n", "ret", "[", "i", "]", "=", "match", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// ReplaceDeserializedAttributesWithVersionsFromInstances takes some independently loaded Attributes and // matches them up with a candidate FixedDataGrid.
[ "ReplaceDeserializedAttributesWithVersionsFromInstances", "takes", "some", "independently", "loaded", "Attributes", "and", "matches", "them", "up", "with", "a", "candidate", "FixedDataGrid", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/serialize_attributes.go#L126-L136
164,744
sjwhitworth/golearn
base/dense.go
NewDenseInstances
func NewDenseInstances() *DenseInstances { return &DenseInstances{ make(map[string]int), make(map[int]string), make([]AttributeGroup, 0), sync.Mutex{}, false, make(map[AttributeSpec]bool), 0, make([]Attribute, 0), make(map[Attribute]string), 0, 0, 0, } }
go
func NewDenseInstances() *DenseInstances { return &DenseInstances{ make(map[string]int), make(map[int]string), make([]AttributeGroup, 0), sync.Mutex{}, false, make(map[AttributeSpec]bool), 0, make([]Attribute, 0), make(map[Attribute]string), 0, 0, 0, } }
[ "func", "NewDenseInstances", "(", ")", "*", "DenseInstances", "{", "return", "&", "DenseInstances", "{", "make", "(", "map", "[", "string", "]", "int", ")", ",", "make", "(", "map", "[", "int", "]", "string", ")", ",", "make", "(", "[", "]", "AttributeGroup", ",", "0", ")", ",", "sync", ".", "Mutex", "{", "}", ",", "false", ",", "make", "(", "map", "[", "AttributeSpec", "]", "bool", ")", ",", "0", ",", "make", "(", "[", "]", "Attribute", ",", "0", ")", ",", "make", "(", "map", "[", "Attribute", "]", "string", ")", ",", "0", ",", "0", ",", "0", ",", "}", "\n", "}" ]
// NewDenseInstances generates a new DenseInstances set // with an anonymous EDF mapping and default settings.
[ "NewDenseInstances", "generates", "a", "new", "DenseInstances", "set", "with", "an", "anonymous", "EDF", "mapping", "and", "default", "settings", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L30-L45
164,745
sjwhitworth/golearn
base/dense.go
NewStructuralCopy
func NewStructuralCopy(of FixedDataGrid) *DenseInstances { ret, _, _ := copyFixedDataGridStructure(of) return ret }
go
func NewStructuralCopy(of FixedDataGrid) *DenseInstances { ret, _, _ := copyFixedDataGridStructure(of) return ret }
[ "func", "NewStructuralCopy", "(", "of", "FixedDataGrid", ")", "*", "DenseInstances", "{", "ret", ",", "_", ",", "_", ":=", "copyFixedDataGridStructure", "(", "of", ")", "\n", "return", "ret", "\n", "}" ]
// NewStructuralCopy generates an empty DenseInstances with the same layout as // an existing FixedDataGrid, but with no data.
[ "NewStructuralCopy", "generates", "an", "empty", "DenseInstances", "with", "the", "same", "layout", "as", "an", "existing", "FixedDataGrid", "but", "with", "no", "data", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L74-L77
164,746
sjwhitworth/golearn
base/dense.go
NewDenseCopy
func NewDenseCopy(of FixedDataGrid) *DenseInstances { ret, specs1, specs2 := copyFixedDataGridStructure(of) // Allocate memory _, rows := of.Size() ret.Extend(rows) // Copy each row from the old one to the new of.MapOverRows(specs1, func(v [][]byte, r int) (bool, error) { for i, c := range v { ret.Set(specs2[i], r, c) } return true, nil }) return ret }
go
func NewDenseCopy(of FixedDataGrid) *DenseInstances { ret, specs1, specs2 := copyFixedDataGridStructure(of) // Allocate memory _, rows := of.Size() ret.Extend(rows) // Copy each row from the old one to the new of.MapOverRows(specs1, func(v [][]byte, r int) (bool, error) { for i, c := range v { ret.Set(specs2[i], r, c) } return true, nil }) return ret }
[ "func", "NewDenseCopy", "(", "of", "FixedDataGrid", ")", "*", "DenseInstances", "{", "ret", ",", "specs1", ",", "specs2", ":=", "copyFixedDataGridStructure", "(", "of", ")", "\n\n", "// Allocate memory", "_", ",", "rows", ":=", "of", ".", "Size", "(", ")", "\n", "ret", ".", "Extend", "(", "rows", ")", "\n\n", "// Copy each row from the old one to the new", "of", ".", "MapOverRows", "(", "specs1", ",", "func", "(", "v", "[", "]", "[", "]", "byte", ",", "r", "int", ")", "(", "bool", ",", "error", ")", "{", "for", "i", ",", "c", ":=", "range", "v", "{", "ret", ".", "Set", "(", "specs2", "[", "i", "]", ",", "r", ",", "c", ")", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n\n", "return", "ret", "\n", "}" ]
// NewDenseCopy generates a new DenseInstances set // from an existing FixedDataGrid.
[ "NewDenseCopy", "generates", "a", "new", "DenseInstances", "set", "from", "an", "existing", "FixedDataGrid", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L81-L98
164,747
sjwhitworth/golearn
base/dense.go
CreateAttributeGroup
func (inst *DenseInstances) CreateAttributeGroup(name string, size int) (err error) { defer func() { if r := recover(); r != nil { var ok bool if err, ok = r.(error); !ok { err = fmt.Errorf("CreateAttributeGroup: %v (not created)", r) } } }() inst.lock.Lock() defer inst.lock.Unlock() inst.createAttributeGroup(name, size) return nil }
go
func (inst *DenseInstances) CreateAttributeGroup(name string, size int) (err error) { defer func() { if r := recover(); r != nil { var ok bool if err, ok = r.(error); !ok { err = fmt.Errorf("CreateAttributeGroup: %v (not created)", r) } } }() inst.lock.Lock() defer inst.lock.Unlock() inst.createAttributeGroup(name, size) return nil }
[ "func", "(", "inst", "*", "DenseInstances", ")", "CreateAttributeGroup", "(", "name", "string", ",", "size", "int", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "r", ":=", "recover", "(", ")", ";", "r", "!=", "nil", "{", "var", "ok", "bool", "\n", "if", "err", ",", "ok", "=", "r", ".", "(", "error", ")", ";", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "inst", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "inst", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "inst", ".", "createAttributeGroup", "(", "name", ",", "size", ")", "\n", "return", "nil", "\n", "}" ]
// CreateAttributeGroup adds a new AttributeGroup to this set of instances // with a given name. If the size is 0, a bit-ag is added // if the size of not 0, then the size of each ag attribute // is set to that number of bytes.
[ "CreateAttributeGroup", "adds", "a", "new", "AttributeGroup", "to", "this", "set", "of", "instances", "with", "a", "given", "name", ".", "If", "the", "size", "is", "0", "a", "bit", "-", "ag", "is", "added", "if", "the", "size", "of", "not", "0", "then", "the", "size", "of", "each", "ag", "attribute", "is", "set", "to", "that", "number", "of", "bytes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L139-L154
164,748
sjwhitworth/golearn
base/dense.go
AllAttributeGroups
func (inst *DenseInstances) AllAttributeGroups() map[string]AttributeGroup { ret := make(map[string]AttributeGroup) for a := range inst.agMap { ret[a] = inst.ags[inst.agMap[a]] } return ret }
go
func (inst *DenseInstances) AllAttributeGroups() map[string]AttributeGroup { ret := make(map[string]AttributeGroup) for a := range inst.agMap { ret[a] = inst.ags[inst.agMap[a]] } return ret }
[ "func", "(", "inst", "*", "DenseInstances", ")", "AllAttributeGroups", "(", ")", "map", "[", "string", "]", "AttributeGroup", "{", "ret", ":=", "make", "(", "map", "[", "string", "]", "AttributeGroup", ")", "\n", "for", "a", ":=", "range", "inst", ".", "agMap", "{", "ret", "[", "a", "]", "=", "inst", ".", "ags", "[", "inst", ".", "agMap", "[", "a", "]", "]", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// AllAttributeGroups returns a copy of the available AttributeGroups
[ "AllAttributeGroups", "returns", "a", "copy", "of", "the", "available", "AttributeGroups" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L157-L163
164,749
sjwhitworth/golearn
base/dense.go
AddAttributeToAttributeGroup
func (inst *DenseInstances) AddAttributeToAttributeGroup(newAttribute Attribute, ag string) (AttributeSpec, error) { inst.lock.Lock() defer inst.lock.Unlock() // Check if the ag exists if _, ok := inst.agMap[ag]; !ok { return AttributeSpec{-1, 0, nil}, fmt.Errorf("AttributeGroup '%s' doesn't exist. Call CreateAttributeGroup() first", ag) } id := inst.agMap[ag] p := inst.ags[id] for i, a := range p.Attributes() { if !a.Compatible(newAttribute) { return AttributeSpec{-1, 0, nil}, fmt.Errorf("Attribute %s is not Compatible with %s in pond '%s' (position %d)", newAttribute, a, ag, i) } } p.AddAttribute(newAttribute) inst.attributes = append(inst.attributes, newAttribute) return AttributeSpec{id, len(p.Attributes()) - 1, newAttribute}, nil }
go
func (inst *DenseInstances) AddAttributeToAttributeGroup(newAttribute Attribute, ag string) (AttributeSpec, error) { inst.lock.Lock() defer inst.lock.Unlock() // Check if the ag exists if _, ok := inst.agMap[ag]; !ok { return AttributeSpec{-1, 0, nil}, fmt.Errorf("AttributeGroup '%s' doesn't exist. Call CreateAttributeGroup() first", ag) } id := inst.agMap[ag] p := inst.ags[id] for i, a := range p.Attributes() { if !a.Compatible(newAttribute) { return AttributeSpec{-1, 0, nil}, fmt.Errorf("Attribute %s is not Compatible with %s in pond '%s' (position %d)", newAttribute, a, ag, i) } } p.AddAttribute(newAttribute) inst.attributes = append(inst.attributes, newAttribute) return AttributeSpec{id, len(p.Attributes()) - 1, newAttribute}, nil }
[ "func", "(", "inst", "*", "DenseInstances", ")", "AddAttributeToAttributeGroup", "(", "newAttribute", "Attribute", ",", "ag", "string", ")", "(", "AttributeSpec", ",", "error", ")", "{", "inst", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "inst", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "// Check if the ag exists", "if", "_", ",", "ok", ":=", "inst", ".", "agMap", "[", "ag", "]", ";", "!", "ok", "{", "return", "AttributeSpec", "{", "-", "1", ",", "0", ",", "nil", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ag", ")", "\n", "}", "\n\n", "id", ":=", "inst", ".", "agMap", "[", "ag", "]", "\n", "p", ":=", "inst", ".", "ags", "[", "id", "]", "\n", "for", "i", ",", "a", ":=", "range", "p", ".", "Attributes", "(", ")", "{", "if", "!", "a", ".", "Compatible", "(", "newAttribute", ")", "{", "return", "AttributeSpec", "{", "-", "1", ",", "0", ",", "nil", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "newAttribute", ",", "a", ",", "ag", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "p", ".", "AddAttribute", "(", "newAttribute", ")", "\n", "inst", ".", "attributes", "=", "append", "(", "inst", ".", "attributes", ",", "newAttribute", ")", "\n", "return", "AttributeSpec", "{", "id", ",", "len", "(", "p", ".", "Attributes", "(", ")", ")", "-", "1", ",", "newAttribute", "}", ",", "nil", "\n", "}" ]
// AddAttributeToAttributeGroup adds an Attribute to a given ag
[ "AddAttributeToAttributeGroup", "adds", "an", "Attribute", "to", "a", "given", "ag" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L236-L256
164,750
sjwhitworth/golearn
base/dense.go
AllAttributes
func (inst *DenseInstances) AllAttributes() []Attribute { inst.lock.Lock() defer inst.lock.Unlock() ret := make([]Attribute, 0) for _, p := range inst.ags { for _, a := range p.Attributes() { ret = append(ret, a) } } return ret }
go
func (inst *DenseInstances) AllAttributes() []Attribute { inst.lock.Lock() defer inst.lock.Unlock() ret := make([]Attribute, 0) for _, p := range inst.ags { for _, a := range p.Attributes() { ret = append(ret, a) } } return ret }
[ "func", "(", "inst", "*", "DenseInstances", ")", "AllAttributes", "(", ")", "[", "]", "Attribute", "{", "inst", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "inst", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "0", ")", "\n", "for", "_", ",", "p", ":=", "range", "inst", ".", "ags", "{", "for", "_", ",", "a", ":=", "range", "p", ".", "Attributes", "(", ")", "{", "ret", "=", "append", "(", "ret", ",", "a", ")", "\n", "}", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// AllAttributes returns a slice of all Attributes.
[ "AllAttributes", "returns", "a", "slice", "of", "all", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L279-L291
164,751
sjwhitworth/golearn
base/dense.go
AddClassAttribute
func (inst *DenseInstances) AddClassAttribute(a Attribute) error { as, err := inst.GetAttribute(a) if err != nil { return err } inst.lock.Lock() defer inst.lock.Unlock() inst.classAttrs[as] = true return nil }
go
func (inst *DenseInstances) AddClassAttribute(a Attribute) error { as, err := inst.GetAttribute(a) if err != nil { return err } inst.lock.Lock() defer inst.lock.Unlock() inst.classAttrs[as] = true return nil }
[ "func", "(", "inst", "*", "DenseInstances", ")", "AddClassAttribute", "(", "a", "Attribute", ")", "error", "{", "as", ",", "err", ":=", "inst", ".", "GetAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "inst", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "inst", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "inst", ".", "classAttrs", "[", "as", "]", "=", "true", "\n", "return", "nil", "\n", "}" ]
// AddClassAttribute sets an Attribute to be a class Attribute.
[ "AddClassAttribute", "sets", "an", "Attribute", "to", "be", "a", "class", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L294-L306
164,752
sjwhitworth/golearn
base/dense.go
RemoveClassAttribute
func (inst *DenseInstances) RemoveClassAttribute(a Attribute) error { as, err := inst.GetAttribute(a) if err != nil { return err } inst.lock.Lock() defer inst.lock.Unlock() inst.classAttrs[as] = false return nil }
go
func (inst *DenseInstances) RemoveClassAttribute(a Attribute) error { as, err := inst.GetAttribute(a) if err != nil { return err } inst.lock.Lock() defer inst.lock.Unlock() inst.classAttrs[as] = false return nil }
[ "func", "(", "inst", "*", "DenseInstances", ")", "RemoveClassAttribute", "(", "a", "Attribute", ")", "error", "{", "as", ",", "err", ":=", "inst", ".", "GetAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "inst", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "inst", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "inst", ".", "classAttrs", "[", "as", "]", "=", "false", "\n", "return", "nil", "\n", "}" ]
// RemoveClassAttribute removes an Attribute from the set of class Attributes.
[ "RemoveClassAttribute", "removes", "an", "Attribute", "from", "the", "set", "of", "class", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L309-L321
164,753
sjwhitworth/golearn
base/dense.go
AllClassAttributes
func (inst *DenseInstances) AllClassAttributes() []Attribute { inst.lock.Lock() defer inst.lock.Unlock() return inst.allClassAttributes() }
go
func (inst *DenseInstances) AllClassAttributes() []Attribute { inst.lock.Lock() defer inst.lock.Unlock() return inst.allClassAttributes() }
[ "func", "(", "inst", "*", "DenseInstances", ")", "AllClassAttributes", "(", ")", "[", "]", "Attribute", "{", "inst", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "inst", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "inst", ".", "allClassAttributes", "(", ")", "\n", "}" ]
// AllClassAttributes returns a slice of Attributes which have // been designated class Attributes.
[ "AllClassAttributes", "returns", "a", "slice", "of", "Attributes", "which", "have", "been", "designated", "class", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L325-L329
164,754
sjwhitworth/golearn
base/dense.go
realiseAttributeGroups
func (inst *DenseInstances) realiseAttributeGroups() error { for a := range inst.tmpAttrAgMap { // Generate a default AttributeGroup name ag := inst.tmpAttrAgMap[a] // Augment with some additional information // Find out whether this attribute is also a class classAttribute := false for _, c := range inst.allClassAttributes() { if c.Equals(a) { classAttribute = true } } // This might result in multiple ClassAttribute groups // but hopefully nothing too crazy if classAttribute { // ag = fmt.Sprintf("CLASS_%s", ag) } // Create the ag if it doesn't exist if agId, ok := inst.agMap[ag]; !ok { _, generatingBinClass := inst.ags[agId].(*BinaryAttributeGroup) if !generatingBinClass { inst.createAttributeGroup(ag, 8) } else { inst.createAttributeGroup(ag, 0) } } id := inst.agMap[ag] p := inst.ags[id] err := p.AddAttribute(a) if err != nil { return err } } return nil }
go
func (inst *DenseInstances) realiseAttributeGroups() error { for a := range inst.tmpAttrAgMap { // Generate a default AttributeGroup name ag := inst.tmpAttrAgMap[a] // Augment with some additional information // Find out whether this attribute is also a class classAttribute := false for _, c := range inst.allClassAttributes() { if c.Equals(a) { classAttribute = true } } // This might result in multiple ClassAttribute groups // but hopefully nothing too crazy if classAttribute { // ag = fmt.Sprintf("CLASS_%s", ag) } // Create the ag if it doesn't exist if agId, ok := inst.agMap[ag]; !ok { _, generatingBinClass := inst.ags[agId].(*BinaryAttributeGroup) if !generatingBinClass { inst.createAttributeGroup(ag, 8) } else { inst.createAttributeGroup(ag, 0) } } id := inst.agMap[ag] p := inst.ags[id] err := p.AddAttribute(a) if err != nil { return err } } return nil }
[ "func", "(", "inst", "*", "DenseInstances", ")", "realiseAttributeGroups", "(", ")", "error", "{", "for", "a", ":=", "range", "inst", ".", "tmpAttrAgMap", "{", "// Generate a default AttributeGroup name", "ag", ":=", "inst", ".", "tmpAttrAgMap", "[", "a", "]", "\n\n", "// Augment with some additional information", "// Find out whether this attribute is also a class", "classAttribute", ":=", "false", "\n", "for", "_", ",", "c", ":=", "range", "inst", ".", "allClassAttributes", "(", ")", "{", "if", "c", ".", "Equals", "(", "a", ")", "{", "classAttribute", "=", "true", "\n", "}", "\n", "}", "\n\n", "// This might result in multiple ClassAttribute groups", "// but hopefully nothing too crazy", "if", "classAttribute", "{", "// ag = fmt.Sprintf(\"CLASS_%s\", ag)", "}", "\n\n", "// Create the ag if it doesn't exist", "if", "agId", ",", "ok", ":=", "inst", ".", "agMap", "[", "ag", "]", ";", "!", "ok", "{", "_", ",", "generatingBinClass", ":=", "inst", ".", "ags", "[", "agId", "]", ".", "(", "*", "BinaryAttributeGroup", ")", "\n", "if", "!", "generatingBinClass", "{", "inst", ".", "createAttributeGroup", "(", "ag", ",", "8", ")", "\n", "}", "else", "{", "inst", ".", "createAttributeGroup", "(", "ag", ",", "0", ")", "\n", "}", "\n", "}", "\n", "id", ":=", "inst", ".", "agMap", "[", "ag", "]", "\n", "p", ":=", "inst", ".", "ags", "[", "id", "]", "\n", "err", ":=", "p", ".", "AddAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// // Allocation functions // // realiseAttributeGroups decides which Attributes are going // to be stored in which groups
[ "Allocation", "functions", "realiseAttributeGroups", "decides", "which", "Attributes", "are", "going", "to", "be", "stored", "in", "which", "groups" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L349-L386
164,755
sjwhitworth/golearn
base/dense.go
MapOverRows
func (inst *DenseInstances) MapOverRows(asv []AttributeSpec, mapFunc func([][]byte, int) (bool, error)) error { rowBuf := make([][]byte, len(asv)) for i := 0; i < inst.maxRow; i++ { for j, as := range asv { p := inst.ags[as.pond] rowBuf[j] = p.get(as.position, i) } ok, err := mapFunc(rowBuf, i) if err != nil { return err } if !ok { break } } return nil }
go
func (inst *DenseInstances) MapOverRows(asv []AttributeSpec, mapFunc func([][]byte, int) (bool, error)) error { rowBuf := make([][]byte, len(asv)) for i := 0; i < inst.maxRow; i++ { for j, as := range asv { p := inst.ags[as.pond] rowBuf[j] = p.get(as.position, i) } ok, err := mapFunc(rowBuf, i) if err != nil { return err } if !ok { break } } return nil }
[ "func", "(", "inst", "*", "DenseInstances", ")", "MapOverRows", "(", "asv", "[", "]", "AttributeSpec", ",", "mapFunc", "func", "(", "[", "]", "[", "]", "byte", ",", "int", ")", "(", "bool", ",", "error", ")", ")", "error", "{", "rowBuf", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "asv", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "inst", ".", "maxRow", ";", "i", "++", "{", "for", "j", ",", "as", ":=", "range", "asv", "{", "p", ":=", "inst", ".", "ags", "[", "as", ".", "pond", "]", "\n", "rowBuf", "[", "j", "]", "=", "p", ".", "get", "(", "as", ".", "position", ",", "i", ")", "\n", "}", "\n", "ok", ",", "err", ":=", "mapFunc", "(", "rowBuf", ",", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "ok", "{", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MapOverRows passes each row map into a function. // First argument is a list of AttributeSpec in the order // they're needed in for the function. The second is the function // to call on each row.
[ "MapOverRows", "passes", "each", "row", "map", "into", "a", "function", ".", "First", "argument", "is", "a", "list", "of", "AttributeSpec", "in", "the", "order", "they", "re", "needed", "in", "for", "the", "function", ".", "The", "second", "is", "the", "function", "to", "call", "on", "each", "row", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L460-L476
164,756
sjwhitworth/golearn
base/dense.go
Size
func (inst *DenseInstances) Size() (int, int) { return len(inst.AllAttributes()), inst.maxRow }
go
func (inst *DenseInstances) Size() (int, int) { return len(inst.AllAttributes()), inst.maxRow }
[ "func", "(", "inst", "*", "DenseInstances", ")", "Size", "(", ")", "(", "int", ",", "int", ")", "{", "return", "len", "(", "inst", ".", "AllAttributes", "(", ")", ")", ",", "inst", ".", "maxRow", "\n", "}" ]
// Size returns the number of Attributes as the first return value // and the maximum allocated row as the second value.
[ "Size", "returns", "the", "number", "of", "Attributes", "as", "the", "first", "return", "value", "and", "the", "maximum", "allocated", "row", "as", "the", "second", "value", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L480-L482
164,757
sjwhitworth/golearn
base/dense.go
swapRows
func (inst *DenseInstances) swapRows(i, j int) { as := ResolveAllAttributes(inst) for _, a := range as { v1 := inst.Get(a, i) v2 := inst.Get(a, j) v3 := make([]byte, len(v2)) copy(v3, v2) inst.Set(a, j, v1) inst.Set(a, i, v3) } }
go
func (inst *DenseInstances) swapRows(i, j int) { as := ResolveAllAttributes(inst) for _, a := range as { v1 := inst.Get(a, i) v2 := inst.Get(a, j) v3 := make([]byte, len(v2)) copy(v3, v2) inst.Set(a, j, v1) inst.Set(a, i, v3) } }
[ "func", "(", "inst", "*", "DenseInstances", ")", "swapRows", "(", "i", ",", "j", "int", ")", "{", "as", ":=", "ResolveAllAttributes", "(", "inst", ")", "\n", "for", "_", ",", "a", ":=", "range", "as", "{", "v1", ":=", "inst", ".", "Get", "(", "a", ",", "i", ")", "\n", "v2", ":=", "inst", ".", "Get", "(", "a", ",", "j", ")", "\n", "v3", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "v2", ")", ")", "\n", "copy", "(", "v3", ",", "v2", ")", "\n", "inst", ".", "Set", "(", "a", ",", "j", ",", "v1", ")", "\n", "inst", ".", "Set", "(", "a", ",", "i", ",", "v3", ")", "\n", "}", "\n", "}" ]
// swapRows swaps over rows i and j
[ "swapRows", "swaps", "over", "rows", "i", "and", "j" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L485-L495
164,758
sjwhitworth/golearn
base/dense.go
String
func (inst *DenseInstances) String() string { var buffer bytes.Buffer // Get all Attribute information as := ResolveAllAttributes(inst) // Print header cols, rows := inst.Size() buffer.WriteString("Instances with ") buffer.WriteString(fmt.Sprintf("%d row(s) ", rows)) buffer.WriteString(fmt.Sprintf("%d attribute(s)\n", cols)) buffer.WriteString(fmt.Sprintf("Attributes: \n")) for _, a := range as { prefix := "\t" if inst.classAttrs[a] { prefix = "*\t" } buffer.WriteString(fmt.Sprintf("%s%s\n", prefix, a.attr)) } buffer.WriteString("\nData:\n") maxRows := 30 if rows < maxRows { maxRows = rows } for i := 0; i < maxRows; i++ { buffer.WriteString("\t") for _, a := range as { val := inst.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 (inst *DenseInstances) String() string { var buffer bytes.Buffer // Get all Attribute information as := ResolveAllAttributes(inst) // Print header cols, rows := inst.Size() buffer.WriteString("Instances with ") buffer.WriteString(fmt.Sprintf("%d row(s) ", rows)) buffer.WriteString(fmt.Sprintf("%d attribute(s)\n", cols)) buffer.WriteString(fmt.Sprintf("Attributes: \n")) for _, a := range as { prefix := "\t" if inst.classAttrs[a] { prefix = "*\t" } buffer.WriteString(fmt.Sprintf("%s%s\n", prefix, a.attr)) } buffer.WriteString("\nData:\n") maxRows := 30 if rows < maxRows { maxRows = rows } for i := 0; i < maxRows; i++ { buffer.WriteString("\t") for _, a := range as { val := inst.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", "(", "inst", "*", "DenseInstances", ")", "String", "(", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n\n", "// Get all Attribute information", "as", ":=", "ResolveAllAttributes", "(", "inst", ")", "\n\n", "// Print header", "cols", ",", "rows", ":=", "inst", ".", "Size", "(", ")", "\n", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rows", ")", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "cols", ")", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ")", ")", "\n\n", "for", "_", ",", "a", ":=", "range", "as", "{", "prefix", ":=", "\"", "\\t", "\"", "\n", "if", "inst", ".", "classAttrs", "[", "a", "]", "{", "prefix", "=", "\"", "\\t", "\"", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "prefix", ",", "a", ".", "attr", ")", ")", "\n", "}", "\n\n", "buffer", ".", "WriteString", "(", "\"", "\\n", "\\n", "\"", ")", "\n", "maxRows", ":=", "30", "\n", "if", "rows", "<", "maxRows", "{", "maxRows", "=", "rows", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "maxRows", ";", "i", "++", "{", "buffer", ".", "WriteString", "(", "\"", "\\t", "\"", ")", "\n", "for", "_", ",", "a", ":=", "range", "as", "{", "val", ":=", "inst", ".", "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 dataset.
[ "String", "returns", "a", "human", "-", "readable", "summary", "of", "this", "dataset", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/dense.go#L498-L542
164,759
sjwhitworth/golearn
filters/float.go
NewFloatConvertFilter
func NewFloatConvertFilter() *FloatConvertFilter { ret := &FloatConvertFilter{ make([]base.Attribute, 0), make([]base.FilteredAttribute, 0), make(map[base.Attribute]bool), make(map[base.Attribute]map[uint64]base.Attribute), } return ret }
go
func NewFloatConvertFilter() *FloatConvertFilter { ret := &FloatConvertFilter{ make([]base.Attribute, 0), make([]base.FilteredAttribute, 0), make(map[base.Attribute]bool), make(map[base.Attribute]map[uint64]base.Attribute), } return ret }
[ "func", "NewFloatConvertFilter", "(", ")", "*", "FloatConvertFilter", "{", "ret", ":=", "&", "FloatConvertFilter", "{", "make", "(", "[", "]", "base", ".", "Attribute", ",", "0", ")", ",", "make", "(", "[", "]", "base", ".", "FilteredAttribute", ",", "0", ")", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "bool", ")", ",", "make", "(", "map", "[", "base", ".", "Attribute", "]", "map", "[", "uint64", "]", "base", ".", "Attribute", ")", ",", "}", "\n", "return", "ret", "\n", "}" ]
// NewFloatConvertFilter creates a blank FloatConvertFilter
[ "NewFloatConvertFilter", "creates", "a", "blank", "FloatConvertFilter" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/float.go#L24-L32
164,760
sjwhitworth/golearn
base/float.go
MarshalJSON
func (f *FloatAttribute) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "type": "float", "name": f.Name, "attr": map[string]interface{}{ "precision": f.Precision, }, }) }
go
func (f *FloatAttribute) MarshalJSON() ([]byte, error) { return json.Marshal(map[string]interface{}{ "type": "float", "name": f.Name, "attr": map[string]interface{}{ "precision": f.Precision, }, }) }
[ "func", "(", "f", "*", "FloatAttribute", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "f", ".", "Name", ",", "\"", "\"", ":", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "f", ".", "Precision", ",", "}", ",", "}", ")", "\n", "}" ]
// MarshalJSON returns a JSON representation of this Attribute // for serialisation.
[ "MarshalJSON", "returns", "a", "JSON", "representation", "of", "this", "Attribute", "for", "serialisation", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/float.go#L18-L26
164,761
sjwhitworth/golearn
base/float.go
UnmarshalJSON
func (f *FloatAttribute) UnmarshalJSON(data []byte) error { var d map[string]interface{} err := json.Unmarshal(data, &d) if err != nil { return err } if precision, ok := d["precision"]; ok { f.Precision = int(precision.(float64)) return nil } return fmt.Errorf("Precision must be specified") }
go
func (f *FloatAttribute) UnmarshalJSON(data []byte) error { var d map[string]interface{} err := json.Unmarshal(data, &d) if err != nil { return err } if precision, ok := d["precision"]; ok { f.Precision = int(precision.(float64)) return nil } return fmt.Errorf("Precision must be specified") }
[ "func", "(", "f", "*", "FloatAttribute", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "var", "d", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "d", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "precision", ",", "ok", ":=", "d", "[", "\"", "\"", "]", ";", "ok", "{", "f", ".", "Precision", "=", "int", "(", "precision", ".", "(", "float64", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// UnmarshalJSON reads a JSON representation of this Attribute.
[ "UnmarshalJSON", "reads", "a", "JSON", "representation", "of", "this", "Attribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/float.go#L29-L40
164,762
sjwhitworth/golearn
base/float.go
Equals
func (Attr *FloatAttribute) Equals(other Attribute) bool { // Check whether this FloatAttribute is equal to another _, ok := other.(*FloatAttribute) if !ok { // Not the same type, so can't be equal return false } if Attr.GetName() != other.GetName() { return false } return true }
go
func (Attr *FloatAttribute) Equals(other Attribute) bool { // Check whether this FloatAttribute is equal to another _, ok := other.(*FloatAttribute) if !ok { // Not the same type, so can't be equal return false } if Attr.GetName() != other.GetName() { return false } return true }
[ "func", "(", "Attr", "*", "FloatAttribute", ")", "Equals", "(", "other", "Attribute", ")", "bool", "{", "// Check whether this FloatAttribute is equal to another", "_", ",", "ok", ":=", "other", ".", "(", "*", "FloatAttribute", ")", "\n", "if", "!", "ok", "{", "// Not the same type, so can't be equal", "return", "false", "\n", "}", "\n", "if", "Attr", ".", "GetName", "(", ")", "!=", "other", ".", "GetName", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equals tests a FloatAttribute for equality with another Attribute. // // Returns false if the other Attribute has a different name // or if the other Attribute is not a FloatAttribute.
[ "Equals", "tests", "a", "FloatAttribute", "for", "equality", "with", "another", "Attribute", ".", "Returns", "false", "if", "the", "other", "Attribute", "has", "a", "different", "name", "or", "if", "the", "other", "Attribute", "is", "not", "a", "FloatAttribute", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/float.go#L59-L70
164,763
sjwhitworth/golearn
base/float.go
CheckSysValFromString
func (Attr *FloatAttribute) CheckSysValFromString(rawVal string) ([]byte, error) { f, err := strconv.ParseFloat(rawVal, 64) if err != nil { return nil, err } ret := PackFloatToBytes(f) return ret, nil }
go
func (Attr *FloatAttribute) CheckSysValFromString(rawVal string) ([]byte, error) { f, err := strconv.ParseFloat(rawVal, 64) if err != nil { return nil, err } ret := PackFloatToBytes(f) return ret, nil }
[ "func", "(", "Attr", "*", "FloatAttribute", ")", "CheckSysValFromString", "(", "rawVal", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "f", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "rawVal", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ret", ":=", "PackFloatToBytes", "(", "f", ")", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// CheckSysValFromString confirms whether a given rawVal can // be converted into a valid system representation. If it can't, // the returned value is nil.
[ "CheckSysValFromString", "confirms", "whether", "a", "given", "rawVal", "can", "be", "converted", "into", "a", "valid", "system", "representation", ".", "If", "it", "can", "t", "the", "returned", "value", "is", "nil", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/float.go#L96-L104
164,764
sjwhitworth/golearn
base/float.go
GetStringFromSysVal
func (Attr *FloatAttribute) GetStringFromSysVal(rawVal []byte) string { f := UnpackBytesToFloat(rawVal) formatString := fmt.Sprintf("%%.%df", Attr.Precision) return fmt.Sprintf(formatString, f) }
go
func (Attr *FloatAttribute) GetStringFromSysVal(rawVal []byte) string { f := UnpackBytesToFloat(rawVal) formatString := fmt.Sprintf("%%.%df", Attr.Precision) return fmt.Sprintf(formatString, f) }
[ "func", "(", "Attr", "*", "FloatAttribute", ")", "GetStringFromSysVal", "(", "rawVal", "[", "]", "byte", ")", "string", "{", "f", ":=", "UnpackBytesToFloat", "(", "rawVal", ")", "\n", "formatString", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "Attr", ".", "Precision", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "formatString", ",", "f", ")", "\n", "}" ]
// GetStringFromSysVal converts a given system value to to a string with two decimal // places of precision.
[ "GetStringFromSysVal", "converts", "a", "given", "system", "value", "to", "to", "a", "string", "with", "two", "decimal", "places", "of", "precision", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/float.go#L126-L130
164,765
sjwhitworth/golearn
neural/network.go
NewNetwork
func NewNetwork(size int, input int, f NeuralFunction) *Network { ret := new(Network) ret.weights = mat.NewDense(size, size, make([]float64, size*size)) ret.biases = make([]float64, size) ret.funcs = make([]NeuralFunction, size) ret.size = size ret.input = input for i := range ret.funcs { ret.funcs[i] = f } for i := 0; i < input; i++ { ret.funcs[i] = Linear ret.SetWeight(i+1, i+1, 1.0) } return ret }
go
func NewNetwork(size int, input int, f NeuralFunction) *Network { ret := new(Network) ret.weights = mat.NewDense(size, size, make([]float64, size*size)) ret.biases = make([]float64, size) ret.funcs = make([]NeuralFunction, size) ret.size = size ret.input = input for i := range ret.funcs { ret.funcs[i] = f } for i := 0; i < input; i++ { ret.funcs[i] = Linear ret.SetWeight(i+1, i+1, 1.0) } return ret }
[ "func", "NewNetwork", "(", "size", "int", ",", "input", "int", ",", "f", "NeuralFunction", ")", "*", "Network", "{", "ret", ":=", "new", "(", "Network", ")", "\n", "ret", ".", "weights", "=", "mat", ".", "NewDense", "(", "size", ",", "size", ",", "make", "(", "[", "]", "float64", ",", "size", "*", "size", ")", ")", "\n", "ret", ".", "biases", "=", "make", "(", "[", "]", "float64", ",", "size", ")", "\n", "ret", ".", "funcs", "=", "make", "(", "[", "]", "NeuralFunction", ",", "size", ")", "\n", "ret", ".", "size", "=", "size", "\n", "ret", ".", "input", "=", "input", "\n", "for", "i", ":=", "range", "ret", ".", "funcs", "{", "ret", ".", "funcs", "[", "i", "]", "=", "f", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "input", ";", "i", "++", "{", "ret", ".", "funcs", "[", "i", "]", "=", "Linear", "\n", "ret", ".", "SetWeight", "(", "i", "+", "1", ",", "i", "+", "1", ",", "1.0", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// NewNetwork creates a new Network containing size neurons, // with a certain number dedicated to input, and a pre-defined // neural function applied to the rest. // // Input nodes are set to have a Linear NeuralFunction and are // connected to themselves for propagation.
[ "NewNetwork", "creates", "a", "new", "Network", "containing", "size", "neurons", "with", "a", "certain", "number", "dedicated", "to", "input", "and", "a", "pre", "-", "defined", "neural", "function", "applied", "to", "the", "rest", ".", "Input", "nodes", "are", "set", "to", "have", "a", "Linear", "NeuralFunction", "and", "are", "connected", "to", "themselves", "for", "propagation", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/neural/network.go#L28-L43
164,766
sjwhitworth/golearn
neural/network.go
String
func (n *Network) String() string { var buf bytes.Buffer var biases bytes.Buffer for i := 0; i < n.size; i++ { for j := 0; j < n.size; j++ { v := n.weights.At(j, i) if math.Abs(v) > 0 { buf.WriteString(fmt.Sprintf("\t(%d %d %.2f)\n", i+1, j+1, v)) } } } for _, v := range n.biases { biases.WriteString(fmt.Sprintf(" %.2f", v)) } return fmt.Sprintf("Network(%d, %s, %s)", n.size, biases.String(), buf.String()) }
go
func (n *Network) String() string { var buf bytes.Buffer var biases bytes.Buffer for i := 0; i < n.size; i++ { for j := 0; j < n.size; j++ { v := n.weights.At(j, i) if math.Abs(v) > 0 { buf.WriteString(fmt.Sprintf("\t(%d %d %.2f)\n", i+1, j+1, v)) } } } for _, v := range n.biases { biases.WriteString(fmt.Sprintf(" %.2f", v)) } return fmt.Sprintf("Network(%d, %s, %s)", n.size, biases.String(), buf.String()) }
[ "func", "(", "n", "*", "Network", ")", "String", "(", ")", "string", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "var", "biases", "bytes", ".", "Buffer", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "n", ".", "size", ";", "i", "++", "{", "for", "j", ":=", "0", ";", "j", "<", "n", ".", "size", ";", "j", "++", "{", "v", ":=", "n", ".", "weights", ".", "At", "(", "j", ",", "i", ")", "\n", "if", "math", ".", "Abs", "(", "v", ")", ">", "0", "{", "buf", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\t", "\\n", "\"", ",", "i", "+", "1", ",", "j", "+", "1", ",", "v", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "v", ":=", "range", "n", ".", "biases", "{", "biases", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ")", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ".", "size", ",", "biases", ".", "String", "(", ")", ",", "buf", ".", "String", "(", ")", ")", "\n", "}" ]
// String gets a human-readable representation of this network.
[ "String", "gets", "a", "human", "-", "readable", "representation", "of", "this", "network", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/neural/network.go#L46-L64
164,767
sjwhitworth/golearn
meta/bagging.go
generateTrainingAttrs
func (b *BaggedModel) generateTrainingAttrs(model int, from base.FixedDataGrid) []base.Attribute { ret := make([]base.Attribute, 0) attrs := base.NonClassAttributes(from) if b.RandomFeatures == 0 { ret = attrs } else { for { if len(ret) >= b.RandomFeatures { break } attrIndex := rand.Intn(len(attrs)) attr := attrs[attrIndex] matched := false for _, a := range ret { if a.Equals(attr) { matched = true break } } if !matched { ret = append(ret, attr) } } } for _, a := range from.AllClassAttributes() { ret = append(ret, a) } b.lock.Lock() b.selectedAttributes[model] = ret b.lock.Unlock() return ret }
go
func (b *BaggedModel) generateTrainingAttrs(model int, from base.FixedDataGrid) []base.Attribute { ret := make([]base.Attribute, 0) attrs := base.NonClassAttributes(from) if b.RandomFeatures == 0 { ret = attrs } else { for { if len(ret) >= b.RandomFeatures { break } attrIndex := rand.Intn(len(attrs)) attr := attrs[attrIndex] matched := false for _, a := range ret { if a.Equals(attr) { matched = true break } } if !matched { ret = append(ret, attr) } } } for _, a := range from.AllClassAttributes() { ret = append(ret, a) } b.lock.Lock() b.selectedAttributes[model] = ret b.lock.Unlock() return ret }
[ "func", "(", "b", "*", "BaggedModel", ")", "generateTrainingAttrs", "(", "model", "int", ",", "from", "base", ".", "FixedDataGrid", ")", "[", "]", "base", ".", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "base", ".", "Attribute", ",", "0", ")", "\n", "attrs", ":=", "base", ".", "NonClassAttributes", "(", "from", ")", "\n", "if", "b", ".", "RandomFeatures", "==", "0", "{", "ret", "=", "attrs", "\n", "}", "else", "{", "for", "{", "if", "len", "(", "ret", ")", ">=", "b", ".", "RandomFeatures", "{", "break", "\n", "}", "\n", "attrIndex", ":=", "rand", ".", "Intn", "(", "len", "(", "attrs", ")", ")", "\n", "attr", ":=", "attrs", "[", "attrIndex", "]", "\n", "matched", ":=", "false", "\n", "for", "_", ",", "a", ":=", "range", "ret", "{", "if", "a", ".", "Equals", "(", "attr", ")", "{", "matched", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "matched", "{", "ret", "=", "append", "(", "ret", ",", "attr", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "a", ":=", "range", "from", ".", "AllClassAttributes", "(", ")", "{", "ret", "=", "append", "(", "ret", ",", "a", ")", "\n", "}", "\n", "b", ".", "lock", ".", "Lock", "(", ")", "\n", "b", ".", "selectedAttributes", "[", "model", "]", "=", "ret", "\n", "b", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "ret", "\n", "}" ]
// generateTrainingAttrs selects RandomFeatures number of base.Attributes from // the provided base.Instances.
[ "generateTrainingAttrs", "selects", "RandomFeatures", "number", "of", "base", ".", "Attributes", "from", "the", "provided", "base", ".", "Instances", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/meta/bagging.go#L25-L56
164,768
sjwhitworth/golearn
meta/bagging.go
generatePredictionInstances
func (b *BaggedModel) generatePredictionInstances(model int, from base.FixedDataGrid) base.FixedDataGrid { selected := b.selectedAttributes[model] return base.NewInstancesViewFromAttrs(from, selected) }
go
func (b *BaggedModel) generatePredictionInstances(model int, from base.FixedDataGrid) base.FixedDataGrid { selected := b.selectedAttributes[model] return base.NewInstancesViewFromAttrs(from, selected) }
[ "func", "(", "b", "*", "BaggedModel", ")", "generatePredictionInstances", "(", "model", "int", ",", "from", "base", ".", "FixedDataGrid", ")", "base", ".", "FixedDataGrid", "{", "selected", ":=", "b", ".", "selectedAttributes", "[", "model", "]", "\n", "return", "base", ".", "NewInstancesViewFromAttrs", "(", "from", ",", "selected", ")", "\n", "}" ]
// generatePredictionInstances returns a modified version of the // requested base.Instances with only the base.Attributes selected // for training the model.
[ "generatePredictionInstances", "returns", "a", "modified", "version", "of", "the", "requested", "base", ".", "Instances", "with", "only", "the", "base", ".", "Attributes", "selected", "for", "training", "the", "model", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/meta/bagging.go#L61-L64
164,769
sjwhitworth/golearn
meta/bagging.go
generateTrainingInstances
func (b *BaggedModel) generateTrainingInstances(model int, from base.FixedDataGrid) base.FixedDataGrid { _, rows := from.Size() insts := base.SampleWithReplacement(from, rows) selected := b.generateTrainingAttrs(model, from) return base.NewInstancesViewFromAttrs(insts, selected) }
go
func (b *BaggedModel) generateTrainingInstances(model int, from base.FixedDataGrid) base.FixedDataGrid { _, rows := from.Size() insts := base.SampleWithReplacement(from, rows) selected := b.generateTrainingAttrs(model, from) return base.NewInstancesViewFromAttrs(insts, selected) }
[ "func", "(", "b", "*", "BaggedModel", ")", "generateTrainingInstances", "(", "model", "int", ",", "from", "base", ".", "FixedDataGrid", ")", "base", ".", "FixedDataGrid", "{", "_", ",", "rows", ":=", "from", ".", "Size", "(", ")", "\n", "insts", ":=", "base", ".", "SampleWithReplacement", "(", "from", ",", "rows", ")", "\n", "selected", ":=", "b", ".", "generateTrainingAttrs", "(", "model", ",", "from", ")", "\n", "return", "base", ".", "NewInstancesViewFromAttrs", "(", "insts", ",", "selected", ")", "\n", "}" ]
// generateTrainingInstances generates RandomFeatures number of // attributes and returns a modified version of base.Instances // for training the model
[ "generateTrainingInstances", "generates", "RandomFeatures", "number", "of", "attributes", "and", "returns", "a", "modified", "version", "of", "base", ".", "Instances", "for", "training", "the", "model" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/meta/bagging.go#L69-L74
164,770
sjwhitworth/golearn
meta/bagging.go
AddModel
func (b *BaggedModel) AddModel(m base.Classifier) { b.Models = append(b.Models, m) }
go
func (b *BaggedModel) AddModel(m base.Classifier) { b.Models = append(b.Models, m) }
[ "func", "(", "b", "*", "BaggedModel", ")", "AddModel", "(", "m", "base", ".", "Classifier", ")", "{", "b", ".", "Models", "=", "append", "(", "b", ".", "Models", ",", "m", ")", "\n", "}" ]
// AddModel adds a base.Classifier to the current model
[ "AddModel", "adds", "a", "base", ".", "Classifier", "to", "the", "current", "model" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/meta/bagging.go#L77-L79
164,771
sjwhitworth/golearn
meta/bagging.go
Fit
func (b *BaggedModel) Fit(from base.FixedDataGrid) { var wait sync.WaitGroup b.selectedAttributes = make(map[int][]base.Attribute) for i, m := range b.Models { wait.Add(1) go func(c base.Classifier, f base.FixedDataGrid, model int) { l := b.generateTrainingInstances(model, f) c.Fit(l) wait.Done() }(m, from, i) } wait.Wait() b.fitOn = base.NewStructuralCopy(from) }
go
func (b *BaggedModel) Fit(from base.FixedDataGrid) { var wait sync.WaitGroup b.selectedAttributes = make(map[int][]base.Attribute) for i, m := range b.Models { wait.Add(1) go func(c base.Classifier, f base.FixedDataGrid, model int) { l := b.generateTrainingInstances(model, f) c.Fit(l) wait.Done() }(m, from, i) } wait.Wait() b.fitOn = base.NewStructuralCopy(from) }
[ "func", "(", "b", "*", "BaggedModel", ")", "Fit", "(", "from", "base", ".", "FixedDataGrid", ")", "{", "var", "wait", "sync", ".", "WaitGroup", "\n", "b", ".", "selectedAttributes", "=", "make", "(", "map", "[", "int", "]", "[", "]", "base", ".", "Attribute", ")", "\n", "for", "i", ",", "m", ":=", "range", "b", ".", "Models", "{", "wait", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "c", "base", ".", "Classifier", ",", "f", "base", ".", "FixedDataGrid", ",", "model", "int", ")", "{", "l", ":=", "b", ".", "generateTrainingInstances", "(", "model", ",", "f", ")", "\n", "c", ".", "Fit", "(", "l", ")", "\n", "wait", ".", "Done", "(", ")", "\n", "}", "(", "m", ",", "from", ",", "i", ")", "\n", "}", "\n", "wait", ".", "Wait", "(", ")", "\n", "b", ".", "fitOn", "=", "base", ".", "NewStructuralCopy", "(", "from", ")", "\n", "}" ]
// Fit generates and trains each model on a randomised subset of // Instances.
[ "Fit", "generates", "and", "trains", "each", "model", "on", "a", "randomised", "subset", "of", "Instances", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/meta/bagging.go#L83-L96
164,772
sjwhitworth/golearn
meta/bagging.go
String
func (b *BaggedModel) String() string { children := make([]string, 0) for i, m := range b.Models { children = append(children, fmt.Sprintf("%d: %s", i, m)) } return fmt.Sprintf("BaggedModel(\n%s)", strings.Join(children, "\n\t")) }
go
func (b *BaggedModel) String() string { children := make([]string, 0) for i, m := range b.Models { children = append(children, fmt.Sprintf("%d: %s", i, m)) } return fmt.Sprintf("BaggedModel(\n%s)", strings.Join(children, "\n\t")) }
[ "func", "(", "b", "*", "BaggedModel", ")", "String", "(", ")", "string", "{", "children", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "for", "i", ",", "m", ":=", "range", "b", ".", "Models", "{", "children", "=", "append", "(", "children", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "i", ",", "m", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "strings", ".", "Join", "(", "children", ",", "\"", "\\n", "\\t", "\"", ")", ")", "\n", "}" ]
// String returns a human-readable representation of the // BaggedModel and everything it contains
[ "String", "returns", "a", "human", "-", "readable", "representation", "of", "the", "BaggedModel", "and", "everything", "it", "contains" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/meta/bagging.go#L184-L190
164,773
sjwhitworth/golearn
metrics/pairwise/euclidean.go
InnerProduct
func (e *Euclidean) InnerProduct(vectorX *mat.Dense, vectorY *mat.Dense) float64 { subVector := mat.NewDense(1, 1, nil) subVector.Reset() subVector.MulElem(vectorX, vectorY) result := mat.Sum(subVector) return result }
go
func (e *Euclidean) InnerProduct(vectorX *mat.Dense, vectorY *mat.Dense) float64 { subVector := mat.NewDense(1, 1, nil) subVector.Reset() subVector.MulElem(vectorX, vectorY) result := mat.Sum(subVector) return result }
[ "func", "(", "e", "*", "Euclidean", ")", "InnerProduct", "(", "vectorX", "*", "mat", ".", "Dense", ",", "vectorY", "*", "mat", ".", "Dense", ")", "float64", "{", "subVector", ":=", "mat", ".", "NewDense", "(", "1", ",", "1", ",", "nil", ")", "\n", "subVector", ".", "Reset", "(", ")", "\n", "subVector", ".", "MulElem", "(", "vectorX", ",", "vectorY", ")", "\n", "result", ":=", "mat", ".", "Sum", "(", "subVector", ")", "\n\n", "return", "result", "\n", "}" ]
// InnerProduct computes a Eucledian inner product.
[ "InnerProduct", "computes", "a", "Eucledian", "inner", "product", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/metrics/pairwise/euclidean.go#L16-L23
164,774
sjwhitworth/golearn
base/filewrapper.go
ParseCSVGetRows
func ParseCSVGetRows(filepath string) (int, error) { f, err := os.Open(filepath) if err != nil { return 0, err } defer f.Close() return ParseCSVGetRowsFromReader(f) }
go
func ParseCSVGetRows(filepath string) (int, error) { f, err := os.Open(filepath) if err != nil { return 0, err } defer f.Close() return ParseCSVGetRowsFromReader(f) }
[ "func", "ParseCSVGetRows", "(", "filepath", "string", ")", "(", "int", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVGetRowsFromReader", "(", "f", ")", "\n", "}" ]
// ParseCSVGetRows returns the number of rows in a given file.
[ "ParseCSVGetRows", "returns", "the", "number", "of", "rows", "in", "a", "given", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L8-L16
164,775
sjwhitworth/golearn
base/filewrapper.go
ParseCSVEstimateFilePrecision
func ParseCSVEstimateFilePrecision(filepath string) (int, error) { // Open the source file f, err := os.Open(filepath) if err != nil { return 0, err } defer f.Close() return ParseCSVEstimateFilePrecisionFromReader(f) }
go
func ParseCSVEstimateFilePrecision(filepath string) (int, error) { // Open the source file f, err := os.Open(filepath) if err != nil { return 0, err } defer f.Close() return ParseCSVEstimateFilePrecisionFromReader(f) }
[ "func", "ParseCSVEstimateFilePrecision", "(", "filepath", "string", ")", "(", "int", ",", "error", ")", "{", "// Open the source file", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVEstimateFilePrecisionFromReader", "(", "f", ")", "\n", "}" ]
// ParseCSVEstimateFilePrecision determines what the maximum number of // digits occuring anywhere after the decimal point within the file.
[ "ParseCSVEstimateFilePrecision", "determines", "what", "the", "maximum", "number", "of", "digits", "occuring", "anywhere", "after", "the", "decimal", "point", "within", "the", "file", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L20-L29
164,776
sjwhitworth/golearn
base/filewrapper.go
ParseCSVGetAttributes
func ParseCSVGetAttributes(filepath string, hasHeaders bool) []Attribute { f, err := os.Open(filepath) if err != nil { panic(err) } defer f.Close() return ParseCSVGetAttributesFromReader(f, hasHeaders) }
go
func ParseCSVGetAttributes(filepath string, hasHeaders bool) []Attribute { f, err := os.Open(filepath) if err != nil { panic(err) } defer f.Close() return ParseCSVGetAttributesFromReader(f, hasHeaders) }
[ "func", "ParseCSVGetAttributes", "(", "filepath", "string", ",", "hasHeaders", "bool", ")", "[", "]", "Attribute", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVGetAttributesFromReader", "(", "f", ",", "hasHeaders", ")", "\n", "}" ]
// ParseCSVGetAttributes returns an ordered slice of appropriate-ly typed // and named Attributes.
[ "ParseCSVGetAttributes", "returns", "an", "ordered", "slice", "of", "appropriate", "-", "ly", "typed", "and", "named", "Attributes", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L33-L41
164,777
sjwhitworth/golearn
base/filewrapper.go
ParseCSVSniffAttributeNames
func ParseCSVSniffAttributeNames(filepath string, hasHeaders bool) []string { f, err := os.Open(filepath) if err != nil { panic(err) } defer f.Close() return ParseCSVSniffAttributeNamesFromReader(f, hasHeaders) }
go
func ParseCSVSniffAttributeNames(filepath string, hasHeaders bool) []string { f, err := os.Open(filepath) if err != nil { panic(err) } defer f.Close() return ParseCSVSniffAttributeNamesFromReader(f, hasHeaders) }
[ "func", "ParseCSVSniffAttributeNames", "(", "filepath", "string", ",", "hasHeaders", "bool", ")", "[", "]", "string", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVSniffAttributeNamesFromReader", "(", "f", ",", "hasHeaders", ")", "\n", "}" ]
// ParseCSVSniffAttributeNames returns a slice containing the top row // of a given CSV file, or placeholders if hasHeaders is false.
[ "ParseCSVSniffAttributeNames", "returns", "a", "slice", "containing", "the", "top", "row", "of", "a", "given", "CSV", "file", "or", "placeholders", "if", "hasHeaders", "is", "false", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L45-L53
164,778
sjwhitworth/golearn
base/filewrapper.go
ParseCSVSniffAttributeTypes
func ParseCSVSniffAttributeTypes(filepath string, hasHeaders bool) []Attribute { // Open file f, err := os.Open(filepath) if err != nil { panic(err) } defer f.Close() return ParseCSVSniffAttributeTypesFromReader(f, hasHeaders) }
go
func ParseCSVSniffAttributeTypes(filepath string, hasHeaders bool) []Attribute { // Open file f, err := os.Open(filepath) if err != nil { panic(err) } defer f.Close() return ParseCSVSniffAttributeTypesFromReader(f, hasHeaders) }
[ "func", "ParseCSVSniffAttributeTypes", "(", "filepath", "string", ",", "hasHeaders", "bool", ")", "[", "]", "Attribute", "{", "// Open file", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVSniffAttributeTypesFromReader", "(", "f", ",", "hasHeaders", ")", "\n", "}" ]
// ParseCSVSniffAttributeTypes returns a slice of appropriately-typed Attributes. // // The type of a given attribute is determined by looking at the first data row // of the CSV.
[ "ParseCSVSniffAttributeTypes", "returns", "a", "slice", "of", "appropriately", "-", "typed", "Attributes", ".", "The", "type", "of", "a", "given", "attribute", "is", "determined", "by", "looking", "at", "the", "first", "data", "row", "of", "the", "CSV", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L59-L68
164,779
sjwhitworth/golearn
base/filewrapper.go
ParseCSVToInstances
func ParseCSVToInstances(filepath string, hasHeaders bool) (instances *DenseInstances, err error) { // Open the file f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() return ParseCSVToInstancesFromReader(f, hasHeaders) }
go
func ParseCSVToInstances(filepath string, hasHeaders bool) (instances *DenseInstances, err error) { // Open the file f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() return ParseCSVToInstancesFromReader(f, hasHeaders) }
[ "func", "ParseCSVToInstances", "(", "filepath", "string", ",", "hasHeaders", "bool", ")", "(", "instances", "*", "DenseInstances", ",", "err", "error", ")", "{", "// Open the file", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVToInstancesFromReader", "(", "f", ",", "hasHeaders", ")", "\n", "}" ]
// ParseCSVToInstances reads the CSV file given by filepath and returns // the read Instances.
[ "ParseCSVToInstances", "reads", "the", "CSV", "file", "given", "by", "filepath", "and", "returns", "the", "read", "Instances", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L72-L81
164,780
sjwhitworth/golearn
base/filewrapper.go
ParseCSVToTemplatedInstances
func ParseCSVToTemplatedInstances(filepath string, hasHeaders bool, template *DenseInstances) (instances *DenseInstances, err error) { // Open the file f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() return ParseCSVToTemplatedInstancesFromReader(f, hasHeaders, template) }
go
func ParseCSVToTemplatedInstances(filepath string, hasHeaders bool, template *DenseInstances) (instances *DenseInstances, err error) { // Open the file f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() return ParseCSVToTemplatedInstancesFromReader(f, hasHeaders, template) }
[ "func", "ParseCSVToTemplatedInstances", "(", "filepath", "string", ",", "hasHeaders", "bool", ",", "template", "*", "DenseInstances", ")", "(", "instances", "*", "DenseInstances", ",", "err", "error", ")", "{", "// Open the file", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVToTemplatedInstancesFromReader", "(", "f", ",", "hasHeaders", ",", "template", ")", "\n", "}" ]
// ParseCSVToInstancesTemplated reads the CSV file given by filepath and returns // the read Instances, using another already read DenseInstances as a template.
[ "ParseCSVToInstancesTemplated", "reads", "the", "CSV", "file", "given", "by", "filepath", "and", "returns", "the", "read", "Instances", "using", "another", "already", "read", "DenseInstances", "as", "a", "template", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L85-L94
164,781
sjwhitworth/golearn
base/filewrapper.go
ParseCSVToInstancesWithAttributeGroups
func ParseCSVToInstancesWithAttributeGroups(filepath string, attrGroups, classAttrGroups map[string]string, attrOverrides map[int]Attribute, hasHeaders bool) (instances *DenseInstances, err error) { // Open file f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() return ParseCSVToInstancesWithAttributeGroupsFromReader(f, attrGroups, classAttrGroups, attrOverrides, hasHeaders) }
go
func ParseCSVToInstancesWithAttributeGroups(filepath string, attrGroups, classAttrGroups map[string]string, attrOverrides map[int]Attribute, hasHeaders bool) (instances *DenseInstances, err error) { // Open file f, err := os.Open(filepath) if err != nil { return nil, err } defer f.Close() return ParseCSVToInstancesWithAttributeGroupsFromReader(f, attrGroups, classAttrGroups, attrOverrides, hasHeaders) }
[ "func", "ParseCSVToInstancesWithAttributeGroups", "(", "filepath", "string", ",", "attrGroups", ",", "classAttrGroups", "map", "[", "string", "]", "string", ",", "attrOverrides", "map", "[", "int", "]", "Attribute", ",", "hasHeaders", "bool", ")", "(", "instances", "*", "DenseInstances", ",", "err", "error", ")", "{", "// Open file", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "ParseCSVToInstancesWithAttributeGroupsFromReader", "(", "f", ",", "attrGroups", ",", "classAttrGroups", ",", "attrOverrides", ",", "hasHeaders", ")", "\n", "}" ]
// ParseCSVToInstancesWithAttributeGroups reads the CSV file given by filepath, // and returns the read DenseInstances, but also makes sure to group any Attributes // specified in the first argument and also any class Attributes specified in the second
[ "ParseCSVToInstancesWithAttributeGroups", "reads", "the", "CSV", "file", "given", "by", "filepath", "and", "returns", "the", "read", "DenseInstances", "but", "also", "makes", "sure", "to", "group", "any", "Attributes", "specified", "in", "the", "first", "argument", "and", "also", "any", "class", "Attributes", "specified", "in", "the", "second" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filewrapper.go#L99-L108
164,782
sjwhitworth/golearn
naive/bernoulli_nb.go
NewBernoulliNBClassifier
func NewBernoulliNBClassifier() *BernoulliNBClassifier { nb := BernoulliNBClassifier{} nb.condProb = make(map[string][]float64) nb.features = 0 nb.trainingInstances = 0 return &nb }
go
func NewBernoulliNBClassifier() *BernoulliNBClassifier { nb := BernoulliNBClassifier{} nb.condProb = make(map[string][]float64) nb.features = 0 nb.trainingInstances = 0 return &nb }
[ "func", "NewBernoulliNBClassifier", "(", ")", "*", "BernoulliNBClassifier", "{", "nb", ":=", "BernoulliNBClassifier", "{", "}", "\n", "nb", ".", "condProb", "=", "make", "(", "map", "[", "string", "]", "[", "]", "float64", ")", "\n", "nb", ".", "features", "=", "0", "\n", "nb", ".", "trainingInstances", "=", "0", "\n", "return", "&", "nb", "\n", "}" ]
// Create a new Bernoulli Naive Bayes Classifier. The argument 'classes' // is the number of possible labels in the classification task.
[ "Create", "a", "new", "Bernoulli", "Naive", "Bayes", "Classifier", ".", "The", "argument", "classes", "is", "the", "number", "of", "possible", "labels", "in", "the", "classification", "task", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/naive/bernoulli_nb.go#L175-L181
164,783
sjwhitworth/golearn
clustering/clustering.go
Invert
func (ref ClusterMap) Invert() (map[int]int, error) { ret := make(map[int]int) for c := range ref { for _, p := range ref[c] { if _, ok := ret[p]; ok { return nil, fmt.Errorf("Not a valid cluster map (points appear in more than one cluster)") } else { ret[p] = c } } } return ret, nil }
go
func (ref ClusterMap) Invert() (map[int]int, error) { ret := make(map[int]int) for c := range ref { for _, p := range ref[c] { if _, ok := ret[p]; ok { return nil, fmt.Errorf("Not a valid cluster map (points appear in more than one cluster)") } else { ret[p] = c } } } return ret, nil }
[ "func", "(", "ref", "ClusterMap", ")", "Invert", "(", ")", "(", "map", "[", "int", "]", "int", ",", "error", ")", "{", "ret", ":=", "make", "(", "map", "[", "int", "]", "int", ")", "\n", "for", "c", ":=", "range", "ref", "{", "for", "_", ",", "p", ":=", "range", "ref", "[", "c", "]", "{", "if", "_", ",", "ok", ":=", "ret", "[", "p", "]", ";", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "else", "{", "ret", "[", "p", "]", "=", "c", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// Invert returns an alternative form of cluster map where the key represents the point // index and the value represents the cluster index it's assigned to
[ "Invert", "returns", "an", "alternative", "form", "of", "cluster", "map", "where", "the", "key", "represents", "the", "point", "index", "and", "the", "value", "represents", "the", "cluster", "index", "it", "s", "assigned", "to" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/clustering/clustering.go#L29-L41
164,784
sjwhitworth/golearn
filters/disc.go
AddAttribute
func (d *AbstractDiscretizeFilter) AddAttribute(a base.Attribute) error { if _, ok := a.(*base.FloatAttribute); !ok { return fmt.Errorf("%s is not a FloatAttribute", a) } _, err := d.train.GetAttribute(a) if err != nil { return fmt.Errorf("invalid attribute") } d.attrs[a] = true return nil }
go
func (d *AbstractDiscretizeFilter) AddAttribute(a base.Attribute) error { if _, ok := a.(*base.FloatAttribute); !ok { return fmt.Errorf("%s is not a FloatAttribute", a) } _, err := d.train.GetAttribute(a) if err != nil { return fmt.Errorf("invalid attribute") } d.attrs[a] = true return nil }
[ "func", "(", "d", "*", "AbstractDiscretizeFilter", ")", "AddAttribute", "(", "a", "base", ".", "Attribute", ")", "error", "{", "if", "_", ",", "ok", ":=", "a", ".", "(", "*", "base", ".", "FloatAttribute", ")", ";", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "a", ")", "\n", "}", "\n", "_", ",", "err", ":=", "d", ".", "train", ".", "GetAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "d", ".", "attrs", "[", "a", "]", "=", "true", "\n", "return", "nil", "\n", "}" ]
// AddAttribute adds the AttributeSpec of the given attribute `a' // to the AbstractFloatFilter for discretisation.
[ "AddAttribute", "adds", "the", "AttributeSpec", "of", "the", "given", "attribute", "a", "to", "the", "AbstractFloatFilter", "for", "discretisation", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/filters/disc.go#L16-L26
164,785
sjwhitworth/golearn
metrics/pairwise/manhattan.go
Distance
func (m *Manhattan) Distance(vectorX *mat.Dense, vectorY *mat.Dense) float64 { r1, c1 := vectorX.Dims() r2, c2 := vectorY.Dims() if r1 != r2 || c1 != c2 { panic(matrix.ErrShape) } result := .0 for i := 0; i < r1; i++ { for j := 0; j < c1; j++ { result += math.Abs(vectorX.At(i, j) - vectorY.At(i, j)) } } return result }
go
func (m *Manhattan) Distance(vectorX *mat.Dense, vectorY *mat.Dense) float64 { r1, c1 := vectorX.Dims() r2, c2 := vectorY.Dims() if r1 != r2 || c1 != c2 { panic(matrix.ErrShape) } result := .0 for i := 0; i < r1; i++ { for j := 0; j < c1; j++ { result += math.Abs(vectorX.At(i, j) - vectorY.At(i, j)) } } return result }
[ "func", "(", "m", "*", "Manhattan", ")", "Distance", "(", "vectorX", "*", "mat", ".", "Dense", ",", "vectorY", "*", "mat", ".", "Dense", ")", "float64", "{", "r1", ",", "c1", ":=", "vectorX", ".", "Dims", "(", ")", "\n", "r2", ",", "c2", ":=", "vectorY", ".", "Dims", "(", ")", "\n", "if", "r1", "!=", "r2", "||", "c1", "!=", "c2", "{", "panic", "(", "matrix", ".", "ErrShape", ")", "\n", "}", "\n\n", "result", ":=", ".0", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "r1", ";", "i", "++", "{", "for", "j", ":=", "0", ";", "j", "<", "c1", ";", "j", "++", "{", "result", "+=", "math", ".", "Abs", "(", "vectorX", ".", "At", "(", "i", ",", "j", ")", "-", "vectorY", ".", "At", "(", "i", ",", "j", ")", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Distance computes the Manhattan distance, also known as L1 distance. // == the sum of the absolute values of elements.
[ "Distance", "computes", "the", "Manhattan", "distance", "also", "known", "as", "L1", "distance", ".", "==", "the", "sum", "of", "the", "absolute", "values", "of", "elements", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/metrics/pairwise/manhattan.go#L18-L33
164,786
sjwhitworth/golearn
base/filtered.go
NewLazilyFilteredInstances
func NewLazilyFilteredInstances(src FixedDataGrid, f Filter) *LazilyFilteredInstances { // Get the Attributes after filtering attrs := f.GetAttributesAfterFiltering() // Build a set of Attributes which have undergone filtering unFilteredMap := make(map[Attribute]bool) for _, a := range src.AllAttributes() { unFilteredMap[a] = true } for _, a := range attrs { unFilteredMap[a.Old] = false } // Create the return structure ret := &LazilyFilteredInstances{ f, src, attrs, make(map[Attribute]bool), unFilteredMap, } // Transfer class Attributes for _, a := range src.AllClassAttributes() { ret.AddClassAttribute(a) } return ret }
go
func NewLazilyFilteredInstances(src FixedDataGrid, f Filter) *LazilyFilteredInstances { // Get the Attributes after filtering attrs := f.GetAttributesAfterFiltering() // Build a set of Attributes which have undergone filtering unFilteredMap := make(map[Attribute]bool) for _, a := range src.AllAttributes() { unFilteredMap[a] = true } for _, a := range attrs { unFilteredMap[a.Old] = false } // Create the return structure ret := &LazilyFilteredInstances{ f, src, attrs, make(map[Attribute]bool), unFilteredMap, } // Transfer class Attributes for _, a := range src.AllClassAttributes() { ret.AddClassAttribute(a) } return ret }
[ "func", "NewLazilyFilteredInstances", "(", "src", "FixedDataGrid", ",", "f", "Filter", ")", "*", "LazilyFilteredInstances", "{", "// Get the Attributes after filtering", "attrs", ":=", "f", ".", "GetAttributesAfterFiltering", "(", ")", "\n\n", "// Build a set of Attributes which have undergone filtering", "unFilteredMap", ":=", "make", "(", "map", "[", "Attribute", "]", "bool", ")", "\n", "for", "_", ",", "a", ":=", "range", "src", ".", "AllAttributes", "(", ")", "{", "unFilteredMap", "[", "a", "]", "=", "true", "\n", "}", "\n", "for", "_", ",", "a", ":=", "range", "attrs", "{", "unFilteredMap", "[", "a", ".", "Old", "]", "=", "false", "\n", "}", "\n\n", "// Create the return structure", "ret", ":=", "&", "LazilyFilteredInstances", "{", "f", ",", "src", ",", "attrs", ",", "make", "(", "map", "[", "Attribute", "]", "bool", ")", ",", "unFilteredMap", ",", "}", "\n\n", "// Transfer class Attributes", "for", "_", ",", "a", ":=", "range", "src", ".", "AllClassAttributes", "(", ")", "{", "ret", ".", "AddClassAttribute", "(", "a", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// NewLazilyFitleredInstances returns a new FixedDataGrid after // applying the given Filter to the Attributes it includes. Unfiltered // Attributes are passed through without modification.
[ "NewLazilyFitleredInstances", "returns", "a", "new", "FixedDataGrid", "after", "applying", "the", "given", "Filter", "to", "the", "Attributes", "it", "includes", ".", "Unfiltered", "Attributes", "are", "passed", "through", "without", "modification", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filtered.go#L24-L52
164,787
sjwhitworth/golearn
base/filtered.go
GetAttribute
func (l *LazilyFilteredInstances) GetAttribute(target Attribute) (AttributeSpec, error) { if l.unfilteredMap[target] { return l.src.GetAttribute(target) } var ret AttributeSpec ret.pond = -1 for i, a := range l.attrs { if a.New.Equals(target) { ret.position = i ret.attr = target return ret, nil } } return ret, fmt.Errorf("Couldn't resolve %s", target) }
go
func (l *LazilyFilteredInstances) GetAttribute(target Attribute) (AttributeSpec, error) { if l.unfilteredMap[target] { return l.src.GetAttribute(target) } var ret AttributeSpec ret.pond = -1 for i, a := range l.attrs { if a.New.Equals(target) { ret.position = i ret.attr = target return ret, nil } } return ret, fmt.Errorf("Couldn't resolve %s", target) }
[ "func", "(", "l", "*", "LazilyFilteredInstances", ")", "GetAttribute", "(", "target", "Attribute", ")", "(", "AttributeSpec", ",", "error", ")", "{", "if", "l", ".", "unfilteredMap", "[", "target", "]", "{", "return", "l", ".", "src", ".", "GetAttribute", "(", "target", ")", "\n", "}", "\n", "var", "ret", "AttributeSpec", "\n", "ret", ".", "pond", "=", "-", "1", "\n", "for", "i", ",", "a", ":=", "range", "l", ".", "attrs", "{", "if", "a", ".", "New", ".", "Equals", "(", "target", ")", "{", "ret", ".", "position", "=", "i", "\n", "ret", ".", "attr", "=", "target", "\n", "return", "ret", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "ret", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "target", ")", "\n", "}" ]
// GetAttribute returns an AttributeSpecification for a given Attribute
[ "GetAttribute", "returns", "an", "AttributeSpecification", "for", "a", "given", "Attribute" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filtered.go#L55-L69
164,788
sjwhitworth/golearn
base/filtered.go
AllAttributes
func (l *LazilyFilteredInstances) AllAttributes() []Attribute { ret := make([]Attribute, 0) for _, a := range l.src.AllAttributes() { if l.unfilteredMap[a] { ret = append(ret, a) } else { for _, b := range l.attrs { if a.Equals(b.Old) { ret = append(ret, b.New) } } } } return ret }
go
func (l *LazilyFilteredInstances) AllAttributes() []Attribute { ret := make([]Attribute, 0) for _, a := range l.src.AllAttributes() { if l.unfilteredMap[a] { ret = append(ret, a) } else { for _, b := range l.attrs { if a.Equals(b.Old) { ret = append(ret, b.New) } } } } return ret }
[ "func", "(", "l", "*", "LazilyFilteredInstances", ")", "AllAttributes", "(", ")", "[", "]", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "0", ")", "\n", "for", "_", ",", "a", ":=", "range", "l", ".", "src", ".", "AllAttributes", "(", ")", "{", "if", "l", ".", "unfilteredMap", "[", "a", "]", "{", "ret", "=", "append", "(", "ret", ",", "a", ")", "\n", "}", "else", "{", "for", "_", ",", "b", ":=", "range", "l", ".", "attrs", "{", "if", "a", ".", "Equals", "(", "b", ".", "Old", ")", "{", "ret", "=", "append", "(", "ret", ",", "b", ".", "New", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// AllAttributes returns every Attribute defined in the source datagrid, // in addition to the revised Attributes created by the filter.
[ "AllAttributes", "returns", "every", "Attribute", "defined", "in", "the", "source", "datagrid", "in", "addition", "to", "the", "revised", "Attributes", "created", "by", "the", "filter", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filtered.go#L73-L87
164,789
sjwhitworth/golearn
base/filtered.go
AllClassAttributes
func (l *LazilyFilteredInstances) AllClassAttributes() []Attribute { ret := make([]Attribute, 0) for a := range l.classAttrs { if l.classAttrs[a] { ret = append(ret, a) } } return ret }
go
func (l *LazilyFilteredInstances) AllClassAttributes() []Attribute { ret := make([]Attribute, 0) for a := range l.classAttrs { if l.classAttrs[a] { ret = append(ret, a) } } return ret }
[ "func", "(", "l", "*", "LazilyFilteredInstances", ")", "AllClassAttributes", "(", ")", "[", "]", "Attribute", "{", "ret", ":=", "make", "(", "[", "]", "Attribute", ",", "0", ")", "\n", "for", "a", ":=", "range", "l", ".", "classAttrs", "{", "if", "l", ".", "classAttrs", "[", "a", "]", "{", "ret", "=", "append", "(", "ret", ",", "a", ")", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// AllClassAttributes returns details of all Attributes currently specified // as being class Attributes. // // If applicable, the Attributes returned are those after modification // by the Filter.
[ "AllClassAttributes", "returns", "details", "of", "all", "Attributes", "currently", "specified", "as", "being", "class", "Attributes", ".", "If", "applicable", "the", "Attributes", "returned", "are", "those", "after", "modification", "by", "the", "Filter", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filtered.go#L130-L138
164,790
sjwhitworth/golearn
base/filtered.go
Get
func (l *LazilyFilteredInstances) Get(as AttributeSpec, row int) []byte { asOld, err := l.transformNewToOldAttribute(as) if err != nil { panic(fmt.Sprintf("Attribute %s could not be resolved. (Error: %s)", as.String(), err.Error())) } byteSeq := l.src.Get(asOld, row) if l.unfilteredMap[as.attr] { return byteSeq } newByteSeq := l.filter.Transform(asOld.attr, as.attr, byteSeq) return newByteSeq }
go
func (l *LazilyFilteredInstances) Get(as AttributeSpec, row int) []byte { asOld, err := l.transformNewToOldAttribute(as) if err != nil { panic(fmt.Sprintf("Attribute %s could not be resolved. (Error: %s)", as.String(), err.Error())) } byteSeq := l.src.Get(asOld, row) if l.unfilteredMap[as.attr] { return byteSeq } newByteSeq := l.filter.Transform(asOld.attr, as.attr, byteSeq) return newByteSeq }
[ "func", "(", "l", "*", "LazilyFilteredInstances", ")", "Get", "(", "as", "AttributeSpec", ",", "row", "int", ")", "[", "]", "byte", "{", "asOld", ",", "err", ":=", "l", ".", "transformNewToOldAttribute", "(", "as", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "as", ".", "String", "(", ")", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "byteSeq", ":=", "l", ".", "src", ".", "Get", "(", "asOld", ",", "row", ")", "\n", "if", "l", ".", "unfilteredMap", "[", "as", ".", "attr", "]", "{", "return", "byteSeq", "\n", "}", "\n", "newByteSeq", ":=", "l", ".", "filter", ".", "Transform", "(", "asOld", ".", "attr", ",", "as", ".", "attr", ",", "byteSeq", ")", "\n", "return", "newByteSeq", "\n", "}" ]
// Get returns a transformed byte slice stored at a given AttributeSpec and row.
[ "Get", "returns", "a", "transformed", "byte", "slice", "stored", "at", "a", "given", "AttributeSpec", "and", "row", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filtered.go#L157-L168
164,791
sjwhitworth/golearn
base/filtered.go
MapOverRows
func (l *LazilyFilteredInstances) MapOverRows(asv []AttributeSpec, mapFunc func([][]byte, int) (bool, error)) error { // Have to transform each item of asv into an // AttributeSpec in the original oldAsv := make([]AttributeSpec, len(asv)) for i, a := range asv { old, err := l.transformNewToOldAttribute(a) if err != nil { return fmt.Errorf("Couldn't fetch old Attribute: '%s'", a.String()) } oldAsv[i] = old } // Then map over each row in the original newRowBuf := make([][]byte, len(asv)) return l.src.MapOverRows(oldAsv, func(oldRow [][]byte, oldRowNo int) (bool, error) { for i, b := range oldRow { newField := l.filter.Transform(oldAsv[i].attr, asv[i].attr, b) newRowBuf[i] = newField } return mapFunc(newRowBuf, oldRowNo) }) }
go
func (l *LazilyFilteredInstances) MapOverRows(asv []AttributeSpec, mapFunc func([][]byte, int) (bool, error)) error { // Have to transform each item of asv into an // AttributeSpec in the original oldAsv := make([]AttributeSpec, len(asv)) for i, a := range asv { old, err := l.transformNewToOldAttribute(a) if err != nil { return fmt.Errorf("Couldn't fetch old Attribute: '%s'", a.String()) } oldAsv[i] = old } // Then map over each row in the original newRowBuf := make([][]byte, len(asv)) return l.src.MapOverRows(oldAsv, func(oldRow [][]byte, oldRowNo int) (bool, error) { for i, b := range oldRow { newField := l.filter.Transform(oldAsv[i].attr, asv[i].attr, b) newRowBuf[i] = newField } return mapFunc(newRowBuf, oldRowNo) }) }
[ "func", "(", "l", "*", "LazilyFilteredInstances", ")", "MapOverRows", "(", "asv", "[", "]", "AttributeSpec", ",", "mapFunc", "func", "(", "[", "]", "[", "]", "byte", ",", "int", ")", "(", "bool", ",", "error", ")", ")", "error", "{", "// Have to transform each item of asv into an", "// AttributeSpec in the original", "oldAsv", ":=", "make", "(", "[", "]", "AttributeSpec", ",", "len", "(", "asv", ")", ")", "\n", "for", "i", ",", "a", ":=", "range", "asv", "{", "old", ",", "err", ":=", "l", ".", "transformNewToOldAttribute", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "a", ".", "String", "(", ")", ")", "\n", "}", "\n", "oldAsv", "[", "i", "]", "=", "old", "\n", "}", "\n\n", "// Then map over each row in the original", "newRowBuf", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "asv", ")", ")", "\n", "return", "l", ".", "src", ".", "MapOverRows", "(", "oldAsv", ",", "func", "(", "oldRow", "[", "]", "[", "]", "byte", ",", "oldRowNo", "int", ")", "(", "bool", ",", "error", ")", "{", "for", "i", ",", "b", ":=", "range", "oldRow", "{", "newField", ":=", "l", ".", "filter", ".", "Transform", "(", "oldAsv", "[", "i", "]", ".", "attr", ",", "asv", "[", "i", "]", ".", "attr", ",", "b", ")", "\n", "newRowBuf", "[", "i", "]", "=", "newField", "\n", "}", "\n", "return", "mapFunc", "(", "newRowBuf", ",", "oldRowNo", ")", "\n", "}", ")", "\n", "}" ]
// MapOverRows maps an iteration mapFunc over the bytes contained in the source // FixedDataGrid, after modification by the filter.
[ "MapOverRows", "maps", "an", "iteration", "mapFunc", "over", "the", "bytes", "contained", "in", "the", "source", "FixedDataGrid", "after", "modification", "by", "the", "filter", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filtered.go#L172-L194
164,792
sjwhitworth/golearn
base/filtered.go
String
func (l *LazilyFilteredInstances) String() string { var buffer bytes.Buffer // Decide on rows to print _, rows := l.Size() maxRows := 5 if rows < maxRows { maxRows = rows } // Get all Attribute information as := ResolveAllAttributes(l) // Print header buffer.WriteString("Lazily filtered instances using ") buffer.WriteString(fmt.Sprintf("%s\n", l.filter)) buffer.WriteString(fmt.Sprintf("Attributes: \n")) for _, a := range as { prefix := "\t" if l.classAttrs[a.attr] { prefix = "*\t" } buffer.WriteString(fmt.Sprintf("%s%s\n", prefix, a.attr)) } buffer.WriteString("\nData:\n") for i := 0; i < maxRows; i++ { buffer.WriteString("\t") for _, a := range as { val := l.Get(a, i) buffer.WriteString(fmt.Sprintf("%s ", a.attr.GetStringFromSysVal(val))) } buffer.WriteString("\n") } return buffer.String() }
go
func (l *LazilyFilteredInstances) String() string { var buffer bytes.Buffer // Decide on rows to print _, rows := l.Size() maxRows := 5 if rows < maxRows { maxRows = rows } // Get all Attribute information as := ResolveAllAttributes(l) // Print header buffer.WriteString("Lazily filtered instances using ") buffer.WriteString(fmt.Sprintf("%s\n", l.filter)) buffer.WriteString(fmt.Sprintf("Attributes: \n")) for _, a := range as { prefix := "\t" if l.classAttrs[a.attr] { prefix = "*\t" } buffer.WriteString(fmt.Sprintf("%s%s\n", prefix, a.attr)) } buffer.WriteString("\nData:\n") for i := 0; i < maxRows; i++ { buffer.WriteString("\t") for _, a := range as { val := l.Get(a, i) buffer.WriteString(fmt.Sprintf("%s ", a.attr.GetStringFromSysVal(val))) } buffer.WriteString("\n") } return buffer.String() }
[ "func", "(", "l", "*", "LazilyFilteredInstances", ")", "String", "(", ")", "string", "{", "var", "buffer", "bytes", ".", "Buffer", "\n\n", "// Decide on rows to print", "_", ",", "rows", ":=", "l", ".", "Size", "(", ")", "\n", "maxRows", ":=", "5", "\n", "if", "rows", "<", "maxRows", "{", "maxRows", "=", "rows", "\n", "}", "\n\n", "// Get all Attribute information", "as", ":=", "ResolveAllAttributes", "(", "l", ")", "\n\n", "// Print header", "buffer", ".", "WriteString", "(", "\"", "\"", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "l", ".", "filter", ")", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ")", ")", "\n\n", "for", "_", ",", "a", ":=", "range", "as", "{", "prefix", ":=", "\"", "\\t", "\"", "\n", "if", "l", ".", "classAttrs", "[", "a", ".", "attr", "]", "{", "prefix", "=", "\"", "\\t", "\"", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "prefix", ",", "a", ".", "attr", ")", ")", "\n", "}", "\n\n", "buffer", ".", "WriteString", "(", "\"", "\\n", "\\n", "\"", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "maxRows", ";", "i", "++", "{", "buffer", ".", "WriteString", "(", "\"", "\\t", "\"", ")", "\n", "for", "_", ",", "a", ":=", "range", "as", "{", "val", ":=", "l", ".", "Get", "(", "a", ",", "i", ")", "\n", "buffer", ".", "WriteString", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ".", "attr", ".", "GetStringFromSysVal", "(", "val", ")", ")", ")", "\n", "}", "\n", "buffer", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "return", "buffer", ".", "String", "(", ")", "\n", "}" ]
// String returns a human-readable summary of this FixedDataGrid // after filtering.
[ "String", "returns", "a", "human", "-", "readable", "summary", "of", "this", "FixedDataGrid", "after", "filtering", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/base/filtered.go#L225-L262
164,793
sjwhitworth/golearn
trees/random.go
GenerateSplitRule
func (r *RandomTreeRuleGenerator) GenerateSplitRule(f base.FixedDataGrid) *DecisionTreeRule { var consideredAttributes []base.Attribute // First step is to generate the random attributes that we'll consider allAttributes := base.AttributeDifferenceReferences(f.AllAttributes(), f.AllClassAttributes()) maximumAttribute := len(allAttributes) attrCounter := 0 for { if len(consideredAttributes) >= r.Attributes { break } selectedAttrIndex := rand.Intn(maximumAttribute) selectedAttribute := allAttributes[selectedAttrIndex] matched := false for _, a := range consideredAttributes { if a.Equals(selectedAttribute) { matched = true break } } if matched { continue } consideredAttributes = append(consideredAttributes, selectedAttribute) attrCounter++ } return r.internalRule.GetSplitRuleFromSelection(consideredAttributes, f) }
go
func (r *RandomTreeRuleGenerator) GenerateSplitRule(f base.FixedDataGrid) *DecisionTreeRule { var consideredAttributes []base.Attribute // First step is to generate the random attributes that we'll consider allAttributes := base.AttributeDifferenceReferences(f.AllAttributes(), f.AllClassAttributes()) maximumAttribute := len(allAttributes) attrCounter := 0 for { if len(consideredAttributes) >= r.Attributes { break } selectedAttrIndex := rand.Intn(maximumAttribute) selectedAttribute := allAttributes[selectedAttrIndex] matched := false for _, a := range consideredAttributes { if a.Equals(selectedAttribute) { matched = true break } } if matched { continue } consideredAttributes = append(consideredAttributes, selectedAttribute) attrCounter++ } return r.internalRule.GetSplitRuleFromSelection(consideredAttributes, f) }
[ "func", "(", "r", "*", "RandomTreeRuleGenerator", ")", "GenerateSplitRule", "(", "f", "base", ".", "FixedDataGrid", ")", "*", "DecisionTreeRule", "{", "var", "consideredAttributes", "[", "]", "base", ".", "Attribute", "\n\n", "// First step is to generate the random attributes that we'll consider", "allAttributes", ":=", "base", ".", "AttributeDifferenceReferences", "(", "f", ".", "AllAttributes", "(", ")", ",", "f", ".", "AllClassAttributes", "(", ")", ")", "\n", "maximumAttribute", ":=", "len", "(", "allAttributes", ")", "\n\n", "attrCounter", ":=", "0", "\n", "for", "{", "if", "len", "(", "consideredAttributes", ")", ">=", "r", ".", "Attributes", "{", "break", "\n", "}", "\n", "selectedAttrIndex", ":=", "rand", ".", "Intn", "(", "maximumAttribute", ")", "\n", "selectedAttribute", ":=", "allAttributes", "[", "selectedAttrIndex", "]", "\n", "matched", ":=", "false", "\n", "for", "_", ",", "a", ":=", "range", "consideredAttributes", "{", "if", "a", ".", "Equals", "(", "selectedAttribute", ")", "{", "matched", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "matched", "{", "continue", "\n", "}", "\n", "consideredAttributes", "=", "append", "(", "consideredAttributes", ",", "selectedAttribute", ")", "\n", "attrCounter", "++", "\n", "}", "\n\n", "return", "r", ".", "internalRule", ".", "GetSplitRuleFromSelection", "(", "consideredAttributes", ",", "f", ")", "\n", "}" ]
// GenerateSplitRule returns the best attribute out of those randomly chosen // which maximises Information Gain
[ "GenerateSplitRule", "returns", "the", "best", "attribute", "out", "of", "those", "randomly", "chosen", "which", "maximises", "Information", "Gain" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L17-L47
164,794
sjwhitworth/golearn
trees/random.go
NewRandomTree
func NewRandomTree(attrs int) *RandomTree { return &RandomTree{ base.BaseClassifier{}, nil, &RandomTreeRuleGenerator{ attrs, InformationGainRuleGenerator{}, }, } }
go
func NewRandomTree(attrs int) *RandomTree { return &RandomTree{ base.BaseClassifier{}, nil, &RandomTreeRuleGenerator{ attrs, InformationGainRuleGenerator{}, }, } }
[ "func", "NewRandomTree", "(", "attrs", "int", ")", "*", "RandomTree", "{", "return", "&", "RandomTree", "{", "base", ".", "BaseClassifier", "{", "}", ",", "nil", ",", "&", "RandomTreeRuleGenerator", "{", "attrs", ",", "InformationGainRuleGenerator", "{", "}", ",", "}", ",", "}", "\n", "}" ]
// NewRandomTree returns a new RandomTree which considers attrs randomly // chosen attributes at each node.
[ "NewRandomTree", "returns", "a", "new", "RandomTree", "which", "considers", "attrs", "randomly", "chosen", "attributes", "at", "each", "node", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L59-L68
164,795
sjwhitworth/golearn
trees/random.go
Fit
func (rt *RandomTree) Fit(from base.FixedDataGrid) error { rt.Root = InferID3Tree(from, rt.Rule) return nil }
go
func (rt *RandomTree) Fit(from base.FixedDataGrid) error { rt.Root = InferID3Tree(from, rt.Rule) return nil }
[ "func", "(", "rt", "*", "RandomTree", ")", "Fit", "(", "from", "base", ".", "FixedDataGrid", ")", "error", "{", "rt", ".", "Root", "=", "InferID3Tree", "(", "from", ",", "rt", ".", "Rule", ")", "\n", "return", "nil", "\n", "}" ]
// Fit builds a RandomTree suitable for prediction
[ "Fit", "builds", "a", "RandomTree", "suitable", "for", "prediction" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L71-L74
164,796
sjwhitworth/golearn
trees/random.go
Predict
func (rt *RandomTree) Predict(from base.FixedDataGrid) (base.FixedDataGrid, error) { return rt.Root.Predict(from) }
go
func (rt *RandomTree) Predict(from base.FixedDataGrid) (base.FixedDataGrid, error) { return rt.Root.Predict(from) }
[ "func", "(", "rt", "*", "RandomTree", ")", "Predict", "(", "from", "base", ".", "FixedDataGrid", ")", "(", "base", ".", "FixedDataGrid", ",", "error", ")", "{", "return", "rt", ".", "Root", ".", "Predict", "(", "from", ")", "\n", "}" ]
// Predict returns a set of Instances containing predictions
[ "Predict", "returns", "a", "set", "of", "Instances", "containing", "predictions" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L77-L79
164,797
sjwhitworth/golearn
trees/random.go
Save
func (rt *RandomTree) Save(filePath string) error { writer, err := base.CreateSerializedClassifierStub(filePath, rt.GetMetadata()) if err != nil { return err } defer func() { writer.Close() }() return rt.SaveWithPrefix(writer, "") }
go
func (rt *RandomTree) Save(filePath string) error { writer, err := base.CreateSerializedClassifierStub(filePath, rt.GetMetadata()) if err != nil { return err } defer func() { writer.Close() }() return rt.SaveWithPrefix(writer, "") }
[ "func", "(", "rt", "*", "RandomTree", ")", "Save", "(", "filePath", "string", ")", "error", "{", "writer", ",", "err", ":=", "base", ".", "CreateSerializedClassifierStub", "(", "filePath", ",", "rt", ".", "GetMetadata", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "writer", ".", "Close", "(", ")", "\n", "}", "(", ")", "\n", "return", "rt", ".", "SaveWithPrefix", "(", "writer", ",", "\"", "\"", ")", "\n", "}" ]
// Save outputs this model to a file
[ "Save", "outputs", "this", "model", "to", "a", "file" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L93-L102
164,798
sjwhitworth/golearn
trees/random.go
SaveWithPrefix
func (rt *RandomTree) SaveWithPrefix(writer *base.ClassifierSerializer, prefix string) error { return rt.Root.SaveWithPrefix(writer, prefix) }
go
func (rt *RandomTree) SaveWithPrefix(writer *base.ClassifierSerializer, prefix string) error { return rt.Root.SaveWithPrefix(writer, prefix) }
[ "func", "(", "rt", "*", "RandomTree", ")", "SaveWithPrefix", "(", "writer", "*", "base", ".", "ClassifierSerializer", ",", "prefix", "string", ")", "error", "{", "return", "rt", ".", "Root", ".", "SaveWithPrefix", "(", "writer", ",", "prefix", ")", "\n", "}" ]
// SaveWithPrefix outputs this model to a file with a prefix.
[ "SaveWithPrefix", "outputs", "this", "model", "to", "a", "file", "with", "a", "prefix", "." ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L105-L107
164,799
sjwhitworth/golearn
trees/random.go
Load
func (rt *RandomTree) Load(filePath string) error { reader, err := base.ReadSerializedClassifierStub(filePath) if err != nil { return err } return rt.LoadWithPrefix(reader, "") }
go
func (rt *RandomTree) Load(filePath string) error { reader, err := base.ReadSerializedClassifierStub(filePath) if err != nil { return err } return rt.LoadWithPrefix(reader, "") }
[ "func", "(", "rt", "*", "RandomTree", ")", "Load", "(", "filePath", "string", ")", "error", "{", "reader", ",", "err", ":=", "base", ".", "ReadSerializedClassifierStub", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "rt", ".", "LoadWithPrefix", "(", "reader", ",", "\"", "\"", ")", "\n", "}" ]
// Load retrieves this model from a file
[ "Load", "retrieves", "this", "model", "from", "a", "file" ]
82e59c89f5020c45292c68472908f2150a87422e
https://github.com/sjwhitworth/golearn/blob/82e59c89f5020c45292c68472908f2150a87422e/trees/random.go#L110-L116