id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
152,400
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", ":=", "t", ".", "Tokenizer", ".", "Tokenize", "(", "sentence", ")", "\n\n", "return", "t", ".", "TermFrequency", "(", "word", ",", "document", ")", "*", "t", ".", "InverseDocumentFrequency", "(", "word", ")", "\n", "}" ]
// 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", "is", "calculated" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L81-L86
152,401
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", "document", ":=", "t", ".", "Tokenizer", ".", "Tokenize", "(", "sentence", ")", "\n\n", "freq", ":=", "TermFrequencies", "(", "document", ")", "\n", "for", "i", ":=", "range", "freq", "{", "freq", "[", "i", "]", ".", "TFIDF", "=", "freq", "[", "i", "]", ".", "Frequency", "*", "t", ".", "InverseDocumentFrequency", "(", "freq", "[", "i", "]", ".", "Word", ")", "\n", "freq", "[", "i", "]", ".", "Frequency", "=", "float64", "(", "0.0", ")", "\n", "}", "\n\n", "// sort into slice", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "freq", ")", ")", "\n\n", "if", "n", ">", "len", "(", "freq", ")", "{", "return", "freq", "\n", "}", "\n\n", "return", "freq", "[", ":", "n", "]", "\n", "}" ]
// 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", "be", "returned", ".", "The", "returned", "keyword", "slice", "is", "sorted", "by", "importance" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L96-L114
152,402
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", "{", "words", "[", "document", "[", "i", "]", "]", "++", "\n", "}", "\n\n", "// find max word frequency", "var", "maxFreq", "int", "\n", "for", "i", ":=", "range", "words", "{", "if", "words", "[", "i", "]", ">", "maxFreq", "{", "maxFreq", "=", "words", "[", "i", "]", "\n", "}", "\n", "}", "\n\n", "return", "0.5", "*", "(", "1", "+", "float64", "(", "words", "[", "word", "]", ")", "/", "float64", "(", "maxFreq", ")", ")", "\n", "}" ]
// 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
152,403
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", "]", "]", "++", "\n", "}", "\n\n", "var", "maxFreq", "int", "\n", "for", "i", ":=", "range", "words", "{", "if", "words", "[", "i", "]", ">", "maxFreq", "{", "maxFreq", "=", "words", "[", "i", "]", "\n", "}", "\n", "}", "\n\n", "// make frequency map", "frequencies", ":=", "Frequencies", "{", "}", "\n", "for", "i", ":=", "range", "words", "{", "frequencies", "=", "append", "(", "frequencies", ",", "Frequency", "{", "Word", ":", "i", ",", "Frequency", ":", "0.5", "*", "(", "1", "+", "float64", "(", "words", "[", "i", "]", ")", "/", "float64", "(", "maxFreq", ")", ")", ",", "}", ")", "\n", "}", "\n\n", "return", "frequencies", "\n", "}" ]
// 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
152,404
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", ".", "DocumentCount", ")", ")", "-", "math", ".", "Log", "(", "float64", "(", "w", ".", "DocsSeen", ")", "+", "1", ")", "\n", "}" ]
// 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", "calculated" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/tfidf.go#L174-L177
152,405
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", ".", "Sqrt", "(", "sum", ")", "\n\n", "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", "\n", "continue", "\n", "}", "\n\n", "x", "[", "i", "]", "/=", "mag", "\n", "}", "\n", "}" ]
// 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
152,406
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", "(", "strings", ".", "ToLower", "(", "sentence", ")", ",", "t", ".", "SplitOn", ")", "\n", "}" ]
// 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
152,407
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", "(", ")", "\n", "return", "result", ",", "ok", "\n", "}" ]
// 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", "boolean" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L215-L220
152,408
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
152,409
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", "{", "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", ",", "}", "\n", "}" ]
// 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", "function", ".", "It", "must", "comply", "with", "the", "transform", ".", "RemoveFunc", "interface" ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/text/bayes.go#L259-L271
152,410
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", ",", "_", ",", "_", "=", "transform", ".", "String", "(", "b", ".", "sanitize", ",", "sentence", ")", "\n", "words", ":=", "b", ".", "Tokenizer", ".", "Tokenize", "(", "sentence", ")", "\n", "for", "_", ",", "word", ":=", "range", "words", "{", "w", ",", "ok", ":=", "b", ".", "Words", ".", "Get", "(", "word", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n\n", "for", "i", ":=", "range", "sums", "{", "sums", "[", "i", "]", "+=", "math", ".", "Log", "(", "float64", "(", "w", ".", "Count", "[", "i", "]", "+", "1", ")", "/", "float64", "(", "w", ".", "Seen", "+", "b", ".", "DictCount", ")", ")", "\n", "}", "\n", "}", "\n\n", "for", "i", ":=", "range", "sums", "{", "sums", "[", "i", "]", "+=", "math", ".", "Log", "(", "b", ".", "Probabilities", "[", "i", "]", ")", "\n", "}", "\n\n", "// find best class", "var", "maxI", "int", "\n", "for", "i", ":=", "range", "sums", "{", "if", "sums", "[", "i", "]", ">", "sums", "[", "maxI", "]", "{", "maxI", "=", "i", "\n", "}", "\n", "}", "\n\n", "return", "uint8", "(", "maxI", ")", "\n", "}" ]
// 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
152,411
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", "{", "errors", "<-", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ")", "\n", "close", "(", "errors", ")", "\n", "return", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "b", ".", "Output", ",", "\"", "\\n", "\\t", "n\\", "tC", "n\"", ",", " ", "en(", "b", ".", "C", "ount)", ")", "", "\n\n", "var", "point", "base", ".", "TextDatapoint", "\n", "var", "more", "bool", "\n\n", "for", "{", "point", ",", "more", "=", "<-", "b", ".", "stream", "\n\n", "if", "more", "{", "// sanitize and break up document", "sanitized", ",", "_", ",", "_", ":=", "transform", ".", "String", "(", "b", ".", "sanitize", ",", "point", ".", "X", ")", "\n", "words", ":=", "b", ".", "Tokenizer", ".", "Tokenize", "(", "sanitized", ")", "\n\n", "C", ":=", "int", "(", "point", ".", "Y", ")", "\n\n", "if", "C", ">", "len", "(", "b", ".", "Count", ")", "-", "1", "{", "errors", "<-", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ")", "\n", "continue", "\n", "}", "\n\n", "// update global class probabilities", "b", ".", "Count", "[", "C", "]", "++", "\n", "b", ".", "DocumentCount", "++", "\n", "for", "i", ":=", "range", "b", ".", "Probabilities", "{", "b", ".", "Probabilities", "[", "i", "]", "=", "float64", "(", "b", ".", "Count", "[", "i", "]", ")", "/", "float64", "(", "b", ".", "DocumentCount", ")", "\n", "}", "\n\n", "// store words seen in document (to add to DocsSeen)", "seenCount", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n\n", "// update probabilities for words", "for", "_", ",", "word", ":=", "range", "words", "{", "if", "len", "(", "word", ")", "<", "3", "{", "continue", "\n", "}", "\n\n", "w", ",", "ok", ":=", "b", ".", "Words", ".", "Get", "(", "word", ")", "\n\n", "if", "!", "ok", "{", "w", "=", "Word", "{", "Count", ":", "make", "(", "[", "]", "uint64", ",", "len", "(", "b", ".", "Count", ")", ")", ",", "Seen", ":", "uint64", "(", "0", ")", ",", "}", "\n\n", "b", ".", "DictCount", "++", "\n", "}", "\n\n", "w", ".", "Count", "[", "C", "]", "++", "\n", "w", ".", "Seen", "++", "\n\n", "b", ".", "Words", ".", "Set", "(", "word", ",", "w", ")", "\n\n", "seenCount", "[", "word", "]", "=", "1", "\n", "}", "\n\n", "// add to DocsSeen", "for", "term", ":=", "range", "seenCount", "{", "tmp", ",", "_", ":=", "b", ".", "Words", ".", "Get", "(", "term", ")", "\n", "tmp", ".", "DocsSeen", "++", "\n", "b", ".", "Words", ".", "Set", "(", "term", ",", "tmp", ")", "\n", "}", "\n", "}", "else", "{", "fmt", ".", "Fprintf", "(", "b", ".", "Output", ",", "\"", "\\n", "\\n", "\\n", "\"", ",", "b", ")", "\n", "close", "(", "errors", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// 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
152,412
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
152,413
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", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "err", ":=", "json", ".", "NewDecoder", "(", "data", ")", ".", "Decode", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "b", ".", "sanitize", "=", "transform", ".", "RemoveFunc", "(", "sanitizer", ")", "\n", "b", ".", "Tokenizer", "=", "tokenizer", "\n", "return", "nil", "\n", "}" ]
// 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
152,414
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", "=", "len", "(", "trainingSet", "[", "0", "]", ")", "\n", "}", "\n\n", "// start all guesses with the zero vector.", "// they will be changed during learning", "var", "guesses", "[", "]", "int", "\n", "var", "info", "[", "]", "pointInfo", "\n", "guesses", "=", "make", "(", "[", "]", "int", ",", "len", "(", "trainingSet", ")", ")", "\n", "info", "=", "make", "(", "[", "]", "pointInfo", ",", "len", "(", "trainingSet", ")", ")", "\n", "for", "i", ":=", "range", "info", "{", "info", "[", "i", "]", "=", "pointInfo", "{", "lower", ":", "make", "(", "[", "]", "float64", ",", "k", ")", ",", "upper", ":", "0", ",", "recompute", ":", "true", ",", "}", "\n", "}", "\n\n", "rand", ".", "Seed", "(", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Unix", "(", ")", ")", "\n", "centroids", ":=", "make", "(", "[", "]", "[", "]", "float64", ",", "k", ")", "\n", "centroidDist", ":=", "make", "(", "[", "]", "[", "]", "float64", ",", "k", ")", "\n", "minCentroidDist", ":=", "make", "(", "[", "]", "float64", ",", "k", ")", "\n", "for", "i", ":=", "range", "centroids", "{", "centroids", "[", "i", "]", "=", "make", "(", "[", "]", "float64", ",", "features", ")", "\n", "centroidDist", "[", "i", "]", "=", "make", "(", "[", "]", "float64", ",", "k", ")", "\n", "}", "\n\n", "return", "&", "TriangleKMeans", "{", "maxIterations", ":", "maxIterations", ",", "trainingSet", ":", "trainingSet", ",", "guesses", ":", "guesses", ",", "info", ":", "info", ",", "Centroids", ":", "centroids", ",", "centroidDist", ":", "centroidDist", ",", "minCentroidDist", ":", "minCentroidDist", ",", "Output", ":", "os", ".", "Stdout", ",", "}", "\n", "}" ]
// 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", "-", "means", "++", "algorithm", "implemented", "in", "NewKMeans", "are", "discribed", "in", "the", "struct", "comments", "and", "in", "the", "paper", "URL", "found", "within", "those", "." ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/triangle_kmeans.go#L183-L225
152,415
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", ":=", "make", "(", "[", "]", "int64", ",", "len", "(", "k", ".", "Centroids", ")", ")", "\n\n", "for", "j", ":=", "range", "k", ".", "Centroids", "{", "classTotal", "[", "j", "]", "=", "make", "(", "[", "]", "float64", ",", "len", "(", "k", ".", "trainingSet", "[", "0", "]", ")", ")", "\n", "}", "\n\n", "for", "i", ",", "x", ":=", "range", "k", ".", "trainingSet", "{", "classCount", "[", "k", ".", "guesses", "[", "i", "]", "]", "++", "\n", "for", "j", ":=", "range", "x", "{", "classTotal", "[", "k", ".", "guesses", "[", "i", "]", "]", "[", "j", "]", "+=", "x", "[", "j", "]", "\n", "}", "\n", "}", "\n\n", "centroids", ":=", "append", "(", "[", "]", "[", "]", "float64", "{", "}", ",", "k", ".", "Centroids", "...", ")", "\n", "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", ")", "\n", "}", "\n", "continue", "\n", "}", "\n\n", "for", "l", ":=", "range", "centroids", "[", "j", "]", "{", "centroids", "[", "j", "]", "[", "l", "]", "=", "classTotal", "[", "j", "]", "[", "l", "]", "/", "float64", "(", "classCount", "[", "j", "]", ")", "\n", "}", "\n", "}", "\n\n", "return", "centroids", "\n", "}" ]
// 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", "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", "." ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/triangle_kmeans.go#L341-L373
152,416
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", "=", "append", "(", "floatGuesses", ",", "float64", "(", "val", ")", ")", "\n", "}", "\n\n", "return", "base", ".", "SaveDataToCSV", "(", "filepath", ",", "k", ".", "trainingSet", ",", "floatGuesses", ",", "true", ")", "\n", "}" ]
// 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", "for", "the", "base", ".", "SaveDataToCSV", "with", "the", "K", "-", "Means", "data", "." ]
e1f51f7135988cf33ef5feafa6d1558e4f28d981
https://github.com/cdipaolo/goml/blob/e1f51f7135988cf33ef5feafa6d1558e4f28d981/cluster/triangle_kmeans.go#L588-L595
152,417
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", "fmt", ".", "Fprintf", "(", "l", ".", "Output", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "examples", ":=", "len", "(", "l", ".", "trainingSet", ")", "\n", "if", "examples", "==", "0", "||", "len", "(", "l", ".", "trainingSet", "[", "0", "]", ")", "==", "0", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "l", ".", "Output", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n", "if", "len", "(", "l", ".", "expectedResults", ")", "==", "0", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "l", ".", "Output", ",", "err", ".", "Error", "(", ")", ")", "\n", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "l", ".", "Output", ",", "\"", "\\n", "\\t", "\\n", "\\t", "\\n", "\\t", "\\n", "\\t", "\\n", "\\t", "n\\", "tR", "..", "\\n", "\",", " ", "l", "m", "e", "thod, ", "e", "amples, ", "l", "n(l", ".", "t", "r", "ainingSet[0", "]", ")", ",", " ", "l", "a", "l", "pha, ", "l", "r", "e", "gularization)", "", "\n\n", "var", "err", "error", "\n", "if", "l", ".", "method", "==", "base", ".", "BatchGA", "{", "err", "=", "base", ".", "GradientAscent", "(", "l", ")", "\n", "}", "else", "if", "l", ".", "method", "==", "base", ".", "StochasticGA", "{", "err", "=", "base", ".", "StochasticGradientAscent", "(", "l", ")", "\n", "}", "else", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "l", ".", "Output", ",", "\"", "\\n", "\\t", "%v", "\\n", "\",", " ", "e", "r)", "", "\n", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Fprintf", "(", "l", ".", "Output", ",", "\"", "\\n", "\\n", "\\n", "\"", ",", "l", ")", "\n", "return", "nil", "\n", "}" ]
// 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
152,418
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", "(", "l", ".", "trainingSet", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "sum", "+=", "(", "l", ".", "expectedResults", "[", "i", "]", "-", "prediction", "[", "0", "]", ")", "*", "(", "l", ".", "expectedResults", "[", "i", "]", "-", "prediction", "[", "0", "]", ")", "\n", "}", "\n\n", "// 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", "]", "\n", "}", "\n\n", "return", "sum", "/", "float64", "(", "2", "*", "len", "(", "l", ".", "trainingSet", ")", ")", ",", "nil", "\n", "}" ]
// 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
152,419
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", ":", "addr", ",", "Handler", ":", "handler", "}", ",", "cert_file", ",", "key_file", ")", "\n", "}" ]
// 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
152,420
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", "}", "\n\n", "ctx", ",", "err", ":=", "NewCtxFromFiles", "(", "cert_file", ",", "key_file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "l", ",", "err", ":=", "Listen", "(", "\"", "\"", ",", "addr", ",", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "srv", ".", "Serve", "(", "l", ")", "\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
152,421
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", "(", "errs", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "C", ".", "GoString", "(", "C", ".", "ERR_lib_error_string", "(", "err", ")", ")", ",", "C", ".", "GoString", "(", "C", ".", "ERR_func_error_string", "(", "err", ")", ")", ",", "C", ".", "GoString", "(", "C", ".", "ERR_reason_error_string", "(", "err", ")", ")", ")", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "errs", ",", "\"", "\\n", "\"", ")", ")", ")", "\n", "}" ]
// 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
152,422
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", ":=", "&", "Name", "{", "name", ":", "n", "}", "\n", "runtime", ".", "SetFinalizer", "(", "name", ",", "func", "(", "n", "*", "Name", ")", "{", "C", ".", "X509_NAME_free", "(", "n", ".", "name", ")", "\n", "}", ")", "\n", "return", "name", ",", "nil", "\n", "}" ]
// 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
152,423
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", ")", ")", "\n", "cvalue", ":=", "(", "*", "C", ".", "uchar", ")", "(", "unsafe", ".", "Pointer", "(", "C", ".", "CString", "(", "value", ")", ")", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cvalue", ")", ")", "\n", "ret", ":=", "C", ".", "X509_NAME_add_entry_by_txt", "(", "n", ".", "name", ",", "cfield", ",", "C", ".", "MBSTRING_ASC", ",", "cvalue", ",", "-", "1", ",", "-", "1", ",", "0", ")", "\n", "if", "ret", "!=", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,424
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", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,425
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", ".", "SetFinalizer", "(", "c", ",", "func", "(", "c", "*", "Certificate", ")", "{", "C", ".", "X509_free", "(", "c", ".", "x", ")", "\n", "}", ")", "\n\n", "name", ",", "err", ":=", "c", ".", "GetSubjectName", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "name", ".", "AddTextEntries", "(", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "info", ".", "Country", ",", "\"", "\"", ":", "info", ".", "Organization", ",", "\"", "\"", ":", "info", ".", "CommonName", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// self-issue for now", "if", "err", ":=", "c", ".", "SetIssuerName", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "SetSerial", "(", "info", ".", "Serial", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "SetIssueDate", "(", "info", ".", "Issued", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "SetExpireDate", "(", "info", ".", "Expires", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "c", ".", "SetPubKey", "(", "key", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// 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
152,426
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", "if", "err", "=", "c", ".", "SetIssuerName", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "Issuer", "=", "issuer", "\n", "return", "nil", "\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
152,427
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", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,428
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", ":=", "C", ".", "BN_new", "(", ")", "\n", "defer", "C", ".", "BN_free", "(", "bn", ")", "\n\n", "serialBytes", ":=", "serial", ".", "Bytes", "(", ")", "\n", "if", "bn", "=", "C", ".", "BN_bin2bn", "(", "(", "*", "C", ".", "uchar", ")", "(", "unsafe", ".", "Pointer", "(", "&", "serialBytes", "[", "0", "]", ")", ")", ",", "C", ".", "int", "(", "len", "(", "serialBytes", ")", ")", ",", "bn", ")", ";", "bn", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "sno", "=", "C", ".", "BN_to_ASN1_INTEGER", "(", "bn", ",", "sno", ")", ";", "sno", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "C", ".", "X509_set_serialNumber", "(", "c", ".", "x", ",", "sno", ")", "!=", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,429
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", "(", "C", ".", "X_X509_get0_notAfter", "(", "c", ".", "x", ")", ",", "offset", ")", "\n", "if", "result", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,430
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", "(", ")", ")", "!=", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,431
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", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n", "return", "c", ".", "insecureSign", "(", "privKey", ",", "digest", ")", "\n", "}" ]
// 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
152,432
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", ",", "value", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,433
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", "}", "\n", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n", "bio", ":=", "C", ".", "BIO_new_mem_buf", "(", "unsafe", ".", "Pointer", "(", "&", "pem_block", "[", "0", "]", ")", ",", "C", ".", "int", "(", "len", "(", "pem_block", ")", ")", ")", "\n", "cert", ":=", "C", ".", "PEM_read_bio_X509", "(", "bio", ",", "nil", ",", "nil", ",", "nil", ")", "\n", "C", ".", "BIO_free", "(", "bio", ")", "\n", "if", "cert", "==", "nil", "{", "return", "nil", ",", "errorFromErrorQueue", "(", ")", "\n", "}", "\n", "x", ":=", "&", "Certificate", "{", "x", ":", "cert", "}", "\n", "runtime", ".", "SetFinalizer", "(", "x", ",", "func", "(", "x", "*", "Certificate", ")", "{", "C", ".", "X509_free", "(", "x", ".", "x", ")", "\n", "}", ")", "\n", "return", "x", ",", "nil", "\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
152,434
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", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "BIO_free", "(", "bio", ")", "\n", "if", "int", "(", "C", ".", "PEM_write_bio_X509", "(", "bio", ",", "c", ".", "x", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "ioutil", ".", "ReadAll", "(", "asAnyBio", "(", "bio", ")", ")", "\n", "}" ]
// 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
152,435
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", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "key", ":=", "&", "pKey", "{", "key", ":", "pkey", "}", "\n", "runtime", ".", "SetFinalizer", "(", "key", ",", "func", "(", "key", "*", "pKey", ")", "{", "C", ".", "EVP_PKEY_free", "(", "key", ".", "key", ")", "\n", "}", ")", "\n", "return", "key", ",", "nil", "\n", "}" ]
// 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
152,436
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", ",", "nil", ")", "\n", "hex", ":=", "C", ".", "BN_bn2hex", "(", "bignum", ")", "\n", "serial", "=", "C", ".", "GoString", "(", "hex", ")", "\n", "C", ".", "BN_free", "(", "bignum", ")", "\n", "C", ".", "X_OPENSSL_free", "(", "unsafe", ".", "Pointer", "(", "hex", ")", ")", "\n", "return", "\n", "}" ]
// 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
152,437
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", ")", "!=", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,438
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", ",", "err", "\n", "}", "\n", "C", ".", "SSL_set_accept_state", "(", "c", ".", "ssl", ")", "\n", "return", "c", ",", "nil", "\n", "}" ]
// 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
152,439
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_shutdown", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "x", ":=", "C", ".", "SSL_get_peer_certificate", "(", "c", ".", "ssl", ")", "\n", "if", "x", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "cert", ":=", "&", "Certificate", "{", "x", ":", "x", "}", "\n", "runtime", ".", "SetFinalizer", "(", "cert", ",", "func", "(", "cert", "*", "Certificate", ")", "{", "C", ".", "X509_free", "(", "cert", ".", "x", ")", "\n", "}", ")", "\n", "return", "cert", ",", "nil", "\n", "}" ]
// 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
152,440
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", "rv", "=", "make", "(", "[", "]", "*", "Certificate", ",", "0", ",", "sk_num", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "sk_num", ";", "i", "++", "{", "x", ":=", "C", ".", "X_sk_X509_value", "(", "sk", ",", "C", ".", "int", "(", "i", ")", ")", "\n", "// 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", "}", ")", "\n", "}", "\n", "return", "rv", "\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
152,441
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", ".", "is_shutdown", "=", "true", "\n", "c", ".", "mtx", ".", "Unlock", "(", ")", "\n", "var", "errs", "utils", ".", "ErrorGroup", "\n", "errs", ".", "Add", "(", "c", ".", "shutdownLoop", "(", ")", ")", "\n", "errs", ".", "Add", "(", "c", ".", "conn", ".", "Close", "(", ")", ")", "\n", "return", "errs", ".", "Finalize", "(", ")", "\n", "}" ]
// 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
152,442
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", "=", "tryAgain", "\n", "for", "err", "==", "tryAgain", "{", "n", ",", "errcb", ":=", "c", ".", "write", "(", "b", ")", "\n", "err", "=", "c", ".", "handleError", "(", "errcb", ")", "\n", "if", "err", "==", "nil", "{", "return", "n", ",", "c", ".", "flushOutputBuffer", "(", ")", "\n", "}", "\n", "}", "\n", "return", "0", ",", "err", "\n", "}" ]
// 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
152,443
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", "(", "host", ")", "\n", "}" ]
// 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
152,444
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", "p", ":=", "C", ".", "X_EVP_get_digestbyname", "(", "cname", ")", "\n", "if", "p", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "// we can consider digests to use static mem; don't need to free", "return", "&", "Digest", "{", "ptr", ":", "p", "}", ",", "nil", "\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
152,445
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", "(", "sn", ")", "\n", "}" ]
// 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
152,446
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
152,447
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", ".", "Errors", "[", "0", "]", "\n", "}", "\n", "msgs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "e", ".", "Errors", ")", ")", "\n", "for", "_", ",", "err", ":=", "range", "e", ".", "Errors", "{", "msgs", "=", "append", "(", "msgs", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "errors", ".", "New", "(", "strings", ".", "Join", "(", "msgs", ",", "\"", "\\n", "\"", ")", ")", "\n", "}" ]
// 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", "that", "error", ".", "Otherwise", "Finalize", "will", "make", "a", "new", "error", "consisting", "of", "the", "messages", "from", "the", "constituent", "errors", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/utils/errors.go#L38-L50
152,448
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", ":", "false", ",", "val", ":", "nil", ",", "err", ":", "nil", ",", "}", "\n", "}" ]
// 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
152,449
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", "self", ".", "received", "{", "return", "self", ".", "val", ",", "self", ".", "err", "\n", "}", "\n", "self", ".", "cond", ".", "Wait", "(", ")", "\n", "}", "\n", "}" ]
// 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
152,450
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
152,451
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", ".", "received", "{", "return", "\n", "}", "\n", "self", ".", "received", "=", "true", "\n", "self", ".", "val", "=", "val", "\n", "self", ".", "err", "=", "err", "\n", "self", ".", "cond", ".", "Broadcast", "(", ")", "\n", "}" ]
// 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
152,452
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", "}", "\n", "bio", ":=", "C", ".", "BIO_new_mem_buf", "(", "unsafe", ".", "Pointer", "(", "&", "pem_block", "[", "0", "]", ")", ",", "C", ".", "int", "(", "len", "(", "pem_block", ")", ")", ")", "\n", "if", "bio", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "BIO_free", "(", "bio", ")", "\n\n", "key", ":=", "C", ".", "PEM_read_bio_PrivateKey", "(", "bio", ",", "nil", ",", "nil", ",", "nil", ")", "\n", "if", "key", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "pKey", "{", "key", ":", "key", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\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
152,453
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", "(", "\"", "\"", ")", "\n", "}", "\n", "bio", ":=", "C", ".", "BIO_new_mem_buf", "(", "unsafe", ".", "Pointer", "(", "&", "pem_block", "[", "0", "]", ")", ",", "C", ".", "int", "(", "len", "(", "pem_block", ")", ")", ")", "\n", "if", "bio", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "BIO_free", "(", "bio", ")", "\n", "cs", ":=", "C", ".", "CString", "(", "password", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cs", ")", ")", "\n", "key", ":=", "C", ".", "PEM_read_bio_PrivateKey", "(", "bio", ",", "nil", ",", "nil", ",", "unsafe", ".", "Pointer", "(", "cs", ")", ")", "\n", "if", "key", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "pKey", "{", "key", ":", "key", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// 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
152,454
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", "}", "\n", "bio", ":=", "C", ".", "BIO_new_mem_buf", "(", "unsafe", ".", "Pointer", "(", "&", "der_block", "[", "0", "]", ")", ",", "C", ".", "int", "(", "len", "(", "der_block", ")", ")", ")", "\n", "if", "bio", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "BIO_free", "(", "bio", ")", "\n\n", "key", ":=", "C", ".", "d2i_PrivateKey_bio", "(", "bio", ",", "nil", ")", "\n", "if", "key", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "pKey", "{", "key", ":", "key", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\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
152,455
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
152,456
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", "bio", ":=", "C", ".", "BIO_new_mem_buf", "(", "unsafe", ".", "Pointer", "(", "&", "pem_block", "[", "0", "]", ")", ",", "C", ".", "int", "(", "len", "(", "pem_block", ")", ")", ")", "\n", "if", "bio", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "BIO_free", "(", "bio", ")", "\n\n", "key", ":=", "C", ".", "PEM_read_bio_PUBKEY", "(", "bio", ",", "nil", ",", "nil", ",", "nil", ")", "\n", "if", "key", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "pKey", "{", "key", ":", "key", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\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
152,457
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", "bio", ":=", "C", ".", "BIO_new_mem_buf", "(", "unsafe", ".", "Pointer", "(", "&", "der_block", "[", "0", "]", ")", ",", "C", ".", "int", "(", "len", "(", "der_block", ")", ")", ")", "\n", "if", "bio", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "BIO_free", "(", "bio", ")", "\n\n", "key", ":=", "C", ".", "d2i_PUBKEY_bio", "(", "bio", ",", "nil", ")", "\n", "if", "key", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "pKey", "{", "key", ":", "key", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\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
152,458
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", ")", ",", "nil", ",", "nil", ")", "\n", "if", "rsa", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "key", ":=", "C", ".", "X_EVP_PKEY_new", "(", ")", "\n", "if", "key", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "C", ".", "X_EVP_PKEY_assign_charp", "(", "key", ",", "C", ".", "EVP_PKEY_RSA", ",", "(", "*", "C", ".", "char", ")", "(", "unsafe", ".", "Pointer", "(", "rsa", ")", ")", ")", "!=", "1", "{", "C", ".", "X_EVP_PKEY_free", "(", "key", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ":=", "&", "pKey", "{", "key", ":", "key", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// 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
152,459
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", "paramCtx", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "EVP_PKEY_CTX_free", "(", "paramCtx", ")", "\n\n", "// Intialize the parameter generation", "if", "int", "(", "C", ".", "EVP_PKEY_paramgen_init", "(", "paramCtx", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// 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", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Create parameter object", "var", "params", "*", "C", ".", "EVP_PKEY", "\n", "if", "int", "(", "C", ".", "EVP_PKEY_paramgen", "(", "paramCtx", ",", "&", "params", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "EVP_PKEY_free", "(", "params", ")", "\n\n", "// Create context for the key generation", "keyCtx", ":=", "C", ".", "EVP_PKEY_CTX_new", "(", "params", ",", "nil", ")", "\n", "if", "keyCtx", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "EVP_PKEY_CTX_free", "(", "keyCtx", ")", "\n\n", "// Generate the key", "var", "privKey", "*", "C", ".", "EVP_PKEY", "\n", "if", "int", "(", "C", ".", "EVP_PKEY_keygen_init", "(", "keyCtx", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "int", "(", "C", ".", "EVP_PKEY_keygen", "(", "keyCtx", ",", "&", "privKey", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "pKey", "{", "key", ":", "privKey", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// 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
152,460
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", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "EVP_PKEY_CTX_free", "(", "keyCtx", ")", "\n\n", "// Generate the key", "var", "privKey", "*", "C", ".", "EVP_PKEY", "\n", "if", "int", "(", "C", ".", "EVP_PKEY_keygen_init", "(", "keyCtx", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "int", "(", "C", ".", "EVP_PKEY_keygen", "(", "keyCtx", ",", "&", "privKey", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "pKey", "{", "key", ":", "privKey", "}", "\n", "runtime", ".", "SetFinalizer", "(", "p", ",", "func", "(", "p", "*", "pKey", ")", "{", "C", ".", "X_EVP_PKEY_free", "(", "p", ".", "key", ")", "\n", "}", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// GenerateED25519Key generates a Ed25519 key
[ "GenerateED25519Key", "generates", "a", "Ed25519", "key" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/key.go#L482-L504
152,461
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", "}", "\n", "bio", ":=", "C", ".", "BIO_new_mem_buf", "(", "unsafe", ".", "Pointer", "(", "&", "pem_block", "[", "0", "]", ")", ",", "C", ".", "int", "(", "len", "(", "pem_block", ")", ")", ")", "\n", "if", "bio", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "BIO_free", "(", "bio", ")", "\n\n", "params", ":=", "C", ".", "PEM_read_bio_DHparams", "(", "bio", ",", "nil", ",", "nil", ",", "nil", ")", "\n", "if", "params", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "dhparams", ":=", "&", "DH", "{", "dh", ":", "params", "}", "\n", "runtime", ".", "SetFinalizer", "(", "dhparams", ",", "func", "(", "dhparams", "*", "DH", ")", "{", "C", ".", "DH_free", "(", "dhparams", ".", "dh", ")", "\n", "}", ")", "\n", "return", "dhparams", ",", "nil", "\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
152,462
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", ".", "evpPKey", "(", ")", ",", "nil", ")", "\n", "if", "dhCtx", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "EVP_PKEY_CTX_free", "(", "dhCtx", ")", "\n\n", "// Initialize the context", "if", "int", "(", "C", ".", "EVP_PKEY_derive_init", "(", "dhCtx", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Provide the peer's public key", "if", "int", "(", "C", ".", "EVP_PKEY_derive_set_peer", "(", "dhCtx", ",", "public", ".", "evpPKey", "(", ")", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Determine how large of a buffer we need for the shared secret", "var", "buffLen", "C", ".", "size_t", "\n", "if", "int", "(", "C", ".", "EVP_PKEY_derive", "(", "dhCtx", ",", "nil", ",", "&", "buffLen", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Allocate a buffer", "buffer", ":=", "C", ".", "X_OPENSSL_malloc", "(", "buffLen", ")", "\n", "if", "buffer", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "X_OPENSSL_free", "(", "buffer", ")", "\n\n", "// Derive the shared secret", "if", "int", "(", "C", ".", "EVP_PKEY_derive", "(", "dhCtx", ",", "(", "*", "C", ".", "uchar", ")", "(", "buffer", ")", ",", "&", "buffLen", ")", ")", "!=", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "secret", ":=", "C", ".", "GoBytes", "(", "unsafe", ".", "Pointer", "(", "buffer", ")", ",", "C", ".", "int", "(", "buffLen", ")", ")", "\n", "return", "secret", ",", "nil", "\n", "}" ]
// 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", "is", "most", "commonly", "a", "variant", "of", "Diffie", "-", "Hellman", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/dh.go#L28-L66
152,463
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", ",", "nil", ")", "\n", "}", "else", "{", "C", ".", "X_SSL_CTX_set_tlsext_ticket_key_cb", "(", "c", ".", "ctx", ",", "(", "*", "[", "0", "]", "byte", ")", "(", "C", ".", "X_SSL_CTX_ticket_key_cb", ")", ")", "\n", "}", "\n", "}" ]
// 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
152,464
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
152,465
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", "}", "\n", "l", ",", "err", ":=", "net", ".", "Listen", "(", "network", ",", "laddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewListener", "(", "l", ",", "ctx", ")", ",", "nil", "\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
152,466
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", "[", "len", "(", "host", ")", "-", "1", "]", "==", "']'", "{", "ip", "=", "net", ".", "ParseIP", "(", "host", "[", "1", ":", "len", "(", "host", ")", "-", "1", "]", ")", "\n", "}", "else", "{", "ip", "=", "net", ".", "ParseIP", "(", "host", ")", "\n", "}", "\n", "if", "ip", "!=", "nil", "{", "return", "c", ".", "CheckIP", "(", "ip", ",", "0", ")", "\n", "}", "\n", "return", "c", ".", "CheckHost", "(", "host", ",", "0", ")", "\n", "}" ]
// 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", "checked", "as", "a", "hostname", ".", "Specifically", "returns", "ValidationError", "if", "the", "Certificate", "didn", "t", "match", "but", "there", "was", "no", "internal", "error", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/hostname.go#L121-L132
152,467
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", "}", "\n", "return", "c", ",", "err", "\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
152,468
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", "}", "\n\n", "cert_bytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "cert_file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "certs", ":=", "SplitPEM", "(", "cert_bytes", ")", "\n", "if", "len", "(", "certs", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cert_file", ")", "\n", "}", "\n", "first", ",", "certs", ":=", "certs", "[", "0", "]", ",", "certs", "[", "1", ":", "]", "\n", "cert", ",", "err", ":=", "LoadCertificateFromPEM", "(", "first", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "ctx", ".", "UseCertificate", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "pem", ":=", "range", "certs", "{", "cert", ",", "err", ":=", "LoadCertificateFromPEM", "(", "pem", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "ctx", ".", "AddChainCertificate", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "key_bytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "key_file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "key", ",", "err", ":=", "LoadPrivateKeyFromPEM", "(", "key_bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "err", "=", "ctx", ".", "UsePrivateKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "ctx", ",", "nil", "\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
152,469
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_name", "(", "C", ".", "int", "(", "curve", ")", ")", "\n", "if", "k", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "defer", "C", ".", "EC_KEY_free", "(", "k", ")", "\n\n", "if", "int", "(", "C", ".", "X_SSL_CTX_set_tmp_ecdh", "(", "c", ".", "ctx", ",", "k", ")", ")", "!=", "1", "{", "return", "errorFromErrorQueue", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// 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
152,470
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", "if", "int", "(", "C", ".", "SSL_CTX_use_certificate", "(", "c", ".", "ctx", ",", "cert", ".", "x", ")", ")", "!=", "1", "{", "return", "errorFromErrorQueue", "(", ")", "\n", "}", "\n", "return", "nil", "\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
152,471
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", "(", "c", ".", "chain", ",", "cert", ")", "\n", "if", "int", "(", "C", ".", "X_SSL_CTX_add_extra_chain_cert", "(", "c", ".", "ctx", ",", "cert", ".", "x", ")", ")", "!=", "1", "{", "return", "errorFromErrorQueue", "(", ")", "\n", "}", "\n", "// OpenSSL takes ownership via SSL_CTX_add_extra_chain_cert", "runtime", ".", "SetFinalizer", "(", "cert", ",", "nil", ")", "\n", "return", "nil", "\n", "}" ]
// 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
152,472
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", "(", "C", ".", "SSL_CTX_use_PrivateKey", "(", "c", ".", "ctx", ",", "key", ".", "evpPKey", "(", ")", ")", ")", "!=", "1", "{", "return", "errorFromErrorQueue", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
152,473
spacemonkeygo/openssl
ctx.go
NewCertificateStore
func NewCertificateStore() (*CertificateStore, error) { s := C.X509_STORE_new() if s == nil { return nil, errors.New("failed to allocate X509_STORE") } store := &CertificateStore{store: s} runtime.SetFinalizer(store, func(s *CertificateStore) { C.X509_STORE_free(s.store) }) return store, nil }
go
func NewCertificateStore() (*CertificateStore, error) { s := C.X509_STORE_new() if s == nil { return nil, errors.New("failed to allocate X509_STORE") } store := &CertificateStore{store: s} runtime.SetFinalizer(store, func(s *CertificateStore) { C.X509_STORE_free(s.store) }) return store, nil }
[ "func", "NewCertificateStore", "(", ")", "(", "*", "CertificateStore", ",", "error", ")", "{", "s", ":=", "C", ".", "X509_STORE_new", "(", ")", "\n", "if", "s", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "store", ":=", "&", "CertificateStore", "{", "store", ":", "s", "}", "\n", "runtime", ".", "SetFinalizer", "(", "store", ",", "func", "(", "s", "*", "CertificateStore", ")", "{", "C", ".", "X509_STORE_free", "(", "s", ".", "store", ")", "\n", "}", ")", "\n", "return", "store", ",", "nil", "\n", "}" ]
// Allocate a new, empty CertificateStore
[ "Allocate", "a", "new", "empty", "CertificateStore" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L250-L260
152,474
spacemonkeygo/openssl
ctx.go
LoadCertificatesFromPEM
func (s *CertificateStore) LoadCertificatesFromPEM(data []byte) error { pems := SplitPEM(data) for _, pem := range pems { cert, err := LoadCertificateFromPEM(pem) if err != nil { return err } err = s.AddCertificate(cert) if err != nil { return err } } return nil }
go
func (s *CertificateStore) LoadCertificatesFromPEM(data []byte) error { pems := SplitPEM(data) for _, pem := range pems { cert, err := LoadCertificateFromPEM(pem) if err != nil { return err } err = s.AddCertificate(cert) if err != nil { return err } } return nil }
[ "func", "(", "s", "*", "CertificateStore", ")", "LoadCertificatesFromPEM", "(", "data", "[", "]", "byte", ")", "error", "{", "pems", ":=", "SplitPEM", "(", "data", ")", "\n", "for", "_", ",", "pem", ":=", "range", "pems", "{", "cert", ",", "err", ":=", "LoadCertificateFromPEM", "(", "pem", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "s", ".", "AddCertificate", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Parse a chained PEM file, loading all certificates into the Store.
[ "Parse", "a", "chained", "PEM", "file", "loading", "all", "certificates", "into", "the", "Store", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L263-L276
152,475
spacemonkeygo/openssl
ctx.go
GetCertificateStore
func (c *Ctx) GetCertificateStore() *CertificateStore { // we don't need to dealloc the cert store pointer here, because it points // to a ctx internal. so we do need to keep the ctx around return &CertificateStore{ store: C.SSL_CTX_get_cert_store(c.ctx), ctx: c} }
go
func (c *Ctx) GetCertificateStore() *CertificateStore { // we don't need to dealloc the cert store pointer here, because it points // to a ctx internal. so we do need to keep the ctx around return &CertificateStore{ store: C.SSL_CTX_get_cert_store(c.ctx), ctx: c} }
[ "func", "(", "c", "*", "Ctx", ")", "GetCertificateStore", "(", ")", "*", "CertificateStore", "{", "// we don't need to dealloc the cert store pointer here, because it points", "// to a ctx internal. so we do need to keep the ctx around", "return", "&", "CertificateStore", "{", "store", ":", "C", ".", "SSL_CTX_get_cert_store", "(", "c", ".", "ctx", ")", ",", "ctx", ":", "c", "}", "\n", "}" ]
// GetCertificateStore returns the context's certificate store that will be // used for peer validation.
[ "GetCertificateStore", "returns", "the", "context", "s", "certificate", "store", "that", "will", "be", "used", "for", "peer", "validation", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L280-L286
152,476
spacemonkeygo/openssl
ctx.go
AddCertificate
func (s *CertificateStore) AddCertificate(cert *Certificate) error { runtime.LockOSThread() defer runtime.UnlockOSThread() s.certs = append(s.certs, cert) if int(C.X509_STORE_add_cert(s.store, cert.x)) != 1 { return errorFromErrorQueue() } return nil }
go
func (s *CertificateStore) AddCertificate(cert *Certificate) error { runtime.LockOSThread() defer runtime.UnlockOSThread() s.certs = append(s.certs, cert) if int(C.X509_STORE_add_cert(s.store, cert.x)) != 1 { return errorFromErrorQueue() } return nil }
[ "func", "(", "s", "*", "CertificateStore", ")", "AddCertificate", "(", "cert", "*", "Certificate", ")", "error", "{", "runtime", ".", "LockOSThread", "(", ")", "\n", "defer", "runtime", ".", "UnlockOSThread", "(", ")", "\n", "s", ".", "certs", "=", "append", "(", "s", ".", "certs", ",", "cert", ")", "\n", "if", "int", "(", "C", ".", "X509_STORE_add_cert", "(", "s", ".", "store", ",", "cert", ".", "x", ")", ")", "!=", "1", "{", "return", "errorFromErrorQueue", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddCertificate marks the provided Certificate as a trusted certificate in // the given CertificateStore.
[ "AddCertificate", "marks", "the", "provided", "Certificate", "as", "a", "trusted", "certificate", "in", "the", "given", "CertificateStore", "." ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L290-L298
152,477
spacemonkeygo/openssl
ctx.go
GetCurrentCert
func (self *CertificateStoreCtx) GetCurrentCert() *Certificate { x509 := C.X509_STORE_CTX_get_current_cert(self.ctx) if x509 == nil { return nil } // add a ref if 1 != C.X_X509_add_ref(x509) { return nil } cert := &Certificate{ x: x509, } runtime.SetFinalizer(cert, func(cert *Certificate) { C.X509_free(cert.x) }) return cert }
go
func (self *CertificateStoreCtx) GetCurrentCert() *Certificate { x509 := C.X509_STORE_CTX_get_current_cert(self.ctx) if x509 == nil { return nil } // add a ref if 1 != C.X_X509_add_ref(x509) { return nil } cert := &Certificate{ x: x509, } runtime.SetFinalizer(cert, func(cert *Certificate) { C.X509_free(cert.x) }) return cert }
[ "func", "(", "self", "*", "CertificateStoreCtx", ")", "GetCurrentCert", "(", ")", "*", "Certificate", "{", "x509", ":=", "C", ".", "X509_STORE_CTX_get_current_cert", "(", "self", ".", "ctx", ")", "\n", "if", "x509", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "// add a ref", "if", "1", "!=", "C", ".", "X_X509_add_ref", "(", "x509", ")", "{", "return", "nil", "\n", "}", "\n", "cert", ":=", "&", "Certificate", "{", "x", ":", "x509", ",", "}", "\n", "runtime", ".", "SetFinalizer", "(", "cert", ",", "func", "(", "cert", "*", "Certificate", ")", "{", "C", ".", "X509_free", "(", "cert", ".", "x", ")", "\n", "}", ")", "\n", "return", "cert", "\n", "}" ]
// the certicate returned is only valid for the lifetime of the underlying // X509_STORE_CTX
[ "the", "certicate", "returned", "is", "only", "valid", "for", "the", "lifetime", "of", "the", "underlying", "X509_STORE_CTX" ]
c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730
https://github.com/spacemonkeygo/openssl/blob/c2dcc5cca94ac8f7f3f0c20e20050d4cce9d9730/ctx.go#L324-L340
152,478
jaytaylor/html2text
html2text.go
NewPrettyTablesOptions
func NewPrettyTablesOptions() *PrettyTablesOptions { return &PrettyTablesOptions{ AutoFormatHeader: true, AutoWrapText: true, ReflowDuringAutoWrap: true, ColWidth: tablewriter.MAX_ROW_WIDTH, ColumnSeparator: tablewriter.COLUMN, RowSeparator: tablewriter.ROW, CenterSeparator: tablewriter.CENTER, HeaderAlignment: tablewriter.ALIGN_DEFAULT, FooterAlignment: tablewriter.ALIGN_DEFAULT, Alignment: tablewriter.ALIGN_DEFAULT, ColumnAlignment: []int{}, NewLine: tablewriter.NEWLINE, HeaderLine: true, RowLine: false, AutoMergeCells: false, Borders: tablewriter.Border{Left: true, Right: true, Bottom: true, Top: true}, } }
go
func NewPrettyTablesOptions() *PrettyTablesOptions { return &PrettyTablesOptions{ AutoFormatHeader: true, AutoWrapText: true, ReflowDuringAutoWrap: true, ColWidth: tablewriter.MAX_ROW_WIDTH, ColumnSeparator: tablewriter.COLUMN, RowSeparator: tablewriter.ROW, CenterSeparator: tablewriter.CENTER, HeaderAlignment: tablewriter.ALIGN_DEFAULT, FooterAlignment: tablewriter.ALIGN_DEFAULT, Alignment: tablewriter.ALIGN_DEFAULT, ColumnAlignment: []int{}, NewLine: tablewriter.NEWLINE, HeaderLine: true, RowLine: false, AutoMergeCells: false, Borders: tablewriter.Border{Left: true, Right: true, Bottom: true, Top: true}, } }
[ "func", "NewPrettyTablesOptions", "(", ")", "*", "PrettyTablesOptions", "{", "return", "&", "PrettyTablesOptions", "{", "AutoFormatHeader", ":", "true", ",", "AutoWrapText", ":", "true", ",", "ReflowDuringAutoWrap", ":", "true", ",", "ColWidth", ":", "tablewriter", ".", "MAX_ROW_WIDTH", ",", "ColumnSeparator", ":", "tablewriter", ".", "COLUMN", ",", "RowSeparator", ":", "tablewriter", ".", "ROW", ",", "CenterSeparator", ":", "tablewriter", ".", "CENTER", ",", "HeaderAlignment", ":", "tablewriter", ".", "ALIGN_DEFAULT", ",", "FooterAlignment", ":", "tablewriter", ".", "ALIGN_DEFAULT", ",", "Alignment", ":", "tablewriter", ".", "ALIGN_DEFAULT", ",", "ColumnAlignment", ":", "[", "]", "int", "{", "}", ",", "NewLine", ":", "tablewriter", ".", "NEWLINE", ",", "HeaderLine", ":", "true", ",", "RowLine", ":", "false", ",", "AutoMergeCells", ":", "false", ",", "Borders", ":", "tablewriter", ".", "Border", "{", "Left", ":", "true", ",", "Right", ":", "true", ",", "Bottom", ":", "true", ",", "Top", ":", "true", "}", ",", "}", "\n", "}" ]
// NewPrettyTablesOptions creates PrettyTablesOptions with default settings
[ "NewPrettyTablesOptions", "creates", "PrettyTablesOptions", "with", "default", "settings" ]
01ec452cbe43774f989516272881441cae40c16b
https://github.com/jaytaylor/html2text/blob/01ec452cbe43774f989516272881441cae40c16b/html2text.go#L44-L63
152,479
jaytaylor/html2text
html2text.go
FromHTMLNode
func FromHTMLNode(doc *html.Node, o ...Options) (string, error) { var options Options if len(o) > 0 { options = o[0] } ctx := textifyTraverseContext{ buf: bytes.Buffer{}, options: options, } if err := ctx.traverse(doc); err != nil { return "", err } text := strings.TrimSpace(newlineRe.ReplaceAllString( strings.Replace(ctx.buf.String(), "\n ", "\n", -1), "\n\n"), ) return text, nil }
go
func FromHTMLNode(doc *html.Node, o ...Options) (string, error) { var options Options if len(o) > 0 { options = o[0] } ctx := textifyTraverseContext{ buf: bytes.Buffer{}, options: options, } if err := ctx.traverse(doc); err != nil { return "", err } text := strings.TrimSpace(newlineRe.ReplaceAllString( strings.Replace(ctx.buf.String(), "\n ", "\n", -1), "\n\n"), ) return text, nil }
[ "func", "FromHTMLNode", "(", "doc", "*", "html", ".", "Node", ",", "o", "...", "Options", ")", "(", "string", ",", "error", ")", "{", "var", "options", "Options", "\n", "if", "len", "(", "o", ")", ">", "0", "{", "options", "=", "o", "[", "0", "]", "\n", "}", "\n\n", "ctx", ":=", "textifyTraverseContext", "{", "buf", ":", "bytes", ".", "Buffer", "{", "}", ",", "options", ":", "options", ",", "}", "\n", "if", "err", ":=", "ctx", ".", "traverse", "(", "doc", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "text", ":=", "strings", ".", "TrimSpace", "(", "newlineRe", ".", "ReplaceAllString", "(", "strings", ".", "Replace", "(", "ctx", ".", "buf", ".", "String", "(", ")", ",", "\"", "\\n", "\"", ",", "\"", "\\n", "\"", ",", "-", "1", ")", ",", "\"", "\\n", "\\n", "\"", ")", ",", ")", "\n", "return", "text", ",", "nil", "\n", "}" ]
// FromHTMLNode renders text output from a pre-parsed HTML document.
[ "FromHTMLNode", "renders", "text", "output", "from", "a", "pre", "-", "parsed", "HTML", "document", "." ]
01ec452cbe43774f989516272881441cae40c16b
https://github.com/jaytaylor/html2text/blob/01ec452cbe43774f989516272881441cae40c16b/html2text.go#L66-L84
152,480
jaytaylor/html2text
html2text.go
FromReader
func FromReader(reader io.Reader, options ...Options) (string, error) { newReader, err := bom.NewReaderWithoutBom(reader) if err != nil { return "", err } doc, err := html.Parse(newReader) if err != nil { return "", err } return FromHTMLNode(doc, options...) }
go
func FromReader(reader io.Reader, options ...Options) (string, error) { newReader, err := bom.NewReaderWithoutBom(reader) if err != nil { return "", err } doc, err := html.Parse(newReader) if err != nil { return "", err } return FromHTMLNode(doc, options...) }
[ "func", "FromReader", "(", "reader", "io", ".", "Reader", ",", "options", "...", "Options", ")", "(", "string", ",", "error", ")", "{", "newReader", ",", "err", ":=", "bom", ".", "NewReaderWithoutBom", "(", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "doc", ",", "err", ":=", "html", ".", "Parse", "(", "newReader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "FromHTMLNode", "(", "doc", ",", "options", "...", ")", "\n", "}" ]
// FromReader renders text output after parsing HTML for the specified // io.Reader.
[ "FromReader", "renders", "text", "output", "after", "parsing", "HTML", "for", "the", "specified", "io", ".", "Reader", "." ]
01ec452cbe43774f989516272881441cae40c16b
https://github.com/jaytaylor/html2text/blob/01ec452cbe43774f989516272881441cae40c16b/html2text.go#L88-L98
152,481
jaytaylor/html2text
html2text.go
FromString
func FromString(input string, options ...Options) (string, error) { bs := bom.CleanBom([]byte(input)) text, err := FromReader(bytes.NewReader(bs), options...) if err != nil { return "", err } return text, nil }
go
func FromString(input string, options ...Options) (string, error) { bs := bom.CleanBom([]byte(input)) text, err := FromReader(bytes.NewReader(bs), options...) if err != nil { return "", err } return text, nil }
[ "func", "FromString", "(", "input", "string", ",", "options", "...", "Options", ")", "(", "string", ",", "error", ")", "{", "bs", ":=", "bom", ".", "CleanBom", "(", "[", "]", "byte", "(", "input", ")", ")", "\n", "text", ",", "err", ":=", "FromReader", "(", "bytes", ".", "NewReader", "(", "bs", ")", ",", "options", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "text", ",", "nil", "\n", "}" ]
// FromString parses HTML from the input string, then renders the text form.
[ "FromString", "parses", "HTML", "from", "the", "input", "string", "then", "renders", "the", "text", "form", "." ]
01ec452cbe43774f989516272881441cae40c16b
https://github.com/jaytaylor/html2text/blob/01ec452cbe43774f989516272881441cae40c16b/html2text.go#L101-L108
152,482
jaytaylor/html2text
html2text.go
paragraphHandler
func (ctx *textifyTraverseContext) paragraphHandler(node *html.Node) error { if err := ctx.emit("\n\n"); err != nil { return err } if err := ctx.traverseChildren(node); err != nil { return err } return ctx.emit("\n\n") }
go
func (ctx *textifyTraverseContext) paragraphHandler(node *html.Node) error { if err := ctx.emit("\n\n"); err != nil { return err } if err := ctx.traverseChildren(node); err != nil { return err } return ctx.emit("\n\n") }
[ "func", "(", "ctx", "*", "textifyTraverseContext", ")", "paragraphHandler", "(", "node", "*", "html", ".", "Node", ")", "error", "{", "if", "err", ":=", "ctx", ".", "emit", "(", "\"", "\\n", "\\n", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ctx", ".", "traverseChildren", "(", "node", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ctx", ".", "emit", "(", "\"", "\\n", "\\n", "\"", ")", "\n", "}" ]
// paragraphHandler renders node children surrounded by double newlines.
[ "paragraphHandler", "renders", "node", "children", "surrounded", "by", "double", "newlines", "." ]
01ec452cbe43774f989516272881441cae40c16b
https://github.com/jaytaylor/html2text/blob/01ec452cbe43774f989516272881441cae40c16b/html2text.go#L291-L299
152,483
jaytaylor/html2text
html2text.go
handleTableElement
func (ctx *textifyTraverseContext) handleTableElement(node *html.Node) error { if !ctx.options.PrettyTables { panic("handleTableElement invoked when PrettyTables not active") } switch node.DataAtom { case atom.Table: if err := ctx.emit("\n\n"); err != nil { return err } // Re-intialize all table context. ctx.tableCtx.init() // Browse children, enriching context with table data. if err := ctx.traverseChildren(node); err != nil { return err } buf := &bytes.Buffer{} table := tablewriter.NewWriter(buf) if ctx.options.PrettyTablesOptions != nil { options := ctx.options.PrettyTablesOptions table.SetAutoFormatHeaders(options.AutoFormatHeader) table.SetAutoWrapText(options.AutoWrapText) table.SetReflowDuringAutoWrap(options.ReflowDuringAutoWrap) table.SetColWidth(options.ColWidth) table.SetColumnSeparator(options.ColumnSeparator) table.SetRowSeparator(options.RowSeparator) table.SetCenterSeparator(options.CenterSeparator) table.SetHeaderAlignment(options.HeaderAlignment) table.SetFooterAlignment(options.FooterAlignment) table.SetAlignment(options.Alignment) table.SetColumnAlignment(options.ColumnAlignment) table.SetNewLine(options.NewLine) table.SetHeaderLine(options.HeaderLine) table.SetRowLine(options.RowLine) table.SetAutoMergeCells(options.AutoMergeCells) table.SetBorders(options.Borders) } table.SetHeader(ctx.tableCtx.header) table.SetFooter(ctx.tableCtx.footer) table.AppendBulk(ctx.tableCtx.body) // Render the table using ASCII. table.Render() if err := ctx.emit(buf.String()); err != nil { return err } return ctx.emit("\n\n") case atom.Tfoot: ctx.tableCtx.isInFooter = true if err := ctx.traverseChildren(node); err != nil { return err } ctx.tableCtx.isInFooter = false case atom.Tr: ctx.tableCtx.body = append(ctx.tableCtx.body, []string{}) if err := ctx.traverseChildren(node); err != nil { return err } ctx.tableCtx.tmpRow++ case atom.Th: res, err := ctx.renderEachChild(node) if err != nil { return err } ctx.tableCtx.header = append(ctx.tableCtx.header, res) case atom.Td: res, err := ctx.renderEachChild(node) if err != nil { return err } if ctx.tableCtx.isInFooter { ctx.tableCtx.footer = append(ctx.tableCtx.footer, res) } else { ctx.tableCtx.body[ctx.tableCtx.tmpRow] = append(ctx.tableCtx.body[ctx.tableCtx.tmpRow], res) } } return nil }
go
func (ctx *textifyTraverseContext) handleTableElement(node *html.Node) error { if !ctx.options.PrettyTables { panic("handleTableElement invoked when PrettyTables not active") } switch node.DataAtom { case atom.Table: if err := ctx.emit("\n\n"); err != nil { return err } // Re-intialize all table context. ctx.tableCtx.init() // Browse children, enriching context with table data. if err := ctx.traverseChildren(node); err != nil { return err } buf := &bytes.Buffer{} table := tablewriter.NewWriter(buf) if ctx.options.PrettyTablesOptions != nil { options := ctx.options.PrettyTablesOptions table.SetAutoFormatHeaders(options.AutoFormatHeader) table.SetAutoWrapText(options.AutoWrapText) table.SetReflowDuringAutoWrap(options.ReflowDuringAutoWrap) table.SetColWidth(options.ColWidth) table.SetColumnSeparator(options.ColumnSeparator) table.SetRowSeparator(options.RowSeparator) table.SetCenterSeparator(options.CenterSeparator) table.SetHeaderAlignment(options.HeaderAlignment) table.SetFooterAlignment(options.FooterAlignment) table.SetAlignment(options.Alignment) table.SetColumnAlignment(options.ColumnAlignment) table.SetNewLine(options.NewLine) table.SetHeaderLine(options.HeaderLine) table.SetRowLine(options.RowLine) table.SetAutoMergeCells(options.AutoMergeCells) table.SetBorders(options.Borders) } table.SetHeader(ctx.tableCtx.header) table.SetFooter(ctx.tableCtx.footer) table.AppendBulk(ctx.tableCtx.body) // Render the table using ASCII. table.Render() if err := ctx.emit(buf.String()); err != nil { return err } return ctx.emit("\n\n") case atom.Tfoot: ctx.tableCtx.isInFooter = true if err := ctx.traverseChildren(node); err != nil { return err } ctx.tableCtx.isInFooter = false case atom.Tr: ctx.tableCtx.body = append(ctx.tableCtx.body, []string{}) if err := ctx.traverseChildren(node); err != nil { return err } ctx.tableCtx.tmpRow++ case atom.Th: res, err := ctx.renderEachChild(node) if err != nil { return err } ctx.tableCtx.header = append(ctx.tableCtx.header, res) case atom.Td: res, err := ctx.renderEachChild(node) if err != nil { return err } if ctx.tableCtx.isInFooter { ctx.tableCtx.footer = append(ctx.tableCtx.footer, res) } else { ctx.tableCtx.body[ctx.tableCtx.tmpRow] = append(ctx.tableCtx.body[ctx.tableCtx.tmpRow], res) } } return nil }
[ "func", "(", "ctx", "*", "textifyTraverseContext", ")", "handleTableElement", "(", "node", "*", "html", ".", "Node", ")", "error", "{", "if", "!", "ctx", ".", "options", ".", "PrettyTables", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "node", ".", "DataAtom", "{", "case", "atom", ".", "Table", ":", "if", "err", ":=", "ctx", ".", "emit", "(", "\"", "\\n", "\\n", "\"", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Re-intialize all table context.", "ctx", ".", "tableCtx", ".", "init", "(", ")", "\n\n", "// Browse children, enriching context with table data.", "if", "err", ":=", "ctx", ".", "traverseChildren", "(", "node", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "table", ":=", "tablewriter", ".", "NewWriter", "(", "buf", ")", "\n", "if", "ctx", ".", "options", ".", "PrettyTablesOptions", "!=", "nil", "{", "options", ":=", "ctx", ".", "options", ".", "PrettyTablesOptions", "\n", "table", ".", "SetAutoFormatHeaders", "(", "options", ".", "AutoFormatHeader", ")", "\n", "table", ".", "SetAutoWrapText", "(", "options", ".", "AutoWrapText", ")", "\n", "table", ".", "SetReflowDuringAutoWrap", "(", "options", ".", "ReflowDuringAutoWrap", ")", "\n", "table", ".", "SetColWidth", "(", "options", ".", "ColWidth", ")", "\n", "table", ".", "SetColumnSeparator", "(", "options", ".", "ColumnSeparator", ")", "\n", "table", ".", "SetRowSeparator", "(", "options", ".", "RowSeparator", ")", "\n", "table", ".", "SetCenterSeparator", "(", "options", ".", "CenterSeparator", ")", "\n", "table", ".", "SetHeaderAlignment", "(", "options", ".", "HeaderAlignment", ")", "\n", "table", ".", "SetFooterAlignment", "(", "options", ".", "FooterAlignment", ")", "\n", "table", ".", "SetAlignment", "(", "options", ".", "Alignment", ")", "\n", "table", ".", "SetColumnAlignment", "(", "options", ".", "ColumnAlignment", ")", "\n", "table", ".", "SetNewLine", "(", "options", ".", "NewLine", ")", "\n", "table", ".", "SetHeaderLine", "(", "options", ".", "HeaderLine", ")", "\n", "table", ".", "SetRowLine", "(", "options", ".", "RowLine", ")", "\n", "table", ".", "SetAutoMergeCells", "(", "options", ".", "AutoMergeCells", ")", "\n", "table", ".", "SetBorders", "(", "options", ".", "Borders", ")", "\n", "}", "\n", "table", ".", "SetHeader", "(", "ctx", ".", "tableCtx", ".", "header", ")", "\n", "table", ".", "SetFooter", "(", "ctx", ".", "tableCtx", ".", "footer", ")", "\n", "table", ".", "AppendBulk", "(", "ctx", ".", "tableCtx", ".", "body", ")", "\n\n", "// Render the table using ASCII.", "table", ".", "Render", "(", ")", "\n", "if", "err", ":=", "ctx", ".", "emit", "(", "buf", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "ctx", ".", "emit", "(", "\"", "\\n", "\\n", "\"", ")", "\n\n", "case", "atom", ".", "Tfoot", ":", "ctx", ".", "tableCtx", ".", "isInFooter", "=", "true", "\n", "if", "err", ":=", "ctx", ".", "traverseChildren", "(", "node", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ctx", ".", "tableCtx", ".", "isInFooter", "=", "false", "\n\n", "case", "atom", ".", "Tr", ":", "ctx", ".", "tableCtx", ".", "body", "=", "append", "(", "ctx", ".", "tableCtx", ".", "body", ",", "[", "]", "string", "{", "}", ")", "\n", "if", "err", ":=", "ctx", ".", "traverseChildren", "(", "node", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ctx", ".", "tableCtx", ".", "tmpRow", "++", "\n\n", "case", "atom", ".", "Th", ":", "res", ",", "err", ":=", "ctx", ".", "renderEachChild", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ctx", ".", "tableCtx", ".", "header", "=", "append", "(", "ctx", ".", "tableCtx", ".", "header", ",", "res", ")", "\n\n", "case", "atom", ".", "Td", ":", "res", ",", "err", ":=", "ctx", ".", "renderEachChild", "(", "node", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "ctx", ".", "tableCtx", ".", "isInFooter", "{", "ctx", ".", "tableCtx", ".", "footer", "=", "append", "(", "ctx", ".", "tableCtx", ".", "footer", ",", "res", ")", "\n", "}", "else", "{", "ctx", ".", "tableCtx", ".", "body", "[", "ctx", ".", "tableCtx", ".", "tmpRow", "]", "=", "append", "(", "ctx", ".", "tableCtx", ".", "body", "[", "ctx", ".", "tableCtx", ".", "tmpRow", "]", ",", "res", ")", "\n", "}", "\n\n", "}", "\n", "return", "nil", "\n", "}" ]
// handleTableElement is only to be invoked when options.PrettyTables is active.
[ "handleTableElement", "is", "only", "to", "be", "invoked", "when", "options", ".", "PrettyTables", "is", "active", "." ]
01ec452cbe43774f989516272881441cae40c16b
https://github.com/jaytaylor/html2text/blob/01ec452cbe43774f989516272881441cae40c16b/html2text.go#L302-L390
152,484
jaytaylor/html2text
html2text.go
renderEachChild
func (ctx *textifyTraverseContext) renderEachChild(node *html.Node) (string, error) { buf := &bytes.Buffer{} for c := node.FirstChild; c != nil; c = c.NextSibling { s, err := FromHTMLNode(c, ctx.options) if err != nil { return "", err } if _, err = buf.WriteString(s); err != nil { return "", err } if c.NextSibling != nil { if err = buf.WriteByte('\n'); err != nil { return "", err } } } return buf.String(), nil }
go
func (ctx *textifyTraverseContext) renderEachChild(node *html.Node) (string, error) { buf := &bytes.Buffer{} for c := node.FirstChild; c != nil; c = c.NextSibling { s, err := FromHTMLNode(c, ctx.options) if err != nil { return "", err } if _, err = buf.WriteString(s); err != nil { return "", err } if c.NextSibling != nil { if err = buf.WriteByte('\n'); err != nil { return "", err } } } return buf.String(), nil }
[ "func", "(", "ctx", "*", "textifyTraverseContext", ")", "renderEachChild", "(", "node", "*", "html", ".", "Node", ")", "(", "string", ",", "error", ")", "{", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "for", "c", ":=", "node", ".", "FirstChild", ";", "c", "!=", "nil", ";", "c", "=", "c", ".", "NextSibling", "{", "s", ",", "err", ":=", "FromHTMLNode", "(", "c", ",", "ctx", ".", "options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "_", ",", "err", "=", "buf", ".", "WriteString", "(", "s", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "c", ".", "NextSibling", "!=", "nil", "{", "if", "err", "=", "buf", ".", "WriteByte", "(", "'\\n'", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// renderEachChild visits each direct child of a node and collects the sequence of // textuual representaitons separated by a single newline.
[ "renderEachChild", "visits", "each", "direct", "child", "of", "a", "node", "and", "collects", "the", "sequence", "of", "textuual", "representaitons", "separated", "by", "a", "single", "newline", "." ]
01ec452cbe43774f989516272881441cae40c16b
https://github.com/jaytaylor/html2text/blob/01ec452cbe43774f989516272881441cae40c16b/html2text.go#L508-L525
152,485
sparrc/go-ping
ping.go
NewPinger
func NewPinger(addr string) (*Pinger, error) { ipaddr, err := net.ResolveIPAddr("ip", addr) if err != nil { return nil, err } var ipv4 bool if isIPv4(ipaddr.IP) { ipv4 = true } else if isIPv6(ipaddr.IP) { ipv4 = false } r := rand.New(rand.NewSource(time.Now().UnixNano())) return &Pinger{ ipaddr: ipaddr, addr: addr, Interval: time.Second, Timeout: time.Second * 100000, Count: -1, id: r.Intn(math.MaxInt16), network: "udp", ipv4: ipv4, Size: timeSliceLength, Tracker: r.Int63n(math.MaxInt64), done: make(chan bool), }, nil }
go
func NewPinger(addr string) (*Pinger, error) { ipaddr, err := net.ResolveIPAddr("ip", addr) if err != nil { return nil, err } var ipv4 bool if isIPv4(ipaddr.IP) { ipv4 = true } else if isIPv6(ipaddr.IP) { ipv4 = false } r := rand.New(rand.NewSource(time.Now().UnixNano())) return &Pinger{ ipaddr: ipaddr, addr: addr, Interval: time.Second, Timeout: time.Second * 100000, Count: -1, id: r.Intn(math.MaxInt16), network: "udp", ipv4: ipv4, Size: timeSliceLength, Tracker: r.Int63n(math.MaxInt64), done: make(chan bool), }, nil }
[ "func", "NewPinger", "(", "addr", "string", ")", "(", "*", "Pinger", ",", "error", ")", "{", "ipaddr", ",", "err", ":=", "net", ".", "ResolveIPAddr", "(", "\"", "\"", ",", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "ipv4", "bool", "\n", "if", "isIPv4", "(", "ipaddr", ".", "IP", ")", "{", "ipv4", "=", "true", "\n", "}", "else", "if", "isIPv6", "(", "ipaddr", ".", "IP", ")", "{", "ipv4", "=", "false", "\n", "}", "\n\n", "r", ":=", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ")", "\n", "return", "&", "Pinger", "{", "ipaddr", ":", "ipaddr", ",", "addr", ":", "addr", ",", "Interval", ":", "time", ".", "Second", ",", "Timeout", ":", "time", ".", "Second", "*", "100000", ",", "Count", ":", "-", "1", ",", "id", ":", "r", ".", "Intn", "(", "math", ".", "MaxInt16", ")", ",", "network", ":", "\"", "\"", ",", "ipv4", ":", "ipv4", ",", "Size", ":", "timeSliceLength", ",", "Tracker", ":", "r", ".", "Int63n", "(", "math", ".", "MaxInt64", ")", ",", "done", ":", "make", "(", "chan", "bool", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewPinger returns a new Pinger struct pointer
[ "NewPinger", "returns", "a", "new", "Pinger", "struct", "pointer" ]
ef3ab45e41b017889941ea5bb796dd502d2b5a1b
https://github.com/sparrc/go-ping/blob/ef3ab45e41b017889941ea5bb796dd502d2b5a1b/ping.go#L73-L100
152,486
sparrc/go-ping
ping.go
SetIPAddr
func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr) { var ipv4 bool if isIPv4(ipaddr.IP) { ipv4 = true } else if isIPv6(ipaddr.IP) { ipv4 = false } p.ipaddr = ipaddr p.addr = ipaddr.String() p.ipv4 = ipv4 }
go
func (p *Pinger) SetIPAddr(ipaddr *net.IPAddr) { var ipv4 bool if isIPv4(ipaddr.IP) { ipv4 = true } else if isIPv6(ipaddr.IP) { ipv4 = false } p.ipaddr = ipaddr p.addr = ipaddr.String() p.ipv4 = ipv4 }
[ "func", "(", "p", "*", "Pinger", ")", "SetIPAddr", "(", "ipaddr", "*", "net", ".", "IPAddr", ")", "{", "var", "ipv4", "bool", "\n", "if", "isIPv4", "(", "ipaddr", ".", "IP", ")", "{", "ipv4", "=", "true", "\n", "}", "else", "if", "isIPv6", "(", "ipaddr", ".", "IP", ")", "{", "ipv4", "=", "false", "\n", "}", "\n\n", "p", ".", "ipaddr", "=", "ipaddr", "\n", "p", ".", "addr", "=", "ipaddr", ".", "String", "(", ")", "\n", "p", ".", "ipv4", "=", "ipv4", "\n", "}" ]
// SetIPAddr sets the ip address of the target host.
[ "SetIPAddr", "sets", "the", "ip", "address", "of", "the", "target", "host", "." ]
ef3ab45e41b017889941ea5bb796dd502d2b5a1b
https://github.com/sparrc/go-ping/blob/ef3ab45e41b017889941ea5bb796dd502d2b5a1b/ping.go#L213-L224
152,487
sparrc/go-ping
ping.go
Statistics
func (p *Pinger) Statistics() *Statistics { loss := float64(p.PacketsSent-p.PacketsRecv) / float64(p.PacketsSent) * 100 var min, max, total time.Duration if len(p.rtts) > 0 { min = p.rtts[0] max = p.rtts[0] } for _, rtt := range p.rtts { if rtt < min { min = rtt } if rtt > max { max = rtt } total += rtt } s := Statistics{ PacketsSent: p.PacketsSent, PacketsRecv: p.PacketsRecv, PacketLoss: loss, Rtts: p.rtts, Addr: p.addr, IPAddr: p.ipaddr, MaxRtt: max, MinRtt: min, } if len(p.rtts) > 0 { s.AvgRtt = total / time.Duration(len(p.rtts)) var sumsquares time.Duration for _, rtt := range p.rtts { sumsquares += (rtt - s.AvgRtt) * (rtt - s.AvgRtt) } s.StdDevRtt = time.Duration(math.Sqrt( float64(sumsquares / time.Duration(len(p.rtts))))) } return &s }
go
func (p *Pinger) Statistics() *Statistics { loss := float64(p.PacketsSent-p.PacketsRecv) / float64(p.PacketsSent) * 100 var min, max, total time.Duration if len(p.rtts) > 0 { min = p.rtts[0] max = p.rtts[0] } for _, rtt := range p.rtts { if rtt < min { min = rtt } if rtt > max { max = rtt } total += rtt } s := Statistics{ PacketsSent: p.PacketsSent, PacketsRecv: p.PacketsRecv, PacketLoss: loss, Rtts: p.rtts, Addr: p.addr, IPAddr: p.ipaddr, MaxRtt: max, MinRtt: min, } if len(p.rtts) > 0 { s.AvgRtt = total / time.Duration(len(p.rtts)) var sumsquares time.Duration for _, rtt := range p.rtts { sumsquares += (rtt - s.AvgRtt) * (rtt - s.AvgRtt) } s.StdDevRtt = time.Duration(math.Sqrt( float64(sumsquares / time.Duration(len(p.rtts))))) } return &s }
[ "func", "(", "p", "*", "Pinger", ")", "Statistics", "(", ")", "*", "Statistics", "{", "loss", ":=", "float64", "(", "p", ".", "PacketsSent", "-", "p", ".", "PacketsRecv", ")", "/", "float64", "(", "p", ".", "PacketsSent", ")", "*", "100", "\n", "var", "min", ",", "max", ",", "total", "time", ".", "Duration", "\n", "if", "len", "(", "p", ".", "rtts", ")", ">", "0", "{", "min", "=", "p", ".", "rtts", "[", "0", "]", "\n", "max", "=", "p", ".", "rtts", "[", "0", "]", "\n", "}", "\n", "for", "_", ",", "rtt", ":=", "range", "p", ".", "rtts", "{", "if", "rtt", "<", "min", "{", "min", "=", "rtt", "\n", "}", "\n", "if", "rtt", ">", "max", "{", "max", "=", "rtt", "\n", "}", "\n", "total", "+=", "rtt", "\n", "}", "\n", "s", ":=", "Statistics", "{", "PacketsSent", ":", "p", ".", "PacketsSent", ",", "PacketsRecv", ":", "p", ".", "PacketsRecv", ",", "PacketLoss", ":", "loss", ",", "Rtts", ":", "p", ".", "rtts", ",", "Addr", ":", "p", ".", "addr", ",", "IPAddr", ":", "p", ".", "ipaddr", ",", "MaxRtt", ":", "max", ",", "MinRtt", ":", "min", ",", "}", "\n", "if", "len", "(", "p", ".", "rtts", ")", ">", "0", "{", "s", ".", "AvgRtt", "=", "total", "/", "time", ".", "Duration", "(", "len", "(", "p", ".", "rtts", ")", ")", "\n", "var", "sumsquares", "time", ".", "Duration", "\n", "for", "_", ",", "rtt", ":=", "range", "p", ".", "rtts", "{", "sumsquares", "+=", "(", "rtt", "-", "s", ".", "AvgRtt", ")", "*", "(", "rtt", "-", "s", ".", "AvgRtt", ")", "\n", "}", "\n", "s", ".", "StdDevRtt", "=", "time", ".", "Duration", "(", "math", ".", "Sqrt", "(", "float64", "(", "sumsquares", "/", "time", ".", "Duration", "(", "len", "(", "p", ".", "rtts", ")", ")", ")", ")", ")", "\n", "}", "\n", "return", "&", "s", "\n", "}" ]
// Statistics returns the statistics of the pinger. This can be run while the // pinger is running or after it is finished. OnFinish calls this function to // get it's finished statistics.
[ "Statistics", "returns", "the", "statistics", "of", "the", "pinger", ".", "This", "can", "be", "run", "while", "the", "pinger", "is", "running", "or", "after", "it", "is", "finished", ".", "OnFinish", "calls", "this", "function", "to", "get", "it", "s", "finished", "statistics", "." ]
ef3ab45e41b017889941ea5bb796dd502d2b5a1b
https://github.com/sparrc/go-ping/blob/ef3ab45e41b017889941ea5bb796dd502d2b5a1b/ping.go#L349-L385
152,488
Azure/go-autorest
autorest/preparer.go
Prepare
func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) { return pf(r) }
go
func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) { return pf(r) }
[ "func", "(", "pf", "PreparerFunc", ")", "Prepare", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "return", "pf", "(", "r", ")", "\n", "}" ]
// Prepare implements the Preparer interface on PreparerFunc.
[ "Prepare", "implements", "the", "Preparer", "interface", "on", "PreparerFunc", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L51-L53
152,489
Azure/go-autorest
autorest/preparer.go
CreatePreparer
func CreatePreparer(decorators ...PrepareDecorator) Preparer { return DecoratePreparer( Preparer(PreparerFunc(func(r *http.Request) (*http.Request, error) { return r, nil })), decorators...) }
go
func CreatePreparer(decorators ...PrepareDecorator) Preparer { return DecoratePreparer( Preparer(PreparerFunc(func(r *http.Request) (*http.Request, error) { return r, nil })), decorators...) }
[ "func", "CreatePreparer", "(", "decorators", "...", "PrepareDecorator", ")", "Preparer", "{", "return", "DecoratePreparer", "(", "Preparer", "(", "PreparerFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "return", "r", ",", "nil", "}", ")", ")", ",", "decorators", "...", ")", "\n", "}" ]
// CreatePreparer creates, decorates, and returns a Preparer. // Without decorators, the returned Preparer returns the passed http.Request unmodified. // Preparers are safe to share and re-use.
[ "CreatePreparer", "creates", "decorates", "and", "returns", "a", "Preparer", ".", "Without", "decorators", "the", "returned", "Preparer", "returns", "the", "passed", "http", ".", "Request", "unmodified", ".", "Preparers", "are", "safe", "to", "share", "and", "re", "-", "use", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L62-L66
152,490
Azure/go-autorest
autorest/preparer.go
Prepare
func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) { if r == nil { return nil, NewError("autorest", "Prepare", "Invoked without an http.Request") } return CreatePreparer(decorators...).Prepare(r) }
go
func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) { if r == nil { return nil, NewError("autorest", "Prepare", "Invoked without an http.Request") } return CreatePreparer(decorators...).Prepare(r) }
[ "func", "Prepare", "(", "r", "*", "http", ".", "Request", ",", "decorators", "...", "PrepareDecorator", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "if", "r", "==", "nil", "{", "return", "nil", ",", "NewError", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "CreatePreparer", "(", "decorators", "...", ")", ".", "Prepare", "(", "r", ")", "\n", "}" ]
// Prepare accepts an http.Request and a, possibly empty, set of PrepareDecorators. // It creates a Preparer from the decorators which it then applies to the passed http.Request.
[ "Prepare", "accepts", "an", "http", ".", "Request", "and", "a", "possibly", "empty", "set", "of", "PrepareDecorators", ".", "It", "creates", "a", "Preparer", "from", "the", "decorators", "which", "it", "then", "applies", "to", "the", "passed", "http", ".", "Request", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L81-L86
152,491
Azure/go-autorest
autorest/preparer.go
WithNothing
func WithNothing() PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { return p.Prepare(r) }) } }
go
func WithNothing() PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { return p.Prepare(r) }) } }
[ "func", "WithNothing", "(", ")", "PrepareDecorator", "{", "return", "func", "(", "p", "Preparer", ")", "Preparer", "{", "return", "PreparerFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "return", "p", ".", "Prepare", "(", "r", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// WithNothing returns a "do nothing" PrepareDecorator that makes no changes to the passed // http.Request.
[ "WithNothing", "returns", "a", "do", "nothing", "PrepareDecorator", "that", "makes", "no", "changes", "to", "the", "passed", "http", ".", "Request", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L90-L96
152,492
Azure/go-autorest
autorest/preparer.go
WithMethod
func WithMethod(method string) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r.Method = method return p.Prepare(r) }) } }
go
func WithMethod(method string) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r.Method = method return p.Prepare(r) }) } }
[ "func", "WithMethod", "(", "method", "string", ")", "PrepareDecorator", "{", "return", "func", "(", "p", "Preparer", ")", "Preparer", "{", "return", "PreparerFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "r", ".", "Method", "=", "method", "\n", "return", "p", ".", "Prepare", "(", "r", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// WithMethod returns a PrepareDecorator that sets the HTTP method of the passed request. The // decorator does not validate that the passed method string is a known HTTP method.
[ "WithMethod", "returns", "a", "PrepareDecorator", "that", "sets", "the", "HTTP", "method", "of", "the", "passed", "request", ".", "The", "decorator", "does", "not", "validate", "that", "the", "passed", "method", "string", "is", "a", "known", "HTTP", "method", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L175-L182
152,493
Azure/go-autorest
autorest/preparer.go
WithBaseURL
func WithBaseURL(baseURL string) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { var u *url.URL if u, err = url.Parse(baseURL); err != nil { return r, err } if u.Scheme == "" { err = fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) } if err == nil { r.URL = u } } return r, err }) } }
go
func WithBaseURL(baseURL string) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { var u *url.URL if u, err = url.Parse(baseURL); err != nil { return r, err } if u.Scheme == "" { err = fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) } if err == nil { r.URL = u } } return r, err }) } }
[ "func", "WithBaseURL", "(", "baseURL", "string", ")", "PrepareDecorator", "{", "return", "func", "(", "p", "Preparer", ")", "Preparer", "{", "return", "PreparerFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "r", ",", "err", ":=", "p", ".", "Prepare", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "var", "u", "*", "url", ".", "URL", "\n", "if", "u", ",", "err", "=", "url", ".", "Parse", "(", "baseURL", ")", ";", "err", "!=", "nil", "{", "return", "r", ",", "err", "\n", "}", "\n", "if", "u", ".", "Scheme", "==", "\"", "\"", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "baseURL", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "r", ".", "URL", "=", "u", "\n", "}", "\n", "}", "\n", "return", "r", ",", "err", "\n", "}", ")", "\n", "}", "\n", "}" ]
// WithBaseURL returns a PrepareDecorator that populates the http.Request with a url.URL constructed // from the supplied baseUrl.
[ "WithBaseURL", "returns", "a", "PrepareDecorator", "that", "populates", "the", "http", ".", "Request", "with", "a", "url", ".", "URL", "constructed", "from", "the", "supplied", "baseUrl", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L207-L226
152,494
Azure/go-autorest
autorest/preparer.go
WithFile
func WithFile(f io.ReadCloser) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { b, err := ioutil.ReadAll(f) if err != nil { return r, err } r.Body = ioutil.NopCloser(bytes.NewReader(b)) r.ContentLength = int64(len(b)) } return r, err }) } }
go
func WithFile(f io.ReadCloser) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { b, err := ioutil.ReadAll(f) if err != nil { return r, err } r.Body = ioutil.NopCloser(bytes.NewReader(b)) r.ContentLength = int64(len(b)) } return r, err }) } }
[ "func", "WithFile", "(", "f", "io", ".", "ReadCloser", ")", "PrepareDecorator", "{", "return", "func", "(", "p", "Preparer", ")", "Preparer", "{", "return", "PreparerFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "r", ",", "err", ":=", "p", ".", "Prepare", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "r", ",", "err", "\n", "}", "\n", "r", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "b", ")", ")", "\n", "r", ".", "ContentLength", "=", "int64", "(", "len", "(", "b", ")", ")", "\n", "}", "\n", "return", "r", ",", "err", "\n", "}", ")", "\n", "}", "\n", "}" ]
// WithFile returns a PrepareDecorator that sends file in request body.
[ "WithFile", "returns", "a", "PrepareDecorator", "that", "sends", "file", "in", "request", "body", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L300-L315
152,495
Azure/go-autorest
autorest/preparer.go
WithString
func WithString(v string) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { r.ContentLength = int64(len(v)) r.Body = ioutil.NopCloser(strings.NewReader(v)) } return r, err }) } }
go
func WithString(v string) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { r.ContentLength = int64(len(v)) r.Body = ioutil.NopCloser(strings.NewReader(v)) } return r, err }) } }
[ "func", "WithString", "(", "v", "string", ")", "PrepareDecorator", "{", "return", "func", "(", "p", "Preparer", ")", "Preparer", "{", "return", "PreparerFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "r", ",", "err", ":=", "p", ".", "Prepare", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "r", ".", "ContentLength", "=", "int64", "(", "len", "(", "v", ")", ")", "\n", "r", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "strings", ".", "NewReader", "(", "v", ")", ")", "\n", "}", "\n", "return", "r", ",", "err", "\n", "}", ")", "\n", "}", "\n", "}" ]
// WithString returns a PrepareDecorator that encodes the passed string into the body of the request // and sets the Content-Length header.
[ "WithString", "returns", "a", "PrepareDecorator", "that", "encodes", "the", "passed", "string", "into", "the", "body", "of", "the", "request", "and", "sets", "the", "Content", "-", "Length", "header", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L349-L360
152,496
Azure/go-autorest
autorest/preparer.go
WithJSON
func WithJSON(v interface{}) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { b, err := json.Marshal(v) if err == nil { r.ContentLength = int64(len(b)) r.Body = ioutil.NopCloser(bytes.NewReader(b)) } } return r, err }) } }
go
func WithJSON(v interface{}) PrepareDecorator { return func(p Preparer) Preparer { return PreparerFunc(func(r *http.Request) (*http.Request, error) { r, err := p.Prepare(r) if err == nil { b, err := json.Marshal(v) if err == nil { r.ContentLength = int64(len(b)) r.Body = ioutil.NopCloser(bytes.NewReader(b)) } } return r, err }) } }
[ "func", "WithJSON", "(", "v", "interface", "{", "}", ")", "PrepareDecorator", "{", "return", "func", "(", "p", "Preparer", ")", "Preparer", "{", "return", "PreparerFunc", "(", "func", "(", "r", "*", "http", ".", "Request", ")", "(", "*", "http", ".", "Request", ",", "error", ")", "{", "r", ",", "err", ":=", "p", ".", "Prepare", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "v", ")", "\n", "if", "err", "==", "nil", "{", "r", ".", "ContentLength", "=", "int64", "(", "len", "(", "b", ")", ")", "\n", "r", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewReader", "(", "b", ")", ")", "\n", "}", "\n", "}", "\n", "return", "r", ",", "err", "\n", "}", ")", "\n", "}", "\n", "}" ]
// WithJSON returns a PrepareDecorator that encodes the data passed as JSON into the body of the // request and sets the Content-Length header.
[ "WithJSON", "returns", "a", "PrepareDecorator", "that", "encodes", "the", "data", "passed", "as", "JSON", "into", "the", "body", "of", "the", "request", "and", "sets", "the", "Content", "-", "Length", "header", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/preparer.go#L364-L378
152,497
Azure/go-autorest
autorest/azure/environments.go
EnvironmentFromName
func EnvironmentFromName(name string) (Environment, error) { // IMPORTANT // As per @radhikagupta5: // This is technical debt, fundamentally here because Kubernetes is not currently accepting // contributions to the providers. Once that is an option, the provider should be updated to // directly call `EnvironmentFromFile`. Until then, we rely on dispatching Azure Stack environment creation // from this method based on the name that is provided to us. if strings.EqualFold(name, "AZURESTACKCLOUD") { return EnvironmentFromFile(os.Getenv(EnvironmentFilepathName)) } name = strings.ToUpper(name) env, ok := environments[name] if !ok { return env, fmt.Errorf("autorest/azure: There is no cloud environment matching the name %q", name) } return env, nil }
go
func EnvironmentFromName(name string) (Environment, error) { // IMPORTANT // As per @radhikagupta5: // This is technical debt, fundamentally here because Kubernetes is not currently accepting // contributions to the providers. Once that is an option, the provider should be updated to // directly call `EnvironmentFromFile`. Until then, we rely on dispatching Azure Stack environment creation // from this method based on the name that is provided to us. if strings.EqualFold(name, "AZURESTACKCLOUD") { return EnvironmentFromFile(os.Getenv(EnvironmentFilepathName)) } name = strings.ToUpper(name) env, ok := environments[name] if !ok { return env, fmt.Errorf("autorest/azure: There is no cloud environment matching the name %q", name) } return env, nil }
[ "func", "EnvironmentFromName", "(", "name", "string", ")", "(", "Environment", ",", "error", ")", "{", "// IMPORTANT", "// As per @radhikagupta5:", "// This is technical debt, fundamentally here because Kubernetes is not currently accepting", "// contributions to the providers. Once that is an option, the provider should be updated to", "// directly call `EnvironmentFromFile`. Until then, we rely on dispatching Azure Stack environment creation", "// from this method based on the name that is provided to us.", "if", "strings", ".", "EqualFold", "(", "name", ",", "\"", "\"", ")", "{", "return", "EnvironmentFromFile", "(", "os", ".", "Getenv", "(", "EnvironmentFilepathName", ")", ")", "\n", "}", "\n\n", "name", "=", "strings", ".", "ToUpper", "(", "name", ")", "\n", "env", ",", "ok", ":=", "environments", "[", "name", "]", "\n", "if", "!", "ok", "{", "return", "env", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "return", "env", ",", "nil", "\n", "}" ]
// EnvironmentFromName returns an Environment based on the common name specified.
[ "EnvironmentFromName", "returns", "an", "Environment", "based", "on", "the", "common", "name", "specified", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/environments.go#L207-L225
152,498
Azure/go-autorest
autorest/azure/environments.go
EnvironmentFromFile
func EnvironmentFromFile(location string) (unmarshaled Environment, err error) { fileContents, err := ioutil.ReadFile(location) if err != nil { return } err = json.Unmarshal(fileContents, &unmarshaled) return }
go
func EnvironmentFromFile(location string) (unmarshaled Environment, err error) { fileContents, err := ioutil.ReadFile(location) if err != nil { return } err = json.Unmarshal(fileContents, &unmarshaled) return }
[ "func", "EnvironmentFromFile", "(", "location", "string", ")", "(", "unmarshaled", "Environment", ",", "err", "error", ")", "{", "fileContents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "location", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "fileContents", ",", "&", "unmarshaled", ")", "\n\n", "return", "\n", "}" ]
// EnvironmentFromFile loads an Environment from a configuration file available on disk. // This function is particularly useful in the Hybrid Cloud model, where one must define their own // endpoints.
[ "EnvironmentFromFile", "loads", "an", "Environment", "from", "a", "configuration", "file", "available", "on", "disk", ".", "This", "function", "is", "particularly", "useful", "in", "the", "Hybrid", "Cloud", "model", "where", "one", "must", "define", "their", "own", "endpoints", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/environments.go#L230-L239
152,499
Azure/go-autorest
autorest/responder.go
Respond
func Respond(r *http.Response, decorators ...RespondDecorator) error { if r == nil { return nil } return CreateResponder(decorators...).Respond(r) }
go
func Respond(r *http.Response, decorators ...RespondDecorator) error { if r == nil { return nil } return CreateResponder(decorators...).Respond(r) }
[ "func", "Respond", "(", "r", "*", "http", ".", "Response", ",", "decorators", "...", "RespondDecorator", ")", "error", "{", "if", "r", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "CreateResponder", "(", "decorators", "...", ")", ".", "Respond", "(", "r", ")", "\n", "}" ]
// Respond accepts an http.Response and a, possibly empty, set of RespondDecorators. // It creates a Responder from the decorators it then applies to the passed http.Response.
[ "Respond", "accepts", "an", "http", ".", "Response", "and", "a", "possibly", "empty", "set", "of", "RespondDecorators", ".", "It", "creates", "a", "Responder", "from", "the", "decorators", "it", "then", "applies", "to", "the", "passed", "http", ".", "Response", "." ]
da8db3a19ec5aba5d01f6032407abf1bb1cc15d3
https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/responder.go#L74-L79