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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
apex/log
entry.go
Fatal
func (e *Entry) Fatal(msg string) { e.Logger.log(FatalLevel, e, msg) os.Exit(1) }
go
func (e *Entry) Fatal(msg string) { e.Logger.log(FatalLevel, e, msg) os.Exit(1) }
[ "func", "(", "e", "*", "Entry", ")", "Fatal", "(", "msg", "string", ")", "{", "e", ".", "Logger", ".", "log", "(", "FatalLevel", ",", "e", ",", "msg", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Fatal level message, followed by an exit.
[ "Fatal", "level", "message", "followed", "by", "an", "exit", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/entry.go#L100-L103
train
apex/log
entry.go
Stop
func (e *Entry) Stop(err *error) { if err == nil || *err == nil { e.WithField("duration", time.Since(e.start)).Info(e.Message) } else { e.WithField("duration", time.Since(e.start)).WithError(*err).Error(e.Message) } }
go
func (e *Entry) Stop(err *error) { if err == nil || *err == nil { e.WithField("duration", time.Since(e.start)).Info(e.Message) } else { e.WithField("duration", time.Since(e.start)).WithError(*err).Error(e.Message) } }
[ "func", "(", "e", "*", "Entry", ")", "Stop", "(", "err", "*", "error", ")", "{", "if", "err", "==", "nil", "||", "*", "err", "==", "nil", "{", "e", ".", "WithField", "(", "\"", "\"", ",", "time", ".", "Since", "(", "e", ".", "start", ")", "...
// Stop should be used with Trace, to fire off the completion message. When // an `err` is passed the "error" field is set, and the log level is error.
[ "Stop", "should", "be", "used", "with", "Trace", "to", "fire", "off", "the", "completion", "message", ".", "When", "an", "err", "is", "passed", "the", "error", "field", "is", "set", "and", "the", "log", "level", "is", "error", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/entry.go#L142-L148
train
apex/log
entry.go
mergedFields
func (e *Entry) mergedFields() Fields { f := Fields{} for _, fields := range e.fields { for k, v := range fields { f[k] = v } } return f }
go
func (e *Entry) mergedFields() Fields { f := Fields{} for _, fields := range e.fields { for k, v := range fields { f[k] = v } } return f }
[ "func", "(", "e", "*", "Entry", ")", "mergedFields", "(", ")", "Fields", "{", "f", ":=", "Fields", "{", "}", "\n\n", "for", "_", ",", "fields", ":=", "range", "e", ".", "fields", "{", "for", "k", ",", "v", ":=", "range", "fields", "{", "f", "["...
// mergedFields returns the fields list collapsed into a single map.
[ "mergedFields", "returns", "the", "fields", "list", "collapsed", "into", "a", "single", "map", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/entry.go#L151-L161
train
apex/log
entry.go
finalize
func (e *Entry) finalize(level Level, msg string) *Entry { return &Entry{ Logger: e.Logger, Fields: e.mergedFields(), Level: level, Message: msg, Timestamp: Now(), } }
go
func (e *Entry) finalize(level Level, msg string) *Entry { return &Entry{ Logger: e.Logger, Fields: e.mergedFields(), Level: level, Message: msg, Timestamp: Now(), } }
[ "func", "(", "e", "*", "Entry", ")", "finalize", "(", "level", "Level", ",", "msg", "string", ")", "*", "Entry", "{", "return", "&", "Entry", "{", "Logger", ":", "e", ".", "Logger", ",", "Fields", ":", "e", ".", "mergedFields", "(", ")", ",", "Le...
// finalize returns a copy of the Entry with Fields merged.
[ "finalize", "returns", "a", "copy", "of", "the", "Entry", "with", "Fields", "merged", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/entry.go#L164-L172
train
apex/log
levels.go
ParseLevel
func ParseLevel(s string) (Level, error) { l, ok := levelStrings[strings.ToLower(s)] if !ok { return InvalidLevel, ErrInvalidLevel } return l, nil }
go
func ParseLevel(s string) (Level, error) { l, ok := levelStrings[strings.ToLower(s)] if !ok { return InvalidLevel, ErrInvalidLevel } return l, nil }
[ "func", "ParseLevel", "(", "s", "string", ")", "(", "Level", ",", "error", ")", "{", "l", ",", "ok", ":=", "levelStrings", "[", "strings", ".", "ToLower", "(", "s", ")", "]", "\n", "if", "!", "ok", "{", "return", "InvalidLevel", ",", "ErrInvalidLevel...
// ParseLevel parses level string.
[ "ParseLevel", "parses", "level", "string", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/levels.go#L64-L71
train
apex/log
levels.go
MustParseLevel
func MustParseLevel(s string) Level { l, err := ParseLevel(s) if err != nil { panic("invalid log level") } return l }
go
func MustParseLevel(s string) Level { l, err := ParseLevel(s) if err != nil { panic("invalid log level") } return l }
[ "func", "MustParseLevel", "(", "s", "string", ")", "Level", "{", "l", ",", "err", ":=", "ParseLevel", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "l", "\n", "}" ]
// MustParseLevel parses level string or panics.
[ "MustParseLevel", "parses", "level", "string", "or", "panics", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/levels.go#L74-L81
train
apex/log
handlers/delta/delta.go
Close
func (h *Handler) Close() error { h.done <- struct{}{} close(h.done) close(h.entries) return nil }
go
func (h *Handler) Close() error { h.done <- struct{}{} close(h.done) close(h.entries) return nil }
[ "func", "(", "h", "*", "Handler", ")", "Close", "(", ")", "error", "{", "h", ".", "done", "<-", "struct", "{", "}", "{", "}", "\n", "close", "(", "h", ".", "done", ")", "\n", "close", "(", "h", ".", "entries", ")", "\n", "return", "nil", "\n"...
// Close the handler.
[ "Close", "the", "handler", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/handlers/delta/delta.go#L99-L104
train
apex/log
handlers/delta/delta.go
loop
func (h *Handler) loop() { ticker := time.NewTicker(100 * time.Millisecond) for { select { case e := <-h.entries: if h.prev != nil { h.render(h.prev, true) } h.render(e, false) h.prev = e case <-ticker.C: if h.prev != nil { h.render(h.prev, false) } h.spin.Next() case <-h.done: ticker.Stop() if h.prev != nil { h.render(h.prev, true) } return } } }
go
func (h *Handler) loop() { ticker := time.NewTicker(100 * time.Millisecond) for { select { case e := <-h.entries: if h.prev != nil { h.render(h.prev, true) } h.render(e, false) h.prev = e case <-ticker.C: if h.prev != nil { h.render(h.prev, false) } h.spin.Next() case <-h.done: ticker.Stop() if h.prev != nil { h.render(h.prev, true) } return } } }
[ "func", "(", "h", "*", "Handler", ")", "loop", "(", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "100", "*", "time", ".", "Millisecond", ")", "\n\n", "for", "{", "select", "{", "case", "e", ":=", "<-", "h", ".", "entries", ":", "if", ...
// loop for rendering.
[ "loop", "for", "rendering", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/handlers/delta/delta.go#L107-L131
train
apex/log
logger.go
Names
func (f Fields) Names() (v []string) { for k := range f { v = append(v, k) } sort.Strings(v) return }
go
func (f Fields) Names() (v []string) { for k := range f { v = append(v, k) } sort.Strings(v) return }
[ "func", "(", "f", "Fields", ")", "Names", "(", ")", "(", "v", "[", "]", "string", ")", "{", "for", "k", ":=", "range", "f", "{", "v", "=", "append", "(", "v", ",", "k", ")", "\n", "}", "\n\n", "sort", ".", "Strings", "(", "v", ")", "\n", ...
// Names returns field names sorted.
[ "Names", "returns", "field", "names", "sorted", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/logger.go#L30-L37
train
apex/log
logger.go
WithField
func (l *Logger) WithField(key string, value interface{}) *Entry { return NewEntry(l).WithField(key, value) }
go
func (l *Logger) WithField(key string, value interface{}) *Entry { return NewEntry(l).WithField(key, value) }
[ "func", "(", "l", "*", "Logger", ")", "WithField", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "*", "Entry", "{", "return", "NewEntry", "(", "l", ")", ".", "WithField", "(", "key", ",", "value", ")", "\n", "}" ]
// WithField returns a new entry with the `key` and `value` set. // // Note that the `key` should not have spaces in it - use camel // case or underscores
[ "WithField", "returns", "a", "new", "entry", "with", "the", "key", "and", "value", "set", ".", "Note", "that", "the", "key", "should", "not", "have", "spaces", "in", "it", "-", "use", "camel", "case", "or", "underscores" ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/logger.go#L73-L75
train
apex/log
logger.go
WithError
func (l *Logger) WithError(err error) *Entry { return NewEntry(l).WithError(err) }
go
func (l *Logger) WithError(err error) *Entry { return NewEntry(l).WithError(err) }
[ "func", "(", "l", "*", "Logger", ")", "WithError", "(", "err", "error", ")", "*", "Entry", "{", "return", "NewEntry", "(", "l", ")", ".", "WithError", "(", "err", ")", "\n", "}" ]
// WithError returns a new entry with the "error" set to `err`.
[ "WithError", "returns", "a", "new", "entry", "with", "the", "error", "set", "to", "err", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/logger.go#L78-L80
train
apex/log
logger.go
log
func (l *Logger) log(level Level, e *Entry, msg string) { if level < l.Level { return } if err := l.Handler.HandleLog(e.finalize(level, msg)); err != nil { stdlog.Printf("error logging: %s", err) } }
go
func (l *Logger) log(level Level, e *Entry, msg string) { if level < l.Level { return } if err := l.Handler.HandleLog(e.finalize(level, msg)); err != nil { stdlog.Printf("error logging: %s", err) } }
[ "func", "(", "l", "*", "Logger", ")", "log", "(", "level", "Level", ",", "e", "*", "Entry", ",", "msg", "string", ")", "{", "if", "level", "<", "l", ".", "Level", "{", "return", "\n", "}", "\n\n", "if", "err", ":=", "l", ".", "Handler", ".", ...
// log the message, invoking the handler. We clone the entry here // to bypass the overhead in Entry methods when the level is not // met.
[ "log", "the", "message", "invoking", "the", "handler", ".", "We", "clone", "the", "entry", "here", "to", "bypass", "the", "overhead", "in", "Entry", "methods", "when", "the", "level", "is", "not", "met", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/logger.go#L141-L149
train
apex/log
handlers/kinesis/kinesis.go
New
func New(stream string) *Handler { return NewConfig(k.Config{ StreamName: stream, Client: kinesis.New(session.New(aws.NewConfig())), }) }
go
func New(stream string) *Handler { return NewConfig(k.Config{ StreamName: stream, Client: kinesis.New(session.New(aws.NewConfig())), }) }
[ "func", "New", "(", "stream", "string", ")", "*", "Handler", "{", "return", "NewConfig", "(", "k", ".", "Config", "{", "StreamName", ":", "stream", ",", "Client", ":", "kinesis", ".", "New", "(", "session", ".", "New", "(", "aws", ".", "NewConfig", "...
// New handler sending logs to Kinesis. To configure producer options or pass your // own AWS Kinesis client use NewConfig instead.
[ "New", "handler", "sending", "logs", "to", "Kinesis", ".", "To", "configure", "producer", "options", "or", "pass", "your", "own", "AWS", "Kinesis", "client", "use", "NewConfig", "instead", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/handlers/kinesis/kinesis.go#L24-L29
train
apex/log
handlers/kinesis/kinesis.go
NewConfig
func NewConfig(config k.Config) *Handler { producer := k.New(config) producer.Start() return &Handler{ producer: producer, gen: fastuuid.MustNewGenerator(), } }
go
func NewConfig(config k.Config) *Handler { producer := k.New(config) producer.Start() return &Handler{ producer: producer, gen: fastuuid.MustNewGenerator(), } }
[ "func", "NewConfig", "(", "config", "k", ".", "Config", ")", "*", "Handler", "{", "producer", ":=", "k", ".", "New", "(", "config", ")", "\n", "producer", ".", "Start", "(", ")", "\n", "return", "&", "Handler", "{", "producer", ":", "producer", ",", ...
// NewConfig handler sending logs to Kinesis. The `config` given is passed to the batch // Kinesis producer, and a random value is used as the partition key for even distribution.
[ "NewConfig", "handler", "sending", "logs", "to", "Kinesis", ".", "The", "config", "given", "is", "passed", "to", "the", "batch", "Kinesis", "producer", "and", "a", "random", "value", "is", "used", "as", "the", "partition", "key", "for", "even", "distribution...
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/handlers/kinesis/kinesis.go#L33-L40
train
apex/log
pkg.go
SetHandler
func SetHandler(h Handler) { if logger, ok := Log.(*Logger); ok { logger.Handler = h } }
go
func SetHandler(h Handler) { if logger, ok := Log.(*Logger); ok { logger.Handler = h } }
[ "func", "SetHandler", "(", "h", "Handler", ")", "{", "if", "logger", ",", "ok", ":=", "Log", ".", "(", "*", "Logger", ")", ";", "ok", "{", "logger", ".", "Handler", "=", "h", "\n", "}", "\n", "}" ]
// SetHandler sets the handler. This is not thread-safe. // The default handler outputs to the stdlib log.
[ "SetHandler", "sets", "the", "handler", ".", "This", "is", "not", "thread", "-", "safe", ".", "The", "default", "handler", "outputs", "to", "the", "stdlib", "log", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/pkg.go#L11-L15
train
apex/log
pkg.go
SetLevel
func SetLevel(l Level) { if logger, ok := Log.(*Logger); ok { logger.Level = l } }
go
func SetLevel(l Level) { if logger, ok := Log.(*Logger); ok { logger.Level = l } }
[ "func", "SetLevel", "(", "l", "Level", ")", "{", "if", "logger", ",", "ok", ":=", "Log", ".", "(", "*", "Logger", ")", ";", "ok", "{", "logger", ".", "Level", "=", "l", "\n", "}", "\n", "}" ]
// SetLevel sets the log level. This is not thread-safe.
[ "SetLevel", "sets", "the", "log", "level", ".", "This", "is", "not", "thread", "-", "safe", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/pkg.go#L18-L22
train
apex/log
pkg.go
SetLevelFromString
func SetLevelFromString(s string) { if logger, ok := Log.(*Logger); ok { logger.Level = MustParseLevel(s) } }
go
func SetLevelFromString(s string) { if logger, ok := Log.(*Logger); ok { logger.Level = MustParseLevel(s) } }
[ "func", "SetLevelFromString", "(", "s", "string", ")", "{", "if", "logger", ",", "ok", ":=", "Log", ".", "(", "*", "Logger", ")", ";", "ok", "{", "logger", ".", "Level", "=", "MustParseLevel", "(", "s", ")", "\n", "}", "\n", "}" ]
// SetLevelFromString sets the log level from a string, panicing when invalid. This is not thread-safe.
[ "SetLevelFromString", "sets", "the", "log", "level", "from", "a", "string", "panicing", "when", "invalid", ".", "This", "is", "not", "thread", "-", "safe", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/pkg.go#L25-L29
train
apex/log
_examples/stack/stack.go
upload
func upload(name string, b []byte) error { err := put("/images/"+name, b) if err != nil { return errors.Wrap(err, "uploading to s3") } return nil }
go
func upload(name string, b []byte) error { err := put("/images/"+name, b) if err != nil { return errors.Wrap(err, "uploading to s3") } return nil }
[ "func", "upload", "(", "name", "string", ",", "b", "[", "]", "byte", ")", "error", "{", "err", ":=", "put", "(", "\"", "\"", "+", "name", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\...
// Faux upload.
[ "Faux", "upload", "." ]
d6c5facec1f2ae23a97782ab0ee18af58734346f
https://github.com/apex/log/blob/d6c5facec1f2ae23a97782ab0ee18af58734346f/_examples/stack/stack.go#L27-L34
train
cdipaolo/goml
cluster/knn.go
insertSorted
func insertSorted(u nn, v []nn, K int) []nn { low := 0 high := len(v) - 1 for low <= high { mid := (low + high) / 2 if u.Distance < v[mid].Distance { high = mid - 1 } else if u.Distance >= v[mid].Distance { low = mid + 1 } } if low >= len(v) && len(v) >= K { return v } sorted := append(v[:low], append([]nn{u}, v[low:]...)...) if len(v) < K { return sorted } return sorted[:len(v)] }
go
func insertSorted(u nn, v []nn, K int) []nn { low := 0 high := len(v) - 1 for low <= high { mid := (low + high) / 2 if u.Distance < v[mid].Distance { high = mid - 1 } else if u.Distance >= v[mid].Distance { low = mid + 1 } } if low >= len(v) && len(v) >= K { return v } sorted := append(v[:low], append([]nn{u}, v[low:]...)...) if len(v) < K { return sorted } return sorted[:len(v)] }
[ "func", "insertSorted", "(", "u", "nn", ",", "v", "[", "]", "nn", ",", "K", "int", ")", "[", "]", "nn", "{", "low", ":=", "0", "\n", "high", ":=", "len", "(", "v", ")", "-", "1", "\n", "for", "low", "<=", "high", "{", "mid", ":=", "(", "l...
// insertSorted takes a array v, and inserts u into // the list in the position such that the list is // sorted inversely. The function will not change the length // of v, though, such that if u would appear last // in the combined sorted list it would just be omitted. // // if the length of V is less than K, then u is inserted // without deleting the last element // // Assumes v has been sorted. Uses binary search.
[ "insertSorted", "takes", "a", "array", "v", "and", "inserts", "u", "into", "the", "list", "in", "the", "position", "such", "that", "the", "list", "is", "sorted", "inversely", ".", "The", "function", "will", "not", "change", "the", "length", "of", "v", "t...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/knn.go#L136-L158
train
cdipaolo/goml
cluster/knn.go
round
func round(a float64) float64 { if a < 0 { return math.Ceil(a - 0.5) } return math.Floor(a + 0.5) }
go
func round(a float64) float64 { if a < 0 { return math.Ceil(a - 0.5) } return math.Floor(a + 0.5) }
[ "func", "round", "(", "a", "float64", ")", "float64", "{", "if", "a", "<", "0", "{", "return", "math", ".", "Ceil", "(", "a", "-", "0.5", ")", "\n", "}", "\n", "return", "math", ".", "Floor", "(", "a", "+", "0.5", ")", "\n", "}" ]
// round rounds a float64
[ "round", "rounds", "a", "float64" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/knn.go#L161-L166
train
cdipaolo/goml
base/sanitize.go
OnlyAsciiWordsAndNumbers
func OnlyAsciiWordsAndNumbers(r rune) bool { switch { case r >= 'A' && r <= 'Z': return false case r >= 'a' && r <= 'z': return false case r >= '0' && r <= '9': return false case r == ' ': return false default: return true } }
go
func OnlyAsciiWordsAndNumbers(r rune) bool { switch { case r >= 'A' && r <= 'Z': return false case r >= 'a' && r <= 'z': return false case r >= '0' && r <= '9': return false case r == ' ': return false default: return true } }
[ "func", "OnlyAsciiWordsAndNumbers", "(", "r", "rune", ")", "bool", "{", "switch", "{", "case", "r", ">=", "'A'", "&&", "r", "<=", "'Z'", ":", "return", "false", "\n", "case", "r", ">=", "'a'", "&&", "r", "<=", "'z'", ":", "return", "false", "\n", "...
// OnlyAsciiWordsAndNumbers is a transform // function that will only let 0-9a-zA-Z, // and spaces through
[ "OnlyAsciiWordsAndNumbers", "is", "a", "transform", "function", "that", "will", "only", "let", "0", "-", "9a", "-", "zA", "-", "Z", "and", "spaces", "through" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/base/sanitize.go#L10-L23
train
cdipaolo/goml
base/sanitize.go
OnlyWordsAndNumbers
func OnlyWordsAndNumbers(r rune) bool { return !(r == ' ' || unicode.IsLetter(r) || unicode.IsDigit(r)) }
go
func OnlyWordsAndNumbers(r rune) bool { return !(r == ' ' || unicode.IsLetter(r) || unicode.IsDigit(r)) }
[ "func", "OnlyWordsAndNumbers", "(", "r", "rune", ")", "bool", "{", "return", "!", "(", "r", "==", "' '", "||", "unicode", ".", "IsLetter", "(", "r", ")", "||", "unicode", ".", "IsDigit", "(", "r", ")", ")", "\n", "}" ]
// OnlyWordsAndNumbers is a transform // function that lets any unicode letter // or digit through as well as spaces
[ "OnlyWordsAndNumbers", "is", "a", "transform", "function", "that", "lets", "any", "unicode", "letter", "or", "digit", "through", "as", "well", "as", "spaces" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/base/sanitize.go#L28-L30
train
cdipaolo/goml
base/sanitize.go
OnlyAsciiWords
func OnlyAsciiWords(r rune) bool { switch { case r >= 'A' && r <= 'Z': return false case r >= 'a' && r <= 'z': return false case r == ' ': return false default: return true } }
go
func OnlyAsciiWords(r rune) bool { switch { case r >= 'A' && r <= 'Z': return false case r >= 'a' && r <= 'z': return false case r == ' ': return false default: return true } }
[ "func", "OnlyAsciiWords", "(", "r", "rune", ")", "bool", "{", "switch", "{", "case", "r", ">=", "'A'", "&&", "r", "<=", "'Z'", ":", "return", "false", "\n", "case", "r", ">=", "'a'", "&&", "r", "<=", "'z'", ":", "return", "false", "\n", "case", "...
// OnlyAsciiWords is a transform function // that will only let a-zA-Z, and // spaces through
[ "OnlyAsciiWords", "is", "a", "transform", "function", "that", "will", "only", "let", "a", "-", "zA", "-", "Z", "and", "spaces", "through" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/base/sanitize.go#L35-L46
train
cdipaolo/goml
base/sanitize.go
OnlyAsciiLetters
func OnlyAsciiLetters(r rune) bool { switch { case r >= 'A' && r <= 'Z': return false case r >= 'a' && r <= 'z': return false default: return true } }
go
func OnlyAsciiLetters(r rune) bool { switch { case r >= 'A' && r <= 'Z': return false case r >= 'a' && r <= 'z': return false default: return true } }
[ "func", "OnlyAsciiLetters", "(", "r", "rune", ")", "bool", "{", "switch", "{", "case", "r", ">=", "'A'", "&&", "r", "<=", "'Z'", ":", "return", "false", "\n", "case", "r", ">=", "'a'", "&&", "r", "<=", "'z'", ":", "return", "false", "\n", "default"...
// OnlyAsciiLetters is a transform function // that will only let a-zA-Z through
[ "OnlyAsciiLetters", "is", "a", "transform", "function", "that", "will", "only", "let", "a", "-", "zA", "-", "Z", "through" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/base/sanitize.go#L57-L66
train
cdipaolo/goml
linear/softmax.go
Learn
func (s *Softmax) Learn() error { if s.trainingSet == nil || s.expectedResults == nil { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(s.Output, err.Error()) return err } examples := len(s.trainingSet) if examples == 0 || len(s.trainingSet[0]) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(s.Output, err.Error()) return err } if len(s.expectedResults) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no expected results! This isn't an unsupervised model!! You'll need to include data before you learn :)\n") fmt.Fprintf(s.Output, err.Error()) return err } fmt.Fprintf(s.Output, "Training:\n\tModel: Softmax Classification\n\tOptimization Method: %v\n\tTraining Examples: %v\n\t Classification Dimensions: %v\n\tFeatures: %v\n\tLearning Rate α: %v\n\tRegularization Parameter λ: %v\n...\n\n", s.method, examples, s.k, len(s.trainingSet[0]), s.alpha, s.regularization) var err error if s.method == base.BatchGA { err = func() error { // if the iterations given is 0, set it to be // 5000 (seems reasonable base value) if s.maxIterations == 0 { s.maxIterations = 5000 } iter := 0 // Stop iterating if the number of iterations exceeds // the limit for ; iter < s.maxIterations; iter++ { // go over each parameter vector for each // classification value newTheta := make([][]float64, len(s.Parameters)) for k, theta := range s.Parameters { newTheta[k] = make([]float64, len(theta)) dj, err := s.Dj(k) if err != nil { return err } for j := range theta { newTheta[k][j] = theta[j] + s.alpha*dj[j] if math.IsInf(newTheta[k][j], 0) || math.IsNaN(newTheta[k][j]) { return fmt.Errorf("Sorry dude! Learning diverged. Some value of the parameter vector theta is ±Inf or NaN") } } } s.Parameters = newTheta } fmt.Fprintf(s.Output, "Went through %v iterations.\n", iter) return nil }() } else if s.method == base.StochasticGA { err = func() error { // if the iterations given is 0, set it to be // 5000 (seems reasonable base value) if s.maxIterations == 0 { s.maxIterations = 5000 } iter := 0 // Stop iterating if the number of iterations exceeds // the limit for ; iter < s.maxIterations; iter++ { for j := range s.trainingSet { newTheta := make([][]float64, len(s.Parameters)) // go over each parameter vector for each // classification value for k, theta := range s.Parameters { newTheta[k] = make([]float64, len(theta)) dj, err := s.Dij(j, k) if err != nil { return err } // now simultaneously update theta for j := range theta { newTheta[k][j] = theta[j] + s.alpha*dj[j] if math.IsInf(newTheta[k][j], 0) || math.IsNaN(newTheta[k][j]) { return fmt.Errorf("Sorry dude! Learning diverged. Some value of the parameter vector theta is ±Inf or NaN") } } } s.Parameters = newTheta } } fmt.Fprintf(s.Output, "Went through %v iterations.\n", iter) return nil }() } else { err = fmt.Errorf("Chose a training method not implemented for Softmax regression") } if err != nil { fmt.Fprintf(s.Output, "\nERROR: Error while learning –\n\t%v\n\n", err) return err } fmt.Fprintf(s.Output, "Training Completed.\n%v\n\n", s) return nil }
go
func (s *Softmax) Learn() error { if s.trainingSet == nil || s.expectedResults == nil { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(s.Output, err.Error()) return err } examples := len(s.trainingSet) if examples == 0 || len(s.trainingSet[0]) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(s.Output, err.Error()) return err } if len(s.expectedResults) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no expected results! This isn't an unsupervised model!! You'll need to include data before you learn :)\n") fmt.Fprintf(s.Output, err.Error()) return err } fmt.Fprintf(s.Output, "Training:\n\tModel: Softmax Classification\n\tOptimization Method: %v\n\tTraining Examples: %v\n\t Classification Dimensions: %v\n\tFeatures: %v\n\tLearning Rate α: %v\n\tRegularization Parameter λ: %v\n...\n\n", s.method, examples, s.k, len(s.trainingSet[0]), s.alpha, s.regularization) var err error if s.method == base.BatchGA { err = func() error { // if the iterations given is 0, set it to be // 5000 (seems reasonable base value) if s.maxIterations == 0 { s.maxIterations = 5000 } iter := 0 // Stop iterating if the number of iterations exceeds // the limit for ; iter < s.maxIterations; iter++ { // go over each parameter vector for each // classification value newTheta := make([][]float64, len(s.Parameters)) for k, theta := range s.Parameters { newTheta[k] = make([]float64, len(theta)) dj, err := s.Dj(k) if err != nil { return err } for j := range theta { newTheta[k][j] = theta[j] + s.alpha*dj[j] if math.IsInf(newTheta[k][j], 0) || math.IsNaN(newTheta[k][j]) { return fmt.Errorf("Sorry dude! Learning diverged. Some value of the parameter vector theta is ±Inf or NaN") } } } s.Parameters = newTheta } fmt.Fprintf(s.Output, "Went through %v iterations.\n", iter) return nil }() } else if s.method == base.StochasticGA { err = func() error { // if the iterations given is 0, set it to be // 5000 (seems reasonable base value) if s.maxIterations == 0 { s.maxIterations = 5000 } iter := 0 // Stop iterating if the number of iterations exceeds // the limit for ; iter < s.maxIterations; iter++ { for j := range s.trainingSet { newTheta := make([][]float64, len(s.Parameters)) // go over each parameter vector for each // classification value for k, theta := range s.Parameters { newTheta[k] = make([]float64, len(theta)) dj, err := s.Dij(j, k) if err != nil { return err } // now simultaneously update theta for j := range theta { newTheta[k][j] = theta[j] + s.alpha*dj[j] if math.IsInf(newTheta[k][j], 0) || math.IsNaN(newTheta[k][j]) { return fmt.Errorf("Sorry dude! Learning diverged. Some value of the parameter vector theta is ±Inf or NaN") } } } s.Parameters = newTheta } } fmt.Fprintf(s.Output, "Went through %v iterations.\n", iter) return nil }() } else { err = fmt.Errorf("Chose a training method not implemented for Softmax regression") } if err != nil { fmt.Fprintf(s.Output, "\nERROR: Error while learning –\n\t%v\n\n", err) return err } fmt.Fprintf(s.Output, "Training Completed.\n%v\n\n", s) return nil }
[ "func", "(", "s", "*", "Softmax", ")", "Learn", "(", ")", "error", "{", "if", "s", ".", "trainingSet", "==", "nil", "||", "s", ".", "expectedResults", "==", "nil", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ")", "\n", "fmt", ...
// Learn takes the struct's dataset and expected results and runs // gradient descent on them, optimizing theta so you can // predict accurately based on those results
[ "Learn", "takes", "the", "struct", "s", "dataset", "and", "expected", "results", "and", "runs", "gradient", "descent", "on", "them", "optimizing", "theta", "so", "you", "can", "predict", "accurately", "based", "on", "those", "results" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/linear/softmax.go#L198-L312
train
cdipaolo/goml
text/tfidf.go
Less
func (f Frequencies) Less(i, j int) bool { return f[i].TFIDF < f[j].TFIDF }
go
func (f Frequencies) Less(i, j int) bool { return f[i].TFIDF < f[j].TFIDF }
[ "func", "(", "f", "Frequencies", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "f", "[", "i", "]", ".", "TFIDF", "<", "f", "[", "j", "]", ".", "TFIDF", "\n", "}" ]
// Less gives whether the ith element // of a frequency list has is lesser // than the jth element by comparing // their TFIDF values
[ "Less", "gives", "whether", "the", "ith", "element", "of", "a", "frequency", "list", "has", "is", "lesser", "than", "the", "jth", "element", "by", "comparing", "their", "TFIDF", "values" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L64-L66
train
cdipaolo/goml
text/tfidf.go
Swap
func (f Frequencies) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
go
func (f Frequencies) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
[ "func", "(", "f", "Frequencies", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "f", "[", "i", "]", ",", "f", "[", "j", "]", "=", "f", "[", "j", "]", ",", "f", "[", "i", "]", "\n", "}" ]
// Swap swaps two indexed values in // a frequency slice
[ "Swap", "swaps", "two", "indexed", "values", "in", "a", "frequency", "slice" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L70-L72
train
cdipaolo/goml
text/tfidf.go
TFIDF
func (t *TFIDF) TFIDF(word string, sentence string) float64 { sentence, _, _ = transform.String(t.sanitize, sentence) document := t.Tokenizer.Tokenize(sentence) return t.TermFrequency(word, document) * t.InverseDocumentFrequency(word) }
go
func (t *TFIDF) TFIDF(word string, sentence string) float64 { sentence, _, _ = transform.String(t.sanitize, sentence) document := t.Tokenizer.Tokenize(sentence) return t.TermFrequency(word, document) * t.InverseDocumentFrequency(word) }
[ "func", "(", "t", "*", "TFIDF", ")", "TFIDF", "(", "word", "string", ",", "sentence", "string", ")", "float64", "{", "sentence", ",", "_", ",", "_", "=", "transform", ".", "String", "(", "t", ".", "sanitize", ",", "sentence", ")", "\n", "document", ...
// TFIDF returns the TermFrequency- // InverseDocumentFrequency of a word // within a corpus given by the trained // NaiveBayes model // // Look at the TFIDF docs to see more about how // this is calculated
[ "TFIDF", "returns", "the", "TermFrequency", "-", "InverseDocumentFrequency", "of", "a", "word", "within", "a", "corpus", "given", "by", "the", "trained", "NaiveBayes", "model", "Look", "at", "the", "TFIDF", "docs", "to", "see", "more", "about", "how", "this", ...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L81-L86
train
cdipaolo/goml
text/tfidf.go
MostImportantWords
func (t *TFIDF) MostImportantWords(sentence string, n int) Frequencies { sentence, _, _ = transform.String(t.sanitize, sentence) document := t.Tokenizer.Tokenize(sentence) freq := TermFrequencies(document) for i := range freq { freq[i].TFIDF = freq[i].Frequency * t.InverseDocumentFrequency(freq[i].Word) freq[i].Frequency = float64(0.0) } // sort into slice sort.Sort(sort.Reverse(freq)) if n > len(freq) { return freq } return freq[:n] }
go
func (t *TFIDF) MostImportantWords(sentence string, n int) Frequencies { sentence, _, _ = transform.String(t.sanitize, sentence) document := t.Tokenizer.Tokenize(sentence) freq := TermFrequencies(document) for i := range freq { freq[i].TFIDF = freq[i].Frequency * t.InverseDocumentFrequency(freq[i].Word) freq[i].Frequency = float64(0.0) } // sort into slice sort.Sort(sort.Reverse(freq)) if n > len(freq) { return freq } return freq[:n] }
[ "func", "(", "t", "*", "TFIDF", ")", "MostImportantWords", "(", "sentence", "string", ",", "n", "int", ")", "Frequencies", "{", "sentence", ",", "_", ",", "_", "=", "transform", ".", "String", "(", "t", ".", "sanitize", ",", "sentence", ")", "\n", "d...
// MostImportantWords runs TFIDF on a // whole document, returning the n most // important words in the document. If // n is greater than the number of words // then all words will be returned. // // The returned keyword slice is sorted // by importance
[ "MostImportantWords", "runs", "TFIDF", "on", "a", "whole", "document", "returning", "the", "n", "most", "important", "words", "in", "the", "document", ".", "If", "n", "is", "greater", "than", "the", "number", "of", "words", "then", "all", "words", "will", ...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L96-L114
train
cdipaolo/goml
text/tfidf.go
TermFrequency
func (t *TFIDF) TermFrequency(word string, document []string) float64 { words := make(map[string]int) for i := range document { words[document[i]]++ } // find max word frequency var maxFreq int for i := range words { if words[i] > maxFreq { maxFreq = words[i] } } return 0.5 * (1 + float64(words[word])/float64(maxFreq)) }
go
func (t *TFIDF) TermFrequency(word string, document []string) float64 { words := make(map[string]int) for i := range document { words[document[i]]++ } // find max word frequency var maxFreq int for i := range words { if words[i] > maxFreq { maxFreq = words[i] } } return 0.5 * (1 + float64(words[word])/float64(maxFreq)) }
[ "func", "(", "t", "*", "TFIDF", ")", "TermFrequency", "(", "word", "string", ",", "document", "[", "]", "string", ")", "float64", "{", "words", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "i", ":=", "range", "document", "...
// TermFrequency returns the term frequency // of a word within a corpus defined by the // trained NaiveBayes model // // Look at the TFIDF docs to see more about how // this is calculated
[ "TermFrequency", "returns", "the", "term", "frequency", "of", "a", "word", "within", "a", "corpus", "defined", "by", "the", "trained", "NaiveBayes", "model", "Look", "at", "the", "TFIDF", "docs", "to", "see", "more", "about", "how", "this", "is", "calculated...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L122-L137
train
cdipaolo/goml
text/tfidf.go
TermFrequencies
func TermFrequencies(document []string) Frequencies { words := make(map[string]int) for i := range document { words[document[i]]++ } var maxFreq int for i := range words { if words[i] > maxFreq { maxFreq = words[i] } } // make frequency map frequencies := Frequencies{} for i := range words { frequencies = append(frequencies, Frequency{ Word: i, Frequency: 0.5 * (1 + float64(words[i])/float64(maxFreq)), }) } return frequencies }
go
func TermFrequencies(document []string) Frequencies { words := make(map[string]int) for i := range document { words[document[i]]++ } var maxFreq int for i := range words { if words[i] > maxFreq { maxFreq = words[i] } } // make frequency map frequencies := Frequencies{} for i := range words { frequencies = append(frequencies, Frequency{ Word: i, Frequency: 0.5 * (1 + float64(words[i])/float64(maxFreq)), }) } return frequencies }
[ "func", "TermFrequencies", "(", "document", "[", "]", "string", ")", "Frequencies", "{", "words", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "i", ":=", "range", "document", "{", "words", "[", "document", "[", "i", "]", "]"...
// TermFrequencies gives the TermFrequency of // all words in a document, and is more efficient // at doing so than calling that function multiple // times
[ "TermFrequencies", "gives", "the", "TermFrequency", "of", "all", "words", "in", "a", "document", "and", "is", "more", "efficient", "at", "doing", "so", "than", "calling", "that", "function", "multiple", "times" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L143-L166
train
cdipaolo/goml
text/tfidf.go
InverseDocumentFrequency
func (t *TFIDF) InverseDocumentFrequency(word string) float64 { w, _ := t.Words.Get(word) return math.Log(float64(t.DocumentCount)) - math.Log(float64(w.DocsSeen)+1) }
go
func (t *TFIDF) InverseDocumentFrequency(word string) float64 { w, _ := t.Words.Get(word) return math.Log(float64(t.DocumentCount)) - math.Log(float64(w.DocsSeen)+1) }
[ "func", "(", "t", "*", "TFIDF", ")", "InverseDocumentFrequency", "(", "word", "string", ")", "float64", "{", "w", ",", "_", ":=", "t", ".", "Words", ".", "Get", "(", "word", ")", "\n", "return", "math", ".", "Log", "(", "float64", "(", "t", ".", ...
// InverseDocumentFrequency returns the 'uniqueness' // of a word within the corpus defined within a // trained NaiveBayes model. // // Look at the TFIDF docs to see more about how // this is calculated
[ "InverseDocumentFrequency", "returns", "the", "uniqueness", "of", "a", "word", "within", "the", "corpus", "defined", "within", "a", "trained", "NaiveBayes", "model", ".", "Look", "at", "the", "TFIDF", "docs", "to", "see", "more", "about", "how", "this", "is", ...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L174-L177
train
cdipaolo/goml
base/munge.go
NormalizePoint
func NormalizePoint(x []float64) { var sum float64 for i := range x { sum += x[i] * x[i] } mag := math.Sqrt(sum) for i := range x { if math.IsInf(x[i]/mag, 0) || math.IsNaN(x[i]/mag) { // fallback to zero when dividing by 0 x[i] = 0 continue } x[i] /= mag } }
go
func NormalizePoint(x []float64) { var sum float64 for i := range x { sum += x[i] * x[i] } mag := math.Sqrt(sum) for i := range x { if math.IsInf(x[i]/mag, 0) || math.IsNaN(x[i]/mag) { // fallback to zero when dividing by 0 x[i] = 0 continue } x[i] /= mag } }
[ "func", "NormalizePoint", "(", "x", "[", "]", "float64", ")", "{", "var", "sum", "float64", "\n", "for", "i", ":=", "range", "x", "{", "sum", "+=", "x", "[", "i", "]", "*", "x", "[", "i", "]", "\n", "}", "\n\n", "mag", ":=", "math", ".", "Sqr...
// NormalizePoint is the same as Normalize, // but it only operates on one singular datapoint, // normalizing it's value to unit length.
[ "NormalizePoint", "is", "the", "same", "as", "Normalize", "but", "it", "only", "operates", "on", "one", "singular", "datapoint", "normalizing", "it", "s", "value", "to", "unit", "length", "." ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/base/munge.go#L23-L41
train
cdipaolo/goml
text/bayes.go
Tokenize
func (t *SimpleTokenizer) Tokenize(sentence string) []string { // is the tokenizer really the best place to be making // everything lowercase? is this really a sanitizaion func? return strings.Split(strings.ToLower(sentence), t.SplitOn) }
go
func (t *SimpleTokenizer) Tokenize(sentence string) []string { // is the tokenizer really the best place to be making // everything lowercase? is this really a sanitizaion func? return strings.Split(strings.ToLower(sentence), t.SplitOn) }
[ "func", "(", "t", "*", "SimpleTokenizer", ")", "Tokenize", "(", "sentence", "string", ")", "[", "]", "string", "{", "// is the tokenizer really the best place to be making", "// everything lowercase? is this really a sanitizaion func?", "return", "strings", ".", "Split", "(...
// Tokenize splits input sentences into a lowecase slice // of strings. The tokenizer's SlitOn string is used as a // delimiter and it
[ "Tokenize", "splits", "input", "sentences", "into", "a", "lowecase", "slice", "of", "strings", ".", "The", "tokenizer", "s", "SlitOn", "string", "is", "used", "as", "a", "delimiter", "and", "it" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L186-L190
train
cdipaolo/goml
text/bayes.go
Get
func (m *concurrentMap) Get(w string) (Word, bool) { m.RLock() result, ok := m.words[w] m.RUnlock() return result, ok }
go
func (m *concurrentMap) Get(w string) (Word, bool) { m.RLock() result, ok := m.words[w] m.RUnlock() return result, ok }
[ "func", "(", "m", "*", "concurrentMap", ")", "Get", "(", "w", "string", ")", "(", "Word", ",", "bool", ")", "{", "m", ".", "RLock", "(", ")", "\n", "result", ",", "ok", ":=", "m", ".", "words", "[", "w", "]", "\n", "m", ".", "RUnlock", "(", ...
// Get looks up a word from h's Word map and should be used // in place of a direct map lookup. The only caveat is that // it will always return the 'success' boolean
[ "Get", "looks", "up", "a", "word", "from", "h", "s", "Word", "map", "and", "should", "be", "used", "in", "place", "of", "a", "direct", "map", "lookup", ".", "The", "only", "caveat", "is", "that", "it", "will", "always", "return", "the", "success", "b...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L215-L220
train
cdipaolo/goml
text/bayes.go
Set
func (m *concurrentMap) Set(k string, v Word) { m.Lock() m.words[k] = v m.Unlock() }
go
func (m *concurrentMap) Set(k string, v Word) { m.Lock() m.words[k] = v m.Unlock() }
[ "func", "(", "m", "*", "concurrentMap", ")", "Set", "(", "k", "string", ",", "v", "Word", ")", "{", "m", ".", "Lock", "(", ")", "\n", "m", ".", "words", "[", "k", "]", "=", "v", "\n", "m", ".", "Unlock", "(", ")", "\n", "}" ]
// Set sets word k's value to v in h's Word map
[ "Set", "sets", "word", "k", "s", "value", "to", "v", "in", "h", "s", "Word", "map" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L223-L227
train
cdipaolo/goml
text/bayes.go
NewNaiveBayes
func NewNaiveBayes(stream <-chan base.TextDatapoint, classes uint8, sanitize func(rune) bool) *NaiveBayes { return &NaiveBayes{ Words: concurrentMap{sync.RWMutex{}, make(map[string]Word)}, Count: make([]uint64, classes), Probabilities: make([]float64, classes), sanitize: transform.RemoveFunc(sanitize), stream: stream, Tokenizer: &SimpleTokenizer{SplitOn: " "}, Output: os.Stdout, } }
go
func NewNaiveBayes(stream <-chan base.TextDatapoint, classes uint8, sanitize func(rune) bool) *NaiveBayes { return &NaiveBayes{ Words: concurrentMap{sync.RWMutex{}, make(map[string]Word)}, Count: make([]uint64, classes), Probabilities: make([]float64, classes), sanitize: transform.RemoveFunc(sanitize), stream: stream, Tokenizer: &SimpleTokenizer{SplitOn: " "}, Output: os.Stdout, } }
[ "func", "NewNaiveBayes", "(", "stream", "<-", "chan", "base", ".", "TextDatapoint", ",", "classes", "uint8", ",", "sanitize", "func", "(", "rune", ")", "bool", ")", "*", "NaiveBayes", "{", "return", "&", "NaiveBayes", "{", "Words", ":", "concurrentMap", "{...
// NewNaiveBayes returns a NaiveBayes model the // given number of classes instantiated, ready // to learn off the given data stream. The sanitization // function is set to the given function. It must // comply with the transform.RemoveFunc interface
[ "NewNaiveBayes", "returns", "a", "NaiveBayes", "model", "the", "given", "number", "of", "classes", "instantiated", "ready", "to", "learn", "off", "the", "given", "data", "stream", ".", "The", "sanitization", "function", "is", "set", "to", "the", "given", "func...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L259-L271
train
cdipaolo/goml
text/bayes.go
Predict
func (b *NaiveBayes) Predict(sentence string) uint8 { sums := make([]float64, len(b.Count)) sentence, _, _ = transform.String(b.sanitize, sentence) words := b.Tokenizer.Tokenize(sentence) for _, word := range words { w, ok := b.Words.Get(word) if !ok { continue } for i := range sums { sums[i] += math.Log(float64(w.Count[i]+1) / float64(w.Seen+b.DictCount)) } } for i := range sums { sums[i] += math.Log(b.Probabilities[i]) } // find best class var maxI int for i := range sums { if sums[i] > sums[maxI] { maxI = i } } return uint8(maxI) }
go
func (b *NaiveBayes) Predict(sentence string) uint8 { sums := make([]float64, len(b.Count)) sentence, _, _ = transform.String(b.sanitize, sentence) words := b.Tokenizer.Tokenize(sentence) for _, word := range words { w, ok := b.Words.Get(word) if !ok { continue } for i := range sums { sums[i] += math.Log(float64(w.Count[i]+1) / float64(w.Seen+b.DictCount)) } } for i := range sums { sums[i] += math.Log(b.Probabilities[i]) } // find best class var maxI int for i := range sums { if sums[i] > sums[maxI] { maxI = i } } return uint8(maxI) }
[ "func", "(", "b", "*", "NaiveBayes", ")", "Predict", "(", "sentence", "string", ")", "uint8", "{", "sums", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "b", ".", "Count", ")", ")", "\n\n", "sentence", ",", "_", ",", "_", "=", "transfo...
// Predict takes in a document, predicts the // class of the document based on the training // data passed so far, and returns the class // estimated for the document.
[ "Predict", "takes", "in", "a", "document", "predicts", "the", "class", "of", "the", "document", "based", "on", "the", "training", "data", "passed", "so", "far", "and", "returns", "the", "class", "estimated", "for", "the", "document", "." ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L277-L306
train
cdipaolo/goml
text/bayes.go
OnlineLearn
func (b *NaiveBayes) OnlineLearn(errors chan<- error) { if errors == nil { errors = make(chan error) } if b.stream == nil { errors <- fmt.Errorf("ERROR: attempting to learn with nil data stream!\n") close(errors) return } fmt.Fprintf(b.Output, "Training:\n\tModel: Multinomial Naïve Bayes\n\tClasses: %v\n", len(b.Count)) var point base.TextDatapoint var more bool for { point, more = <-b.stream if more { // sanitize and break up document sanitized, _, _ := transform.String(b.sanitize, point.X) words := b.Tokenizer.Tokenize(sanitized) C := int(point.Y) if C > len(b.Count)-1 { errors <- fmt.Errorf("ERROR: given document class is greater than the number of classes in the model!\n") continue } // update global class probabilities b.Count[C]++ b.DocumentCount++ for i := range b.Probabilities { b.Probabilities[i] = float64(b.Count[i]) / float64(b.DocumentCount) } // store words seen in document (to add to DocsSeen) seenCount := make(map[string]int) // update probabilities for words for _, word := range words { if len(word) < 3 { continue } w, ok := b.Words.Get(word) if !ok { w = Word{ Count: make([]uint64, len(b.Count)), Seen: uint64(0), } b.DictCount++ } w.Count[C]++ w.Seen++ b.Words.Set(word, w) seenCount[word] = 1 } // add to DocsSeen for term := range seenCount { tmp, _ := b.Words.Get(term) tmp.DocsSeen++ b.Words.Set(term, tmp) } } else { fmt.Fprintf(b.Output, "Training Completed.\n%v\n\n", b) close(errors) return } } }
go
func (b *NaiveBayes) OnlineLearn(errors chan<- error) { if errors == nil { errors = make(chan error) } if b.stream == nil { errors <- fmt.Errorf("ERROR: attempting to learn with nil data stream!\n") close(errors) return } fmt.Fprintf(b.Output, "Training:\n\tModel: Multinomial Naïve Bayes\n\tClasses: %v\n", len(b.Count)) var point base.TextDatapoint var more bool for { point, more = <-b.stream if more { // sanitize and break up document sanitized, _, _ := transform.String(b.sanitize, point.X) words := b.Tokenizer.Tokenize(sanitized) C := int(point.Y) if C > len(b.Count)-1 { errors <- fmt.Errorf("ERROR: given document class is greater than the number of classes in the model!\n") continue } // update global class probabilities b.Count[C]++ b.DocumentCount++ for i := range b.Probabilities { b.Probabilities[i] = float64(b.Count[i]) / float64(b.DocumentCount) } // store words seen in document (to add to DocsSeen) seenCount := make(map[string]int) // update probabilities for words for _, word := range words { if len(word) < 3 { continue } w, ok := b.Words.Get(word) if !ok { w = Word{ Count: make([]uint64, len(b.Count)), Seen: uint64(0), } b.DictCount++ } w.Count[C]++ w.Seen++ b.Words.Set(word, w) seenCount[word] = 1 } // add to DocsSeen for term := range seenCount { tmp, _ := b.Words.Get(term) tmp.DocsSeen++ b.Words.Set(term, tmp) } } else { fmt.Fprintf(b.Output, "Training Completed.\n%v\n\n", b) close(errors) return } } }
[ "func", "(", "b", "*", "NaiveBayes", ")", "OnlineLearn", "(", "errors", "chan", "<-", "error", ")", "{", "if", "errors", "==", "nil", "{", "errors", "=", "make", "(", "chan", "error", ")", "\n", "}", "\n", "if", "b", ".", "stream", "==", "nil", "...
// OnlineLearn lets the NaiveBayes model learn // from the datastream, waiting for new data to // come into the stream from a separate goroutine
[ "OnlineLearn", "lets", "the", "NaiveBayes", "model", "learn", "from", "the", "datastream", "waiting", "for", "new", "data", "to", "come", "into", "the", "stream", "from", "a", "separate", "goroutine" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L364-L441
train
cdipaolo/goml
text/bayes.go
UpdateSanitize
func (b *NaiveBayes) UpdateSanitize(sanitize func(rune) bool) { b.sanitize = transform.RemoveFunc(sanitize) }
go
func (b *NaiveBayes) UpdateSanitize(sanitize func(rune) bool) { b.sanitize = transform.RemoveFunc(sanitize) }
[ "func", "(", "b", "*", "NaiveBayes", ")", "UpdateSanitize", "(", "sanitize", "func", "(", "rune", ")", "bool", ")", "{", "b", ".", "sanitize", "=", "transform", ".", "RemoveFunc", "(", "sanitize", ")", "\n", "}" ]
// UpdateSanitize updates the NaiveBayes model's // text sanitization transformation function
[ "UpdateSanitize", "updates", "the", "NaiveBayes", "model", "s", "text", "sanitization", "transformation", "function" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L451-L453
train
cdipaolo/goml
text/bayes.go
RestoreWithFuncs
func (b *NaiveBayes) RestoreWithFuncs(data io.Reader, sanitizer func(rune) bool, tokenizer Tokenizer) error { if b == nil { return errors.New("Cannot restore a model to a nil pointer") } err := json.NewDecoder(data).Decode(b) if err != nil { return err } b.sanitize = transform.RemoveFunc(sanitizer) b.Tokenizer = tokenizer return nil }
go
func (b *NaiveBayes) RestoreWithFuncs(data io.Reader, sanitizer func(rune) bool, tokenizer Tokenizer) error { if b == nil { return errors.New("Cannot restore a model to a nil pointer") } err := json.NewDecoder(data).Decode(b) if err != nil { return err } b.sanitize = transform.RemoveFunc(sanitizer) b.Tokenizer = tokenizer return nil }
[ "func", "(", "b", "*", "NaiveBayes", ")", "RestoreWithFuncs", "(", "data", "io", ".", "Reader", ",", "sanitizer", "func", "(", "rune", ")", "bool", ",", "tokenizer", "Tokenizer", ")", "error", "{", "if", "b", "==", "nil", "{", "return", "errors", ".", ...
// RestoreWithFuncs takes raw JSON data of a model and // restores a model from it. The tokenizer and sanitizer // passed in will be assigned to the restored model.
[ "RestoreWithFuncs", "takes", "raw", "JSON", "data", "of", "a", "model", "and", "restores", "a", "model", "from", "it", ".", "The", "tokenizer", "and", "sanitizer", "passed", "in", "will", "be", "assigned", "to", "the", "restored", "model", "." ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L513-L524
train
cdipaolo/goml
cluster/triangle_kmeans.go
NewTriangleKMeans
func NewTriangleKMeans(k, maxIterations int, trainingSet [][]float64) *TriangleKMeans { var features int if len(trainingSet) != 0 { features = len(trainingSet[0]) } // start all guesses with the zero vector. // they will be changed during learning var guesses []int var info []pointInfo guesses = make([]int, len(trainingSet)) info = make([]pointInfo, len(trainingSet)) for i := range info { info[i] = pointInfo{ lower: make([]float64, k), upper: 0, recompute: true, } } rand.Seed(time.Now().UTC().Unix()) centroids := make([][]float64, k) centroidDist := make([][]float64, k) minCentroidDist := make([]float64, k) for i := range centroids { centroids[i] = make([]float64, features) centroidDist[i] = make([]float64, k) } return &TriangleKMeans{ maxIterations: maxIterations, trainingSet: trainingSet, guesses: guesses, info: info, Centroids: centroids, centroidDist: centroidDist, minCentroidDist: minCentroidDist, Output: os.Stdout, } }
go
func NewTriangleKMeans(k, maxIterations int, trainingSet [][]float64) *TriangleKMeans { var features int if len(trainingSet) != 0 { features = len(trainingSet[0]) } // start all guesses with the zero vector. // they will be changed during learning var guesses []int var info []pointInfo guesses = make([]int, len(trainingSet)) info = make([]pointInfo, len(trainingSet)) for i := range info { info[i] = pointInfo{ lower: make([]float64, k), upper: 0, recompute: true, } } rand.Seed(time.Now().UTC().Unix()) centroids := make([][]float64, k) centroidDist := make([][]float64, k) minCentroidDist := make([]float64, k) for i := range centroids { centroids[i] = make([]float64, features) centroidDist[i] = make([]float64, k) } return &TriangleKMeans{ maxIterations: maxIterations, trainingSet: trainingSet, guesses: guesses, info: info, Centroids: centroids, centroidDist: centroidDist, minCentroidDist: minCentroidDist, Output: os.Stdout, } }
[ "func", "NewTriangleKMeans", "(", "k", ",", "maxIterations", "int", ",", "trainingSet", "[", "]", "[", "]", "float64", ")", "*", "TriangleKMeans", "{", "var", "features", "int", "\n", "if", "len", "(", "trainingSet", ")", "!=", "0", "{", "features", "=",...
// NewTriangleKMeans returns a pointer to the k-means // model, which clusters given inputs in an // unsupervised manner. The differences between // this algorithm and the standard k-means++ // algorithm implemented in NewKMeans are discribed // in the struct comments and in the paper URL // found within those.
[ "NewTriangleKMeans", "returns", "a", "pointer", "to", "the", "k", "-", "means", "model", "which", "clusters", "given", "inputs", "in", "an", "unsupervised", "manner", ".", "The", "differences", "between", "this", "algorithm", "and", "the", "standard", "k", "-"...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/triangle_kmeans.go#L183-L225
train
cdipaolo/goml
cluster/triangle_kmeans.go
recalculateCentroids
func (k *TriangleKMeans) recalculateCentroids() [][]float64 { classTotal := make([][]float64, len(k.Centroids)) classCount := make([]int64, len(k.Centroids)) for j := range k.Centroids { classTotal[j] = make([]float64, len(k.trainingSet[0])) } for i, x := range k.trainingSet { classCount[k.guesses[i]]++ for j := range x { classTotal[k.guesses[i]][j] += x[j] } } centroids := append([][]float64{}, k.Centroids...) for j := range centroids { // if no objects are in the same class, // reinitialize it to a random vector if classCount[j] == 0 { for l := range centroids[j] { centroids[j][l] = 10 * (rand.Float64() - 0.5) } continue } for l := range centroids[j] { centroids[j][l] = classTotal[j][l] / float64(classCount[j]) } } return centroids }
go
func (k *TriangleKMeans) recalculateCentroids() [][]float64 { classTotal := make([][]float64, len(k.Centroids)) classCount := make([]int64, len(k.Centroids)) for j := range k.Centroids { classTotal[j] = make([]float64, len(k.trainingSet[0])) } for i, x := range k.trainingSet { classCount[k.guesses[i]]++ for j := range x { classTotal[k.guesses[i]][j] += x[j] } } centroids := append([][]float64{}, k.Centroids...) for j := range centroids { // if no objects are in the same class, // reinitialize it to a random vector if classCount[j] == 0 { for l := range centroids[j] { centroids[j][l] = 10 * (rand.Float64() - 0.5) } continue } for l := range centroids[j] { centroids[j][l] = classTotal[j][l] / float64(classCount[j]) } } return centroids }
[ "func", "(", "k", "*", "TriangleKMeans", ")", "recalculateCentroids", "(", ")", "[", "]", "[", "]", "float64", "{", "classTotal", ":=", "make", "(", "[", "]", "[", "]", "float64", ",", "len", "(", "k", ".", "Centroids", ")", ")", "\n", "classCount", ...
// recalculateCentroids assigns each centroid to // the mean of all points assigned to it. This // method is abstracted within the Triangle // accelerated KMeans variant because you are // skipping a lot of distance calculations within // the actual algorithm, so finding the mean of // assigned points is harder to embed. // // The method returns the new centers instead of // modifying the model's centroids.
[ "recalculateCentroids", "assigns", "each", "centroid", "to", "the", "mean", "of", "all", "points", "assigned", "to", "it", ".", "This", "method", "is", "abstracted", "within", "the", "Triangle", "accelerated", "KMeans", "variant", "because", "you", "are", "skipp...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/triangle_kmeans.go#L341-L373
train
cdipaolo/goml
cluster/triangle_kmeans.go
SaveClusteredData
func (k *TriangleKMeans) SaveClusteredData(filepath string) error { floatGuesses := []float64{} for _, val := range k.guesses { floatGuesses = append(floatGuesses, float64(val)) } return base.SaveDataToCSV(filepath, k.trainingSet, floatGuesses, true) }
go
func (k *TriangleKMeans) SaveClusteredData(filepath string) error { floatGuesses := []float64{} for _, val := range k.guesses { floatGuesses = append(floatGuesses, float64(val)) } return base.SaveDataToCSV(filepath, k.trainingSet, floatGuesses, true) }
[ "func", "(", "k", "*", "TriangleKMeans", ")", "SaveClusteredData", "(", "filepath", "string", ")", "error", "{", "floatGuesses", ":=", "[", "]", "float64", "{", "}", "\n", "for", "_", ",", "val", ":=", "range", "k", ".", "guesses", "{", "floatGuesses", ...
// SaveClusteredData takes operates on a k-means // model, concatenating the given dataset with the // assigned class from clustering and saving it to // file. // // Basically just a wrapper for the base.SaveDataToCSV // with the K-Means data.
[ "SaveClusteredData", "takes", "operates", "on", "a", "k", "-", "means", "model", "concatenating", "the", "given", "dataset", "with", "the", "assigned", "class", "from", "clustering", "and", "saving", "it", "to", "file", ".", "Basically", "just", "a", "wrapper"...
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/triangle_kmeans.go#L588-L595
train
cdipaolo/goml
linear/linear.go
Learn
func (l *LeastSquares) Learn() error { if l.trainingSet == nil || l.expectedResults == nil { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(l.Output, err.Error()) return err } examples := len(l.trainingSet) if examples == 0 || len(l.trainingSet[0]) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(l.Output, err.Error()) return err } if len(l.expectedResults) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no expected results! This isn't an unsupervised model!! You'll need to include data before you learn :)\n") fmt.Fprintf(l.Output, err.Error()) return err } fmt.Fprintf(l.Output, "Training:\n\tModel: Logistic (Binary) Classification\n\tOptimization Method: %v\n\tTraining Examples: %v\n\tFeatures: %v\n\tLearning Rate α: %v\n\tRegularization Parameter λ: %v\n...\n\n", l.method, examples, len(l.trainingSet[0]), l.alpha, l.regularization) var err error if l.method == base.BatchGA { err = base.GradientAscent(l) } else if l.method == base.StochasticGA { err = base.StochasticGradientAscent(l) } else { err = fmt.Errorf("Chose a training method not implemented for LeastSquares regression") } if err != nil { fmt.Fprintf(l.Output, "\nERROR: Error while learning –\n\t%v\n\n", err) return err } fmt.Fprintf(l.Output, "Training Completed.\n%v\n\n", l) return nil }
go
func (l *LeastSquares) Learn() error { if l.trainingSet == nil || l.expectedResults == nil { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(l.Output, err.Error()) return err } examples := len(l.trainingSet) if examples == 0 || len(l.trainingSet[0]) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no training examples!\n") fmt.Fprintf(l.Output, err.Error()) return err } if len(l.expectedResults) == 0 { err := fmt.Errorf("ERROR: Attempting to learn with no expected results! This isn't an unsupervised model!! You'll need to include data before you learn :)\n") fmt.Fprintf(l.Output, err.Error()) return err } fmt.Fprintf(l.Output, "Training:\n\tModel: Logistic (Binary) Classification\n\tOptimization Method: %v\n\tTraining Examples: %v\n\tFeatures: %v\n\tLearning Rate α: %v\n\tRegularization Parameter λ: %v\n...\n\n", l.method, examples, len(l.trainingSet[0]), l.alpha, l.regularization) var err error if l.method == base.BatchGA { err = base.GradientAscent(l) } else if l.method == base.StochasticGA { err = base.StochasticGradientAscent(l) } else { err = fmt.Errorf("Chose a training method not implemented for LeastSquares regression") } if err != nil { fmt.Fprintf(l.Output, "\nERROR: Error while learning –\n\t%v\n\n", err) return err } fmt.Fprintf(l.Output, "Training Completed.\n%v\n\n", l) return nil }
[ "func", "(", "l", "*", "LeastSquares", ")", "Learn", "(", ")", "error", "{", "if", "l", ".", "trainingSet", "==", "nil", "||", "l", ".", "expectedResults", "==", "nil", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ")", "\n", "f...
// Learn takes the struct's dataset and expected results and runs // batch gradient descent on them, optimizing theta so you can // predict based on those results
[ "Learn", "takes", "the", "struct", "s", "dataset", "and", "expected", "results", "and", "runs", "batch", "gradient", "descent", "on", "them", "optimizing", "theta", "so", "you", "can", "predict", "based", "on", "those", "results" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/linear/linear.go#L236-L273
train
cdipaolo/goml
linear/linear.go
J
func (l *LeastSquares) J() (float64, error) { var sum float64 for i := range l.trainingSet { prediction, err := l.Predict(l.trainingSet[i]) if err != nil { return 0, err } sum += (l.expectedResults[i] - prediction[0]) * (l.expectedResults[i] - prediction[0]) } // add regularization term! // // notice that the constant term doesn't matter for i := 1; i < len(l.Parameters); i++ { sum += l.regularization * l.Parameters[i] * l.Parameters[i] } return sum / float64(2*len(l.trainingSet)), nil }
go
func (l *LeastSquares) J() (float64, error) { var sum float64 for i := range l.trainingSet { prediction, err := l.Predict(l.trainingSet[i]) if err != nil { return 0, err } sum += (l.expectedResults[i] - prediction[0]) * (l.expectedResults[i] - prediction[0]) } // add regularization term! // // notice that the constant term doesn't matter for i := 1; i < len(l.Parameters); i++ { sum += l.regularization * l.Parameters[i] * l.Parameters[i] } return sum / float64(2*len(l.trainingSet)), nil }
[ "func", "(", "l", "*", "LeastSquares", ")", "J", "(", ")", "(", "float64", ",", "error", ")", "{", "var", "sum", "float64", "\n\n", "for", "i", ":=", "range", "l", ".", "trainingSet", "{", "prediction", ",", "err", ":=", "l", ".", "Predict", "(", ...
// J returns the Least Squares cost function of the given linear // model. Could be useful in testing convergence
[ "J", "returns", "the", "Least", "Squares", "cost", "function", "of", "the", "given", "linear", "model", ".", "Could", "be", "useful", "in", "testing", "convergence" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/linear/linear.go#L562-L582
train
spacemonkeygo/openssl
http.go
ListenAndServeTLS
func ListenAndServeTLS(addr string, cert_file string, key_file string, handler http.Handler) error { return ServerListenAndServeTLS( &http.Server{Addr: addr, Handler: handler}, cert_file, key_file) }
go
func ListenAndServeTLS(addr string, cert_file string, key_file string, handler http.Handler) error { return ServerListenAndServeTLS( &http.Server{Addr: addr, Handler: handler}, cert_file, key_file) }
[ "func", "ListenAndServeTLS", "(", "addr", "string", ",", "cert_file", "string", ",", "key_file", "string", ",", "handler", "http", ".", "Handler", ")", "error", "{", "return", "ServerListenAndServeTLS", "(", "&", "http", ".", "Server", "{", "Addr", ":", "add...
// ListenAndServeTLS will take an http.Handler and serve it using OpenSSL over // the given tcp address, configured to use the provided cert and key files.
[ "ListenAndServeTLS", "will", "take", "an", "http", ".", "Handler", "and", "serve", "it", "using", "OpenSSL", "over", "the", "given", "tcp", "address", "configured", "to", "use", "the", "provided", "cert", "and", "key", "files", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/http.go#L23-L27
train
spacemonkeygo/openssl
http.go
ServerListenAndServeTLS
func ServerListenAndServeTLS(srv *http.Server, cert_file, key_file string) error { addr := srv.Addr if addr == "" { addr = ":https" } ctx, err := NewCtxFromFiles(cert_file, key_file) if err != nil { return err } l, err := Listen("tcp", addr, ctx) if err != nil { return err } return srv.Serve(l) }
go
func ServerListenAndServeTLS(srv *http.Server, cert_file, key_file string) error { addr := srv.Addr if addr == "" { addr = ":https" } ctx, err := NewCtxFromFiles(cert_file, key_file) if err != nil { return err } l, err := Listen("tcp", addr, ctx) if err != nil { return err } return srv.Serve(l) }
[ "func", "ServerListenAndServeTLS", "(", "srv", "*", "http", ".", "Server", ",", "cert_file", ",", "key_file", "string", ")", "error", "{", "addr", ":=", "srv", ".", "Addr", "\n", "if", "addr", "==", "\"", "\"", "{", "addr", "=", "\"", "\"", "\n", "}"...
// ServerListenAndServeTLS will take an http.Server and serve it using OpenSSL // configured to use the provided cert and key files.
[ "ServerListenAndServeTLS", "will", "take", "an", "http", ".", "Server", "and", "serve", "it", "using", "OpenSSL", "configured", "to", "use", "the", "provided", "cert", "and", "key", "files", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/http.go#L31-L49
train
spacemonkeygo/openssl
init.go
errorFromErrorQueue
func errorFromErrorQueue() error { var errs []string for { err := C.ERR_get_error() if err == 0 { break } errs = append(errs, fmt.Sprintf("%s:%s:%s", C.GoString(C.ERR_lib_error_string(err)), C.GoString(C.ERR_func_error_string(err)), C.GoString(C.ERR_reason_error_string(err)))) } return errors.New(fmt.Sprintf("SSL errors: %s", strings.Join(errs, "\n"))) }
go
func errorFromErrorQueue() error { var errs []string for { err := C.ERR_get_error() if err == 0 { break } errs = append(errs, fmt.Sprintf("%s:%s:%s", C.GoString(C.ERR_lib_error_string(err)), C.GoString(C.ERR_func_error_string(err)), C.GoString(C.ERR_reason_error_string(err)))) } return errors.New(fmt.Sprintf("SSL errors: %s", strings.Join(errs, "\n"))) }
[ "func", "errorFromErrorQueue", "(", ")", "error", "{", "var", "errs", "[", "]", "string", "\n", "for", "{", "err", ":=", "C", ".", "ERR_get_error", "(", ")", "\n", "if", "err", "==", "0", "{", "break", "\n", "}", "\n", "errs", "=", "append", "(", ...
// errorFromErrorQueue needs to run in the same OS thread as the operation // that caused the possible error
[ "errorFromErrorQueue", "needs", "to", "run", "in", "the", "same", "OS", "thread", "as", "the", "operation", "that", "caused", "the", "possible", "error" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/init.go#L104-L117
train
spacemonkeygo/openssl
cert.go
NewName
func NewName() (*Name, error) { n := C.X509_NAME_new() if n == nil { return nil, errors.New("could not create x509 name") } name := &Name{name: n} runtime.SetFinalizer(name, func(n *Name) { C.X509_NAME_free(n.name) }) return name, nil }
go
func NewName() (*Name, error) { n := C.X509_NAME_new() if n == nil { return nil, errors.New("could not create x509 name") } name := &Name{name: n} runtime.SetFinalizer(name, func(n *Name) { C.X509_NAME_free(n.name) }) return name, nil }
[ "func", "NewName", "(", ")", "(", "*", "Name", ",", "error", ")", "{", "n", ":=", "C", ".", "X509_NAME_new", "(", ")", "\n", "if", "n", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "name...
// Allocate and return a new Name object.
[ "Allocate", "and", "return", "a", "new", "Name", "object", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L78-L88
train
spacemonkeygo/openssl
cert.go
AddTextEntry
func (n *Name) AddTextEntry(field, value string) error { cfield := C.CString(field) defer C.free(unsafe.Pointer(cfield)) cvalue := (*C.uchar)(unsafe.Pointer(C.CString(value))) defer C.free(unsafe.Pointer(cvalue)) ret := C.X509_NAME_add_entry_by_txt( n.name, cfield, C.MBSTRING_ASC, cvalue, -1, -1, 0) if ret != 1 { return errors.New("failed to add x509 name text entry") } return nil }
go
func (n *Name) AddTextEntry(field, value string) error { cfield := C.CString(field) defer C.free(unsafe.Pointer(cfield)) cvalue := (*C.uchar)(unsafe.Pointer(C.CString(value))) defer C.free(unsafe.Pointer(cvalue)) ret := C.X509_NAME_add_entry_by_txt( n.name, cfield, C.MBSTRING_ASC, cvalue, -1, -1, 0) if ret != 1 { return errors.New("failed to add x509 name text entry") } return nil }
[ "func", "(", "n", "*", "Name", ")", "AddTextEntry", "(", "field", ",", "value", "string", ")", "error", "{", "cfield", ":=", "C", ".", "CString", "(", "field", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cfield", ")",...
// AddTextEntry appends a text entry to an X509 NAME.
[ "AddTextEntry", "appends", "a", "text", "entry", "to", "an", "X509", "NAME", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L91-L102
train
spacemonkeygo/openssl
cert.go
AddTextEntries
func (n *Name) AddTextEntries(entries map[string]string) error { for f, v := range entries { if err := n.AddTextEntry(f, v); err != nil { return err } } return nil }
go
func (n *Name) AddTextEntries(entries map[string]string) error { for f, v := range entries { if err := n.AddTextEntry(f, v); err != nil { return err } } return nil }
[ "func", "(", "n", "*", "Name", ")", "AddTextEntries", "(", "entries", "map", "[", "string", "]", "string", ")", "error", "{", "for", "f", ",", "v", ":=", "range", "entries", "{", "if", "err", ":=", "n", ".", "AddTextEntry", "(", "f", ",", "v", ")...
// AddTextEntries allows adding multiple entries to a name in one call.
[ "AddTextEntries", "allows", "adding", "multiple", "entries", "to", "a", "name", "in", "one", "call", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L105-L112
train
spacemonkeygo/openssl
cert.go
NewCertificate
func NewCertificate(info *CertificateInfo, key PublicKey) (*Certificate, error) { c := &Certificate{x: C.X509_new()} runtime.SetFinalizer(c, func(c *Certificate) { C.X509_free(c.x) }) name, err := c.GetSubjectName() if err != nil { return nil, err } err = name.AddTextEntries(map[string]string{ "C": info.Country, "O": info.Organization, "CN": info.CommonName, }) if err != nil { return nil, err } // self-issue for now if err := c.SetIssuerName(name); err != nil { return nil, err } if err := c.SetSerial(info.Serial); err != nil { return nil, err } if err := c.SetIssueDate(info.Issued); err != nil { return nil, err } if err := c.SetExpireDate(info.Expires); err != nil { return nil, err } if err := c.SetPubKey(key); err != nil { return nil, err } return c, nil }
go
func NewCertificate(info *CertificateInfo, key PublicKey) (*Certificate, error) { c := &Certificate{x: C.X509_new()} runtime.SetFinalizer(c, func(c *Certificate) { C.X509_free(c.x) }) name, err := c.GetSubjectName() if err != nil { return nil, err } err = name.AddTextEntries(map[string]string{ "C": info.Country, "O": info.Organization, "CN": info.CommonName, }) if err != nil { return nil, err } // self-issue for now if err := c.SetIssuerName(name); err != nil { return nil, err } if err := c.SetSerial(info.Serial); err != nil { return nil, err } if err := c.SetIssueDate(info.Issued); err != nil { return nil, err } if err := c.SetExpireDate(info.Expires); err != nil { return nil, err } if err := c.SetPubKey(key); err != nil { return nil, err } return c, nil }
[ "func", "NewCertificate", "(", "info", "*", "CertificateInfo", ",", "key", "PublicKey", ")", "(", "*", "Certificate", ",", "error", ")", "{", "c", ":=", "&", "Certificate", "{", "x", ":", "C", ".", "X509_new", "(", ")", "}", "\n", "runtime", ".", "Se...
// NewCertificate generates a basic certificate based // on the provided CertificateInfo struct
[ "NewCertificate", "generates", "a", "basic", "certificate", "based", "on", "the", "provided", "CertificateInfo", "struct" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L129-L164
train
spacemonkeygo/openssl
cert.go
SetIssuer
func (c *Certificate) SetIssuer(issuer *Certificate) error { name, err := issuer.GetSubjectName() if err != nil { return err } if err = c.SetIssuerName(name); err != nil { return err } c.Issuer = issuer return nil }
go
func (c *Certificate) SetIssuer(issuer *Certificate) error { name, err := issuer.GetSubjectName() if err != nil { return err } if err = c.SetIssuerName(name); err != nil { return err } c.Issuer = issuer return nil }
[ "func", "(", "c", "*", "Certificate", ")", "SetIssuer", "(", "issuer", "*", "Certificate", ")", "error", "{", "name", ",", "err", ":=", "issuer", ".", "GetSubjectName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", ...
// SetIssuer updates the stored Issuer cert // and the internal x509 Issuer Name of a certificate. // The stored Issuer reference is used when adding extensions.
[ "SetIssuer", "updates", "the", "stored", "Issuer", "cert", "and", "the", "internal", "x509", "Issuer", "Name", "of", "a", "certificate", ".", "The", "stored", "Issuer", "reference", "is", "used", "when", "adding", "extensions", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L192-L202
train
spacemonkeygo/openssl
cert.go
SetIssuerName
func (c *Certificate) SetIssuerName(name *Name) error { if C.X509_set_issuer_name(c.x, name.name) != 1 { return errors.New("failed to set subject name") } return nil }
go
func (c *Certificate) SetIssuerName(name *Name) error { if C.X509_set_issuer_name(c.x, name.name) != 1 { return errors.New("failed to set subject name") } return nil }
[ "func", "(", "c", "*", "Certificate", ")", "SetIssuerName", "(", "name", "*", "Name", ")", "error", "{", "if", "C", ".", "X509_set_issuer_name", "(", "c", ".", "x", ",", "name", ".", "name", ")", "!=", "1", "{", "return", "errors", ".", "New", "(",...
// SetIssuerName populates the issuer name of a certificate. // Use SetIssuer instead, if possible.
[ "SetIssuerName", "populates", "the", "issuer", "name", "of", "a", "certificate", ".", "Use", "SetIssuer", "instead", "if", "possible", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L206-L211
train
spacemonkeygo/openssl
cert.go
SetSerial
func (c *Certificate) SetSerial(serial *big.Int) error { sno := C.ASN1_INTEGER_new() defer C.ASN1_INTEGER_free(sno) bn := C.BN_new() defer C.BN_free(bn) serialBytes := serial.Bytes() if bn = C.BN_bin2bn((*C.uchar)(unsafe.Pointer(&serialBytes[0])), C.int(len(serialBytes)), bn); bn == nil { return errors.New("failed to set serial") } if sno = C.BN_to_ASN1_INTEGER(bn, sno); sno == nil { return errors.New("failed to set serial") } if C.X509_set_serialNumber(c.x, sno) != 1 { return errors.New("failed to set serial") } return nil }
go
func (c *Certificate) SetSerial(serial *big.Int) error { sno := C.ASN1_INTEGER_new() defer C.ASN1_INTEGER_free(sno) bn := C.BN_new() defer C.BN_free(bn) serialBytes := serial.Bytes() if bn = C.BN_bin2bn((*C.uchar)(unsafe.Pointer(&serialBytes[0])), C.int(len(serialBytes)), bn); bn == nil { return errors.New("failed to set serial") } if sno = C.BN_to_ASN1_INTEGER(bn, sno); sno == nil { return errors.New("failed to set serial") } if C.X509_set_serialNumber(c.x, sno) != 1 { return errors.New("failed to set serial") } return nil }
[ "func", "(", "c", "*", "Certificate", ")", "SetSerial", "(", "serial", "*", "big", ".", "Int", ")", "error", "{", "sno", ":=", "C", ".", "ASN1_INTEGER_new", "(", ")", "\n", "defer", "C", ".", "ASN1_INTEGER_free", "(", "sno", ")", "\n", "bn", ":=", ...
// SetSerial sets the serial of a certificate.
[ "SetSerial", "sets", "the", "serial", "of", "a", "certificate", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L214-L231
train
spacemonkeygo/openssl
cert.go
SetExpireDate
func (c *Certificate) SetExpireDate(when time.Duration) error { offset := C.long(when / time.Second) result := C.X509_gmtime_adj(C.X_X509_get0_notAfter(c.x), offset) if result == nil { return errors.New("failed to set expire date") } return nil }
go
func (c *Certificate) SetExpireDate(when time.Duration) error { offset := C.long(when / time.Second) result := C.X509_gmtime_adj(C.X_X509_get0_notAfter(c.x), offset) if result == nil { return errors.New("failed to set expire date") } return nil }
[ "func", "(", "c", "*", "Certificate", ")", "SetExpireDate", "(", "when", "time", ".", "Duration", ")", "error", "{", "offset", ":=", "C", ".", "long", "(", "when", "/", "time", ".", "Second", ")", "\n", "result", ":=", "C", ".", "X509_gmtime_adj", "(...
// SetExpireDate sets the certificate issue date relative to the current time.
[ "SetExpireDate", "sets", "the", "certificate", "issue", "date", "relative", "to", "the", "current", "time", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L244-L251
train
spacemonkeygo/openssl
cert.go
SetPubKey
func (c *Certificate) SetPubKey(pubKey PublicKey) error { c.pubKey = pubKey if C.X509_set_pubkey(c.x, pubKey.evpPKey()) != 1 { return errors.New("failed to set public key") } return nil }
go
func (c *Certificate) SetPubKey(pubKey PublicKey) error { c.pubKey = pubKey if C.X509_set_pubkey(c.x, pubKey.evpPKey()) != 1 { return errors.New("failed to set public key") } return nil }
[ "func", "(", "c", "*", "Certificate", ")", "SetPubKey", "(", "pubKey", "PublicKey", ")", "error", "{", "c", ".", "pubKey", "=", "pubKey", "\n", "if", "C", ".", "X509_set_pubkey", "(", "c", ".", "x", ",", "pubKey", ".", "evpPKey", "(", ")", ")", "!=...
// SetPubKey assigns a new public key to a certificate.
[ "SetPubKey", "assigns", "a", "new", "public", "key", "to", "a", "certificate", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L254-L260
train
spacemonkeygo/openssl
cert.go
Sign
func (c *Certificate) Sign(privKey PrivateKey, digest EVP_MD) error { switch digest { case EVP_SHA256: case EVP_SHA384: case EVP_SHA512: default: return errors.New("Unsupported digest" + "You're probably looking for 'EVP_SHA256' or 'EVP_SHA512'.") } return c.insecureSign(privKey, digest) }
go
func (c *Certificate) Sign(privKey PrivateKey, digest EVP_MD) error { switch digest { case EVP_SHA256: case EVP_SHA384: case EVP_SHA512: default: return errors.New("Unsupported digest" + "You're probably looking for 'EVP_SHA256' or 'EVP_SHA512'.") } return c.insecureSign(privKey, digest) }
[ "func", "(", "c", "*", "Certificate", ")", "Sign", "(", "privKey", "PrivateKey", ",", "digest", "EVP_MD", ")", "error", "{", "switch", "digest", "{", "case", "EVP_SHA256", ":", "case", "EVP_SHA384", ":", "case", "EVP_SHA512", ":", "default", ":", "return",...
// Sign a certificate using a private key and a digest name. // Accepted digest names are 'sha256', 'sha384', and 'sha512'.
[ "Sign", "a", "certificate", "using", "a", "private", "key", "and", "a", "digest", "name", ".", "Accepted", "digest", "names", "are", "sha256", "sha384", "and", "sha512", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L264-L274
train
spacemonkeygo/openssl
cert.go
AddExtensions
func (c *Certificate) AddExtensions(extensions map[NID]string) error { for nid, value := range extensions { if err := c.AddExtension(nid, value); err != nil { return err } } return nil }
go
func (c *Certificate) AddExtensions(extensions map[NID]string) error { for nid, value := range extensions { if err := c.AddExtension(nid, value); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "Certificate", ")", "AddExtensions", "(", "extensions", "map", "[", "NID", "]", "string", ")", "error", "{", "for", "nid", ",", "value", ":=", "range", "extensions", "{", "if", "err", ":=", "c", ".", "AddExtension", "(", "nid", ...
// Wraps AddExtension using a map of NID to text extension. // Will return without finishing if it encounters an error.
[ "Wraps", "AddExtension", "using", "a", "map", "of", "NID", "to", "text", "extension", ".", "Will", "return", "without", "finishing", "if", "it", "encounters", "an", "error", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L336-L343
train
spacemonkeygo/openssl
cert.go
LoadCertificateFromPEM
func LoadCertificateFromPEM(pem_block []byte) (*Certificate, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } runtime.LockOSThread() defer runtime.UnlockOSThread() bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) cert := C.PEM_read_bio_X509(bio, nil, nil, nil) C.BIO_free(bio) if cert == nil { return nil, errorFromErrorQueue() } x := &Certificate{x: cert} runtime.SetFinalizer(x, func(x *Certificate) { C.X509_free(x.x) }) return x, nil }
go
func LoadCertificateFromPEM(pem_block []byte) (*Certificate, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } runtime.LockOSThread() defer runtime.UnlockOSThread() bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) cert := C.PEM_read_bio_X509(bio, nil, nil, nil) C.BIO_free(bio) if cert == nil { return nil, errorFromErrorQueue() } x := &Certificate{x: cert} runtime.SetFinalizer(x, func(x *Certificate) { C.X509_free(x.x) }) return x, nil }
[ "func", "LoadCertificateFromPEM", "(", "pem_block", "[", "]", "byte", ")", "(", "*", "Certificate", ",", "error", ")", "{", "if", "len", "(", "pem_block", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", ...
// LoadCertificateFromPEM loads an X509 certificate from a PEM-encoded block.
[ "LoadCertificateFromPEM", "loads", "an", "X509", "certificate", "from", "a", "PEM", "-", "encoded", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L346-L364
train
spacemonkeygo/openssl
cert.go
MarshalPEM
func (c *Certificate) MarshalPEM() (pem_block []byte, err error) { bio := C.BIO_new(C.BIO_s_mem()) if bio == nil { return nil, errors.New("failed to allocate memory BIO") } defer C.BIO_free(bio) if int(C.PEM_write_bio_X509(bio, c.x)) != 1 { return nil, errors.New("failed dumping certificate") } return ioutil.ReadAll(asAnyBio(bio)) }
go
func (c *Certificate) MarshalPEM() (pem_block []byte, err error) { bio := C.BIO_new(C.BIO_s_mem()) if bio == nil { return nil, errors.New("failed to allocate memory BIO") } defer C.BIO_free(bio) if int(C.PEM_write_bio_X509(bio, c.x)) != 1 { return nil, errors.New("failed dumping certificate") } return ioutil.ReadAll(asAnyBio(bio)) }
[ "func", "(", "c", "*", "Certificate", ")", "MarshalPEM", "(", ")", "(", "pem_block", "[", "]", "byte", ",", "err", "error", ")", "{", "bio", ":=", "C", ".", "BIO_new", "(", "C", ".", "BIO_s_mem", "(", ")", ")", "\n", "if", "bio", "==", "nil", "...
// MarshalPEM converts the X509 certificate to PEM-encoded format
[ "MarshalPEM", "converts", "the", "X509", "certificate", "to", "PEM", "-", "encoded", "format" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L367-L377
train
spacemonkeygo/openssl
cert.go
PublicKey
func (c *Certificate) PublicKey() (PublicKey, error) { pkey := C.X509_get_pubkey(c.x) if pkey == nil { return nil, errors.New("no public key found") } key := &pKey{key: pkey} runtime.SetFinalizer(key, func(key *pKey) { C.EVP_PKEY_free(key.key) }) return key, nil }
go
func (c *Certificate) PublicKey() (PublicKey, error) { pkey := C.X509_get_pubkey(c.x) if pkey == nil { return nil, errors.New("no public key found") } key := &pKey{key: pkey} runtime.SetFinalizer(key, func(key *pKey) { C.EVP_PKEY_free(key.key) }) return key, nil }
[ "func", "(", "c", "*", "Certificate", ")", "PublicKey", "(", ")", "(", "PublicKey", ",", "error", ")", "{", "pkey", ":=", "C", ".", "X509_get_pubkey", "(", "c", ".", "x", ")", "\n", "if", "pkey", "==", "nil", "{", "return", "nil", ",", "errors", ...
// PublicKey returns the public key embedded in the X509 certificate.
[ "PublicKey", "returns", "the", "public", "key", "embedded", "in", "the", "X509", "certificate", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L380-L390
train
spacemonkeygo/openssl
cert.go
GetSerialNumberHex
func (c *Certificate) GetSerialNumberHex() (serial string) { asn1_i := C.X509_get_serialNumber(c.x) bignum := C.ASN1_INTEGER_to_BN(asn1_i, nil) hex := C.BN_bn2hex(bignum) serial = C.GoString(hex) C.BN_free(bignum) C.X_OPENSSL_free(unsafe.Pointer(hex)) return }
go
func (c *Certificate) GetSerialNumberHex() (serial string) { asn1_i := C.X509_get_serialNumber(c.x) bignum := C.ASN1_INTEGER_to_BN(asn1_i, nil) hex := C.BN_bn2hex(bignum) serial = C.GoString(hex) C.BN_free(bignum) C.X_OPENSSL_free(unsafe.Pointer(hex)) return }
[ "func", "(", "c", "*", "Certificate", ")", "GetSerialNumberHex", "(", ")", "(", "serial", "string", ")", "{", "asn1_i", ":=", "C", ".", "X509_get_serialNumber", "(", "c", ".", "x", ")", "\n", "bignum", ":=", "C", ".", "ASN1_INTEGER_to_BN", "(", "asn1_i",...
// GetSerialNumberHex returns the certificate's serial number in hex format
[ "GetSerialNumberHex", "returns", "the", "certificate", "s", "serial", "number", "in", "hex", "format" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L393-L401
train
spacemonkeygo/openssl
cert.go
SetVersion
func (c *Certificate) SetVersion(version X509_Version) error { cvers := C.long(version) if C.X_X509_set_version(c.x, cvers) != 1 { return errors.New("failed to set certificate version") } return nil }
go
func (c *Certificate) SetVersion(version X509_Version) error { cvers := C.long(version) if C.X_X509_set_version(c.x, cvers) != 1 { return errors.New("failed to set certificate version") } return nil }
[ "func", "(", "c", "*", "Certificate", ")", "SetVersion", "(", "version", "X509_Version", ")", "error", "{", "cvers", ":=", "C", ".", "long", "(", "version", ")", "\n", "if", "C", ".", "X_X509_set_version", "(", "c", ".", "x", ",", "cvers", ")", "!=",...
// SetVersion sets the X509 version of the certificate.
[ "SetVersion", "sets", "the", "X509", "version", "of", "the", "certificate", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/cert.go#L409-L415
train
spacemonkeygo/openssl
conn.go
Server
func Server(conn net.Conn, ctx *Ctx) (*Conn, error) { c, err := newConn(conn, ctx) if err != nil { return nil, err } C.SSL_set_accept_state(c.ssl) return c, nil }
go
func Server(conn net.Conn, ctx *Ctx) (*Conn, error) { c, err := newConn(conn, ctx) if err != nil { return nil, err } C.SSL_set_accept_state(c.ssl) return c, nil }
[ "func", "Server", "(", "conn", "net", ".", "Conn", ",", "ctx", "*", "Ctx", ")", "(", "*", "Conn", ",", "error", ")", "{", "c", ",", "err", ":=", "newConn", "(", "conn", ",", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",...
// Server wraps an existing stream connection and puts it in the accept state // for any subsequent handshakes.
[ "Server", "wraps", "an", "existing", "stream", "connection", "and", "puts", "it", "in", "the", "accept", "state", "for", "any", "subsequent", "handshakes", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/conn.go#L181-L188
train
spacemonkeygo/openssl
conn.go
PeerCertificate
func (c *Conn) PeerCertificate() (*Certificate, error) { c.mtx.Lock() defer c.mtx.Unlock() if c.is_shutdown { return nil, errors.New("connection closed") } x := C.SSL_get_peer_certificate(c.ssl) if x == nil { return nil, errors.New("no peer certificate found") } cert := &Certificate{x: x} runtime.SetFinalizer(cert, func(cert *Certificate) { C.X509_free(cert.x) }) return cert, nil }
go
func (c *Conn) PeerCertificate() (*Certificate, error) { c.mtx.Lock() defer c.mtx.Unlock() if c.is_shutdown { return nil, errors.New("connection closed") } x := C.SSL_get_peer_certificate(c.ssl) if x == nil { return nil, errors.New("no peer certificate found") } cert := &Certificate{x: x} runtime.SetFinalizer(cert, func(cert *Certificate) { C.X509_free(cert.x) }) return cert, nil }
[ "func", "(", "c", "*", "Conn", ")", "PeerCertificate", "(", ")", "(", "*", "Certificate", ",", "error", ")", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "if", "c", ".", "is_shutdow...
// PeerCertificate returns the Certificate of the peer with which you're // communicating. Only valid after a handshake.
[ "PeerCertificate", "returns", "the", "Certificate", "of", "the", "peer", "with", "which", "you", "re", "communicating", ".", "Only", "valid", "after", "a", "handshake", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/conn.go#L316-L331
train
spacemonkeygo/openssl
conn.go
loadCertificateStack
func (c *Conn) loadCertificateStack(sk *C.struct_stack_st_X509) ( rv []*Certificate) { sk_num := int(C.X_sk_X509_num(sk)) rv = make([]*Certificate, 0, sk_num) for i := 0; i < sk_num; i++ { x := C.X_sk_X509_value(sk, C.int(i)) // ref holds on to the underlying connection memory so we don't need to // worry about incrementing refcounts manually or freeing the X509 rv = append(rv, &Certificate{x: x, ref: c}) } return rv }
go
func (c *Conn) loadCertificateStack(sk *C.struct_stack_st_X509) ( rv []*Certificate) { sk_num := int(C.X_sk_X509_num(sk)) rv = make([]*Certificate, 0, sk_num) for i := 0; i < sk_num; i++ { x := C.X_sk_X509_value(sk, C.int(i)) // ref holds on to the underlying connection memory so we don't need to // worry about incrementing refcounts manually or freeing the X509 rv = append(rv, &Certificate{x: x, ref: c}) } return rv }
[ "func", "(", "c", "*", "Conn", ")", "loadCertificateStack", "(", "sk", "*", "C", ".", "struct_stack_st_X509", ")", "(", "rv", "[", "]", "*", "Certificate", ")", "{", "sk_num", ":=", "int", "(", "C", ".", "X_sk_X509_num", "(", "sk", ")", ")", "\n", ...
// loadCertificateStack loads up a stack of x509 certificates and returns them, // handling memory ownership.
[ "loadCertificateStack", "loads", "up", "a", "stack", "of", "x509", "certificates", "and", "returns", "them", "handling", "memory", "ownership", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/conn.go#L335-L347
train
spacemonkeygo/openssl
conn.go
Close
func (c *Conn) Close() error { c.mtx.Lock() if c.is_shutdown { c.mtx.Unlock() return nil } c.is_shutdown = true c.mtx.Unlock() var errs utils.ErrorGroup errs.Add(c.shutdownLoop()) errs.Add(c.conn.Close()) return errs.Finalize() }
go
func (c *Conn) Close() error { c.mtx.Lock() if c.is_shutdown { c.mtx.Unlock() return nil } c.is_shutdown = true c.mtx.Unlock() var errs utils.ErrorGroup errs.Add(c.shutdownLoop()) errs.Add(c.conn.Close()) return errs.Finalize() }
[ "func", "(", "c", "*", "Conn", ")", "Close", "(", ")", "error", "{", "c", ".", "mtx", ".", "Lock", "(", ")", "\n", "if", "c", ".", "is_shutdown", "{", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "c", "....
// Close shuts down the SSL connection and closes the underlying wrapped // connection.
[ "Close", "shuts", "down", "the", "SSL", "connection", "and", "closes", "the", "underlying", "wrapped", "connection", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/conn.go#L427-L439
train
spacemonkeygo/openssl
conn.go
Write
func (c *Conn) Write(b []byte) (written int, err error) { if len(b) == 0 { return 0, nil } err = tryAgain for err == tryAgain { n, errcb := c.write(b) err = c.handleError(errcb) if err == nil { return n, c.flushOutputBuffer() } } return 0, err }
go
func (c *Conn) Write(b []byte) (written int, err error) { if len(b) == 0 { return 0, nil } err = tryAgain for err == tryAgain { n, errcb := c.write(b) err = c.handleError(errcb) if err == nil { return n, c.flushOutputBuffer() } } return 0, err }
[ "func", "(", "c", "*", "Conn", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "written", "int", ",", "err", "error", ")", "{", "if", "len", "(", "b", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "err", "=", "tryAgai...
// Write will encrypt the contents of b and write it to the underlying stream. // Performance will be vastly improved if the size of b is a multiple of // SSLRecordSize.
[ "Write", "will", "encrypt", "the", "contents", "of", "b", "and", "write", "it", "to", "the", "underlying", "stream", ".", "Performance", "will", "be", "vastly", "improved", "if", "the", "size", "of", "b", "is", "a", "multiple", "of", "SSLRecordSize", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/conn.go#L503-L516
train
spacemonkeygo/openssl
conn.go
VerifyHostname
func (c *Conn) VerifyHostname(host string) error { cert, err := c.PeerCertificate() if err != nil { return err } return cert.VerifyHostname(host) }
go
func (c *Conn) VerifyHostname(host string) error { cert, err := c.PeerCertificate() if err != nil { return err } return cert.VerifyHostname(host) }
[ "func", "(", "c", "*", "Conn", ")", "VerifyHostname", "(", "host", "string", ")", "error", "{", "cert", ",", "err", ":=", "c", ".", "PeerCertificate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "cert"...
// VerifyHostname pulls the PeerCertificate and calls VerifyHostname on the // certificate.
[ "VerifyHostname", "pulls", "the", "PeerCertificate", "and", "calls", "VerifyHostname", "on", "the", "certificate", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/conn.go#L520-L526
train
spacemonkeygo/openssl
digest.go
GetDigestByName
func GetDigestByName(name string) (*Digest, error) { cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) p := C.X_EVP_get_digestbyname(cname) if p == nil { return nil, fmt.Errorf("Digest %v not found", name) } // we can consider digests to use static mem; don't need to free return &Digest{ptr: p}, nil }
go
func GetDigestByName(name string) (*Digest, error) { cname := C.CString(name) defer C.free(unsafe.Pointer(cname)) p := C.X_EVP_get_digestbyname(cname) if p == nil { return nil, fmt.Errorf("Digest %v not found", name) } // we can consider digests to use static mem; don't need to free return &Digest{ptr: p}, nil }
[ "func", "GetDigestByName", "(", "name", "string", ")", "(", "*", "Digest", ",", "error", ")", "{", "cname", ":=", "C", ".", "CString", "(", "name", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cname", ")", ")", "\n", ...
// GetDigestByName returns the Digest with the name or nil and an error if the // digest was not found.
[ "GetDigestByName", "returns", "the", "Digest", "with", "the", "name", "or", "nil", "and", "an", "error", "if", "the", "digest", "was", "not", "found", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/digest.go#L32-L41
train
spacemonkeygo/openssl
digest.go
GetDigestByNid
func GetDigestByNid(nid NID) (*Digest, error) { sn, err := Nid2ShortName(nid) if err != nil { return nil, err } return GetDigestByName(sn) }
go
func GetDigestByNid(nid NID) (*Digest, error) { sn, err := Nid2ShortName(nid) if err != nil { return nil, err } return GetDigestByName(sn) }
[ "func", "GetDigestByNid", "(", "nid", "NID", ")", "(", "*", "Digest", ",", "error", ")", "{", "sn", ",", "err", ":=", "Nid2ShortName", "(", "nid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "...
// GetDigestByName returns the Digest with the NID or nil and an error if the // digest was not found.
[ "GetDigestByName", "returns", "the", "Digest", "with", "the", "NID", "or", "nil", "and", "an", "error", "if", "the", "digest", "was", "not", "found", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/digest.go#L45-L51
train
spacemonkeygo/openssl
utils/errors.go
Add
func (e *ErrorGroup) Add(err error) { if err != nil { e.Errors = append(e.Errors, err) } }
go
func (e *ErrorGroup) Add(err error) { if err != nil { e.Errors = append(e.Errors, err) } }
[ "func", "(", "e", "*", "ErrorGroup", ")", "Add", "(", "err", "error", ")", "{", "if", "err", "!=", "nil", "{", "e", ".", "Errors", "=", "append", "(", "e", ".", "Errors", ",", "err", ")", "\n", "}", "\n", "}" ]
// Add adds an error to an existing error group
[ "Add", "adds", "an", "error", "to", "an", "existing", "error", "group" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/utils/errors.go#L28-L32
train
spacemonkeygo/openssl
utils/errors.go
Finalize
func (e *ErrorGroup) Finalize() error { if len(e.Errors) == 0 { return nil } if len(e.Errors) == 1 { return e.Errors[0] } msgs := make([]string, 0, len(e.Errors)) for _, err := range e.Errors { msgs = append(msgs, err.Error()) } return errors.New(strings.Join(msgs, "\n")) }
go
func (e *ErrorGroup) Finalize() error { if len(e.Errors) == 0 { return nil } if len(e.Errors) == 1 { return e.Errors[0] } msgs := make([]string, 0, len(e.Errors)) for _, err := range e.Errors { msgs = append(msgs, err.Error()) } return errors.New(strings.Join(msgs, "\n")) }
[ "func", "(", "e", "*", "ErrorGroup", ")", "Finalize", "(", ")", "error", "{", "if", "len", "(", "e", ".", "Errors", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "len", "(", "e", ".", "Errors", ")", "==", "1", "{", "return", "e...
// Finalize returns an error corresponding to the ErrorGroup state. If there's // no errors in the group, finalize returns nil. If there's only one error, // Finalize returns that error. Otherwise, Finalize will make a new error // consisting of the messages from the constituent errors.
[ "Finalize", "returns", "an", "error", "corresponding", "to", "the", "ErrorGroup", "state", ".", "If", "there", "s", "no", "errors", "in", "the", "group", "finalize", "returns", "nil", ".", "If", "there", "s", "only", "one", "error", "Finalize", "returns", ...
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/utils/errors.go#L38-L50
train
spacemonkeygo/openssl
utils/future.go
NewFuture
func NewFuture() *Future { mutex := &sync.Mutex{} return &Future{ mutex: mutex, cond: sync.NewCond(mutex), received: false, val: nil, err: nil, } }
go
func NewFuture() *Future { mutex := &sync.Mutex{} return &Future{ mutex: mutex, cond: sync.NewCond(mutex), received: false, val: nil, err: nil, } }
[ "func", "NewFuture", "(", ")", "*", "Future", "{", "mutex", ":=", "&", "sync", ".", "Mutex", "{", "}", "\n", "return", "&", "Future", "{", "mutex", ":", "mutex", ",", "cond", ":", "sync", ".", "NewCond", "(", "mutex", ")", ",", "received", ":", "...
// NewFuture returns an initialized and ready Future.
[ "NewFuture", "returns", "an", "initialized", "and", "ready", "Future", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/utils/future.go#L36-L45
train
spacemonkeygo/openssl
utils/future.go
Get
func (self *Future) Get() (interface{}, error) { self.mutex.Lock() defer self.mutex.Unlock() for { if self.received { return self.val, self.err } self.cond.Wait() } }
go
func (self *Future) Get() (interface{}, error) { self.mutex.Lock() defer self.mutex.Unlock() for { if self.received { return self.val, self.err } self.cond.Wait() } }
[ "func", "(", "self", "*", "Future", ")", "Get", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "self", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "self", ".", "mutex", ".", "Unlock", "(", ")", "\n", "for", "{", "if", "...
// Get blocks until the Future has a value set.
[ "Get", "blocks", "until", "the", "Future", "has", "a", "value", "set", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/utils/future.go#L48-L57
train
spacemonkeygo/openssl
utils/future.go
Fired
func (self *Future) Fired() bool { self.mutex.Lock() defer self.mutex.Unlock() return self.received }
go
func (self *Future) Fired() bool { self.mutex.Lock() defer self.mutex.Unlock() return self.received }
[ "func", "(", "self", "*", "Future", ")", "Fired", "(", ")", "bool", "{", "self", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "self", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "self", ".", "received", "\n", "}" ]
// Fired returns whether or not a value has been set. If Fired is true, Get // won't block.
[ "Fired", "returns", "whether", "or", "not", "a", "value", "has", "been", "set", ".", "If", "Fired", "is", "true", "Get", "won", "t", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/utils/future.go#L61-L65
train
spacemonkeygo/openssl
utils/future.go
Set
func (self *Future) Set(val interface{}, err error) { self.mutex.Lock() defer self.mutex.Unlock() if self.received { return } self.received = true self.val = val self.err = err self.cond.Broadcast() }
go
func (self *Future) Set(val interface{}, err error) { self.mutex.Lock() defer self.mutex.Unlock() if self.received { return } self.received = true self.val = val self.err = err self.cond.Broadcast() }
[ "func", "(", "self", "*", "Future", ")", "Set", "(", "val", "interface", "{", "}", ",", "err", "error", ")", "{", "self", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "self", ".", "mutex", ".", "Unlock", "(", ")", "\n", "if", "self", "."...
// Set provides the value to present and future Get calls. If Set has already // been called, this is a no-op.
[ "Set", "provides", "the", "value", "to", "present", "and", "future", "Get", "calls", ".", "If", "Set", "has", "already", "been", "called", "this", "is", "a", "no", "-", "op", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/utils/future.go#L69-L79
train
spacemonkeygo/openssl
key.go
LoadPrivateKeyFromPEM
func LoadPrivateKeyFromPEM(pem_block []byte) (PrivateKey, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.PEM_read_bio_PrivateKey(bio, nil, nil, nil) if key == nil { return nil, errors.New("failed reading private key") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func LoadPrivateKeyFromPEM(pem_block []byte) (PrivateKey, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.PEM_read_bio_PrivateKey(bio, nil, nil, nil) if key == nil { return nil, errors.New("failed reading private key") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "LoadPrivateKeyFromPEM", "(", "pem_block", "[", "]", "byte", ")", "(", "PrivateKey", ",", "error", ")", "{", "if", "len", "(", "pem_block", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\...
// LoadPrivateKeyFromPEM loads a private key from a PEM-encoded block.
[ "LoadPrivateKeyFromPEM", "loads", "a", "private", "key", "from", "a", "PEM", "-", "encoded", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L276-L297
train
spacemonkeygo/openssl
key.go
LoadPrivateKeyFromPEMWithPassword
func LoadPrivateKeyFromPEMWithPassword(pem_block []byte, password string) ( PrivateKey, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) cs := C.CString(password) defer C.free(unsafe.Pointer(cs)) key := C.PEM_read_bio_PrivateKey(bio, nil, nil, unsafe.Pointer(cs)) if key == nil { return nil, errors.New("failed reading private key") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func LoadPrivateKeyFromPEMWithPassword(pem_block []byte, password string) ( PrivateKey, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) cs := C.CString(password) defer C.free(unsafe.Pointer(cs)) key := C.PEM_read_bio_PrivateKey(bio, nil, nil, unsafe.Pointer(cs)) if key == nil { return nil, errors.New("failed reading private key") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "LoadPrivateKeyFromPEMWithPassword", "(", "pem_block", "[", "]", "byte", ",", "password", "string", ")", "(", "PrivateKey", ",", "error", ")", "{", "if", "len", "(", "pem_block", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(...
// LoadPrivateKeyFromPEMWithPassword loads a private key from a PEM-encoded block.
[ "LoadPrivateKeyFromPEMWithPassword", "loads", "a", "private", "key", "from", "a", "PEM", "-", "encoded", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L300-L323
train
spacemonkeygo/openssl
key.go
LoadPrivateKeyFromDER
func LoadPrivateKeyFromDER(der_block []byte) (PrivateKey, error) { if len(der_block) == 0 { return nil, errors.New("empty der block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&der_block[0]), C.int(len(der_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.d2i_PrivateKey_bio(bio, nil) if key == nil { return nil, errors.New("failed reading private key der") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func LoadPrivateKeyFromDER(der_block []byte) (PrivateKey, error) { if len(der_block) == 0 { return nil, errors.New("empty der block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&der_block[0]), C.int(len(der_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.d2i_PrivateKey_bio(bio, nil) if key == nil { return nil, errors.New("failed reading private key der") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "LoadPrivateKeyFromDER", "(", "der_block", "[", "]", "byte", ")", "(", "PrivateKey", ",", "error", ")", "{", "if", "len", "(", "der_block", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\...
// LoadPrivateKeyFromDER loads a private key from a DER-encoded block.
[ "LoadPrivateKeyFromDER", "loads", "a", "private", "key", "from", "a", "DER", "-", "encoded", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L326-L347
train
spacemonkeygo/openssl
key.go
LoadPrivateKeyFromPEMWidthPassword
func LoadPrivateKeyFromPEMWidthPassword(pem_block []byte, password string) ( PrivateKey, error) { return LoadPrivateKeyFromPEMWithPassword(pem_block, password) }
go
func LoadPrivateKeyFromPEMWidthPassword(pem_block []byte, password string) ( PrivateKey, error) { return LoadPrivateKeyFromPEMWithPassword(pem_block, password) }
[ "func", "LoadPrivateKeyFromPEMWidthPassword", "(", "pem_block", "[", "]", "byte", ",", "password", "string", ")", "(", "PrivateKey", ",", "error", ")", "{", "return", "LoadPrivateKeyFromPEMWithPassword", "(", "pem_block", ",", "password", ")", "\n", "}" ]
// LoadPrivateKeyFromPEMWidthPassword loads a private key from a PEM-encoded block. // Backwards-compatible with typo
[ "LoadPrivateKeyFromPEMWidthPassword", "loads", "a", "private", "key", "from", "a", "PEM", "-", "encoded", "block", ".", "Backwards", "-", "compatible", "with", "typo" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L351-L354
train
spacemonkeygo/openssl
key.go
LoadPublicKeyFromPEM
func LoadPublicKeyFromPEM(pem_block []byte) (PublicKey, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.PEM_read_bio_PUBKEY(bio, nil, nil, nil) if key == nil { return nil, errors.New("failed reading public key der") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func LoadPublicKeyFromPEM(pem_block []byte) (PublicKey, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.PEM_read_bio_PUBKEY(bio, nil, nil, nil) if key == nil { return nil, errors.New("failed reading public key der") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "LoadPublicKeyFromPEM", "(", "pem_block", "[", "]", "byte", ")", "(", "PublicKey", ",", "error", ")", "{", "if", "len", "(", "pem_block", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n"...
// LoadPublicKeyFromPEM loads a public key from a PEM-encoded block.
[ "LoadPublicKeyFromPEM", "loads", "a", "public", "key", "from", "a", "PEM", "-", "encoded", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L357-L378
train
spacemonkeygo/openssl
key.go
LoadPublicKeyFromDER
func LoadPublicKeyFromDER(der_block []byte) (PublicKey, error) { if len(der_block) == 0 { return nil, errors.New("empty der block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&der_block[0]), C.int(len(der_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.d2i_PUBKEY_bio(bio, nil) if key == nil { return nil, errors.New("failed reading public key der") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func LoadPublicKeyFromDER(der_block []byte) (PublicKey, error) { if len(der_block) == 0 { return nil, errors.New("empty der block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&der_block[0]), C.int(len(der_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) key := C.d2i_PUBKEY_bio(bio, nil) if key == nil { return nil, errors.New("failed reading public key der") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "LoadPublicKeyFromDER", "(", "der_block", "[", "]", "byte", ")", "(", "PublicKey", ",", "error", ")", "{", "if", "len", "(", "der_block", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n"...
// LoadPublicKeyFromDER loads a public key from a DER-encoded block.
[ "LoadPublicKeyFromDER", "loads", "a", "public", "key", "from", "a", "DER", "-", "encoded", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L381-L402
train
spacemonkeygo/openssl
key.go
GenerateRSAKeyWithExponent
func GenerateRSAKeyWithExponent(bits int, exponent int) (PrivateKey, error) { rsa := C.RSA_generate_key(C.int(bits), C.ulong(exponent), nil, nil) if rsa == nil { return nil, errors.New("failed to generate RSA key") } key := C.X_EVP_PKEY_new() if key == nil { return nil, errors.New("failed to allocate EVP_PKEY") } if C.X_EVP_PKEY_assign_charp(key, C.EVP_PKEY_RSA, (*C.char)(unsafe.Pointer(rsa))) != 1 { C.X_EVP_PKEY_free(key) return nil, errors.New("failed to assign RSA key") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func GenerateRSAKeyWithExponent(bits int, exponent int) (PrivateKey, error) { rsa := C.RSA_generate_key(C.int(bits), C.ulong(exponent), nil, nil) if rsa == nil { return nil, errors.New("failed to generate RSA key") } key := C.X_EVP_PKEY_new() if key == nil { return nil, errors.New("failed to allocate EVP_PKEY") } if C.X_EVP_PKEY_assign_charp(key, C.EVP_PKEY_RSA, (*C.char)(unsafe.Pointer(rsa))) != 1 { C.X_EVP_PKEY_free(key) return nil, errors.New("failed to assign RSA key") } p := &pKey{key: key} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "GenerateRSAKeyWithExponent", "(", "bits", "int", ",", "exponent", "int", ")", "(", "PrivateKey", ",", "error", ")", "{", "rsa", ":=", "C", ".", "RSA_generate_key", "(", "C", ".", "int", "(", "bits", ")", ",", "C", ".", "ulong", "(", "exponent"...
// GenerateRSAKeyWithExponent generates a new RSA private key.
[ "GenerateRSAKeyWithExponent", "generates", "a", "new", "RSA", "private", "key", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L410-L428
train
spacemonkeygo/openssl
key.go
GenerateECKey
func GenerateECKey(curve EllipticCurve) (PrivateKey, error) { // Create context for parameter generation paramCtx := C.EVP_PKEY_CTX_new_id(C.EVP_PKEY_EC, nil) if paramCtx == nil { return nil, errors.New("failed creating EC parameter generation context") } defer C.EVP_PKEY_CTX_free(paramCtx) // Intialize the parameter generation if int(C.EVP_PKEY_paramgen_init(paramCtx)) != 1 { return nil, errors.New("failed initializing EC parameter generation context") } // Set curve in EC parameter generation context if int(C.X_EVP_PKEY_CTX_set_ec_paramgen_curve_nid(paramCtx, C.int(curve))) != 1 { return nil, errors.New("failed setting curve in EC parameter generation context") } // Create parameter object var params *C.EVP_PKEY if int(C.EVP_PKEY_paramgen(paramCtx, &params)) != 1 { return nil, errors.New("failed creating EC key generation parameters") } defer C.EVP_PKEY_free(params) // Create context for the key generation keyCtx := C.EVP_PKEY_CTX_new(params, nil) if keyCtx == nil { return nil, errors.New("failed creating EC key generation context") } defer C.EVP_PKEY_CTX_free(keyCtx) // Generate the key var privKey *C.EVP_PKEY if int(C.EVP_PKEY_keygen_init(keyCtx)) != 1 { return nil, errors.New("failed initializing EC key generation context") } if int(C.EVP_PKEY_keygen(keyCtx, &privKey)) != 1 { return nil, errors.New("failed generating EC private key") } p := &pKey{key: privKey} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func GenerateECKey(curve EllipticCurve) (PrivateKey, error) { // Create context for parameter generation paramCtx := C.EVP_PKEY_CTX_new_id(C.EVP_PKEY_EC, nil) if paramCtx == nil { return nil, errors.New("failed creating EC parameter generation context") } defer C.EVP_PKEY_CTX_free(paramCtx) // Intialize the parameter generation if int(C.EVP_PKEY_paramgen_init(paramCtx)) != 1 { return nil, errors.New("failed initializing EC parameter generation context") } // Set curve in EC parameter generation context if int(C.X_EVP_PKEY_CTX_set_ec_paramgen_curve_nid(paramCtx, C.int(curve))) != 1 { return nil, errors.New("failed setting curve in EC parameter generation context") } // Create parameter object var params *C.EVP_PKEY if int(C.EVP_PKEY_paramgen(paramCtx, &params)) != 1 { return nil, errors.New("failed creating EC key generation parameters") } defer C.EVP_PKEY_free(params) // Create context for the key generation keyCtx := C.EVP_PKEY_CTX_new(params, nil) if keyCtx == nil { return nil, errors.New("failed creating EC key generation context") } defer C.EVP_PKEY_CTX_free(keyCtx) // Generate the key var privKey *C.EVP_PKEY if int(C.EVP_PKEY_keygen_init(keyCtx)) != 1 { return nil, errors.New("failed initializing EC key generation context") } if int(C.EVP_PKEY_keygen(keyCtx, &privKey)) != 1 { return nil, errors.New("failed generating EC private key") } p := &pKey{key: privKey} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "GenerateECKey", "(", "curve", "EllipticCurve", ")", "(", "PrivateKey", ",", "error", ")", "{", "// Create context for parameter generation", "paramCtx", ":=", "C", ".", "EVP_PKEY_CTX_new_id", "(", "C", ".", "EVP_PKEY_EC", ",", "nil", ")", "\n", "if", "p...
// GenerateECKey generates a new elliptic curve private key on the speicified // curve.
[ "GenerateECKey", "generates", "a", "new", "elliptic", "curve", "private", "key", "on", "the", "speicified", "curve", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L432-L479
train
spacemonkeygo/openssl
key.go
GenerateED25519Key
func GenerateED25519Key() (PrivateKey, error) { // Key context keyCtx := C.EVP_PKEY_CTX_new_id(C.X_EVP_PKEY_ED25519, nil) if keyCtx == nil { return nil, errors.New("failed creating EC parameter generation context") } defer C.EVP_PKEY_CTX_free(keyCtx) // Generate the key var privKey *C.EVP_PKEY if int(C.EVP_PKEY_keygen_init(keyCtx)) != 1 { return nil, errors.New("failed initializing ED25519 key generation context") } if int(C.EVP_PKEY_keygen(keyCtx, &privKey)) != 1 { return nil, errors.New("failed generating ED25519 private key") } p := &pKey{key: privKey} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
go
func GenerateED25519Key() (PrivateKey, error) { // Key context keyCtx := C.EVP_PKEY_CTX_new_id(C.X_EVP_PKEY_ED25519, nil) if keyCtx == nil { return nil, errors.New("failed creating EC parameter generation context") } defer C.EVP_PKEY_CTX_free(keyCtx) // Generate the key var privKey *C.EVP_PKEY if int(C.EVP_PKEY_keygen_init(keyCtx)) != 1 { return nil, errors.New("failed initializing ED25519 key generation context") } if int(C.EVP_PKEY_keygen(keyCtx, &privKey)) != 1 { return nil, errors.New("failed generating ED25519 private key") } p := &pKey{key: privKey} runtime.SetFinalizer(p, func(p *pKey) { C.X_EVP_PKEY_free(p.key) }) return p, nil }
[ "func", "GenerateED25519Key", "(", ")", "(", "PrivateKey", ",", "error", ")", "{", "// Key context", "keyCtx", ":=", "C", ".", "EVP_PKEY_CTX_new_id", "(", "C", ".", "X_EVP_PKEY_ED25519", ",", "nil", ")", "\n", "if", "keyCtx", "==", "nil", "{", "return", "n...
// GenerateED25519Key generates a Ed25519 key
[ "GenerateED25519Key", "generates", "a", "Ed25519", "key" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L482-L504
train
spacemonkeygo/openssl
dhparam.go
LoadDHParametersFromPEM
func LoadDHParametersFromPEM(pem_block []byte) (*DH, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) params := C.PEM_read_bio_DHparams(bio, nil, nil, nil) if params == nil { return nil, errors.New("failed reading dh parameters") } dhparams := &DH{dh: params} runtime.SetFinalizer(dhparams, func(dhparams *DH) { C.DH_free(dhparams.dh) }) return dhparams, nil }
go
func LoadDHParametersFromPEM(pem_block []byte) (*DH, error) { if len(pem_block) == 0 { return nil, errors.New("empty pem block") } bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]), C.int(len(pem_block))) if bio == nil { return nil, errors.New("failed creating bio") } defer C.BIO_free(bio) params := C.PEM_read_bio_DHparams(bio, nil, nil, nil) if params == nil { return nil, errors.New("failed reading dh parameters") } dhparams := &DH{dh: params} runtime.SetFinalizer(dhparams, func(dhparams *DH) { C.DH_free(dhparams.dh) }) return dhparams, nil }
[ "func", "LoadDHParametersFromPEM", "(", "pem_block", "[", "]", "byte", ")", "(", "*", "DH", ",", "error", ")", "{", "if", "len", "(", "pem_block", ")", "==", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "...
// LoadDHParametersFromPEM loads the Diffie-Hellman parameters from // a PEM-encoded block.
[ "LoadDHParametersFromPEM", "loads", "the", "Diffie", "-", "Hellman", "parameters", "from", "a", "PEM", "-", "encoded", "block", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/dhparam.go#L32-L52
train
spacemonkeygo/openssl
dh.go
DeriveSharedSecret
func DeriveSharedSecret(private PrivateKey, public PublicKey) ([]byte, error) { // Create context for the shared secret derivation dhCtx := C.EVP_PKEY_CTX_new(private.evpPKey(), nil) if dhCtx == nil { return nil, errors.New("failed creating shared secret derivation context") } defer C.EVP_PKEY_CTX_free(dhCtx) // Initialize the context if int(C.EVP_PKEY_derive_init(dhCtx)) != 1 { return nil, errors.New("failed initializing shared secret derivation context") } // Provide the peer's public key if int(C.EVP_PKEY_derive_set_peer(dhCtx, public.evpPKey())) != 1 { return nil, errors.New("failed adding peer public key to context") } // Determine how large of a buffer we need for the shared secret var buffLen C.size_t if int(C.EVP_PKEY_derive(dhCtx, nil, &buffLen)) != 1 { return nil, errors.New("failed determining shared secret length") } // Allocate a buffer buffer := C.X_OPENSSL_malloc(buffLen) if buffer == nil { return nil, errors.New("failed allocating buffer for shared secret") } defer C.X_OPENSSL_free(buffer) // Derive the shared secret if int(C.EVP_PKEY_derive(dhCtx, (*C.uchar)(buffer), &buffLen)) != 1 { return nil, errors.New("failed deriving the shared secret") } secret := C.GoBytes(unsafe.Pointer(buffer), C.int(buffLen)) return secret, nil }
go
func DeriveSharedSecret(private PrivateKey, public PublicKey) ([]byte, error) { // Create context for the shared secret derivation dhCtx := C.EVP_PKEY_CTX_new(private.evpPKey(), nil) if dhCtx == nil { return nil, errors.New("failed creating shared secret derivation context") } defer C.EVP_PKEY_CTX_free(dhCtx) // Initialize the context if int(C.EVP_PKEY_derive_init(dhCtx)) != 1 { return nil, errors.New("failed initializing shared secret derivation context") } // Provide the peer's public key if int(C.EVP_PKEY_derive_set_peer(dhCtx, public.evpPKey())) != 1 { return nil, errors.New("failed adding peer public key to context") } // Determine how large of a buffer we need for the shared secret var buffLen C.size_t if int(C.EVP_PKEY_derive(dhCtx, nil, &buffLen)) != 1 { return nil, errors.New("failed determining shared secret length") } // Allocate a buffer buffer := C.X_OPENSSL_malloc(buffLen) if buffer == nil { return nil, errors.New("failed allocating buffer for shared secret") } defer C.X_OPENSSL_free(buffer) // Derive the shared secret if int(C.EVP_PKEY_derive(dhCtx, (*C.uchar)(buffer), &buffLen)) != 1 { return nil, errors.New("failed deriving the shared secret") } secret := C.GoBytes(unsafe.Pointer(buffer), C.int(buffLen)) return secret, nil }
[ "func", "DeriveSharedSecret", "(", "private", "PrivateKey", ",", "public", "PublicKey", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Create context for the shared secret derivation", "dhCtx", ":=", "C", ".", "EVP_PKEY_CTX_new", "(", "private", ".", "evp...
// DeriveSharedSecret derives a shared secret using a private key and a peer's // public key. // The specific algorithm that is used depends on the types of the // keys, but it is most commonly a variant of Diffie-Hellman.
[ "DeriveSharedSecret", "derives", "a", "shared", "secret", "using", "a", "private", "key", "and", "a", "peer", "s", "public", "key", ".", "The", "specific", "algorithm", "that", "is", "used", "depends", "on", "the", "types", "of", "the", "keys", "but", "it"...
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/dh.go#L28-L66
train
spacemonkeygo/openssl
tickets.go
SetTicketStore
func (c *Ctx) SetTicketStore(store *TicketStore) { c.ticket_store = store if store == nil { C.X_SSL_CTX_set_tlsext_ticket_key_cb(c.ctx, nil) } else { C.X_SSL_CTX_set_tlsext_ticket_key_cb(c.ctx, (*[0]byte)(C.X_SSL_CTX_ticket_key_cb)) } }
go
func (c *Ctx) SetTicketStore(store *TicketStore) { c.ticket_store = store if store == nil { C.X_SSL_CTX_set_tlsext_ticket_key_cb(c.ctx, nil) } else { C.X_SSL_CTX_set_tlsext_ticket_key_cb(c.ctx, (*[0]byte)(C.X_SSL_CTX_ticket_key_cb)) } }
[ "func", "(", "c", "*", "Ctx", ")", "SetTicketStore", "(", "store", "*", "TicketStore", ")", "{", "c", ".", "ticket_store", "=", "store", "\n\n", "if", "store", "==", "nil", "{", "C", ".", "X_SSL_CTX_set_tlsext_ticket_key_cb", "(", "c", ".", "ctx", ",", ...
// SetTicketStore sets the ticket store for the context so that clients can do // ticket based session resumption. If the store is nil, the
[ "SetTicketStore", "sets", "the", "ticket", "store", "for", "the", "context", "so", "that", "clients", "can", "do", "ticket", "based", "session", "resumption", ".", "If", "the", "store", "is", "nil", "the" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/tickets.go#L213-L222
train
spacemonkeygo/openssl
net.go
NewListener
func NewListener(inner net.Listener, ctx *Ctx) net.Listener { return &listener{ Listener: inner, ctx: ctx} }
go
func NewListener(inner net.Listener, ctx *Ctx) net.Listener { return &listener{ Listener: inner, ctx: ctx} }
[ "func", "NewListener", "(", "inner", "net", ".", "Listener", ",", "ctx", "*", "Ctx", ")", "net", ".", "Listener", "{", "return", "&", "listener", "{", "Listener", ":", "inner", ",", "ctx", ":", "ctx", "}", "\n", "}" ]
// NewListener wraps an existing net.Listener such that all accepted // connections are wrapped as OpenSSL server connections using the provided // context ctx.
[ "NewListener", "wraps", "an", "existing", "net", ".", "Listener", "such", "that", "all", "accepted", "connections", "are", "wrapped", "as", "OpenSSL", "server", "connections", "using", "the", "provided", "context", "ctx", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/net.go#L43-L47
train
spacemonkeygo/openssl
net.go
Listen
func Listen(network, laddr string, ctx *Ctx) (net.Listener, error) { if ctx == nil { return nil, errors.New("no ssl context provided") } l, err := net.Listen(network, laddr) if err != nil { return nil, err } return NewListener(l, ctx), nil }
go
func Listen(network, laddr string, ctx *Ctx) (net.Listener, error) { if ctx == nil { return nil, errors.New("no ssl context provided") } l, err := net.Listen(network, laddr) if err != nil { return nil, err } return NewListener(l, ctx), nil }
[ "func", "Listen", "(", "network", ",", "laddr", "string", ",", "ctx", "*", "Ctx", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "if", "ctx", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "...
// Listen is a wrapper around net.Listen that wraps incoming connections with // an OpenSSL server connection using the provided context ctx.
[ "Listen", "is", "a", "wrapper", "around", "net", ".", "Listen", "that", "wraps", "incoming", "connections", "with", "an", "OpenSSL", "server", "connection", "using", "the", "provided", "context", "ctx", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/net.go#L51-L60
train
spacemonkeygo/openssl
hostname.go
VerifyHostname
func (c *Certificate) VerifyHostname(host string) error { var ip net.IP if len(host) >= 3 && host[0] == '[' && host[len(host)-1] == ']' { ip = net.ParseIP(host[1 : len(host)-1]) } else { ip = net.ParseIP(host) } if ip != nil { return c.CheckIP(ip, 0) } return c.CheckHost(host, 0) }
go
func (c *Certificate) VerifyHostname(host string) error { var ip net.IP if len(host) >= 3 && host[0] == '[' && host[len(host)-1] == ']' { ip = net.ParseIP(host[1 : len(host)-1]) } else { ip = net.ParseIP(host) } if ip != nil { return c.CheckIP(ip, 0) } return c.CheckHost(host, 0) }
[ "func", "(", "c", "*", "Certificate", ")", "VerifyHostname", "(", "host", "string", ")", "error", "{", "var", "ip", "net", ".", "IP", "\n", "if", "len", "(", "host", ")", ">=", "3", "&&", "host", "[", "0", "]", "==", "'['", "&&", "host", "[", "...
// VerifyHostname is a combination of CheckHost and CheckIP. If the provided // hostname looks like an IP address, it will be checked as an IP address, // otherwise it will be checked as a hostname. // Specifically returns ValidationError if the Certificate didn't match but // there was no internal error.
[ "VerifyHostname", "is", "a", "combination", "of", "CheckHost", "and", "CheckIP", ".", "If", "the", "provided", "hostname", "looks", "like", "an", "IP", "address", "it", "will", "be", "checked", "as", "an", "IP", "address", "otherwise", "it", "will", "be", ...
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/hostname.go#L121-L132
train
spacemonkeygo/openssl
ctx.go
NewCtx
func NewCtx() (*Ctx, error) { c, err := NewCtxWithVersion(AnyVersion) if err == nil { c.SetOptions(NoSSLv2 | NoSSLv3) } return c, err }
go
func NewCtx() (*Ctx, error) { c, err := NewCtxWithVersion(AnyVersion) if err == nil { c.SetOptions(NoSSLv2 | NoSSLv3) } return c, err }
[ "func", "NewCtx", "(", ")", "(", "*", "Ctx", ",", "error", ")", "{", "c", ",", "err", ":=", "NewCtxWithVersion", "(", "AnyVersion", ")", "\n", "if", "err", "==", "nil", "{", "c", ".", "SetOptions", "(", "NoSSLv2", "|", "NoSSLv3", ")", "\n", "}", ...
// NewCtx creates a context that supports any TLS version 1.0 and newer.
[ "NewCtx", "creates", "a", "context", "that", "supports", "any", "TLS", "version", "1", ".", "0", "and", "newer", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L107-L113
train
spacemonkeygo/openssl
ctx.go
NewCtxFromFiles
func NewCtxFromFiles(cert_file string, key_file string) (*Ctx, error) { ctx, err := NewCtx() if err != nil { return nil, err } cert_bytes, err := ioutil.ReadFile(cert_file) if err != nil { return nil, err } certs := SplitPEM(cert_bytes) if len(certs) == 0 { return nil, fmt.Errorf("No PEM certificate found in '%s'", cert_file) } first, certs := certs[0], certs[1:] cert, err := LoadCertificateFromPEM(first) if err != nil { return nil, err } err = ctx.UseCertificate(cert) if err != nil { return nil, err } for _, pem := range certs { cert, err := LoadCertificateFromPEM(pem) if err != nil { return nil, err } err = ctx.AddChainCertificate(cert) if err != nil { return nil, err } } key_bytes, err := ioutil.ReadFile(key_file) if err != nil { return nil, err } key, err := LoadPrivateKeyFromPEM(key_bytes) if err != nil { return nil, err } err = ctx.UsePrivateKey(key) if err != nil { return nil, err } return ctx, nil }
go
func NewCtxFromFiles(cert_file string, key_file string) (*Ctx, error) { ctx, err := NewCtx() if err != nil { return nil, err } cert_bytes, err := ioutil.ReadFile(cert_file) if err != nil { return nil, err } certs := SplitPEM(cert_bytes) if len(certs) == 0 { return nil, fmt.Errorf("No PEM certificate found in '%s'", cert_file) } first, certs := certs[0], certs[1:] cert, err := LoadCertificateFromPEM(first) if err != nil { return nil, err } err = ctx.UseCertificate(cert) if err != nil { return nil, err } for _, pem := range certs { cert, err := LoadCertificateFromPEM(pem) if err != nil { return nil, err } err = ctx.AddChainCertificate(cert) if err != nil { return nil, err } } key_bytes, err := ioutil.ReadFile(key_file) if err != nil { return nil, err } key, err := LoadPrivateKeyFromPEM(key_bytes) if err != nil { return nil, err } err = ctx.UsePrivateKey(key) if err != nil { return nil, err } return ctx, nil }
[ "func", "NewCtxFromFiles", "(", "cert_file", "string", ",", "key_file", "string", ")", "(", "*", "Ctx", ",", "error", ")", "{", "ctx", ",", "err", ":=", "NewCtx", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}"...
// NewCtxFromFiles calls NewCtx, loads the provided files, and configures the // context to use them.
[ "NewCtxFromFiles", "calls", "NewCtx", "loads", "the", "provided", "files", "and", "configures", "the", "context", "to", "use", "them", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L117-L170
train
spacemonkeygo/openssl
ctx.go
SetEllipticCurve
func (c *Ctx) SetEllipticCurve(curve EllipticCurve) error { runtime.LockOSThread() defer runtime.UnlockOSThread() k := C.EC_KEY_new_by_curve_name(C.int(curve)) if k == nil { return errors.New("Unknown curve") } defer C.EC_KEY_free(k) if int(C.X_SSL_CTX_set_tmp_ecdh(c.ctx, k)) != 1 { return errorFromErrorQueue() } return nil }
go
func (c *Ctx) SetEllipticCurve(curve EllipticCurve) error { runtime.LockOSThread() defer runtime.UnlockOSThread() k := C.EC_KEY_new_by_curve_name(C.int(curve)) if k == nil { return errors.New("Unknown curve") } defer C.EC_KEY_free(k) if int(C.X_SSL_CTX_set_tmp_ecdh(c.ctx, k)) != 1 { return errorFromErrorQueue() } return nil }
[ "func", "(", "c", "*", "Ctx", ")", "SetEllipticCurve", "(", "curve", "EllipticCurve", ")", "error", "{", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n\n", "k", ":=", "C", ".", "EC_KEY_new_by_curve_...
// SetEllipticCurve sets the elliptic curve used by the SSL context to // enable an ECDH cipher suite to be selected during the handshake.
[ "SetEllipticCurve", "sets", "the", "elliptic", "curve", "used", "by", "the", "SSL", "context", "to", "enable", "an", "ECDH", "cipher", "suite", "to", "be", "selected", "during", "the", "handshake", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L187-L202
train
spacemonkeygo/openssl
ctx.go
UseCertificate
func (c *Ctx) UseCertificate(cert *Certificate) error { runtime.LockOSThread() defer runtime.UnlockOSThread() c.cert = cert if int(C.SSL_CTX_use_certificate(c.ctx, cert.x)) != 1 { return errorFromErrorQueue() } return nil }
go
func (c *Ctx) UseCertificate(cert *Certificate) error { runtime.LockOSThread() defer runtime.UnlockOSThread() c.cert = cert if int(C.SSL_CTX_use_certificate(c.ctx, cert.x)) != 1 { return errorFromErrorQueue() } return nil }
[ "func", "(", "c", "*", "Ctx", ")", "UseCertificate", "(", "cert", "*", "Certificate", ")", "error", "{", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n", "c", ".", "cert", "=", "cert", "\n", "...
// UseCertificate configures the context to present the given certificate to // peers.
[ "UseCertificate", "configures", "the", "context", "to", "present", "the", "given", "certificate", "to", "peers", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L206-L214
train
spacemonkeygo/openssl
ctx.go
AddChainCertificate
func (c *Ctx) AddChainCertificate(cert *Certificate) error { runtime.LockOSThread() defer runtime.UnlockOSThread() c.chain = append(c.chain, cert) if int(C.X_SSL_CTX_add_extra_chain_cert(c.ctx, cert.x)) != 1 { return errorFromErrorQueue() } // OpenSSL takes ownership via SSL_CTX_add_extra_chain_cert runtime.SetFinalizer(cert, nil) return nil }
go
func (c *Ctx) AddChainCertificate(cert *Certificate) error { runtime.LockOSThread() defer runtime.UnlockOSThread() c.chain = append(c.chain, cert) if int(C.X_SSL_CTX_add_extra_chain_cert(c.ctx, cert.x)) != 1 { return errorFromErrorQueue() } // OpenSSL takes ownership via SSL_CTX_add_extra_chain_cert runtime.SetFinalizer(cert, nil) return nil }
[ "func", "(", "c", "*", "Ctx", ")", "AddChainCertificate", "(", "cert", "*", "Certificate", ")", "error", "{", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n", "c", ".", "chain", "=", "append", "...
// AddChainCertificate adds a certificate to the chain presented in the // handshake.
[ "AddChainCertificate", "adds", "a", "certificate", "to", "the", "chain", "presented", "in", "the", "handshake", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L218-L228
train
spacemonkeygo/openssl
ctx.go
UsePrivateKey
func (c *Ctx) UsePrivateKey(key PrivateKey) error { runtime.LockOSThread() defer runtime.UnlockOSThread() c.key = key if int(C.SSL_CTX_use_PrivateKey(c.ctx, key.evpPKey())) != 1 { return errorFromErrorQueue() } return nil }
go
func (c *Ctx) UsePrivateKey(key PrivateKey) error { runtime.LockOSThread() defer runtime.UnlockOSThread() c.key = key if int(C.SSL_CTX_use_PrivateKey(c.ctx, key.evpPKey())) != 1 { return errorFromErrorQueue() } return nil }
[ "func", "(", "c", "*", "Ctx", ")", "UsePrivateKey", "(", "key", "PrivateKey", ")", "error", "{", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n", "c", ".", "key", "=", "key", "\n", "if", "int"...
// UsePrivateKey configures the context to use the given private key for SSL // handshakes.
[ "UsePrivateKey", "configures", "the", "context", "to", "use", "the", "given", "private", "key", "for", "SSL", "handshakes", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L232-L240
train