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
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
2,000
advancedlogic/GoOse
extractor.go
isHighLinkDensity
func (extr *ContentExtractor) isHighLinkDensity(node *goquery.Selection) bool { links := node.Find("a") if links == nil || links.Size() == 0 { return false } text := node.Text() words := strings.Split(text, " ") nwords := len(words) var sb []string links.Each(func(i int, s *goquery.Selection) { linkText := s.Text() sb = append(sb, linkText) }) linkText := strings.Join(sb, "") linkWords := strings.Split(linkText, " ") nlinkWords := len(linkWords) nlinks := links.Size() linkDivisor := float64(nlinkWords) / float64(nwords) score := linkDivisor * float64(nlinks) if extr.config.debug { var logText string if len(node.Text()) >= 51 { logText = node.Text()[0:50] } else { logText = node.Text() } log.Printf("Calculated link density score as %1.5f for node %s\n", score, logText) } if score > 1.0 { return true } return false }
go
func (extr *ContentExtractor) isHighLinkDensity(node *goquery.Selection) bool { links := node.Find("a") if links == nil || links.Size() == 0 { return false } text := node.Text() words := strings.Split(text, " ") nwords := len(words) var sb []string links.Each(func(i int, s *goquery.Selection) { linkText := s.Text() sb = append(sb, linkText) }) linkText := strings.Join(sb, "") linkWords := strings.Split(linkText, " ") nlinkWords := len(linkWords) nlinks := links.Size() linkDivisor := float64(nlinkWords) / float64(nwords) score := linkDivisor * float64(nlinks) if extr.config.debug { var logText string if len(node.Text()) >= 51 { logText = node.Text()[0:50] } else { logText = node.Text() } log.Printf("Calculated link density score as %1.5f for node %s\n", score, logText) } if score > 1.0 { return true } return false }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "isHighLinkDensity", "(", "node", "*", "goquery", ".", "Selection", ")", "bool", "{", "links", ":=", "node", ".", "Find", "(", "\"", "\"", ")", "\n", "if", "links", "==", "nil", "||", "links", ".", "Size", "(", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "text", ":=", "node", ".", "Text", "(", ")", "\n", "words", ":=", "strings", ".", "Split", "(", "text", ",", "\"", "\"", ")", "\n", "nwords", ":=", "len", "(", "words", ")", "\n", "var", "sb", "[", "]", "string", "\n", "links", ".", "Each", "(", "func", "(", "i", "int", ",", "s", "*", "goquery", ".", "Selection", ")", "{", "linkText", ":=", "s", ".", "Text", "(", ")", "\n", "sb", "=", "append", "(", "sb", ",", "linkText", ")", "\n", "}", ")", "\n", "linkText", ":=", "strings", ".", "Join", "(", "sb", ",", "\"", "\"", ")", "\n", "linkWords", ":=", "strings", ".", "Split", "(", "linkText", ",", "\"", "\"", ")", "\n", "nlinkWords", ":=", "len", "(", "linkWords", ")", "\n", "nlinks", ":=", "links", ".", "Size", "(", ")", "\n", "linkDivisor", ":=", "float64", "(", "nlinkWords", ")", "/", "float64", "(", "nwords", ")", "\n", "score", ":=", "linkDivisor", "*", "float64", "(", "nlinks", ")", "\n\n", "if", "extr", ".", "config", ".", "debug", "{", "var", "logText", "string", "\n", "if", "len", "(", "node", ".", "Text", "(", ")", ")", ">=", "51", "{", "logText", "=", "node", ".", "Text", "(", ")", "[", "0", ":", "50", "]", "\n", "}", "else", "{", "logText", "=", "node", ".", "Text", "(", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "score", ",", "logText", ")", "\n", "}", "\n", "if", "score", ">", "1.0", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
//checks the density of links within a node, is there not much text and most of it contains bad links? //if so it's no good
[ "checks", "the", "density", "of", "links", "within", "a", "node", "is", "there", "not", "much", "text", "and", "most", "of", "it", "contains", "bad", "links?", "if", "so", "it", "s", "no", "good" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L551-L584
2,001
advancedlogic/GoOse
extractor.go
getSiblingsScore
func (extr *ContentExtractor) getSiblingsScore(topNode *goquery.Selection) int { base := 100000 paragraphNumber := 0 paragraphScore := 0 nodesToCheck := topNode.Find("p") nodesToCheck.Each(func(i int, s *goquery.Selection) { textNode := s.Text() ws := extr.config.stopWords.stopWordsCount(extr.config.targetLanguage, textNode) highLinkDensity := extr.isHighLinkDensity(s) if ws.stopWordCount > 2 && !highLinkDensity { paragraphNumber++ paragraphScore += ws.stopWordCount } }) if paragraphNumber > 0 { base = paragraphScore / paragraphNumber } return base }
go
func (extr *ContentExtractor) getSiblingsScore(topNode *goquery.Selection) int { base := 100000 paragraphNumber := 0 paragraphScore := 0 nodesToCheck := topNode.Find("p") nodesToCheck.Each(func(i int, s *goquery.Selection) { textNode := s.Text() ws := extr.config.stopWords.stopWordsCount(extr.config.targetLanguage, textNode) highLinkDensity := extr.isHighLinkDensity(s) if ws.stopWordCount > 2 && !highLinkDensity { paragraphNumber++ paragraphScore += ws.stopWordCount } }) if paragraphNumber > 0 { base = paragraphScore / paragraphNumber } return base }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "getSiblingsScore", "(", "topNode", "*", "goquery", ".", "Selection", ")", "int", "{", "base", ":=", "100000", "\n", "paragraphNumber", ":=", "0", "\n", "paragraphScore", ":=", "0", "\n", "nodesToCheck", ":=", "topNode", ".", "Find", "(", "\"", "\"", ")", "\n", "nodesToCheck", ".", "Each", "(", "func", "(", "i", "int", ",", "s", "*", "goquery", ".", "Selection", ")", "{", "textNode", ":=", "s", ".", "Text", "(", ")", "\n", "ws", ":=", "extr", ".", "config", ".", "stopWords", ".", "stopWordsCount", "(", "extr", ".", "config", ".", "targetLanguage", ",", "textNode", ")", "\n", "highLinkDensity", ":=", "extr", ".", "isHighLinkDensity", "(", "s", ")", "\n", "if", "ws", ".", "stopWordCount", ">", "2", "&&", "!", "highLinkDensity", "{", "paragraphNumber", "++", "\n", "paragraphScore", "+=", "ws", ".", "stopWordCount", "\n", "}", "\n", "}", ")", "\n", "if", "paragraphNumber", ">", "0", "{", "base", "=", "paragraphScore", "/", "paragraphNumber", "\n", "}", "\n", "return", "base", "\n", "}" ]
//we could have long articles that have tons of paragraphs so if we tried to calculate the base score against //the total text score of those paragraphs it would be unfair. So we need to normalize the score based on the average scoring //of the paragraphs within the top node. For example if our total score of 10 paragraphs was 1000 but each had an average value of //100 then 100 should be our base.
[ "we", "could", "have", "long", "articles", "that", "have", "tons", "of", "paragraphs", "so", "if", "we", "tried", "to", "calculate", "the", "base", "score", "against", "the", "total", "text", "score", "of", "those", "paragraphs", "it", "would", "be", "unfair", ".", "So", "we", "need", "to", "normalize", "the", "score", "based", "on", "the", "average", "scoring", "of", "the", "paragraphs", "within", "the", "top", "node", ".", "For", "example", "if", "our", "total", "score", "of", "10", "paragraphs", "was", "1000", "but", "each", "had", "an", "average", "value", "of", "100", "then", "100", "should", "be", "our", "base", "." ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L618-L636
2,002
advancedlogic/GoOse
extractor.go
addSiblings
func (extr *ContentExtractor) addSiblings(topNode *goquery.Selection) *goquery.Selection { if extr.config.debug { log.Println("Starting to add siblings") } baselinescoreSiblingsPara := extr.getSiblingsScore(topNode) results := extr.walkSiblings(topNode) for _, currentNode := range results { ps := extr.getSiblingsContent(currentNode, float64(baselinescoreSiblingsPara)) for _, p := range ps { nodes := make([]*html.Node, len(topNode.Nodes)+1) nodes[0] = p.Get(0) for i, node := range topNode.Nodes { nodes[i+1] = node } topNode.Nodes = nodes } } return topNode }
go
func (extr *ContentExtractor) addSiblings(topNode *goquery.Selection) *goquery.Selection { if extr.config.debug { log.Println("Starting to add siblings") } baselinescoreSiblingsPara := extr.getSiblingsScore(topNode) results := extr.walkSiblings(topNode) for _, currentNode := range results { ps := extr.getSiblingsContent(currentNode, float64(baselinescoreSiblingsPara)) for _, p := range ps { nodes := make([]*html.Node, len(topNode.Nodes)+1) nodes[0] = p.Get(0) for i, node := range topNode.Nodes { nodes[i+1] = node } topNode.Nodes = nodes } } return topNode }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "addSiblings", "(", "topNode", "*", "goquery", ".", "Selection", ")", "*", "goquery", ".", "Selection", "{", "if", "extr", ".", "config", ".", "debug", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "baselinescoreSiblingsPara", ":=", "extr", ".", "getSiblingsScore", "(", "topNode", ")", "\n", "results", ":=", "extr", ".", "walkSiblings", "(", "topNode", ")", "\n", "for", "_", ",", "currentNode", ":=", "range", "results", "{", "ps", ":=", "extr", ".", "getSiblingsContent", "(", "currentNode", ",", "float64", "(", "baselinescoreSiblingsPara", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "ps", "{", "nodes", ":=", "make", "(", "[", "]", "*", "html", ".", "Node", ",", "len", "(", "topNode", ".", "Nodes", ")", "+", "1", ")", "\n", "nodes", "[", "0", "]", "=", "p", ".", "Get", "(", "0", ")", "\n", "for", "i", ",", "node", ":=", "range", "topNode", ".", "Nodes", "{", "nodes", "[", "i", "+", "1", "]", "=", "node", "\n", "}", "\n", "topNode", ".", "Nodes", "=", "nodes", "\n", "}", "\n", "}", "\n", "return", "topNode", "\n", "}" ]
//adds any siblings that may have a decent score to this node
[ "adds", "any", "siblings", "that", "may", "have", "a", "decent", "score", "to", "this", "node" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L683-L701
2,003
advancedlogic/GoOse
extractor.go
PostCleanup
func (extr *ContentExtractor) PostCleanup(targetNode *goquery.Selection) *goquery.Selection { if extr.config.debug { log.Println("Starting cleanup Node") } node := extr.addSiblings(targetNode) children := node.Children() children.Each(func(i int, s *goquery.Selection) { tag := s.Get(0).DataAtom.String() if tag != "p" { if extr.config.debug { log.Printf("CLEANUP NODE: %s class: %s\n", extr.config.parser.name("id", s), extr.config.parser.name("class", s)) } //if extr.isHighLinkDensity(s) || extr.isTableAndNoParaExist(s) || !extr.isNodescoreThresholdMet(node, s) { if extr.isHighLinkDensity(s) { extr.config.parser.removeNode(s) return } subParagraph := s.Find("p") subParagraph.Each(func(j int, e *goquery.Selection) { if len(e.Text()) < 25 { extr.config.parser.removeNode(e) } }) subParagraph2 := s.Find("p") if subParagraph2.Length() == 0 && tag != "td" { if extr.config.debug { log.Println("Removing node because it doesn't have any paragraphs") } extr.config.parser.removeNode(s) } else { if extr.config.debug { log.Println("Not removing TD node") } } return } }) return node }
go
func (extr *ContentExtractor) PostCleanup(targetNode *goquery.Selection) *goquery.Selection { if extr.config.debug { log.Println("Starting cleanup Node") } node := extr.addSiblings(targetNode) children := node.Children() children.Each(func(i int, s *goquery.Selection) { tag := s.Get(0).DataAtom.String() if tag != "p" { if extr.config.debug { log.Printf("CLEANUP NODE: %s class: %s\n", extr.config.parser.name("id", s), extr.config.parser.name("class", s)) } //if extr.isHighLinkDensity(s) || extr.isTableAndNoParaExist(s) || !extr.isNodescoreThresholdMet(node, s) { if extr.isHighLinkDensity(s) { extr.config.parser.removeNode(s) return } subParagraph := s.Find("p") subParagraph.Each(func(j int, e *goquery.Selection) { if len(e.Text()) < 25 { extr.config.parser.removeNode(e) } }) subParagraph2 := s.Find("p") if subParagraph2.Length() == 0 && tag != "td" { if extr.config.debug { log.Println("Removing node because it doesn't have any paragraphs") } extr.config.parser.removeNode(s) } else { if extr.config.debug { log.Println("Not removing TD node") } } return } }) return node }
[ "func", "(", "extr", "*", "ContentExtractor", ")", "PostCleanup", "(", "targetNode", "*", "goquery", ".", "Selection", ")", "*", "goquery", ".", "Selection", "{", "if", "extr", ".", "config", ".", "debug", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "node", ":=", "extr", ".", "addSiblings", "(", "targetNode", ")", "\n", "children", ":=", "node", ".", "Children", "(", ")", "\n", "children", ".", "Each", "(", "func", "(", "i", "int", ",", "s", "*", "goquery", ".", "Selection", ")", "{", "tag", ":=", "s", ".", "Get", "(", "0", ")", ".", "DataAtom", ".", "String", "(", ")", "\n", "if", "tag", "!=", "\"", "\"", "{", "if", "extr", ".", "config", ".", "debug", "{", "log", ".", "Printf", "(", "\"", "\\n", "\"", ",", "extr", ".", "config", ".", "parser", ".", "name", "(", "\"", "\"", ",", "s", ")", ",", "extr", ".", "config", ".", "parser", ".", "name", "(", "\"", "\"", ",", "s", ")", ")", "\n", "}", "\n", "//if extr.isHighLinkDensity(s) || extr.isTableAndNoParaExist(s) || !extr.isNodescoreThresholdMet(node, s) {", "if", "extr", ".", "isHighLinkDensity", "(", "s", ")", "{", "extr", ".", "config", ".", "parser", ".", "removeNode", "(", "s", ")", "\n", "return", "\n", "}", "\n\n", "subParagraph", ":=", "s", ".", "Find", "(", "\"", "\"", ")", "\n", "subParagraph", ".", "Each", "(", "func", "(", "j", "int", ",", "e", "*", "goquery", ".", "Selection", ")", "{", "if", "len", "(", "e", ".", "Text", "(", ")", ")", "<", "25", "{", "extr", ".", "config", ".", "parser", ".", "removeNode", "(", "e", ")", "\n", "}", "\n", "}", ")", "\n\n", "subParagraph2", ":=", "s", ".", "Find", "(", "\"", "\"", ")", "\n", "if", "subParagraph2", ".", "Length", "(", ")", "==", "0", "&&", "tag", "!=", "\"", "\"", "{", "if", "extr", ".", "config", ".", "debug", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "extr", ".", "config", ".", "parser", ".", "removeNode", "(", "s", ")", "\n", "}", "else", "{", "if", "extr", ".", "config", ".", "debug", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}", "\n", "}", ")", "\n", "return", "node", "\n", "}" ]
//PostCleanup removes any divs that looks like non-content, clusters of links, or paras with no gusto
[ "PostCleanup", "removes", "any", "divs", "that", "looks", "like", "non", "-", "content", "clusters", "of", "links", "or", "paras", "with", "no", "gusto" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/extractor.go#L704-L744
2,004
advancedlogic/GoOse
stopwords.go
NewStopwords
func NewStopwords() StopWords { cachedStopWords := make(map[string]*set.Set) for lang, stopwords := range sw { lines := strings.Split(stopwords, "\n") cachedStopWords[lang] = set.New(set.ThreadSafe).(*set.Set) for _, line := range lines { if strings.HasPrefix(line, "#") { continue } line = strings.TrimSpace(line) cachedStopWords[lang].Add(line) } } return StopWords{ cachedStopWords: cachedStopWords, } }
go
func NewStopwords() StopWords { cachedStopWords := make(map[string]*set.Set) for lang, stopwords := range sw { lines := strings.Split(stopwords, "\n") cachedStopWords[lang] = set.New(set.ThreadSafe).(*set.Set) for _, line := range lines { if strings.HasPrefix(line, "#") { continue } line = strings.TrimSpace(line) cachedStopWords[lang].Add(line) } } return StopWords{ cachedStopWords: cachedStopWords, } }
[ "func", "NewStopwords", "(", ")", "StopWords", "{", "cachedStopWords", ":=", "make", "(", "map", "[", "string", "]", "*", "set", ".", "Set", ")", "\n", "for", "lang", ",", "stopwords", ":=", "range", "sw", "{", "lines", ":=", "strings", ".", "Split", "(", "stopwords", ",", "\"", "\\n", "\"", ")", "\n", "cachedStopWords", "[", "lang", "]", "=", "set", ".", "New", "(", "set", ".", "ThreadSafe", ")", ".", "(", "*", "set", ".", "Set", ")", "\n", "for", "_", ",", "line", ":=", "range", "lines", "{", "if", "strings", ".", "HasPrefix", "(", "line", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "line", "=", "strings", ".", "TrimSpace", "(", "line", ")", "\n", "cachedStopWords", "[", "lang", "]", ".", "Add", "(", "line", ")", "\n", "}", "\n", "}", "\n", "return", "StopWords", "{", "cachedStopWords", ":", "cachedStopWords", ",", "}", "\n", "}" ]
// NewStopwords returns an instance of a stop words detector
[ "NewStopwords", "returns", "an", "instance", "of", "a", "stop", "words", "detector" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/stopwords.go#L20-L36
2,005
advancedlogic/GoOse
stopwords.go
SimpleLanguageDetector
func (stop StopWords) SimpleLanguageDetector(text string) string { max := 0 currentLang := "en" for k := range sw { ws := stop.stopWordsCount(k, text) if ws.stopWordCount > max { max = ws.stopWordCount currentLang = k } } return currentLang }
go
func (stop StopWords) SimpleLanguageDetector(text string) string { max := 0 currentLang := "en" for k := range sw { ws := stop.stopWordsCount(k, text) if ws.stopWordCount > max { max = ws.stopWordCount currentLang = k } } return currentLang }
[ "func", "(", "stop", "StopWords", ")", "SimpleLanguageDetector", "(", "text", "string", ")", "string", "{", "max", ":=", "0", "\n", "currentLang", ":=", "\"", "\"", "\n\n", "for", "k", ":=", "range", "sw", "{", "ws", ":=", "stop", ".", "stopWordsCount", "(", "k", ",", "text", ")", "\n", "if", "ws", ".", "stopWordCount", ">", "max", "{", "max", "=", "ws", ".", "stopWordCount", "\n", "currentLang", "=", "k", "\n", "}", "\n", "}", "\n\n", "return", "currentLang", "\n", "}" ]
// SimpleLanguageDetector returns the language code for the text, based on its stop words
[ "SimpleLanguageDetector", "returns", "the", "language", "code", "for", "the", "text", "based", "on", "its", "stop", "words" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/stopwords.go#L96-L109
2,006
advancedlogic/GoOse
stopwords.go
ReadLinesOfFile
func ReadLinesOfFile(filename string) []string { content, err := ioutil.ReadFile(filename) if err != nil { log.Println(err.Error()) } lines := strings.Split(string(content), "\n") return lines }
go
func ReadLinesOfFile(filename string) []string { content, err := ioutil.ReadFile(filename) if err != nil { log.Println(err.Error()) } lines := strings.Split(string(content), "\n") return lines }
[ "func", "ReadLinesOfFile", "(", "filename", "string", ")", "[", "]", "string", "{", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Println", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "lines", ":=", "strings", ".", "Split", "(", "string", "(", "content", ")", ",", "\"", "\\n", "\"", ")", "\n", "return", "lines", "\n", "}" ]
// ReadLinesOfFile returns the lines from a file as a slice of strings
[ "ReadLinesOfFile", "returns", "the", "lines", "from", "a", "file", "as", "a", "slice", "of", "strings" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/stopwords.go#L112-L119
2,007
advancedlogic/GoOse
cleaner.go
Clean
func (c *Cleaner) Clean(docToClean *goquery.Document) *goquery.Document { if c.config.debug { log.Println("Starting cleaning phase with Cleaner") } docToClean = c.cleanBr(docToClean) docToClean = c.cleanArticleTags(docToClean) docToClean = c.cleanEMTags(docToClean) docToClean = c.dropCaps(docToClean) docToClean = c.removeScriptsStyle(docToClean) docToClean = c.cleanBadTags(docToClean, removeNodesRegEx, &[]string{"id", "class", "name"}) docToClean = c.cleanBadTags(docToClean, removeVisibilityStyleRegEx, &[]string{"style"}) docToClean = c.removeTags(docToClean, &[]string{"nav", "footer", "aside", "cite"}) docToClean = c.cleanParaSpans(docToClean) docToClean = c.convertDivsToParagraphs(docToClean, "div") docToClean = c.convertDivsToParagraphs(docToClean, "span") docToClean = c.convertDivsToParagraphs(docToClean, "article") docToClean = c.convertDivsToParagraphs(docToClean, "pre") return docToClean }
go
func (c *Cleaner) Clean(docToClean *goquery.Document) *goquery.Document { if c.config.debug { log.Println("Starting cleaning phase with Cleaner") } docToClean = c.cleanBr(docToClean) docToClean = c.cleanArticleTags(docToClean) docToClean = c.cleanEMTags(docToClean) docToClean = c.dropCaps(docToClean) docToClean = c.removeScriptsStyle(docToClean) docToClean = c.cleanBadTags(docToClean, removeNodesRegEx, &[]string{"id", "class", "name"}) docToClean = c.cleanBadTags(docToClean, removeVisibilityStyleRegEx, &[]string{"style"}) docToClean = c.removeTags(docToClean, &[]string{"nav", "footer", "aside", "cite"}) docToClean = c.cleanParaSpans(docToClean) docToClean = c.convertDivsToParagraphs(docToClean, "div") docToClean = c.convertDivsToParagraphs(docToClean, "span") docToClean = c.convertDivsToParagraphs(docToClean, "article") docToClean = c.convertDivsToParagraphs(docToClean, "pre") return docToClean }
[ "func", "(", "c", "*", "Cleaner", ")", "Clean", "(", "docToClean", "*", "goquery", ".", "Document", ")", "*", "goquery", ".", "Document", "{", "if", "c", ".", "config", ".", "debug", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "}", "\n", "docToClean", "=", "c", ".", "cleanBr", "(", "docToClean", ")", "\n", "docToClean", "=", "c", ".", "cleanArticleTags", "(", "docToClean", ")", "\n", "docToClean", "=", "c", ".", "cleanEMTags", "(", "docToClean", ")", "\n", "docToClean", "=", "c", ".", "dropCaps", "(", "docToClean", ")", "\n", "docToClean", "=", "c", ".", "removeScriptsStyle", "(", "docToClean", ")", "\n", "docToClean", "=", "c", ".", "cleanBadTags", "(", "docToClean", ",", "removeNodesRegEx", ",", "&", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ")", "\n", "docToClean", "=", "c", ".", "cleanBadTags", "(", "docToClean", ",", "removeVisibilityStyleRegEx", ",", "&", "[", "]", "string", "{", "\"", "\"", "}", ")", "\n", "docToClean", "=", "c", ".", "removeTags", "(", "docToClean", ",", "&", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ")", "\n", "docToClean", "=", "c", ".", "cleanParaSpans", "(", "docToClean", ")", "\n\n\n", "docToClean", "=", "c", ".", "convertDivsToParagraphs", "(", "docToClean", ",", "\"", "\"", ")", "\n\n", "docToClean", "=", "c", ".", "convertDivsToParagraphs", "(", "docToClean", ",", "\"", "\"", ")", "\n", "docToClean", "=", "c", ".", "convertDivsToParagraphs", "(", "docToClean", ",", "\"", "\"", ")", "\n", "docToClean", "=", "c", ".", "convertDivsToParagraphs", "(", "docToClean", ",", "\"", "\"", ")", "\n\n", "return", "docToClean", "\n", "}" ]
// Clean removes HTML elements around the main content and prepares the document for parsing
[ "Clean", "removes", "HTML", "elements", "around", "the", "main", "content", "and", "prepares", "the", "document", "for", "parsing" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/cleaner.go#L284-L306
2,008
advancedlogic/GoOse
videos.go
NewVideoExtractor
func NewVideoExtractor() VideoExtractor { return VideoExtractor{ candidates: set.New(set.ThreadSafe).(*set.Set), movies: set.New(set.ThreadSafe).(*set.Set), } }
go
func NewVideoExtractor() VideoExtractor { return VideoExtractor{ candidates: set.New(set.ThreadSafe).(*set.Set), movies: set.New(set.ThreadSafe).(*set.Set), } }
[ "func", "NewVideoExtractor", "(", ")", "VideoExtractor", "{", "return", "VideoExtractor", "{", "candidates", ":", "set", ".", "New", "(", "set", ".", "ThreadSafe", ")", ".", "(", "*", "set", ".", "Set", ")", ",", "movies", ":", "set", ".", "New", "(", "set", ".", "ThreadSafe", ")", ".", "(", "*", "set", ".", "Set", ")", ",", "}", "\n", "}" ]
// NewVideoExtractor returns a new instance of a HTML video extractor
[ "NewVideoExtractor", "returns", "a", "new", "instance", "of", "a", "HTML", "video", "extractor" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/videos.go#L29-L34
2,009
advancedlogic/GoOse
videos.go
GetVideos
func (ve *VideoExtractor) GetVideos(doc *goquery.Document) *set.Set { var nodes *goquery.Selection for _, videoTag := range videoTags { tmpNodes := doc.Find(videoTag) if nodes == nil { nodes = tmpNodes } else { nodes.Union(tmpNodes) } } nodes.Each(func(i int, node *goquery.Selection) { tag := node.Get(0).DataAtom.String() var movie video switch tag { case "video": movie = ve.getVideoTag(node) case "embed": movie = ve.getEmbedTag(node) case "object": movie = ve.getObjectTag(node) case "iframe": movie = ve.getIFrame(node) } if movie.src != "" { ve.movies.Add(movie) } }) return ve.movies }
go
func (ve *VideoExtractor) GetVideos(doc *goquery.Document) *set.Set { var nodes *goquery.Selection for _, videoTag := range videoTags { tmpNodes := doc.Find(videoTag) if nodes == nil { nodes = tmpNodes } else { nodes.Union(tmpNodes) } } nodes.Each(func(i int, node *goquery.Selection) { tag := node.Get(0).DataAtom.String() var movie video switch tag { case "video": movie = ve.getVideoTag(node) case "embed": movie = ve.getEmbedTag(node) case "object": movie = ve.getObjectTag(node) case "iframe": movie = ve.getIFrame(node) } if movie.src != "" { ve.movies.Add(movie) } }) return ve.movies }
[ "func", "(", "ve", "*", "VideoExtractor", ")", "GetVideos", "(", "doc", "*", "goquery", ".", "Document", ")", "*", "set", ".", "Set", "{", "var", "nodes", "*", "goquery", ".", "Selection", "\n", "for", "_", ",", "videoTag", ":=", "range", "videoTags", "{", "tmpNodes", ":=", "doc", ".", "Find", "(", "videoTag", ")", "\n", "if", "nodes", "==", "nil", "{", "nodes", "=", "tmpNodes", "\n", "}", "else", "{", "nodes", ".", "Union", "(", "tmpNodes", ")", "\n", "}", "\n", "}", "\n\n", "nodes", ".", "Each", "(", "func", "(", "i", "int", ",", "node", "*", "goquery", ".", "Selection", ")", "{", "tag", ":=", "node", ".", "Get", "(", "0", ")", ".", "DataAtom", ".", "String", "(", ")", "\n", "var", "movie", "video", "\n", "switch", "tag", "{", "case", "\"", "\"", ":", "movie", "=", "ve", ".", "getVideoTag", "(", "node", ")", "\n", "case", "\"", "\"", ":", "movie", "=", "ve", ".", "getEmbedTag", "(", "node", ")", "\n", "case", "\"", "\"", ":", "movie", "=", "ve", ".", "getObjectTag", "(", "node", ")", "\n", "case", "\"", "\"", ":", "movie", "=", "ve", ".", "getIFrame", "(", "node", ")", "\n", "}", "\n\n", "if", "movie", ".", "src", "!=", "\"", "\"", "{", "ve", ".", "movies", ".", "Add", "(", "movie", ")", "\n", "}", "\n", "}", ")", "\n\n", "return", "ve", ".", "movies", "\n", "}" ]
// GetVideos returns the video tags embedded in the article
[ "GetVideos", "returns", "the", "video", "tags", "embedded", "in", "the", "article" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/videos.go#L134-L165
2,010
advancedlogic/GoOse
images.go
WebPageImageResolver
func WebPageImageResolver(doc *goquery.Document) ([]candidate, int) { imgs := doc.Find("img") var candidates []candidate significantSurface := 320 * 200 significantSurfaceCount := 0 src := "" imgs.Each(func(i int, tag *goquery.Selection) { var surface int src = getImageSrc(tag) if src == "" { return } width, _ := tag.Attr("width") height, _ := tag.Attr("height") if width != "" { w, _ := strconv.Atoi(width) if height != "" { h, _ := strconv.Atoi(height) surface = w * h } else { surface = w } } else { if height != "" { surface, _ = strconv.Atoi(height) } else { surface = 0 } } if surface > significantSurface { significantSurfaceCount++ } tagscore := score(tag) if tagscore >= 0 { c := candidate{ url: src, surface: surface, score: score(tag), } candidates = append(candidates, c) } }) if len(candidates) == 0 { return nil, 0 } return candidates, significantSurfaceCount }
go
func WebPageImageResolver(doc *goquery.Document) ([]candidate, int) { imgs := doc.Find("img") var candidates []candidate significantSurface := 320 * 200 significantSurfaceCount := 0 src := "" imgs.Each(func(i int, tag *goquery.Selection) { var surface int src = getImageSrc(tag) if src == "" { return } width, _ := tag.Attr("width") height, _ := tag.Attr("height") if width != "" { w, _ := strconv.Atoi(width) if height != "" { h, _ := strconv.Atoi(height) surface = w * h } else { surface = w } } else { if height != "" { surface, _ = strconv.Atoi(height) } else { surface = 0 } } if surface > significantSurface { significantSurfaceCount++ } tagscore := score(tag) if tagscore >= 0 { c := candidate{ url: src, surface: surface, score: score(tag), } candidates = append(candidates, c) } }) if len(candidates) == 0 { return nil, 0 } return candidates, significantSurfaceCount }
[ "func", "WebPageImageResolver", "(", "doc", "*", "goquery", ".", "Document", ")", "(", "[", "]", "candidate", ",", "int", ")", "{", "imgs", ":=", "doc", ".", "Find", "(", "\"", "\"", ")", "\n\n", "var", "candidates", "[", "]", "candidate", "\n", "significantSurface", ":=", "320", "*", "200", "\n", "significantSurfaceCount", ":=", "0", "\n", "src", ":=", "\"", "\"", "\n", "imgs", ".", "Each", "(", "func", "(", "i", "int", ",", "tag", "*", "goquery", ".", "Selection", ")", "{", "var", "surface", "int", "\n", "src", "=", "getImageSrc", "(", "tag", ")", "\n", "if", "src", "==", "\"", "\"", "{", "return", "\n", "}", "\n\n", "width", ",", "_", ":=", "tag", ".", "Attr", "(", "\"", "\"", ")", "\n", "height", ",", "_", ":=", "tag", ".", "Attr", "(", "\"", "\"", ")", "\n", "if", "width", "!=", "\"", "\"", "{", "w", ",", "_", ":=", "strconv", ".", "Atoi", "(", "width", ")", "\n", "if", "height", "!=", "\"", "\"", "{", "h", ",", "_", ":=", "strconv", ".", "Atoi", "(", "height", ")", "\n", "surface", "=", "w", "*", "h", "\n", "}", "else", "{", "surface", "=", "w", "\n", "}", "\n", "}", "else", "{", "if", "height", "!=", "\"", "\"", "{", "surface", ",", "_", "=", "strconv", ".", "Atoi", "(", "height", ")", "\n", "}", "else", "{", "surface", "=", "0", "\n", "}", "\n", "}", "\n\n", "if", "surface", ">", "significantSurface", "{", "significantSurfaceCount", "++", "\n", "}", "\n\n", "tagscore", ":=", "score", "(", "tag", ")", "\n", "if", "tagscore", ">=", "0", "{", "c", ":=", "candidate", "{", "url", ":", "src", ",", "surface", ":", "surface", ",", "score", ":", "score", "(", "tag", ")", ",", "}", "\n", "candidates", "=", "append", "(", "candidates", ",", "c", ")", "\n", "}", "\n", "}", ")", "\n\n", "if", "len", "(", "candidates", ")", "==", "0", "{", "return", "nil", ",", "0", "\n", "}", "\n\n", "return", "candidates", ",", "significantSurfaceCount", "\n\n", "}" ]
// WebPageResolver fetches all candidate images from the HTML page
[ "WebPageResolver", "fetches", "all", "candidate", "images", "from", "the", "HTML", "page" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/images.go#L117-L170
2,011
advancedlogic/GoOse
images.go
WebPageResolver
func WebPageResolver(article *Article) string { candidates, significantSurfaceCount := WebPageImageResolver(article.Doc) if candidates == nil { return "" } var bestCandidate candidate var topImage string if significantSurfaceCount > 0 { bestCandidate = findBestCandidateFromSurface(candidates) } else { bestCandidate = findBestCandidateFromScore(candidates) } topImage = bestCandidate.url a, err := url.Parse(topImage) if err != nil { return topImage } finalURL, err := url.Parse(article.FinalURL) if err != nil { return topImage } b := finalURL.ResolveReference(a) topImage = b.String() return topImage }
go
func WebPageResolver(article *Article) string { candidates, significantSurfaceCount := WebPageImageResolver(article.Doc) if candidates == nil { return "" } var bestCandidate candidate var topImage string if significantSurfaceCount > 0 { bestCandidate = findBestCandidateFromSurface(candidates) } else { bestCandidate = findBestCandidateFromScore(candidates) } topImage = bestCandidate.url a, err := url.Parse(topImage) if err != nil { return topImage } finalURL, err := url.Parse(article.FinalURL) if err != nil { return topImage } b := finalURL.ResolveReference(a) topImage = b.String() return topImage }
[ "func", "WebPageResolver", "(", "article", "*", "Article", ")", "string", "{", "candidates", ",", "significantSurfaceCount", ":=", "WebPageImageResolver", "(", "article", ".", "Doc", ")", "\n", "if", "candidates", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "var", "bestCandidate", "candidate", "\n", "var", "topImage", "string", "\n", "if", "significantSurfaceCount", ">", "0", "{", "bestCandidate", "=", "findBestCandidateFromSurface", "(", "candidates", ")", "\n", "}", "else", "{", "bestCandidate", "=", "findBestCandidateFromScore", "(", "candidates", ")", "\n", "}", "\n\n", "topImage", "=", "bestCandidate", ".", "url", "\n", "a", ",", "err", ":=", "url", ".", "Parse", "(", "topImage", ")", "\n", "if", "err", "!=", "nil", "{", "return", "topImage", "\n", "}", "\n", "finalURL", ",", "err", ":=", "url", ".", "Parse", "(", "article", ".", "FinalURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "topImage", "\n", "}", "\n", "b", ":=", "finalURL", ".", "ResolveReference", "(", "a", ")", "\n", "topImage", "=", "b", ".", "String", "(", ")", "\n\n", "return", "topImage", "\n", "}" ]
// WebPageResolver fetches the main image from the HTML page
[ "WebPageResolver", "fetches", "the", "main", "image", "from", "the", "HTML", "page" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/images.go#L173-L199
2,012
advancedlogic/GoOse
images.go
OpenGraphResolver
func OpenGraphResolver(doc *goquery.Document) string { meta := doc.Find("meta") links := doc.Find("link") var topImage string meta = meta.Union(links) var ogImages []ogImage meta.Each(func(i int, tag *goquery.Selection) { for _, ogTag := range ogTags { attr, exist := tag.Attr(ogTag.attribute) value, vexist := tag.Attr(ogTag.value) if exist && attr == ogTag.name && vexist { ogImage := ogImage{ url: value, tpe: ogTag.tpe, score: 0, } ogImages = append(ogImages, ogImage) } } }) if len(ogImages) == 0 { return "" } if len(ogImages) == 1 { topImage = ogImages[0].url goto IMAGE_FINALIZE } for _, ogImage := range ogImages { if largebig.MatchString(ogImage.url) { ogImage.score++ } if ogImage.tpe == "twitter" { ogImage.score++ } } topImage = findBestImageFromScore(ogImages).url IMAGE_FINALIZE: if !strings.HasPrefix(topImage, "http") { topImage = "http://" + topImage } return topImage }
go
func OpenGraphResolver(doc *goquery.Document) string { meta := doc.Find("meta") links := doc.Find("link") var topImage string meta = meta.Union(links) var ogImages []ogImage meta.Each(func(i int, tag *goquery.Selection) { for _, ogTag := range ogTags { attr, exist := tag.Attr(ogTag.attribute) value, vexist := tag.Attr(ogTag.value) if exist && attr == ogTag.name && vexist { ogImage := ogImage{ url: value, tpe: ogTag.tpe, score: 0, } ogImages = append(ogImages, ogImage) } } }) if len(ogImages) == 0 { return "" } if len(ogImages) == 1 { topImage = ogImages[0].url goto IMAGE_FINALIZE } for _, ogImage := range ogImages { if largebig.MatchString(ogImage.url) { ogImage.score++ } if ogImage.tpe == "twitter" { ogImage.score++ } } topImage = findBestImageFromScore(ogImages).url IMAGE_FINALIZE: if !strings.HasPrefix(topImage, "http") { topImage = "http://" + topImage } return topImage }
[ "func", "OpenGraphResolver", "(", "doc", "*", "goquery", ".", "Document", ")", "string", "{", "meta", ":=", "doc", ".", "Find", "(", "\"", "\"", ")", "\n", "links", ":=", "doc", ".", "Find", "(", "\"", "\"", ")", "\n", "var", "topImage", "string", "\n", "meta", "=", "meta", ".", "Union", "(", "links", ")", "\n", "var", "ogImages", "[", "]", "ogImage", "\n", "meta", ".", "Each", "(", "func", "(", "i", "int", ",", "tag", "*", "goquery", ".", "Selection", ")", "{", "for", "_", ",", "ogTag", ":=", "range", "ogTags", "{", "attr", ",", "exist", ":=", "tag", ".", "Attr", "(", "ogTag", ".", "attribute", ")", "\n", "value", ",", "vexist", ":=", "tag", ".", "Attr", "(", "ogTag", ".", "value", ")", "\n", "if", "exist", "&&", "attr", "==", "ogTag", ".", "name", "&&", "vexist", "{", "ogImage", ":=", "ogImage", "{", "url", ":", "value", ",", "tpe", ":", "ogTag", ".", "tpe", ",", "score", ":", "0", ",", "}", "\n\n", "ogImages", "=", "append", "(", "ogImages", ",", "ogImage", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "if", "len", "(", "ogImages", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "ogImages", ")", "==", "1", "{", "topImage", "=", "ogImages", "[", "0", "]", ".", "url", "\n", "goto", "IMAGE_FINALIZE", "\n", "}", "\n", "for", "_", ",", "ogImage", ":=", "range", "ogImages", "{", "if", "largebig", ".", "MatchString", "(", "ogImage", ".", "url", ")", "{", "ogImage", ".", "score", "++", "\n", "}", "\n", "if", "ogImage", ".", "tpe", "==", "\"", "\"", "{", "ogImage", ".", "score", "++", "\n", "}", "\n", "}", "\n", "topImage", "=", "findBestImageFromScore", "(", "ogImages", ")", ".", "url", "\n", "IMAGE_FINALIZE", ":", "if", "!", "strings", ".", "HasPrefix", "(", "topImage", ",", "\"", "\"", ")", "{", "topImage", "=", "\"", "\"", "+", "topImage", "\n", "}", "\n\n", "return", "topImage", "\n", "}" ]
// OpenGraphResolver return OpenGraph properties
[ "OpenGraphResolver", "return", "OpenGraph", "properties" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/images.go#L270-L313
2,013
advancedlogic/GoOse
charset.go
UTF8encode
func UTF8encode(raw string, sourceCharset string) string { enc, name := charset.Lookup(sourceCharset) if nil == enc { log.Println("Cannot convert from", sourceCharset, ":", name) return raw } dst := make([]byte, len(raw)) d := enc.NewDecoder() var ( in int out int ) for in < len(raw) { // Do the transformation ndst, nsrc, err := d.Transform(dst[out:], []byte(raw[in:]), true) in += nsrc out += ndst if err == nil { // Completed transformation break } if err == transform.ErrShortDst { // Our output buffer is too small, so we need to grow it t := make([]byte, (cap(dst)+1)*2) copy(t, dst) dst = t continue } // We're here because of at least one illegal character. Skip over the current rune // and try again. _, width := utf8.DecodeRuneInString(raw[in:]) in += width } return string(dst) }
go
func UTF8encode(raw string, sourceCharset string) string { enc, name := charset.Lookup(sourceCharset) if nil == enc { log.Println("Cannot convert from", sourceCharset, ":", name) return raw } dst := make([]byte, len(raw)) d := enc.NewDecoder() var ( in int out int ) for in < len(raw) { // Do the transformation ndst, nsrc, err := d.Transform(dst[out:], []byte(raw[in:]), true) in += nsrc out += ndst if err == nil { // Completed transformation break } if err == transform.ErrShortDst { // Our output buffer is too small, so we need to grow it t := make([]byte, (cap(dst)+1)*2) copy(t, dst) dst = t continue } // We're here because of at least one illegal character. Skip over the current rune // and try again. _, width := utf8.DecodeRuneInString(raw[in:]) in += width } return string(dst) }
[ "func", "UTF8encode", "(", "raw", "string", ",", "sourceCharset", "string", ")", "string", "{", "enc", ",", "name", ":=", "charset", ".", "Lookup", "(", "sourceCharset", ")", "\n", "if", "nil", "==", "enc", "{", "log", ".", "Println", "(", "\"", "\"", ",", "sourceCharset", ",", "\"", "\"", ",", "name", ")", "\n", "return", "raw", "\n", "}", "\n\n", "dst", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "raw", ")", ")", "\n", "d", ":=", "enc", ".", "NewDecoder", "(", ")", "\n\n", "var", "(", "in", "int", "\n", "out", "int", "\n", ")", "\n", "for", "in", "<", "len", "(", "raw", ")", "{", "// Do the transformation", "ndst", ",", "nsrc", ",", "err", ":=", "d", ".", "Transform", "(", "dst", "[", "out", ":", "]", ",", "[", "]", "byte", "(", "raw", "[", "in", ":", "]", ")", ",", "true", ")", "\n", "in", "+=", "nsrc", "\n", "out", "+=", "ndst", "\n", "if", "err", "==", "nil", "{", "// Completed transformation", "break", "\n", "}", "\n", "if", "err", "==", "transform", ".", "ErrShortDst", "{", "// Our output buffer is too small, so we need to grow it", "t", ":=", "make", "(", "[", "]", "byte", ",", "(", "cap", "(", "dst", ")", "+", "1", ")", "*", "2", ")", "\n", "copy", "(", "t", ",", "dst", ")", "\n", "dst", "=", "t", "\n", "continue", "\n", "}", "\n", "// We're here because of at least one illegal character. Skip over the current rune", "// and try again.", "_", ",", "width", ":=", "utf8", ".", "DecodeRuneInString", "(", "raw", "[", "in", ":", "]", ")", "\n", "in", "+=", "width", "\n", "}", "\n", "return", "string", "(", "dst", ")", "\n", "}" ]
// UTF8encode converts a string from the source character set to UTF-8, skipping invalid byte sequences // @see http://stackoverflow.com/questions/32512500/ignore-illegal-bytes-when-decoding-text-with-go
[ "UTF8encode", "converts", "a", "string", "from", "the", "source", "character", "set", "to", "UTF", "-", "8", "skipping", "invalid", "byte", "sequences" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/charset.go#L56-L92
2,014
advancedlogic/GoOse
configuration.go
GetDefaultConfiguration
func GetDefaultConfiguration(args ...string) Configuration { if len(args) == 0 { return Configuration{ localStoragePath: "", //not used in this version imagesMinBytes: 4500, //not used in this version enableImageFetching: true, useMetaLanguage: true, targetLanguage: "en", imageMagickConvertPath: "/usr/bin/convert", //not used in this version imageMagickIdentifyPath: "/usr/bin/identify", //not used in this version browserUserAgent: defaultUserAgent, debug: false, extractPublishDate: true, additionalDataExtractor: false, stopWordsPath: "resources/stopwords", stopWords: NewStopwords(), //TODO with path parser: NewParser(), timeout: time.Duration(5 * time.Second), } } return Configuration{ localStoragePath: "", //not used in this version imagesMinBytes: 4500, //not used in this version enableImageFetching: true, useMetaLanguage: true, targetLanguage: "en", imageMagickConvertPath: "/usr/bin/convert", //not used in this version imageMagickIdentifyPath: "/usr/bin/identify", //not used in this version browserUserAgent: defaultUserAgent, debug: false, extractPublishDate: true, additionalDataExtractor: false, stopWordsPath: "resources/stopwords", stopWords: NewStopwords(), //TODO with path parser: NewParser(), timeout: time.Duration(5 * time.Second), } }
go
func GetDefaultConfiguration(args ...string) Configuration { if len(args) == 0 { return Configuration{ localStoragePath: "", //not used in this version imagesMinBytes: 4500, //not used in this version enableImageFetching: true, useMetaLanguage: true, targetLanguage: "en", imageMagickConvertPath: "/usr/bin/convert", //not used in this version imageMagickIdentifyPath: "/usr/bin/identify", //not used in this version browserUserAgent: defaultUserAgent, debug: false, extractPublishDate: true, additionalDataExtractor: false, stopWordsPath: "resources/stopwords", stopWords: NewStopwords(), //TODO with path parser: NewParser(), timeout: time.Duration(5 * time.Second), } } return Configuration{ localStoragePath: "", //not used in this version imagesMinBytes: 4500, //not used in this version enableImageFetching: true, useMetaLanguage: true, targetLanguage: "en", imageMagickConvertPath: "/usr/bin/convert", //not used in this version imageMagickIdentifyPath: "/usr/bin/identify", //not used in this version browserUserAgent: defaultUserAgent, debug: false, extractPublishDate: true, additionalDataExtractor: false, stopWordsPath: "resources/stopwords", stopWords: NewStopwords(), //TODO with path parser: NewParser(), timeout: time.Duration(5 * time.Second), } }
[ "func", "GetDefaultConfiguration", "(", "args", "...", "string", ")", "Configuration", "{", "if", "len", "(", "args", ")", "==", "0", "{", "return", "Configuration", "{", "localStoragePath", ":", "\"", "\"", ",", "//not used in this version", "imagesMinBytes", ":", "4500", ",", "//not used in this version", "enableImageFetching", ":", "true", ",", "useMetaLanguage", ":", "true", ",", "targetLanguage", ":", "\"", "\"", ",", "imageMagickConvertPath", ":", "\"", "\"", ",", "//not used in this version", "imageMagickIdentifyPath", ":", "\"", "\"", ",", "//not used in this version", "browserUserAgent", ":", "defaultUserAgent", ",", "debug", ":", "false", ",", "extractPublishDate", ":", "true", ",", "additionalDataExtractor", ":", "false", ",", "stopWordsPath", ":", "\"", "\"", ",", "stopWords", ":", "NewStopwords", "(", ")", ",", "//TODO with path", "parser", ":", "NewParser", "(", ")", ",", "timeout", ":", "time", ".", "Duration", "(", "5", "*", "time", ".", "Second", ")", ",", "}", "\n", "}", "\n", "return", "Configuration", "{", "localStoragePath", ":", "\"", "\"", ",", "//not used in this version", "imagesMinBytes", ":", "4500", ",", "//not used in this version", "enableImageFetching", ":", "true", ",", "useMetaLanguage", ":", "true", ",", "targetLanguage", ":", "\"", "\"", ",", "imageMagickConvertPath", ":", "\"", "\"", ",", "//not used in this version", "imageMagickIdentifyPath", ":", "\"", "\"", ",", "//not used in this version", "browserUserAgent", ":", "defaultUserAgent", ",", "debug", ":", "false", ",", "extractPublishDate", ":", "true", ",", "additionalDataExtractor", ":", "false", ",", "stopWordsPath", ":", "\"", "\"", ",", "stopWords", ":", "NewStopwords", "(", ")", ",", "//TODO with path", "parser", ":", "NewParser", "(", ")", ",", "timeout", ":", "time", ".", "Duration", "(", "5", "*", "time", ".", "Second", ")", ",", "}", "\n", "}" ]
// GetDefaultConfiguration returns safe default configuration options
[ "GetDefaultConfiguration", "returns", "safe", "default", "configuration", "options" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/configuration.go#L32-L69
2,015
advancedlogic/GoOse
goose.go
ExtractFromURL
func (g Goose) ExtractFromURL(url string) (*Article, error) { cc := NewCrawler(g.config, url, "") return cc.Crawl() }
go
func (g Goose) ExtractFromURL(url string) (*Article, error) { cc := NewCrawler(g.config, url, "") return cc.Crawl() }
[ "func", "(", "g", "Goose", ")", "ExtractFromURL", "(", "url", "string", ")", "(", "*", "Article", ",", "error", ")", "{", "cc", ":=", "NewCrawler", "(", "g", ".", "config", ",", "url", ",", "\"", "\"", ")", "\n", "return", "cc", ".", "Crawl", "(", ")", "\n", "}" ]
// ExtractFromURL follows the URL, fetches the HTML page and returns an article object
[ "ExtractFromURL", "follows", "the", "URL", "fetches", "the", "HTML", "page", "and", "returns", "an", "article", "object" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/goose.go#L16-L19
2,016
advancedlogic/GoOse
goose.go
ExtractFromRawHTML
func (g Goose) ExtractFromRawHTML(url string, RawHTML string) (*Article, error) { cc := NewCrawler(g.config, url, RawHTML) return cc.Crawl() }
go
func (g Goose) ExtractFromRawHTML(url string, RawHTML string) (*Article, error) { cc := NewCrawler(g.config, url, RawHTML) return cc.Crawl() }
[ "func", "(", "g", "Goose", ")", "ExtractFromRawHTML", "(", "url", "string", ",", "RawHTML", "string", ")", "(", "*", "Article", ",", "error", ")", "{", "cc", ":=", "NewCrawler", "(", "g", ".", "config", ",", "url", ",", "RawHTML", ")", "\n", "return", "cc", ".", "Crawl", "(", ")", "\n", "}" ]
// ExtractFromRawHTML returns an article object from the raw HTML content
[ "ExtractFromRawHTML", "returns", "an", "article", "object", "from", "the", "raw", "HTML", "content" ]
6cd46faf50eb2105cd5de7328ee8eb62557895c9
https://github.com/advancedlogic/GoOse/blob/6cd46faf50eb2105cd5de7328ee8eb62557895c9/goose.go#L22-L25
2,017
bmatcuk/doublestar
doublestar.go
splitPathOnSeparator
func splitPathOnSeparator(path string, separator rune) []string { // if the separator is '\\', then we can just split... if separator == '\\' { return strings.Split(path, string(separator)) } // otherwise, we need to be careful of situations where the separator was escaped cnt := strings.Count(path, string(separator)) if cnt == 0 { return []string{path} } ret := make([]string, cnt+1) pathlen := len(path) separatorLen := utf8.RuneLen(separator) idx := 0 for start := 0; start < pathlen; { end := indexRuneWithEscaping(path[start:], separator) if end == -1 { end = pathlen } else { end += start } ret[idx] = path[start:end] start = end + separatorLen idx++ } return ret[:idx] }
go
func splitPathOnSeparator(path string, separator rune) []string { // if the separator is '\\', then we can just split... if separator == '\\' { return strings.Split(path, string(separator)) } // otherwise, we need to be careful of situations where the separator was escaped cnt := strings.Count(path, string(separator)) if cnt == 0 { return []string{path} } ret := make([]string, cnt+1) pathlen := len(path) separatorLen := utf8.RuneLen(separator) idx := 0 for start := 0; start < pathlen; { end := indexRuneWithEscaping(path[start:], separator) if end == -1 { end = pathlen } else { end += start } ret[idx] = path[start:end] start = end + separatorLen idx++ } return ret[:idx] }
[ "func", "splitPathOnSeparator", "(", "path", "string", ",", "separator", "rune", ")", "[", "]", "string", "{", "// if the separator is '\\\\', then we can just split...", "if", "separator", "==", "'\\\\'", "{", "return", "strings", ".", "Split", "(", "path", ",", "string", "(", "separator", ")", ")", "\n", "}", "\n\n", "// otherwise, we need to be careful of situations where the separator was escaped", "cnt", ":=", "strings", ".", "Count", "(", "path", ",", "string", "(", "separator", ")", ")", "\n", "if", "cnt", "==", "0", "{", "return", "[", "]", "string", "{", "path", "}", "\n", "}", "\n", "ret", ":=", "make", "(", "[", "]", "string", ",", "cnt", "+", "1", ")", "\n", "pathlen", ":=", "len", "(", "path", ")", "\n", "separatorLen", ":=", "utf8", ".", "RuneLen", "(", "separator", ")", "\n", "idx", ":=", "0", "\n", "for", "start", ":=", "0", ";", "start", "<", "pathlen", ";", "{", "end", ":=", "indexRuneWithEscaping", "(", "path", "[", "start", ":", "]", ",", "separator", ")", "\n", "if", "end", "==", "-", "1", "{", "end", "=", "pathlen", "\n", "}", "else", "{", "end", "+=", "start", "\n", "}", "\n", "ret", "[", "idx", "]", "=", "path", "[", "start", ":", "end", "]", "\n", "start", "=", "end", "+", "separatorLen", "\n", "idx", "++", "\n", "}", "\n", "return", "ret", "[", ":", "idx", "]", "\n", "}" ]
// Split a path on the given separator, respecting escaping.
[ "Split", "a", "path", "on", "the", "given", "separator", "respecting", "escaping", "." ]
85a78806aa1b4707d1dbace9be592cf1ece91ab3
https://github.com/bmatcuk/doublestar/blob/85a78806aa1b4707d1dbace9be592cf1ece91ab3/doublestar.go#L15-L42
2,018
bmatcuk/doublestar
doublestar.go
indexRuneWithEscaping
func indexRuneWithEscaping(s string, r rune) int { end := strings.IndexRune(s, r) if end == -1 { return -1 } if end > 0 && s[end-1] == '\\' { start := end + utf8.RuneLen(r) end = indexRuneWithEscaping(s[start:], r) if end != -1 { end += start } } return end }
go
func indexRuneWithEscaping(s string, r rune) int { end := strings.IndexRune(s, r) if end == -1 { return -1 } if end > 0 && s[end-1] == '\\' { start := end + utf8.RuneLen(r) end = indexRuneWithEscaping(s[start:], r) if end != -1 { end += start } } return end }
[ "func", "indexRuneWithEscaping", "(", "s", "string", ",", "r", "rune", ")", "int", "{", "end", ":=", "strings", ".", "IndexRune", "(", "s", ",", "r", ")", "\n", "if", "end", "==", "-", "1", "{", "return", "-", "1", "\n", "}", "\n", "if", "end", ">", "0", "&&", "s", "[", "end", "-", "1", "]", "==", "'\\\\'", "{", "start", ":=", "end", "+", "utf8", ".", "RuneLen", "(", "r", ")", "\n", "end", "=", "indexRuneWithEscaping", "(", "s", "[", "start", ":", "]", ",", "r", ")", "\n", "if", "end", "!=", "-", "1", "{", "end", "+=", "start", "\n", "}", "\n", "}", "\n", "return", "end", "\n", "}" ]
// Find the first index of a rune in a string, // ignoring any times the rune is escaped using "\".
[ "Find", "the", "first", "index", "of", "a", "rune", "in", "a", "string", "ignoring", "any", "times", "the", "rune", "is", "escaped", "using", "\\", "." ]
85a78806aa1b4707d1dbace9be592cf1ece91ab3
https://github.com/bmatcuk/doublestar/blob/85a78806aa1b4707d1dbace9be592cf1ece91ab3/doublestar.go#L46-L59
2,019
hashicorp/scada-client
client.go
Dial
func Dial(addr string) (*Client, error) { opts := Opts{Addr: addr, TLS: false} return DialOpts(&opts) }
go
func Dial(addr string) (*Client, error) { opts := Opts{Addr: addr, TLS: false} return DialOpts(&opts) }
[ "func", "Dial", "(", "addr", "string", ")", "(", "*", "Client", ",", "error", ")", "{", "opts", ":=", "Opts", "{", "Addr", ":", "addr", ",", "TLS", ":", "false", "}", "\n", "return", "DialOpts", "(", "&", "opts", ")", "\n", "}" ]
// Dial is used to establish a new connection over TCP
[ "Dial", "is", "used", "to", "establish", "a", "new", "connection", "over", "TCP" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/client.go#L51-L54
2,020
hashicorp/scada-client
client.go
DialOpts
func DialOpts(opts *Opts) (*Client, error) { var conn net.Conn var err error if opts.TLS { conn, err = tls.Dial("tcp", opts.Addr, opts.TLSConfig) } else { conn, err = net.DialTimeout("tcp", opts.Addr, 10*time.Second) } if err != nil { return nil, err } return initClient(conn, opts) }
go
func DialOpts(opts *Opts) (*Client, error) { var conn net.Conn var err error if opts.TLS { conn, err = tls.Dial("tcp", opts.Addr, opts.TLSConfig) } else { conn, err = net.DialTimeout("tcp", opts.Addr, 10*time.Second) } if err != nil { return nil, err } return initClient(conn, opts) }
[ "func", "DialOpts", "(", "opts", "*", "Opts", ")", "(", "*", "Client", ",", "error", ")", "{", "var", "conn", "net", ".", "Conn", "\n", "var", "err", "error", "\n", "if", "opts", ".", "TLS", "{", "conn", ",", "err", "=", "tls", ".", "Dial", "(", "\"", "\"", ",", "opts", ".", "Addr", ",", "opts", ".", "TLSConfig", ")", "\n", "}", "else", "{", "conn", ",", "err", "=", "net", ".", "DialTimeout", "(", "\"", "\"", ",", "opts", ".", "Addr", ",", "10", "*", "time", ".", "Second", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "initClient", "(", "conn", ",", "opts", ")", "\n", "}" ]
// DialOpts is a parameterized Dial
[ "DialOpts", "is", "a", "parameterized", "Dial" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/client.go#L63-L75
2,021
hashicorp/scada-client
client.go
initClient
func initClient(conn net.Conn, opts *Opts) (*Client, error) { // Send the preamble _, err := conn.Write([]byte(clientPreamble)) if err != nil { return nil, fmt.Errorf("preamble write failed: %v", err) } // Wrap the connection in yamux for multiplexing ymConf := yamux.DefaultConfig() if opts.LogOutput != nil { ymConf.LogOutput = opts.LogOutput } client, _ := yamux.Client(conn, ymConf) // Create the client c := &Client{ conn: conn, client: client, } return c, nil }
go
func initClient(conn net.Conn, opts *Opts) (*Client, error) { // Send the preamble _, err := conn.Write([]byte(clientPreamble)) if err != nil { return nil, fmt.Errorf("preamble write failed: %v", err) } // Wrap the connection in yamux for multiplexing ymConf := yamux.DefaultConfig() if opts.LogOutput != nil { ymConf.LogOutput = opts.LogOutput } client, _ := yamux.Client(conn, ymConf) // Create the client c := &Client{ conn: conn, client: client, } return c, nil }
[ "func", "initClient", "(", "conn", "net", ".", "Conn", ",", "opts", "*", "Opts", ")", "(", "*", "Client", ",", "error", ")", "{", "// Send the preamble", "_", ",", "err", ":=", "conn", ".", "Write", "(", "[", "]", "byte", "(", "clientPreamble", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Wrap the connection in yamux for multiplexing", "ymConf", ":=", "yamux", ".", "DefaultConfig", "(", ")", "\n", "if", "opts", ".", "LogOutput", "!=", "nil", "{", "ymConf", ".", "LogOutput", "=", "opts", ".", "LogOutput", "\n", "}", "\n", "client", ",", "_", ":=", "yamux", ".", "Client", "(", "conn", ",", "ymConf", ")", "\n\n", "// Create the client", "c", ":=", "&", "Client", "{", "conn", ":", "conn", ",", "client", ":", "client", ",", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// initClient does the common initialization
[ "initClient", "does", "the", "common", "initialization" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/client.go#L78-L98
2,022
hashicorp/scada-client
client.go
Close
func (c *Client) Close() error { c.closedLock.Lock() defer c.closedLock.Unlock() if c.closed { return nil } c.closed = true c.client.GoAway() // Notify the other side of the close return c.client.Close() }
go
func (c *Client) Close() error { c.closedLock.Lock() defer c.closedLock.Unlock() if c.closed { return nil } c.closed = true c.client.GoAway() // Notify the other side of the close return c.client.Close() }
[ "func", "(", "c", "*", "Client", ")", "Close", "(", ")", "error", "{", "c", ".", "closedLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "closedLock", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "closed", "{", "return", "nil", "\n", "}", "\n", "c", ".", "closed", "=", "true", "\n", "c", ".", "client", ".", "GoAway", "(", ")", "// Notify the other side of the close", "\n", "return", "c", ".", "client", ".", "Close", "(", ")", "\n", "}" ]
// Close is used to terminate the client connection
[ "Close", "is", "used", "to", "terminate", "the", "client", "connection" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/client.go#L101-L111
2,023
hashicorp/scada-client
client.go
RPC
func (c *Client) RPC(method string, args interface{}, resp interface{}) error { // Get a stream stream, err := c.Open() if err != nil { return fmt.Errorf("failed to open stream: %v", err) } defer stream.Close() stream.SetDeadline(time.Now().Add(rpcTimeout)) // Create the RPC client cc := msgpackrpc.NewCodec(true, true, stream) return msgpackrpc.CallWithCodec(cc, method, args, resp) }
go
func (c *Client) RPC(method string, args interface{}, resp interface{}) error { // Get a stream stream, err := c.Open() if err != nil { return fmt.Errorf("failed to open stream: %v", err) } defer stream.Close() stream.SetDeadline(time.Now().Add(rpcTimeout)) // Create the RPC client cc := msgpackrpc.NewCodec(true, true, stream) return msgpackrpc.CallWithCodec(cc, method, args, resp) }
[ "func", "(", "c", "*", "Client", ")", "RPC", "(", "method", "string", ",", "args", "interface", "{", "}", ",", "resp", "interface", "{", "}", ")", "error", "{", "// Get a stream", "stream", ",", "err", ":=", "c", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "stream", ".", "Close", "(", ")", "\n", "stream", ".", "SetDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "rpcTimeout", ")", ")", "\n\n", "// Create the RPC client", "cc", ":=", "msgpackrpc", ".", "NewCodec", "(", "true", ",", "true", ",", "stream", ")", "\n", "return", "msgpackrpc", ".", "CallWithCodec", "(", "cc", ",", "method", ",", "args", ",", "resp", ")", "\n", "}" ]
// RPC is used to perform an RPC
[ "RPC", "is", "used", "to", "perform", "an", "RPC" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/client.go#L114-L126
2,024
hashicorp/scada-client
scada/scada.go
providerService
func providerService(c *Config) *sc.ProviderService { ret := &sc.ProviderService{ Service: c.Service, ServiceVersion: c.Version, Capabilities: map[string]int{}, Meta: c.Meta, ResourceType: c.ResourceType, } return ret }
go
func providerService(c *Config) *sc.ProviderService { ret := &sc.ProviderService{ Service: c.Service, ServiceVersion: c.Version, Capabilities: map[string]int{}, Meta: c.Meta, ResourceType: c.ResourceType, } return ret }
[ "func", "providerService", "(", "c", "*", "Config", ")", "*", "sc", ".", "ProviderService", "{", "ret", ":=", "&", "sc", ".", "ProviderService", "{", "Service", ":", "c", ".", "Service", ",", "ServiceVersion", ":", "c", ".", "Version", ",", "Capabilities", ":", "map", "[", "string", "]", "int", "{", "}", ",", "Meta", ":", "c", ".", "Meta", ",", "ResourceType", ":", "c", ".", "ResourceType", ",", "}", "\n\n", "return", "ret", "\n", "}" ]
// ProviderService returns the service information for the provider
[ "ProviderService", "returns", "the", "service", "information", "for", "the", "provider" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/scada/scada.go#L59-L69
2,025
hashicorp/scada-client
scada/scada.go
providerConfig
func providerConfig(c *Config) *sc.ProviderConfig { ret := &sc.ProviderConfig{ Service: providerService(c), Handlers: map[string]sc.CapabilityProvider{}, Endpoint: c.Atlas.Endpoint, ResourceGroup: c.Atlas.Infrastructure, Token: c.Atlas.Token, } // SCADA_INSECURE env variable is used for testing to disable TLS // certificate verification. insecure := c.Insecure if !insecure { if os.Getenv("SCADA_INSECURE") != "" { insecure = true } } if insecure { ret.TLSConfig = &tls.Config{ InsecureSkipVerify: true, } } return ret }
go
func providerConfig(c *Config) *sc.ProviderConfig { ret := &sc.ProviderConfig{ Service: providerService(c), Handlers: map[string]sc.CapabilityProvider{}, Endpoint: c.Atlas.Endpoint, ResourceGroup: c.Atlas.Infrastructure, Token: c.Atlas.Token, } // SCADA_INSECURE env variable is used for testing to disable TLS // certificate verification. insecure := c.Insecure if !insecure { if os.Getenv("SCADA_INSECURE") != "" { insecure = true } } if insecure { ret.TLSConfig = &tls.Config{ InsecureSkipVerify: true, } } return ret }
[ "func", "providerConfig", "(", "c", "*", "Config", ")", "*", "sc", ".", "ProviderConfig", "{", "ret", ":=", "&", "sc", ".", "ProviderConfig", "{", "Service", ":", "providerService", "(", "c", ")", ",", "Handlers", ":", "map", "[", "string", "]", "sc", ".", "CapabilityProvider", "{", "}", ",", "Endpoint", ":", "c", ".", "Atlas", ".", "Endpoint", ",", "ResourceGroup", ":", "c", ".", "Atlas", ".", "Infrastructure", ",", "Token", ":", "c", ".", "Atlas", ".", "Token", ",", "}", "\n\n", "// SCADA_INSECURE env variable is used for testing to disable TLS", "// certificate verification.", "insecure", ":=", "c", ".", "Insecure", "\n", "if", "!", "insecure", "{", "if", "os", ".", "Getenv", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "insecure", "=", "true", "\n", "}", "\n", "}", "\n", "if", "insecure", "{", "ret", ".", "TLSConfig", "=", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "true", ",", "}", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// providerConfig returns the configuration for the SCADA provider
[ "providerConfig", "returns", "the", "configuration", "for", "the", "SCADA", "provider" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/scada/scada.go#L72-L96
2,026
hashicorp/scada-client
scada/scada.go
NewHTTPProvider
func NewHTTPProvider(c *Config, logOutput io.Writer) (*Provider, net.Listener, error) { // Get the configuration of the provider config := providerConfig(c) config.LogOutput = logOutput // Set the HTTP capability config.Service.Capabilities["http"] = 1 // Create an HTTP listener and handler list := newScadaListener(c.Atlas.Infrastructure) config.Handlers["http"] = func(capability string, meta map[string]string, conn io.ReadWriteCloser) error { return list.PushRWC(conn) } // Create the provider provider, err := sc.NewProvider(config) if err != nil { list.Close() return nil, nil, err } return &Provider{provider}, list, nil }
go
func NewHTTPProvider(c *Config, logOutput io.Writer) (*Provider, net.Listener, error) { // Get the configuration of the provider config := providerConfig(c) config.LogOutput = logOutput // Set the HTTP capability config.Service.Capabilities["http"] = 1 // Create an HTTP listener and handler list := newScadaListener(c.Atlas.Infrastructure) config.Handlers["http"] = func(capability string, meta map[string]string, conn io.ReadWriteCloser) error { return list.PushRWC(conn) } // Create the provider provider, err := sc.NewProvider(config) if err != nil { list.Close() return nil, nil, err } return &Provider{provider}, list, nil }
[ "func", "NewHTTPProvider", "(", "c", "*", "Config", ",", "logOutput", "io", ".", "Writer", ")", "(", "*", "Provider", ",", "net", ".", "Listener", ",", "error", ")", "{", "// Get the configuration of the provider", "config", ":=", "providerConfig", "(", "c", ")", "\n", "config", ".", "LogOutput", "=", "logOutput", "\n\n", "// Set the HTTP capability", "config", ".", "Service", ".", "Capabilities", "[", "\"", "\"", "]", "=", "1", "\n\n", "// Create an HTTP listener and handler", "list", ":=", "newScadaListener", "(", "c", ".", "Atlas", ".", "Infrastructure", ")", "\n", "config", ".", "Handlers", "[", "\"", "\"", "]", "=", "func", "(", "capability", "string", ",", "meta", "map", "[", "string", "]", "string", ",", "conn", "io", ".", "ReadWriteCloser", ")", "error", "{", "return", "list", ".", "PushRWC", "(", "conn", ")", "\n", "}", "\n\n", "// Create the provider", "provider", ",", "err", ":=", "sc", ".", "NewProvider", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "list", ".", "Close", "(", ")", "\n", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "Provider", "{", "provider", "}", ",", "list", ",", "nil", "\n", "}" ]
// NewProvider creates a new SCADA provider using the given configuration. // Requests for the HTTP capability are passed off to the listener that is // returned.
[ "NewProvider", "creates", "a", "new", "SCADA", "provider", "using", "the", "given", "configuration", ".", "Requests", "for", "the", "HTTP", "capability", "are", "passed", "off", "to", "the", "listener", "that", "is", "returned", "." ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/scada/scada.go#L101-L124
2,027
hashicorp/scada-client
scada/scada.go
newScadaListener
func newScadaListener(infra string) *scadaListener { l := &scadaListener{ addr: &scadaAddr{infra}, pending: make(chan net.Conn), closedCh: make(chan struct{}), } return l }
go
func newScadaListener(infra string) *scadaListener { l := &scadaListener{ addr: &scadaAddr{infra}, pending: make(chan net.Conn), closedCh: make(chan struct{}), } return l }
[ "func", "newScadaListener", "(", "infra", "string", ")", "*", "scadaListener", "{", "l", ":=", "&", "scadaListener", "{", "addr", ":", "&", "scadaAddr", "{", "infra", "}", ",", "pending", ":", "make", "(", "chan", "net", ".", "Conn", ")", ",", "closedCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "return", "l", "\n", "}" ]
// newScadaListener returns a new listener
[ "newScadaListener", "returns", "a", "new", "listener" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/scada/scada.go#L138-L145
2,028
hashicorp/scada-client
scada/scada.go
PushRWC
func (s *scadaListener) PushRWC(conn io.ReadWriteCloser) error { // Check if this already implements net.Conn if nc, ok := conn.(net.Conn); ok { return s.Push(nc) } // Wrap to implement the interface wrapped := &scadaRWC{conn, s.addr} return s.Push(wrapped) }
go
func (s *scadaListener) PushRWC(conn io.ReadWriteCloser) error { // Check if this already implements net.Conn if nc, ok := conn.(net.Conn); ok { return s.Push(nc) } // Wrap to implement the interface wrapped := &scadaRWC{conn, s.addr} return s.Push(wrapped) }
[ "func", "(", "s", "*", "scadaListener", ")", "PushRWC", "(", "conn", "io", ".", "ReadWriteCloser", ")", "error", "{", "// Check if this already implements net.Conn", "if", "nc", ",", "ok", ":=", "conn", ".", "(", "net", ".", "Conn", ")", ";", "ok", "{", "return", "s", ".", "Push", "(", "nc", ")", "\n", "}", "\n\n", "// Wrap to implement the interface", "wrapped", ":=", "&", "scadaRWC", "{", "conn", ",", "s", ".", "addr", "}", "\n", "return", "s", ".", "Push", "(", "wrapped", ")", "\n", "}" ]
// PushRWC is used to push a io.ReadWriteCloser as a net.Conn
[ "PushRWC", "is", "used", "to", "push", "a", "io", ".", "ReadWriteCloser", "as", "a", "net", ".", "Conn" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/scada/scada.go#L148-L157
2,029
hashicorp/scada-client
scada/scada.go
Push
func (s *scadaListener) Push(conn net.Conn) error { select { case s.pending <- conn: return nil case <-time.After(time.Second): return fmt.Errorf("accept timed out") case <-s.closedCh: return fmt.Errorf("scada listener closed") } }
go
func (s *scadaListener) Push(conn net.Conn) error { select { case s.pending <- conn: return nil case <-time.After(time.Second): return fmt.Errorf("accept timed out") case <-s.closedCh: return fmt.Errorf("scada listener closed") } }
[ "func", "(", "s", "*", "scadaListener", ")", "Push", "(", "conn", "net", ".", "Conn", ")", "error", "{", "select", "{", "case", "s", ".", "pending", "<-", "conn", ":", "return", "nil", "\n", "case", "<-", "time", ".", "After", "(", "time", ".", "Second", ")", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "<-", "s", ".", "closedCh", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Push is used to add a connection to the queu
[ "Push", "is", "used", "to", "add", "a", "connection", "to", "the", "queu" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/scada/scada.go#L160-L169
2,030
hashicorp/scada-client
provider.go
validateConfig
func validateConfig(config *ProviderConfig) error { // Validate the inputs if config == nil { return fmt.Errorf("missing config") } if config.Service == nil { return fmt.Errorf("missing service") } if config.Service.Service == "" { return fmt.Errorf("missing service name") } if config.Service.ServiceVersion == "" { return fmt.Errorf("missing service version") } if config.Service.ResourceType == "" { return fmt.Errorf("missing service resource type") } if config.Handlers == nil && len(config.Service.Capabilities) != 0 { return fmt.Errorf("missing handlers") } for c := range config.Service.Capabilities { if _, ok := config.Handlers[c]; !ok { return fmt.Errorf("missing handler for '%s' capability", c) } } if config.ResourceGroup == "" { return fmt.Errorf("missing resource group") } if config.Token == "" { config.Token = os.Getenv("ATLAS_TOKEN") } if config.Token == "" { return fmt.Errorf("missing token") } // Default the endpoint if config.Endpoint == "" { config.Endpoint = DefaultEndpoint if end := os.Getenv("SCADA_ENDPOINT"); end != "" { config.Endpoint = end } } return nil }
go
func validateConfig(config *ProviderConfig) error { // Validate the inputs if config == nil { return fmt.Errorf("missing config") } if config.Service == nil { return fmt.Errorf("missing service") } if config.Service.Service == "" { return fmt.Errorf("missing service name") } if config.Service.ServiceVersion == "" { return fmt.Errorf("missing service version") } if config.Service.ResourceType == "" { return fmt.Errorf("missing service resource type") } if config.Handlers == nil && len(config.Service.Capabilities) != 0 { return fmt.Errorf("missing handlers") } for c := range config.Service.Capabilities { if _, ok := config.Handlers[c]; !ok { return fmt.Errorf("missing handler for '%s' capability", c) } } if config.ResourceGroup == "" { return fmt.Errorf("missing resource group") } if config.Token == "" { config.Token = os.Getenv("ATLAS_TOKEN") } if config.Token == "" { return fmt.Errorf("missing token") } // Default the endpoint if config.Endpoint == "" { config.Endpoint = DefaultEndpoint if end := os.Getenv("SCADA_ENDPOINT"); end != "" { config.Endpoint = end } } return nil }
[ "func", "validateConfig", "(", "config", "*", "ProviderConfig", ")", "error", "{", "// Validate the inputs", "if", "config", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Service", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Service", ".", "Service", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Service", ".", "ServiceVersion", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Service", ".", "ResourceType", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Handlers", "==", "nil", "&&", "len", "(", "config", ".", "Service", ".", "Capabilities", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "c", ":=", "range", "config", ".", "Service", ".", "Capabilities", "{", "if", "_", ",", "ok", ":=", "config", ".", "Handlers", "[", "c", "]", ";", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ")", "\n", "}", "\n", "}", "\n", "if", "config", ".", "ResourceGroup", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Token", "==", "\"", "\"", "{", "config", ".", "Token", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Token", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Default the endpoint", "if", "config", ".", "Endpoint", "==", "\"", "\"", "{", "config", ".", "Endpoint", "=", "DefaultEndpoint", "\n", "if", "end", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "end", "!=", "\"", "\"", "{", "config", ".", "Endpoint", "=", "end", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateConfig is used to sanity check the configuration
[ "validateConfig", "is", "used", "to", "sanity", "check", "the", "configuration" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L96-L139
2,031
hashicorp/scada-client
provider.go
NewProvider
func NewProvider(config *ProviderConfig) (*Provider, error) { if err := validateConfig(config); err != nil { return nil, err } // Create logger if config.LogOutput == nil { config.LogOutput = os.Stderr } logger := log.New(config.LogOutput, "", log.LstdFlags) p := &Provider{ config: config, logger: logger, shutdownCh: make(chan struct{}), } go p.run() return p, nil }
go
func NewProvider(config *ProviderConfig) (*Provider, error) { if err := validateConfig(config); err != nil { return nil, err } // Create logger if config.LogOutput == nil { config.LogOutput = os.Stderr } logger := log.New(config.LogOutput, "", log.LstdFlags) p := &Provider{ config: config, logger: logger, shutdownCh: make(chan struct{}), } go p.run() return p, nil }
[ "func", "NewProvider", "(", "config", "*", "ProviderConfig", ")", "(", "*", "Provider", ",", "error", ")", "{", "if", "err", ":=", "validateConfig", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create logger", "if", "config", ".", "LogOutput", "==", "nil", "{", "config", ".", "LogOutput", "=", "os", ".", "Stderr", "\n", "}", "\n", "logger", ":=", "log", ".", "New", "(", "config", ".", "LogOutput", ",", "\"", "\"", ",", "log", ".", "LstdFlags", ")", "\n\n", "p", ":=", "&", "Provider", "{", "config", ":", "config", ",", "logger", ":", "logger", ",", "shutdownCh", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "go", "p", ".", "run", "(", ")", "\n", "return", "p", ",", "nil", "\n", "}" ]
// NewProvider is used to create a new provider
[ "NewProvider", "is", "used", "to", "create", "a", "new", "provider" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L142-L160
2,032
hashicorp/scada-client
provider.go
Shutdown
func (p *Provider) Shutdown() { p.shutdownLock.Lock() p.shutdownLock.Unlock() if p.shutdown { return } p.shutdown = true close(p.shutdownCh) }
go
func (p *Provider) Shutdown() { p.shutdownLock.Lock() p.shutdownLock.Unlock() if p.shutdown { return } p.shutdown = true close(p.shutdownCh) }
[ "func", "(", "p", "*", "Provider", ")", "Shutdown", "(", ")", "{", "p", ".", "shutdownLock", ".", "Lock", "(", ")", "\n", "p", ".", "shutdownLock", ".", "Unlock", "(", ")", "\n", "if", "p", ".", "shutdown", "{", "return", "\n", "}", "\n", "p", ".", "shutdown", "=", "true", "\n", "close", "(", "p", ".", "shutdownCh", ")", "\n", "}" ]
// Shutdown is used to close the provider
[ "Shutdown", "is", "used", "to", "close", "the", "provider" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L163-L171
2,033
hashicorp/scada-client
provider.go
backoffDuration
func (p *Provider) backoffDuration() time.Duration { // Use the default backoff backoff := DefaultBackoff // Check for a server specified backoff p.backoffLock.Lock() if p.backoff != 0 { backoff = p.backoff } if p.noRetry { backoff = 0 } p.backoffLock.Unlock() return backoff }
go
func (p *Provider) backoffDuration() time.Duration { // Use the default backoff backoff := DefaultBackoff // Check for a server specified backoff p.backoffLock.Lock() if p.backoff != 0 { backoff = p.backoff } if p.noRetry { backoff = 0 } p.backoffLock.Unlock() return backoff }
[ "func", "(", "p", "*", "Provider", ")", "backoffDuration", "(", ")", "time", ".", "Duration", "{", "// Use the default backoff", "backoff", ":=", "DefaultBackoff", "\n\n", "// Check for a server specified backoff", "p", ".", "backoffLock", ".", "Lock", "(", ")", "\n", "if", "p", ".", "backoff", "!=", "0", "{", "backoff", "=", "p", ".", "backoff", "\n", "}", "\n", "if", "p", ".", "noRetry", "{", "backoff", "=", "0", "\n", "}", "\n", "p", ".", "backoffLock", ".", "Unlock", "(", ")", "\n\n", "return", "backoff", "\n", "}" ]
// backoffDuration is used to compute the next backoff duration
[ "backoffDuration", "is", "used", "to", "compute", "the", "next", "backoff", "duration" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L184-L199
2,034
hashicorp/scada-client
provider.go
wait
func (p *Provider) wait() { // Compute the backoff time backoff := p.backoffDuration() // Setup a wait timer var wait <-chan time.Time if backoff > 0 { jitter := time.Duration(rand.Uint32()) % backoff wait = time.After(backoff + jitter) } // Wait until timer or shutdown select { case <-wait: case <-p.shutdownCh: } }
go
func (p *Provider) wait() { // Compute the backoff time backoff := p.backoffDuration() // Setup a wait timer var wait <-chan time.Time if backoff > 0 { jitter := time.Duration(rand.Uint32()) % backoff wait = time.After(backoff + jitter) } // Wait until timer or shutdown select { case <-wait: case <-p.shutdownCh: } }
[ "func", "(", "p", "*", "Provider", ")", "wait", "(", ")", "{", "// Compute the backoff time", "backoff", ":=", "p", ".", "backoffDuration", "(", ")", "\n\n", "// Setup a wait timer", "var", "wait", "<-", "chan", "time", ".", "Time", "\n", "if", "backoff", ">", "0", "{", "jitter", ":=", "time", ".", "Duration", "(", "rand", ".", "Uint32", "(", ")", ")", "%", "backoff", "\n", "wait", "=", "time", ".", "After", "(", "backoff", "+", "jitter", ")", "\n", "}", "\n\n", "// Wait until timer or shutdown", "select", "{", "case", "<-", "wait", ":", "case", "<-", "p", ".", "shutdownCh", ":", "}", "\n", "}" ]
// wait is used to delay dialing on an error
[ "wait", "is", "used", "to", "delay", "dialing", "on", "an", "error" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L202-L218
2,035
hashicorp/scada-client
provider.go
run
func (p *Provider) run() { for !p.IsShutdown() { // Setup a new connection client, err := p.clientSetup() if err != nil { p.wait() continue } // Handle the session doneCh := make(chan struct{}) go p.handleSession(client, doneCh) // Wait for session termination or shutdown select { case <-doneCh: p.wait() case <-p.shutdownCh: p.clientLock.Lock() client.Close() p.clientLock.Unlock() return } } }
go
func (p *Provider) run() { for !p.IsShutdown() { // Setup a new connection client, err := p.clientSetup() if err != nil { p.wait() continue } // Handle the session doneCh := make(chan struct{}) go p.handleSession(client, doneCh) // Wait for session termination or shutdown select { case <-doneCh: p.wait() case <-p.shutdownCh: p.clientLock.Lock() client.Close() p.clientLock.Unlock() return } } }
[ "func", "(", "p", "*", "Provider", ")", "run", "(", ")", "{", "for", "!", "p", ".", "IsShutdown", "(", ")", "{", "// Setup a new connection", "client", ",", "err", ":=", "p", ".", "clientSetup", "(", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "wait", "(", ")", "\n", "continue", "\n", "}", "\n\n", "// Handle the session", "doneCh", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "p", ".", "handleSession", "(", "client", ",", "doneCh", ")", "\n\n", "// Wait for session termination or shutdown", "select", "{", "case", "<-", "doneCh", ":", "p", ".", "wait", "(", ")", "\n", "case", "<-", "p", ".", "shutdownCh", ":", "p", ".", "clientLock", ".", "Lock", "(", ")", "\n", "client", ".", "Close", "(", ")", "\n", "p", ".", "clientLock", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// run is a long running routine to manage the provider
[ "run", "is", "a", "long", "running", "routine", "to", "manage", "the", "provider" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L221-L245
2,036
hashicorp/scada-client
provider.go
handleSession
func (p *Provider) handleSession(list net.Listener, doneCh chan struct{}) { defer close(doneCh) defer list.Close() // Accept new connections for !p.IsShutdown() { conn, err := list.Accept() if err != nil { p.logger.Printf("[ERR] scada-client: failed to accept connection: %v", err) return } p.logger.Printf("[DEBUG] scada-client: accepted connection") go p.handleConnection(conn) } }
go
func (p *Provider) handleSession(list net.Listener, doneCh chan struct{}) { defer close(doneCh) defer list.Close() // Accept new connections for !p.IsShutdown() { conn, err := list.Accept() if err != nil { p.logger.Printf("[ERR] scada-client: failed to accept connection: %v", err) return } p.logger.Printf("[DEBUG] scada-client: accepted connection") go p.handleConnection(conn) } }
[ "func", "(", "p", "*", "Provider", ")", "handleSession", "(", "list", "net", ".", "Listener", ",", "doneCh", "chan", "struct", "{", "}", ")", "{", "defer", "close", "(", "doneCh", ")", "\n", "defer", "list", ".", "Close", "(", ")", "\n", "// Accept new connections", "for", "!", "p", ".", "IsShutdown", "(", ")", "{", "conn", ",", "err", ":=", "list", ".", "Accept", "(", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ")", "\n", "go", "p", ".", "handleConnection", "(", "conn", ")", "\n", "}", "\n", "}" ]
// handleSession is used to handle an established session
[ "handleSession", "is", "used", "to", "handle", "an", "established", "session" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L248-L261
2,037
hashicorp/scada-client
provider.go
handleConnection
func (p *Provider) handleConnection(conn net.Conn) { // Create an RPC server to handle inbound pe := &providerEndpoint{p: p} rpcServer := rpc.NewServer() rpcServer.RegisterName("Client", pe) rpcCodec := msgpackrpc.NewCodec(false, false, conn) defer func() { if !pe.hijacked() { conn.Close() } }() for !p.IsShutdown() { if err := rpcServer.ServeRequest(rpcCodec); err != nil { if err != io.EOF && !strings.Contains(err.Error(), "closed") { p.logger.Printf("[ERR] scada-client: RPC error: %v", err) } return } // Handle potential hijack in Client.Connect if pe.hijacked() { cb := pe.getHijack() cb(conn) return } } }
go
func (p *Provider) handleConnection(conn net.Conn) { // Create an RPC server to handle inbound pe := &providerEndpoint{p: p} rpcServer := rpc.NewServer() rpcServer.RegisterName("Client", pe) rpcCodec := msgpackrpc.NewCodec(false, false, conn) defer func() { if !pe.hijacked() { conn.Close() } }() for !p.IsShutdown() { if err := rpcServer.ServeRequest(rpcCodec); err != nil { if err != io.EOF && !strings.Contains(err.Error(), "closed") { p.logger.Printf("[ERR] scada-client: RPC error: %v", err) } return } // Handle potential hijack in Client.Connect if pe.hijacked() { cb := pe.getHijack() cb(conn) return } } }
[ "func", "(", "p", "*", "Provider", ")", "handleConnection", "(", "conn", "net", ".", "Conn", ")", "{", "// Create an RPC server to handle inbound", "pe", ":=", "&", "providerEndpoint", "{", "p", ":", "p", "}", "\n", "rpcServer", ":=", "rpc", ".", "NewServer", "(", ")", "\n", "rpcServer", ".", "RegisterName", "(", "\"", "\"", ",", "pe", ")", "\n", "rpcCodec", ":=", "msgpackrpc", ".", "NewCodec", "(", "false", ",", "false", ",", "conn", ")", "\n\n", "defer", "func", "(", ")", "{", "if", "!", "pe", ".", "hijacked", "(", ")", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "for", "!", "p", ".", "IsShutdown", "(", ")", "{", "if", "err", ":=", "rpcServer", ".", "ServeRequest", "(", "rpcCodec", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "&&", "!", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// Handle potential hijack in Client.Connect", "if", "pe", ".", "hijacked", "(", ")", "{", "cb", ":=", "pe", ".", "getHijack", "(", ")", "\n", "cb", "(", "conn", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// handleConnection handles an incoming connection
[ "handleConnection", "handles", "an", "incoming", "connection" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L264-L292
2,038
hashicorp/scada-client
provider.go
clientSetup
func (p *Provider) clientSetup() (*Client, error) { defer metrics.MeasureSince([]string{"scada", "setup"}, time.Now()) // Reset the previous backoff p.backoffLock.Lock() p.noRetry = false p.backoff = 0 p.backoffLock.Unlock() // Dial a new connection opts := Opts{ Addr: p.config.Endpoint, TLS: true, TLSConfig: p.config.TLSConfig, LogOutput: p.config.LogOutput, } client, err := DialOpts(&opts) if err != nil { p.logger.Printf("[ERR] scada-client: failed to dial: %v", err) return nil, err } // Perform a handshake resp, err := p.handshake(client) if err != nil { p.logger.Printf("[ERR] scada-client: failed to handshake: %v", err) client.Close() return nil, err } if resp != nil && resp.SessionID != "" { p.logger.Printf("[DEBUG] scada-client: assigned session '%s'", resp.SessionID) } if resp != nil && !resp.Authenticated { p.logger.Printf("[WARN] scada-client: authentication failed: %v", resp.Reason) } // Set the new client p.clientLock.Lock() if p.client != nil { p.client.Close() } p.client = client p.clientLock.Unlock() p.sessionLock.Lock() p.sessionID = resp.SessionID p.sessionAuth = resp.Authenticated p.sessionLock.Unlock() return client, nil }
go
func (p *Provider) clientSetup() (*Client, error) { defer metrics.MeasureSince([]string{"scada", "setup"}, time.Now()) // Reset the previous backoff p.backoffLock.Lock() p.noRetry = false p.backoff = 0 p.backoffLock.Unlock() // Dial a new connection opts := Opts{ Addr: p.config.Endpoint, TLS: true, TLSConfig: p.config.TLSConfig, LogOutput: p.config.LogOutput, } client, err := DialOpts(&opts) if err != nil { p.logger.Printf("[ERR] scada-client: failed to dial: %v", err) return nil, err } // Perform a handshake resp, err := p.handshake(client) if err != nil { p.logger.Printf("[ERR] scada-client: failed to handshake: %v", err) client.Close() return nil, err } if resp != nil && resp.SessionID != "" { p.logger.Printf("[DEBUG] scada-client: assigned session '%s'", resp.SessionID) } if resp != nil && !resp.Authenticated { p.logger.Printf("[WARN] scada-client: authentication failed: %v", resp.Reason) } // Set the new client p.clientLock.Lock() if p.client != nil { p.client.Close() } p.client = client p.clientLock.Unlock() p.sessionLock.Lock() p.sessionID = resp.SessionID p.sessionAuth = resp.Authenticated p.sessionLock.Unlock() return client, nil }
[ "func", "(", "p", "*", "Provider", ")", "clientSetup", "(", ")", "(", "*", "Client", ",", "error", ")", "{", "defer", "metrics", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "time", ".", "Now", "(", ")", ")", "\n\n", "// Reset the previous backoff", "p", ".", "backoffLock", ".", "Lock", "(", ")", "\n", "p", ".", "noRetry", "=", "false", "\n", "p", ".", "backoff", "=", "0", "\n", "p", ".", "backoffLock", ".", "Unlock", "(", ")", "\n\n", "// Dial a new connection", "opts", ":=", "Opts", "{", "Addr", ":", "p", ".", "config", ".", "Endpoint", ",", "TLS", ":", "true", ",", "TLSConfig", ":", "p", ".", "config", ".", "TLSConfig", ",", "LogOutput", ":", "p", ".", "config", ".", "LogOutput", ",", "}", "\n", "client", ",", "err", ":=", "DialOpts", "(", "&", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Perform a handshake", "resp", ",", "err", ":=", "p", ".", "handshake", "(", "client", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "client", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", "!=", "nil", "&&", "resp", ".", "SessionID", "!=", "\"", "\"", "{", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "resp", ".", "SessionID", ")", "\n", "}", "\n", "if", "resp", "!=", "nil", "&&", "!", "resp", ".", "Authenticated", "{", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "resp", ".", "Reason", ")", "\n", "}", "\n\n", "// Set the new client", "p", ".", "clientLock", ".", "Lock", "(", ")", "\n", "if", "p", ".", "client", "!=", "nil", "{", "p", ".", "client", ".", "Close", "(", ")", "\n", "}", "\n", "p", ".", "client", "=", "client", "\n", "p", ".", "clientLock", ".", "Unlock", "(", ")", "\n\n", "p", ".", "sessionLock", ".", "Lock", "(", ")", "\n", "p", ".", "sessionID", "=", "resp", ".", "SessionID", "\n", "p", ".", "sessionAuth", "=", "resp", ".", "Authenticated", "\n", "p", ".", "sessionLock", ".", "Unlock", "(", ")", "\n\n", "return", "client", ",", "nil", "\n", "}" ]
// clientSetup is used to setup a new connection
[ "clientSetup", "is", "used", "to", "setup", "a", "new", "connection" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L295-L345
2,039
hashicorp/scada-client
provider.go
SessionID
func (p *Provider) SessionID() string { p.sessionLock.RLock() defer p.sessionLock.RUnlock() return p.sessionID }
go
func (p *Provider) SessionID() string { p.sessionLock.RLock() defer p.sessionLock.RUnlock() return p.sessionID }
[ "func", "(", "p", "*", "Provider", ")", "SessionID", "(", ")", "string", "{", "p", ".", "sessionLock", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "sessionLock", ".", "RUnlock", "(", ")", "\n", "return", "p", ".", "sessionID", "\n", "}" ]
// SessionID provides the current session ID
[ "SessionID", "provides", "the", "current", "session", "ID" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L348-L352
2,040
hashicorp/scada-client
provider.go
SessionAuthenticated
func (p *Provider) SessionAuthenticated() bool { p.sessionLock.RLock() defer p.sessionLock.RUnlock() return p.sessionAuth }
go
func (p *Provider) SessionAuthenticated() bool { p.sessionLock.RLock() defer p.sessionLock.RUnlock() return p.sessionAuth }
[ "func", "(", "p", "*", "Provider", ")", "SessionAuthenticated", "(", ")", "bool", "{", "p", ".", "sessionLock", ".", "RLock", "(", ")", "\n", "defer", "p", ".", "sessionLock", ".", "RUnlock", "(", ")", "\n", "return", "p", ".", "sessionAuth", "\n", "}" ]
// SessionAuth checks if the current session is authenticated
[ "SessionAuth", "checks", "if", "the", "current", "session", "is", "authenticated" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L355-L359
2,041
hashicorp/scada-client
provider.go
handshake
func (p *Provider) handshake(client *Client) (*HandshakeResponse, error) { defer metrics.MeasureSince([]string{"scada", "handshake"}, time.Now()) req := HandshakeRequest{ Service: p.config.Service.Service, ServiceVersion: p.config.Service.ServiceVersion, Capabilities: p.config.Service.Capabilities, Meta: p.config.Service.Meta, ResourceType: p.config.Service.ResourceType, ResourceGroup: p.config.ResourceGroup, Token: p.config.Token, } resp := new(HandshakeResponse) if err := client.RPC("Session.Handshake", &req, resp); err != nil { return nil, err } return resp, nil }
go
func (p *Provider) handshake(client *Client) (*HandshakeResponse, error) { defer metrics.MeasureSince([]string{"scada", "handshake"}, time.Now()) req := HandshakeRequest{ Service: p.config.Service.Service, ServiceVersion: p.config.Service.ServiceVersion, Capabilities: p.config.Service.Capabilities, Meta: p.config.Service.Meta, ResourceType: p.config.Service.ResourceType, ResourceGroup: p.config.ResourceGroup, Token: p.config.Token, } resp := new(HandshakeResponse) if err := client.RPC("Session.Handshake", &req, resp); err != nil { return nil, err } return resp, nil }
[ "func", "(", "p", "*", "Provider", ")", "handshake", "(", "client", "*", "Client", ")", "(", "*", "HandshakeResponse", ",", "error", ")", "{", "defer", "metrics", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "time", ".", "Now", "(", ")", ")", "\n", "req", ":=", "HandshakeRequest", "{", "Service", ":", "p", ".", "config", ".", "Service", ".", "Service", ",", "ServiceVersion", ":", "p", ".", "config", ".", "Service", ".", "ServiceVersion", ",", "Capabilities", ":", "p", ".", "config", ".", "Service", ".", "Capabilities", ",", "Meta", ":", "p", ".", "config", ".", "Service", ".", "Meta", ",", "ResourceType", ":", "p", ".", "config", ".", "Service", ".", "ResourceType", ",", "ResourceGroup", ":", "p", ".", "config", ".", "ResourceGroup", ",", "Token", ":", "p", ".", "config", ".", "Token", ",", "}", "\n", "resp", ":=", "new", "(", "HandshakeResponse", ")", "\n", "if", "err", ":=", "client", ".", "RPC", "(", "\"", "\"", ",", "&", "req", ",", "resp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// handshake does the initial handshake
[ "handshake", "does", "the", "initial", "handshake" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L362-L378
2,042
hashicorp/scada-client
provider.go
Connect
func (pe *providerEndpoint) Connect(args *ConnectRequest, resp *ConnectResponse) error { defer metrics.IncrCounter([]string{"scada", "connect", args.Capability}, 1) pe.p.logger.Printf("[INFO] scada-client: connect requested (capability: %s)", args.Capability) // Handle potential flash if args.Severity != "" && args.Message != "" { pe.p.logger.Printf("[%s] scada-client: %s", args.Severity, args.Message) } // Look for the handler handler := pe.p.config.Handlers[args.Capability] if handler == nil { pe.p.logger.Printf("[WARN] scada-client: requested capability '%s' not available", args.Capability) return fmt.Errorf("invalid capability") } // Hijack the connection pe.setHijack(func(a io.ReadWriteCloser) { if err := handler(args.Capability, args.Meta, a); err != nil { pe.p.logger.Printf("[ERR] scada-client: '%s' handler error: %v", args.Capability, err) } }) resp.Success = true return nil }
go
func (pe *providerEndpoint) Connect(args *ConnectRequest, resp *ConnectResponse) error { defer metrics.IncrCounter([]string{"scada", "connect", args.Capability}, 1) pe.p.logger.Printf("[INFO] scada-client: connect requested (capability: %s)", args.Capability) // Handle potential flash if args.Severity != "" && args.Message != "" { pe.p.logger.Printf("[%s] scada-client: %s", args.Severity, args.Message) } // Look for the handler handler := pe.p.config.Handlers[args.Capability] if handler == nil { pe.p.logger.Printf("[WARN] scada-client: requested capability '%s' not available", args.Capability) return fmt.Errorf("invalid capability") } // Hijack the connection pe.setHijack(func(a io.ReadWriteCloser) { if err := handler(args.Capability, args.Meta, a); err != nil { pe.p.logger.Printf("[ERR] scada-client: '%s' handler error: %v", args.Capability, err) } }) resp.Success = true return nil }
[ "func", "(", "pe", "*", "providerEndpoint", ")", "Connect", "(", "args", "*", "ConnectRequest", ",", "resp", "*", "ConnectResponse", ")", "error", "{", "defer", "metrics", ".", "IncrCounter", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "args", ".", "Capability", "}", ",", "1", ")", "\n", "pe", ".", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "args", ".", "Capability", ")", "\n\n", "// Handle potential flash", "if", "args", ".", "Severity", "!=", "\"", "\"", "&&", "args", ".", "Message", "!=", "\"", "\"", "{", "pe", ".", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "args", ".", "Severity", ",", "args", ".", "Message", ")", "\n", "}", "\n\n", "// Look for the handler", "handler", ":=", "pe", ".", "p", ".", "config", ".", "Handlers", "[", "args", ".", "Capability", "]", "\n", "if", "handler", "==", "nil", "{", "pe", ".", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "args", ".", "Capability", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Hijack the connection", "pe", ".", "setHijack", "(", "func", "(", "a", "io", ".", "ReadWriteCloser", ")", "{", "if", "err", ":=", "handler", "(", "args", ".", "Capability", ",", "args", ".", "Meta", ",", "a", ")", ";", "err", "!=", "nil", "{", "pe", ".", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "args", ".", "Capability", ",", "err", ")", "\n", "}", "\n", "}", ")", "\n", "resp", ".", "Success", "=", "true", "\n", "return", "nil", "\n", "}" ]
// Connect is invoked by the broker to connect to a capability
[ "Connect", "is", "invoked", "by", "the", "broker", "to", "connect", "to", "a", "capability" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L405-L432
2,043
hashicorp/scada-client
provider.go
Disconnect
func (pe *providerEndpoint) Disconnect(args *DisconnectRequest, resp *DisconnectResponse) error { defer metrics.IncrCounter([]string{"scada", "disconnect"}, 1) if args.Reason == "" { args.Reason = "<no reason provided>" } pe.p.logger.Printf("[INFO] scada-client: disconnect requested (retry: %v, backoff: %v): %v", !args.NoRetry, args.Backoff, args.Reason) // Use the backoff information pe.p.backoffLock.Lock() pe.p.noRetry = args.NoRetry pe.p.backoff = args.Backoff pe.p.backoffLock.Unlock() // Clear the session information pe.p.sessionLock.Lock() pe.p.sessionID = "" pe.p.sessionAuth = false pe.p.sessionLock.Unlock() // Force the disconnect time.AfterFunc(DisconnectDelay, func() { pe.p.clientLock.Lock() if pe.p.client != nil { pe.p.client.Close() } pe.p.clientLock.Unlock() }) return nil }
go
func (pe *providerEndpoint) Disconnect(args *DisconnectRequest, resp *DisconnectResponse) error { defer metrics.IncrCounter([]string{"scada", "disconnect"}, 1) if args.Reason == "" { args.Reason = "<no reason provided>" } pe.p.logger.Printf("[INFO] scada-client: disconnect requested (retry: %v, backoff: %v): %v", !args.NoRetry, args.Backoff, args.Reason) // Use the backoff information pe.p.backoffLock.Lock() pe.p.noRetry = args.NoRetry pe.p.backoff = args.Backoff pe.p.backoffLock.Unlock() // Clear the session information pe.p.sessionLock.Lock() pe.p.sessionID = "" pe.p.sessionAuth = false pe.p.sessionLock.Unlock() // Force the disconnect time.AfterFunc(DisconnectDelay, func() { pe.p.clientLock.Lock() if pe.p.client != nil { pe.p.client.Close() } pe.p.clientLock.Unlock() }) return nil }
[ "func", "(", "pe", "*", "providerEndpoint", ")", "Disconnect", "(", "args", "*", "DisconnectRequest", ",", "resp", "*", "DisconnectResponse", ")", "error", "{", "defer", "metrics", ".", "IncrCounter", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "1", ")", "\n", "if", "args", ".", "Reason", "==", "\"", "\"", "{", "args", ".", "Reason", "=", "\"", "\"", "\n", "}", "\n", "pe", ".", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "!", "args", ".", "NoRetry", ",", "args", ".", "Backoff", ",", "args", ".", "Reason", ")", "\n\n", "// Use the backoff information", "pe", ".", "p", ".", "backoffLock", ".", "Lock", "(", ")", "\n", "pe", ".", "p", ".", "noRetry", "=", "args", ".", "NoRetry", "\n", "pe", ".", "p", ".", "backoff", "=", "args", ".", "Backoff", "\n", "pe", ".", "p", ".", "backoffLock", ".", "Unlock", "(", ")", "\n\n", "// Clear the session information", "pe", ".", "p", ".", "sessionLock", ".", "Lock", "(", ")", "\n", "pe", ".", "p", ".", "sessionID", "=", "\"", "\"", "\n", "pe", ".", "p", ".", "sessionAuth", "=", "false", "\n", "pe", ".", "p", ".", "sessionLock", ".", "Unlock", "(", ")", "\n\n", "// Force the disconnect", "time", ".", "AfterFunc", "(", "DisconnectDelay", ",", "func", "(", ")", "{", "pe", ".", "p", ".", "clientLock", ".", "Lock", "(", ")", "\n", "if", "pe", ".", "p", ".", "client", "!=", "nil", "{", "pe", ".", "p", ".", "client", ".", "Close", "(", ")", "\n", "}", "\n", "pe", ".", "p", ".", "clientLock", ".", "Unlock", "(", ")", "\n", "}", ")", "\n", "return", "nil", "\n", "}" ]
// Disconnect is invoked by the broker to ask us to backoff
[ "Disconnect", "is", "invoked", "by", "the", "broker", "to", "ask", "us", "to", "backoff" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L435-L464
2,044
hashicorp/scada-client
provider.go
Flash
func (pe *providerEndpoint) Flash(args *FlashRequest, resp *FlashResponse) error { defer metrics.IncrCounter([]string{"scada", "flash"}, 1) if args.Severity != "" && args.Message != "" { pe.p.logger.Printf("[%s] scada-client: %s", args.Severity, args.Message) } return nil }
go
func (pe *providerEndpoint) Flash(args *FlashRequest, resp *FlashResponse) error { defer metrics.IncrCounter([]string{"scada", "flash"}, 1) if args.Severity != "" && args.Message != "" { pe.p.logger.Printf("[%s] scada-client: %s", args.Severity, args.Message) } return nil }
[ "func", "(", "pe", "*", "providerEndpoint", ")", "Flash", "(", "args", "*", "FlashRequest", ",", "resp", "*", "FlashResponse", ")", "error", "{", "defer", "metrics", ".", "IncrCounter", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ",", "1", ")", "\n", "if", "args", ".", "Severity", "!=", "\"", "\"", "&&", "args", ".", "Message", "!=", "\"", "\"", "{", "pe", ".", "p", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "args", ".", "Severity", ",", "args", ".", "Message", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Flash is invoked by the broker log a message
[ "Flash", "is", "invoked", "by", "the", "broker", "log", "a", "message" ]
6e896784f66f82cdc6f17e00052db91699dc277d
https://github.com/hashicorp/scada-client/blob/6e896784f66f82cdc6f17e00052db91699dc277d/provider.go#L467-L473
2,045
masterzen/winrm
ntlm.go
Transport
func (c *ClientNTLM) Transport(endpoint *Endpoint) error { c.clientRequest.Transport(endpoint) c.clientRequest.transport = &ntlmssp.Negotiator{RoundTripper: c.clientRequest.transport} return nil }
go
func (c *ClientNTLM) Transport(endpoint *Endpoint) error { c.clientRequest.Transport(endpoint) c.clientRequest.transport = &ntlmssp.Negotiator{RoundTripper: c.clientRequest.transport} return nil }
[ "func", "(", "c", "*", "ClientNTLM", ")", "Transport", "(", "endpoint", "*", "Endpoint", ")", "error", "{", "c", ".", "clientRequest", ".", "Transport", "(", "endpoint", ")", "\n", "c", ".", "clientRequest", ".", "transport", "=", "&", "ntlmssp", ".", "Negotiator", "{", "RoundTripper", ":", "c", ".", "clientRequest", ".", "transport", "}", "\n", "return", "nil", "\n", "}" ]
// Transport creates the wrapped NTLM transport
[ "Transport", "creates", "the", "wrapped", "NTLM", "transport" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/ntlm.go#L15-L19
2,046
masterzen/winrm
request.go
NewOpenShellRequest
func NewOpenShellRequest(uri string, params *Parameters) *soap.SoapMessage { if params == nil { params = DefaultParameters } message := soap.NewMessage() defaultHeaders(message, uri, params). Action("http://schemas.xmlsoap.org/ws/2004/09/transfer/Create"). ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd"). AddOption(soap.NewHeaderOption("WINRS_NOPROFILE", "FALSE")). AddOption(soap.NewHeaderOption("WINRS_CODEPAGE", "65001")). Build() body := message.CreateBodyElement("Shell", soap.DOM_NS_WIN_SHELL) input := message.CreateElement(body, "InputStreams", soap.DOM_NS_WIN_SHELL) input.SetContent("stdin") output := message.CreateElement(body, "OutputStreams", soap.DOM_NS_WIN_SHELL) output.SetContent("stdout stderr") return message }
go
func NewOpenShellRequest(uri string, params *Parameters) *soap.SoapMessage { if params == nil { params = DefaultParameters } message := soap.NewMessage() defaultHeaders(message, uri, params). Action("http://schemas.xmlsoap.org/ws/2004/09/transfer/Create"). ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd"). AddOption(soap.NewHeaderOption("WINRS_NOPROFILE", "FALSE")). AddOption(soap.NewHeaderOption("WINRS_CODEPAGE", "65001")). Build() body := message.CreateBodyElement("Shell", soap.DOM_NS_WIN_SHELL) input := message.CreateElement(body, "InputStreams", soap.DOM_NS_WIN_SHELL) input.SetContent("stdin") output := message.CreateElement(body, "OutputStreams", soap.DOM_NS_WIN_SHELL) output.SetContent("stdout stderr") return message }
[ "func", "NewOpenShellRequest", "(", "uri", "string", ",", "params", "*", "Parameters", ")", "*", "soap", ".", "SoapMessage", "{", "if", "params", "==", "nil", "{", "params", "=", "DefaultParameters", "\n", "}", "\n\n", "message", ":=", "soap", ".", "NewMessage", "(", ")", "\n", "defaultHeaders", "(", "message", ",", "uri", ",", "params", ")", ".", "Action", "(", "\"", "\"", ")", ".", "ResourceURI", "(", "\"", "\"", ")", ".", "AddOption", "(", "soap", ".", "NewHeaderOption", "(", "\"", "\"", ",", "\"", "\"", ")", ")", ".", "AddOption", "(", "soap", ".", "NewHeaderOption", "(", "\"", "\"", ",", "\"", "\"", ")", ")", ".", "Build", "(", ")", "\n\n", "body", ":=", "message", ".", "CreateBodyElement", "(", "\"", "\"", ",", "soap", ".", "DOM_NS_WIN_SHELL", ")", "\n", "input", ":=", "message", ".", "CreateElement", "(", "body", ",", "\"", "\"", ",", "soap", ".", "DOM_NS_WIN_SHELL", ")", "\n", "input", ".", "SetContent", "(", "\"", "\"", ")", "\n", "output", ":=", "message", ".", "CreateElement", "(", "body", ",", "\"", "\"", ",", "soap", ".", "DOM_NS_WIN_SHELL", ")", "\n", "output", ".", "SetContent", "(", "\"", "\"", ")", "\n\n", "return", "message", "\n", "}" ]
//NewOpenShellRequest makes a new soap request
[ "NewOpenShellRequest", "makes", "a", "new", "soap", "request" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/request.go#L27-L47
2,047
masterzen/winrm
request.go
NewExecuteCommandRequest
func NewExecuteCommandRequest(uri, shellId, command string, arguments []string, params *Parameters) *soap.SoapMessage { if params == nil { params = DefaultParameters } message := soap.NewMessage() defaultHeaders(message, uri, params). Action("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command"). ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd"). ShellId(shellId). AddOption(soap.NewHeaderOption("WINRS_CONSOLEMODE_STDIN", "TRUE")). AddOption(soap.NewHeaderOption("WINRS_SKIP_CMD_SHELL", "FALSE")). Build() body := message.CreateBodyElement("CommandLine", soap.DOM_NS_WIN_SHELL) // ensure special characters like & don't mangle the request XML command = "<![CDATA[" + command + "]]>" commandElement := message.CreateElement(body, "Command", soap.DOM_NS_WIN_SHELL) commandElement.SetContent(command) for _, arg := range arguments { arg = "<![CDATA[" + arg + "]]>" argumentsElement := message.CreateElement(body, "Arguments", soap.DOM_NS_WIN_SHELL) argumentsElement.SetContent(arg) } return message }
go
func NewExecuteCommandRequest(uri, shellId, command string, arguments []string, params *Parameters) *soap.SoapMessage { if params == nil { params = DefaultParameters } message := soap.NewMessage() defaultHeaders(message, uri, params). Action("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command"). ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd"). ShellId(shellId). AddOption(soap.NewHeaderOption("WINRS_CONSOLEMODE_STDIN", "TRUE")). AddOption(soap.NewHeaderOption("WINRS_SKIP_CMD_SHELL", "FALSE")). Build() body := message.CreateBodyElement("CommandLine", soap.DOM_NS_WIN_SHELL) // ensure special characters like & don't mangle the request XML command = "<![CDATA[" + command + "]]>" commandElement := message.CreateElement(body, "Command", soap.DOM_NS_WIN_SHELL) commandElement.SetContent(command) for _, arg := range arguments { arg = "<![CDATA[" + arg + "]]>" argumentsElement := message.CreateElement(body, "Arguments", soap.DOM_NS_WIN_SHELL) argumentsElement.SetContent(arg) } return message }
[ "func", "NewExecuteCommandRequest", "(", "uri", ",", "shellId", ",", "command", "string", ",", "arguments", "[", "]", "string", ",", "params", "*", "Parameters", ")", "*", "soap", ".", "SoapMessage", "{", "if", "params", "==", "nil", "{", "params", "=", "DefaultParameters", "\n", "}", "\n", "message", ":=", "soap", ".", "NewMessage", "(", ")", "\n", "defaultHeaders", "(", "message", ",", "uri", ",", "params", ")", ".", "Action", "(", "\"", "\"", ")", ".", "ResourceURI", "(", "\"", "\"", ")", ".", "ShellId", "(", "shellId", ")", ".", "AddOption", "(", "soap", ".", "NewHeaderOption", "(", "\"", "\"", ",", "\"", "\"", ")", ")", ".", "AddOption", "(", "soap", ".", "NewHeaderOption", "(", "\"", "\"", ",", "\"", "\"", ")", ")", ".", "Build", "(", ")", "\n\n", "body", ":=", "message", ".", "CreateBodyElement", "(", "\"", "\"", ",", "soap", ".", "DOM_NS_WIN_SHELL", ")", "\n\n", "// ensure special characters like & don't mangle the request XML", "command", "=", "\"", "\"", "+", "command", "+", "\"", "\"", "\n", "commandElement", ":=", "message", ".", "CreateElement", "(", "body", ",", "\"", "\"", ",", "soap", ".", "DOM_NS_WIN_SHELL", ")", "\n", "commandElement", ".", "SetContent", "(", "command", ")", "\n\n", "for", "_", ",", "arg", ":=", "range", "arguments", "{", "arg", "=", "\"", "\"", "+", "arg", "+", "\"", "\"", "\n", "argumentsElement", ":=", "message", ".", "CreateElement", "(", "body", ",", "\"", "\"", ",", "soap", ".", "DOM_NS_WIN_SHELL", ")", "\n", "argumentsElement", ".", "SetContent", "(", "arg", ")", "\n", "}", "\n\n", "return", "message", "\n", "}" ]
// NewExecuteCommandRequest exec command on specific shellID
[ "NewExecuteCommandRequest", "exec", "command", "on", "specific", "shellID" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/request.go#L67-L94
2,048
masterzen/winrm
http.go
body
func body(response *http.Response) (string, error) { // if we recived the content we expected if strings.Contains(response.Header.Get("Content-Type"), "application/soap+xml") { body, err := ioutil.ReadAll(response.Body) defer func() { // defer can modify the returned value before // it is actually passed to the calling statement if errClose := response.Body.Close(); errClose != nil && err == nil { err = errClose } }() if err != nil { return "", fmt.Errorf("error while reading request body %s", err) } return string(body), nil } return "", fmt.Errorf("invalid content type") }
go
func body(response *http.Response) (string, error) { // if we recived the content we expected if strings.Contains(response.Header.Get("Content-Type"), "application/soap+xml") { body, err := ioutil.ReadAll(response.Body) defer func() { // defer can modify the returned value before // it is actually passed to the calling statement if errClose := response.Body.Close(); errClose != nil && err == nil { err = errClose } }() if err != nil { return "", fmt.Errorf("error while reading request body %s", err) } return string(body), nil } return "", fmt.Errorf("invalid content type") }
[ "func", "body", "(", "response", "*", "http", ".", "Response", ")", "(", "string", ",", "error", ")", "{", "// if we recived the content we expected", "if", "strings", ".", "Contains", "(", "response", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "\"", "\"", ")", "{", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "response", ".", "Body", ")", "\n", "defer", "func", "(", ")", "{", "// defer can modify the returned value before", "// it is actually passed to the calling statement", "if", "errClose", ":=", "response", ".", "Body", ".", "Close", "(", ")", ";", "errClose", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "errClose", "\n", "}", "\n", "}", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "string", "(", "body", ")", ",", "nil", "\n", "}", "\n\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// body func reads the response body and return it as a string
[ "body", "func", "reads", "the", "response", "body", "and", "return", "it", "as", "a", "string" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/http.go#L18-L38
2,049
masterzen/winrm
http.go
Post
func (c clientRequest) Post(client *Client, request *soap.SoapMessage) (string, error) { httpClient := &http.Client{Transport: c.transport} req, err := http.NewRequest("POST", client.url, strings.NewReader(request.String())) if err != nil { return "", fmt.Errorf("impossible to create http request %s", err) } req.Header.Set("Content-Type", soapXML+";charset=UTF-8") req.SetBasicAuth(client.username, client.password) resp, err := httpClient.Do(req) if err != nil { return "", fmt.Errorf("unknown error %s", err) } body, err := body(resp) if err != nil { return "", fmt.Errorf("http response error: %d - %s", resp.StatusCode, err.Error()) } // if we have different 200 http status code // we must replace the error defer func() { if resp.StatusCode != 200 { body, err = "", fmt.Errorf("http error %d: %s", resp.StatusCode, body) } }() return body, err }
go
func (c clientRequest) Post(client *Client, request *soap.SoapMessage) (string, error) { httpClient := &http.Client{Transport: c.transport} req, err := http.NewRequest("POST", client.url, strings.NewReader(request.String())) if err != nil { return "", fmt.Errorf("impossible to create http request %s", err) } req.Header.Set("Content-Type", soapXML+";charset=UTF-8") req.SetBasicAuth(client.username, client.password) resp, err := httpClient.Do(req) if err != nil { return "", fmt.Errorf("unknown error %s", err) } body, err := body(resp) if err != nil { return "", fmt.Errorf("http response error: %d - %s", resp.StatusCode, err.Error()) } // if we have different 200 http status code // we must replace the error defer func() { if resp.StatusCode != 200 { body, err = "", fmt.Errorf("http error %d: %s", resp.StatusCode, body) } }() return body, err }
[ "func", "(", "c", "clientRequest", ")", "Post", "(", "client", "*", "Client", ",", "request", "*", "soap", ".", "SoapMessage", ")", "(", "string", ",", "error", ")", "{", "httpClient", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "c", ".", "transport", "}", "\n\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "client", ".", "url", ",", "strings", ".", "NewReader", "(", "request", ".", "String", "(", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "soapXML", "+", "\"", "\"", ")", "\n", "req", ".", "SetBasicAuth", "(", "client", ".", "username", ",", "client", ".", "password", ")", "\n", "resp", ",", "err", ":=", "httpClient", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "body", ",", "err", ":=", "body", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "// if we have different 200 http status code", "// we must replace the error", "defer", "func", "(", ")", "{", "if", "resp", ".", "StatusCode", "!=", "200", "{", "body", ",", "err", "=", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ",", "body", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "body", ",", "err", "\n", "}" ]
// Post make post to the winrm soap service
[ "Post", "make", "post", "to", "the", "winrm", "soap", "service" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/http.go#L81-L109
2,050
masterzen/winrm
shell.go
Execute
func (s *Shell) Execute(command string, arguments ...string) (*Command, error) { request := NewExecuteCommandRequest(s.client.url, s.id, command, arguments, &s.client.Parameters) defer request.Free() response, err := s.client.sendRequest(request) if err != nil { return nil, err } commandID, err := ParseExecuteCommandResponse(response) if err != nil { return nil, err } cmd := newCommand(s, commandID) return cmd, nil }
go
func (s *Shell) Execute(command string, arguments ...string) (*Command, error) { request := NewExecuteCommandRequest(s.client.url, s.id, command, arguments, &s.client.Parameters) defer request.Free() response, err := s.client.sendRequest(request) if err != nil { return nil, err } commandID, err := ParseExecuteCommandResponse(response) if err != nil { return nil, err } cmd := newCommand(s, commandID) return cmd, nil }
[ "func", "(", "s", "*", "Shell", ")", "Execute", "(", "command", "string", ",", "arguments", "...", "string", ")", "(", "*", "Command", ",", "error", ")", "{", "request", ":=", "NewExecuteCommandRequest", "(", "s", ".", "client", ".", "url", ",", "s", ".", "id", ",", "command", ",", "arguments", ",", "&", "s", ".", "client", ".", "Parameters", ")", "\n", "defer", "request", ".", "Free", "(", ")", "\n\n", "response", ",", "err", ":=", "s", ".", "client", ".", "sendRequest", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "commandID", ",", "err", ":=", "ParseExecuteCommandResponse", "(", "response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "cmd", ":=", "newCommand", "(", "s", ",", "commandID", ")", "\n\n", "return", "cmd", ",", "nil", "\n", "}" ]
// Execute command on the given Shell, returning either an error or a Command
[ "Execute", "command", "on", "the", "given", "Shell", "returning", "either", "an", "error", "or", "a", "Command" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/shell.go#L10-L27
2,051
masterzen/winrm
shell.go
Close
func (s *Shell) Close() error { request := NewDeleteShellRequest(s.client.url, s.id, &s.client.Parameters) defer request.Free() _, err := s.client.sendRequest(request) return err }
go
func (s *Shell) Close() error { request := NewDeleteShellRequest(s.client.url, s.id, &s.client.Parameters) defer request.Free() _, err := s.client.sendRequest(request) return err }
[ "func", "(", "s", "*", "Shell", ")", "Close", "(", ")", "error", "{", "request", ":=", "NewDeleteShellRequest", "(", "s", ".", "client", ".", "url", ",", "s", ".", "id", ",", "&", "s", ".", "client", ".", "Parameters", ")", "\n", "defer", "request", ".", "Free", "(", ")", "\n\n", "_", ",", "err", ":=", "s", ".", "client", ".", "sendRequest", "(", "request", ")", "\n", "return", "err", "\n", "}" ]
// Close will terminate this shell. No commands can be issued once the shell is closed.
[ "Close", "will", "terminate", "this", "shell", ".", "No", "commands", "can", "be", "issued", "once", "the", "shell", "is", "closed", "." ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/shell.go#L30-L36
2,052
masterzen/winrm
endpoint.go
NewEndpoint
func NewEndpoint(host string, port int, https bool, insecure bool, Cacert, cert, key []byte, timeout time.Duration) *Endpoint { endpoint := &Endpoint{ Host: host, Port: port, HTTPS: https, Insecure: insecure, CACert: Cacert, Key: key, Cert: cert, } // if the timeout was set if timeout != 0 { endpoint.Timeout = timeout } else { // assign default 60sec timeout endpoint.Timeout = 60 * time.Second } return endpoint }
go
func NewEndpoint(host string, port int, https bool, insecure bool, Cacert, cert, key []byte, timeout time.Duration) *Endpoint { endpoint := &Endpoint{ Host: host, Port: port, HTTPS: https, Insecure: insecure, CACert: Cacert, Key: key, Cert: cert, } // if the timeout was set if timeout != 0 { endpoint.Timeout = timeout } else { // assign default 60sec timeout endpoint.Timeout = 60 * time.Second } return endpoint }
[ "func", "NewEndpoint", "(", "host", "string", ",", "port", "int", ",", "https", "bool", ",", "insecure", "bool", ",", "Cacert", ",", "cert", ",", "key", "[", "]", "byte", ",", "timeout", "time", ".", "Duration", ")", "*", "Endpoint", "{", "endpoint", ":=", "&", "Endpoint", "{", "Host", ":", "host", ",", "Port", ":", "port", ",", "HTTPS", ":", "https", ",", "Insecure", ":", "insecure", ",", "CACert", ":", "Cacert", ",", "Key", ":", "key", ",", "Cert", ":", "cert", ",", "}", "\n", "// if the timeout was set", "if", "timeout", "!=", "0", "{", "endpoint", ".", "Timeout", "=", "timeout", "\n", "}", "else", "{", "// assign default 60sec timeout", "endpoint", ".", "Timeout", "=", "60", "*", "time", ".", "Second", "\n", "}", "\n\n", "return", "endpoint", "\n", "}" ]
// NewEndpoint returns new pointer to struct Endpoint, with a default 60s response header timeout
[ "NewEndpoint", "returns", "new", "pointer", "to", "struct", "Endpoint", "with", "a", "default", "60s", "response", "header", "timeout" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/endpoint.go#L44-L63
2,053
masterzen/winrm
parameters.go
NewParameters
func NewParameters(timeout, locale string, envelopeSize int) *Parameters { return &Parameters{ Timeout: timeout, Locale: locale, EnvelopeSize: envelopeSize, } }
go
func NewParameters(timeout, locale string, envelopeSize int) *Parameters { return &Parameters{ Timeout: timeout, Locale: locale, EnvelopeSize: envelopeSize, } }
[ "func", "NewParameters", "(", "timeout", ",", "locale", "string", ",", "envelopeSize", "int", ")", "*", "Parameters", "{", "return", "&", "Parameters", "{", "Timeout", ":", "timeout", ",", "Locale", ":", "locale", ",", "EnvelopeSize", ":", "envelopeSize", ",", "}", "\n", "}" ]
// NewParameters return new struct of type Parameters // this struct makes the configuration for the request, size message, etc.
[ "NewParameters", "return", "new", "struct", "of", "type", "Parameters", "this", "struct", "makes", "the", "configuration", "for", "the", "request", "size", "message", "etc", "." ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/parameters.go#L21-L27
2,054
masterzen/winrm
powershell.go
Powershell
func Powershell(psCmd string) string { // 2 byte chars to make PowerShell happy wideCmd := "" for _, b := range []byte(psCmd) { wideCmd += string(b) + "\x00" } // Base64 encode the command input := []uint8(wideCmd) encodedCmd := base64.StdEncoding.EncodeToString(input) // Create the powershell.exe command line to execute the script return fmt.Sprintf("powershell.exe -EncodedCommand %s", encodedCmd) }
go
func Powershell(psCmd string) string { // 2 byte chars to make PowerShell happy wideCmd := "" for _, b := range []byte(psCmd) { wideCmd += string(b) + "\x00" } // Base64 encode the command input := []uint8(wideCmd) encodedCmd := base64.StdEncoding.EncodeToString(input) // Create the powershell.exe command line to execute the script return fmt.Sprintf("powershell.exe -EncodedCommand %s", encodedCmd) }
[ "func", "Powershell", "(", "psCmd", "string", ")", "string", "{", "// 2 byte chars to make PowerShell happy", "wideCmd", ":=", "\"", "\"", "\n", "for", "_", ",", "b", ":=", "range", "[", "]", "byte", "(", "psCmd", ")", "{", "wideCmd", "+=", "string", "(", "b", ")", "+", "\"", "\\x00", "\"", "\n", "}", "\n\n", "// Base64 encode the command", "input", ":=", "[", "]", "uint8", "(", "wideCmd", ")", "\n", "encodedCmd", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "input", ")", "\n\n", "// Create the powershell.exe command line to execute the script", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "encodedCmd", ")", "\n", "}" ]
// Powershell wraps a PowerShell script // and prepares it for execution by the winrm client
[ "Powershell", "wraps", "a", "PowerShell", "script", "and", "prepares", "it", "for", "execution", "by", "the", "winrm", "client" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/powershell.go#L10-L23
2,055
masterzen/winrm
command.go
Close
func (c *Command) Close() error { if err := c.check(); err != nil { return err } select { // close cancel channel if it's still open case <-c.cancel: default: close(c.cancel) } request := NewSignalRequest(c.client.url, c.shell.id, c.id, &c.client.Parameters) defer request.Free() _, err := c.client.sendRequest(request) return err }
go
func (c *Command) Close() error { if err := c.check(); err != nil { return err } select { // close cancel channel if it's still open case <-c.cancel: default: close(c.cancel) } request := NewSignalRequest(c.client.url, c.shell.id, c.id, &c.client.Parameters) defer request.Free() _, err := c.client.sendRequest(request) return err }
[ "func", "(", "c", "*", "Command", ")", "Close", "(", ")", "error", "{", "if", "err", ":=", "c", ".", "check", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "select", "{", "// close cancel channel if it's still open", "case", "<-", "c", ".", "cancel", ":", "default", ":", "close", "(", "c", ".", "cancel", ")", "\n", "}", "\n\n", "request", ":=", "NewSignalRequest", "(", "c", ".", "client", ".", "url", ",", "c", ".", "shell", ".", "id", ",", "c", ".", "id", ",", "&", "c", ".", "client", ".", "Parameters", ")", "\n", "defer", "request", ".", "Free", "(", ")", "\n\n", "_", ",", "err", ":=", "c", ".", "client", ".", "sendRequest", "(", "request", ")", "\n", "return", "err", "\n", "}" ]
// Close will terminate the running command
[ "Close", "will", "terminate", "the", "running", "command" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/command.go#L104-L120
2,056
masterzen/winrm
command.go
Write
func (w *commandWriter) Write(data []byte) (int, error) { var ( written int err error ) for len(data) > 0 { if w.eof { return written, io.EOF } // never send more data than our EnvelopeSize. n := min(w.client.Parameters.EnvelopeSize-1000, len(data)) if err := w.sendInput(data[:n]); err != nil { break } data = data[n:] written += n } return written, err }
go
func (w *commandWriter) Write(data []byte) (int, error) { var ( written int err error ) for len(data) > 0 { if w.eof { return written, io.EOF } // never send more data than our EnvelopeSize. n := min(w.client.Parameters.EnvelopeSize-1000, len(data)) if err := w.sendInput(data[:n]); err != nil { break } data = data[n:] written += n } return written, err }
[ "func", "(", "w", "*", "commandWriter", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "var", "(", "written", "int", "\n", "err", "error", "\n", ")", "\n\n", "for", "len", "(", "data", ")", ">", "0", "{", "if", "w", ".", "eof", "{", "return", "written", ",", "io", ".", "EOF", "\n", "}", "\n", "// never send more data than our EnvelopeSize.", "n", ":=", "min", "(", "w", ".", "client", ".", "Parameters", ".", "EnvelopeSize", "-", "1000", ",", "len", "(", "data", ")", ")", "\n", "if", "err", ":=", "w", ".", "sendInput", "(", "data", "[", ":", "n", "]", ")", ";", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "data", "=", "data", "[", "n", ":", "]", "\n", "written", "+=", "n", "\n", "}", "\n\n", "return", "written", ",", "err", "\n", "}" ]
// Write data to this Pipe // commandWriter implements io.Writer interface
[ "Write", "data", "to", "this", "Pipe", "commandWriter", "implements", "io", ".", "Writer", "interface" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/command.go#L195-L216
2,057
masterzen/winrm
command.go
Read
func (r *commandReader) Read(buf []byte) (int, error) { n, err := r.read.Read(buf) if err != nil && err != io.EOF { return 0, err } return n, err }
go
func (r *commandReader) Read(buf []byte) (int, error) { n, err := r.read.Read(buf) if err != nil && err != io.EOF { return 0, err } return n, err }
[ "func", "(", "r", "*", "commandReader", ")", "Read", "(", "buf", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ",", "err", ":=", "r", ".", "read", ".", "Read", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "n", ",", "err", "\n", "}" ]
// Read data from this Pipe
[ "Read", "data", "from", "this", "Pipe" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/command.go#L233-L239
2,058
masterzen/winrm
client.go
CreateShell
func (c *Client) CreateShell() (*Shell, error) { request := NewOpenShellRequest(c.url, &c.Parameters) defer request.Free() response, err := c.sendRequest(request) if err != nil { return nil, err } shellID, err := ParseOpenShellResponse(response) if err != nil { return nil, err } return c.NewShell(shellID), nil }
go
func (c *Client) CreateShell() (*Shell, error) { request := NewOpenShellRequest(c.url, &c.Parameters) defer request.Free() response, err := c.sendRequest(request) if err != nil { return nil, err } shellID, err := ParseOpenShellResponse(response) if err != nil { return nil, err } return c.NewShell(shellID), nil }
[ "func", "(", "c", "*", "Client", ")", "CreateShell", "(", ")", "(", "*", "Shell", ",", "error", ")", "{", "request", ":=", "NewOpenShellRequest", "(", "c", ".", "url", ",", "&", "c", ".", "Parameters", ")", "\n", "defer", "request", ".", "Free", "(", ")", "\n\n", "response", ",", "err", ":=", "c", ".", "sendRequest", "(", "request", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "shellID", ",", "err", ":=", "ParseOpenShellResponse", "(", "response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "c", ".", "NewShell", "(", "shellID", ")", ",", "nil", "\n\n", "}" ]
// CreateShell will create a WinRM Shell, // which is the prealable for running commands.
[ "CreateShell", "will", "create", "a", "WinRM", "Shell", "which", "is", "the", "prealable", "for", "running", "commands", "." ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/client.go#L77-L93
2,059
masterzen/winrm
client.go
NewShell
func (c *Client) NewShell(id string) *Shell { return &Shell{client: c, id: id} }
go
func (c *Client) NewShell(id string) *Shell { return &Shell{client: c, id: id} }
[ "func", "(", "c", "*", "Client", ")", "NewShell", "(", "id", "string", ")", "*", "Shell", "{", "return", "&", "Shell", "{", "client", ":", "c", ",", "id", ":", "id", "}", "\n", "}" ]
// NewShell will create a new WinRM Shell for the given shellID
[ "NewShell", "will", "create", "a", "new", "WinRM", "Shell", "for", "the", "given", "shellID" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/client.go#L96-L98
2,060
masterzen/winrm
client.go
sendRequest
func (c *Client) sendRequest(request *soap.SoapMessage) (string, error) { return c.http.Post(c, request) }
go
func (c *Client) sendRequest(request *soap.SoapMessage) (string, error) { return c.http.Post(c, request) }
[ "func", "(", "c", "*", "Client", ")", "sendRequest", "(", "request", "*", "soap", ".", "SoapMessage", ")", "(", "string", ",", "error", ")", "{", "return", "c", ".", "http", ".", "Post", "(", "c", ",", "request", ")", "\n", "}" ]
// sendRequest exec the custom http func from the client
[ "sendRequest", "exec", "the", "custom", "http", "func", "from", "the", "client" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/client.go#L101-L103
2,061
masterzen/winrm
client.go
RunWithString
func (c *Client) RunWithString(command string, stdin string) (string, string, int, error) { shell, err := c.CreateShell() if err != nil { return "", "", 1, err } defer shell.Close() cmd, err := shell.Execute(command) if err != nil { return "", "", 1, err } if len(stdin) > 0 { cmd.Stdin.Write([]byte(stdin)) } var outWriter, errWriter bytes.Buffer var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() io.Copy(&outWriter, cmd.Stdout) }() go func() { defer wg.Done() io.Copy(&errWriter, cmd.Stderr) }() cmd.Wait() wg.Wait() return outWriter.String(), errWriter.String(), cmd.ExitCode(), cmd.err }
go
func (c *Client) RunWithString(command string, stdin string) (string, string, int, error) { shell, err := c.CreateShell() if err != nil { return "", "", 1, err } defer shell.Close() cmd, err := shell.Execute(command) if err != nil { return "", "", 1, err } if len(stdin) > 0 { cmd.Stdin.Write([]byte(stdin)) } var outWriter, errWriter bytes.Buffer var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() io.Copy(&outWriter, cmd.Stdout) }() go func() { defer wg.Done() io.Copy(&errWriter, cmd.Stderr) }() cmd.Wait() wg.Wait() return outWriter.String(), errWriter.String(), cmd.ExitCode(), cmd.err }
[ "func", "(", "c", "*", "Client", ")", "RunWithString", "(", "command", "string", ",", "stdin", "string", ")", "(", "string", ",", "string", ",", "int", ",", "error", ")", "{", "shell", ",", "err", ":=", "c", ".", "CreateShell", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "1", ",", "err", "\n", "}", "\n", "defer", "shell", ".", "Close", "(", ")", "\n\n", "cmd", ",", "err", ":=", "shell", ".", "Execute", "(", "command", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "1", ",", "err", "\n", "}", "\n", "if", "len", "(", "stdin", ")", ">", "0", "{", "cmd", ".", "Stdin", ".", "Write", "(", "[", "]", "byte", "(", "stdin", ")", ")", "\n", "}", "\n\n", "var", "outWriter", ",", "errWriter", "bytes", ".", "Buffer", "\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "wg", ".", "Add", "(", "2", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "io", ".", "Copy", "(", "&", "outWriter", ",", "cmd", ".", "Stdout", ")", "\n", "}", "(", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "io", ".", "Copy", "(", "&", "errWriter", ",", "cmd", ".", "Stderr", ")", "\n", "}", "(", ")", "\n\n", "cmd", ".", "Wait", "(", ")", "\n", "wg", ".", "Wait", "(", ")", "\n\n", "return", "outWriter", ".", "String", "(", ")", ",", "errWriter", ".", "String", "(", ")", ",", "cmd", ".", "ExitCode", "(", ")", ",", "cmd", ".", "err", "\n", "}" ]
// RunWithString will run command on the the remote host, returning the process stdout and stderr // as strings, and using the input stdin string as the process input
[ "RunWithString", "will", "run", "command", "on", "the", "the", "remote", "host", "returning", "the", "process", "stdout", "and", "stderr", "as", "strings", "and", "using", "the", "input", "stdin", "string", "as", "the", "process", "input" ]
1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e
https://github.com/masterzen/winrm/blob/1d17eaf15943ca3554cdebb3b1b10aaa543a0b7e/client.go#L139-L171
2,062
gordonklaus/ineffassign
ineffassign.go
maybePanic
func (bld *builder) maybePanic() { if len(bld.results) == 0 { return } res := bld.results[len(bld.results)-1] if res == nil { return } for _, f := range res.List { for _, id := range f.Names { bld.use(id) } } }
go
func (bld *builder) maybePanic() { if len(bld.results) == 0 { return } res := bld.results[len(bld.results)-1] if res == nil { return } for _, f := range res.List { for _, id := range f.Names { bld.use(id) } } }
[ "func", "(", "bld", "*", "builder", ")", "maybePanic", "(", ")", "{", "if", "len", "(", "bld", ".", "results", ")", "==", "0", "{", "return", "\n", "}", "\n", "res", ":=", "bld", ".", "results", "[", "len", "(", "bld", ".", "results", ")", "-", "1", "]", "\n", "if", "res", "==", "nil", "{", "return", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "res", ".", "List", "{", "for", "_", ",", "id", ":=", "range", "f", ".", "Names", "{", "bld", ".", "use", "(", "id", ")", "\n", "}", "\n", "}", "\n", "}" ]
// An operation that might panic marks named function results as used.
[ "An", "operation", "that", "might", "panic", "marks", "named", "function", "results", "as", "used", "." ]
1003c8bd00dc2869cb5ca5282e6ce33834fed514
https://github.com/gordonklaus/ineffassign/blob/1003c8bd00dc2869cb5ca5282e6ce33834fed514/ineffassign.go#L450-L463
2,063
cloudflare/golibs
bytepool/bytepool.go
Put
func (tp *BytePool) Put(el []byte) { if cap(el) < 1 || cap(el) > tp.maxSize { return } el = el[:cap(el)] o := log2Floor(uint32(cap(el))) p := &tp.list_of_pools[o] p.mu.Lock() p.list = append(p.list, el) p.mu.Unlock() }
go
func (tp *BytePool) Put(el []byte) { if cap(el) < 1 || cap(el) > tp.maxSize { return } el = el[:cap(el)] o := log2Floor(uint32(cap(el))) p := &tp.list_of_pools[o] p.mu.Lock() p.list = append(p.list, el) p.mu.Unlock() }
[ "func", "(", "tp", "*", "BytePool", ")", "Put", "(", "el", "[", "]", "byte", ")", "{", "if", "cap", "(", "el", ")", "<", "1", "||", "cap", "(", "el", ")", ">", "tp", ".", "maxSize", "{", "return", "\n", "}", "\n", "el", "=", "el", "[", ":", "cap", "(", "el", ")", "]", "\n", "o", ":=", "log2Floor", "(", "uint32", "(", "cap", "(", "el", ")", ")", ")", "\n", "p", ":=", "&", "tp", ".", "list_of_pools", "[", "o", "]", "\n", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "p", ".", "list", "=", "append", "(", "p", ".", "list", ",", "el", ")", "\n", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// Put the byte slice back in pool.
[ "Put", "the", "byte", "slice", "back", "in", "pool", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/bytepool/bytepool.go#L48-L58
2,064
cloudflare/golibs
bytepool/bytepool.go
Get
func (tp *BytePool) Get(size int) []byte { if size < 1 || size > tp.maxSize { return make([]byte, size) } var x []byte o := log2Ceil(uint32(size)) p := &tp.list_of_pools[o] p.mu.Lock() if n := len(p.list); n > 0 { x = p.list[n-1] p.list[n-1] = nil p.list = p.list[:n-1] } p.mu.Unlock() if x == nil { x = make([]byte, 1<<o) } return x[:size] }
go
func (tp *BytePool) Get(size int) []byte { if size < 1 || size > tp.maxSize { return make([]byte, size) } var x []byte o := log2Ceil(uint32(size)) p := &tp.list_of_pools[o] p.mu.Lock() if n := len(p.list); n > 0 { x = p.list[n-1] p.list[n-1] = nil p.list = p.list[:n-1] } p.mu.Unlock() if x == nil { x = make([]byte, 1<<o) } return x[:size] }
[ "func", "(", "tp", "*", "BytePool", ")", "Get", "(", "size", "int", ")", "[", "]", "byte", "{", "if", "size", "<", "1", "||", "size", ">", "tp", ".", "maxSize", "{", "return", "make", "(", "[", "]", "byte", ",", "size", ")", "\n", "}", "\n", "var", "x", "[", "]", "byte", "\n\n", "o", ":=", "log2Ceil", "(", "uint32", "(", "size", ")", ")", "\n", "p", ":=", "&", "tp", ".", "list_of_pools", "[", "o", "]", "\n", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "n", ":=", "len", "(", "p", ".", "list", ")", ";", "n", ">", "0", "{", "x", "=", "p", ".", "list", "[", "n", "-", "1", "]", "\n", "p", ".", "list", "[", "n", "-", "1", "]", "=", "nil", "\n", "p", ".", "list", "=", "p", ".", "list", "[", ":", "n", "-", "1", "]", "\n", "}", "\n", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "x", "==", "nil", "{", "x", "=", "make", "(", "[", "]", "byte", ",", "1", "<<", "o", ")", "\n", "}", "\n", "return", "x", "[", ":", "size", "]", "\n", "}" ]
// Get a byte slice from the pool.
[ "Get", "a", "byte", "slice", "from", "the", "pool", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/bytepool/bytepool.go#L61-L80
2,065
cloudflare/golibs
bytepool/bytepool.go
Drain
func (tp *BytePool) Drain() { for o := 0; o < len(tp.list_of_pools); o++ { p := &tp.list_of_pools[o] p.mu.Lock() p.list = make([][]byte, 0, cap(p.list)/2) p.mu.Unlock() } }
go
func (tp *BytePool) Drain() { for o := 0; o < len(tp.list_of_pools); o++ { p := &tp.list_of_pools[o] p.mu.Lock() p.list = make([][]byte, 0, cap(p.list)/2) p.mu.Unlock() } }
[ "func", "(", "tp", "*", "BytePool", ")", "Drain", "(", ")", "{", "for", "o", ":=", "0", ";", "o", "<", "len", "(", "tp", ".", "list_of_pools", ")", ";", "o", "++", "{", "p", ":=", "&", "tp", ".", "list_of_pools", "[", "o", "]", "\n", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "p", ".", "list", "=", "make", "(", "[", "]", "[", "]", "byte", ",", "0", ",", "cap", "(", "p", ".", "list", ")", "/", "2", ")", "\n", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// Drain removes all items from the pool and make them availabe for garbage // collection.
[ "Drain", "removes", "all", "items", "from", "the", "pool", "and", "make", "them", "availabe", "for", "garbage", "collection", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/bytepool/bytepool.go#L84-L91
2,066
cloudflare/golibs
bytepool/bytepool.go
Close
func (tp *BytePool) Close() { tp.Drain() if tp.drainTicker != nil { tp.drainTicker.Stop() tp.drainTicker = nil } }
go
func (tp *BytePool) Close() { tp.Drain() if tp.drainTicker != nil { tp.drainTicker.Stop() tp.drainTicker = nil } }
[ "func", "(", "tp", "*", "BytePool", ")", "Close", "(", ")", "{", "tp", ".", "Drain", "(", ")", "\n", "if", "tp", ".", "drainTicker", "!=", "nil", "{", "tp", ".", "drainTicker", ".", "Stop", "(", ")", "\n", "tp", ".", "drainTicker", "=", "nil", "\n", "}", "\n", "}" ]
// Stop the drain ticker.
[ "Stop", "the", "drain", "ticker", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/bytepool/bytepool.go#L94-L100
2,067
cloudflare/golibs
bytepool/bytepool.go
entries
func (tp *BytePool) entries() uint { var s uint for o := 0; o < len(tp.list_of_pools); o++ { p := &tp.list_of_pools[o] p.mu.Lock() s += uint(len(p.list)) p.mu.Unlock() } return s }
go
func (tp *BytePool) entries() uint { var s uint for o := 0; o < len(tp.list_of_pools); o++ { p := &tp.list_of_pools[o] p.mu.Lock() s += uint(len(p.list)) p.mu.Unlock() } return s }
[ "func", "(", "tp", "*", "BytePool", ")", "entries", "(", ")", "uint", "{", "var", "s", "uint", "\n", "for", "o", ":=", "0", ";", "o", "<", "len", "(", "tp", ".", "list_of_pools", ")", ";", "o", "++", "{", "p", ":=", "&", "tp", ".", "list_of_pools", "[", "o", "]", "\n", "p", ".", "mu", ".", "Lock", "(", ")", "\n", "s", "+=", "uint", "(", "len", "(", "p", ".", "list", ")", ")", "\n", "p", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Get number of entries, for debugging
[ "Get", "number", "of", "entries", "for", "debugging" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/bytepool/bytepool.go#L103-L112
2,068
cloudflare/golibs
tokenbucket/bucket.go
New
func New(num int, rate float64, depth uint64) *Filter { b := new(Filter) if depth <= 0 { panic("depth of bucket must be greater than 0") } b.touchCost = uint64((float64(1*time.Second) / rate)) b.creditMax = depth * b.touchCost b.items = make([]item, num) // Not the full range of a uint64, but we can // live with 2 bits of entropy missing b.key0 = uint64(rand.Int63()) b.key1 = uint64(rand.Int63()) return b }
go
func New(num int, rate float64, depth uint64) *Filter { b := new(Filter) if depth <= 0 { panic("depth of bucket must be greater than 0") } b.touchCost = uint64((float64(1*time.Second) / rate)) b.creditMax = depth * b.touchCost b.items = make([]item, num) // Not the full range of a uint64, but we can // live with 2 bits of entropy missing b.key0 = uint64(rand.Int63()) b.key1 = uint64(rand.Int63()) return b }
[ "func", "New", "(", "num", "int", ",", "rate", "float64", ",", "depth", "uint64", ")", "*", "Filter", "{", "b", ":=", "new", "(", "Filter", ")", "\n", "if", "depth", "<=", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "b", ".", "touchCost", "=", "uint64", "(", "(", "float64", "(", "1", "*", "time", ".", "Second", ")", "/", "rate", ")", ")", "\n", "b", ".", "creditMax", "=", "depth", "*", "b", ".", "touchCost", "\n", "b", ".", "items", "=", "make", "(", "[", "]", "item", ",", "num", ")", "\n\n", "// Not the full range of a uint64, but we can", "// live with 2 bits of entropy missing", "b", ".", "key0", "=", "uint64", "(", "rand", ".", "Int63", "(", ")", ")", "\n", "b", ".", "key1", "=", "uint64", "(", "rand", ".", "Int63", "(", ")", ")", "\n\n", "return", "b", "\n", "}" ]
// New creates a new token bucket filter with num buckets, accruing tokens at rate per second. The depth specifies // the depth of the bucket.
[ "New", "creates", "a", "new", "token", "bucket", "filter", "with", "num", "buckets", "accruing", "tokens", "at", "rate", "per", "second", ".", "The", "depth", "specifies", "the", "depth", "of", "the", "bucket", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/tokenbucket/bucket.go#L27-L42
2,069
cloudflare/golibs
tokenbucket/bucket.go
Touch
func (b *Filter) Touch(d []byte) bool { n := len(b.items) h := hash(b.key0, b.key1, d) i := h % uint64(n) return b.touch(&b.items[i]) }
go
func (b *Filter) Touch(d []byte) bool { n := len(b.items) h := hash(b.key0, b.key1, d) i := h % uint64(n) return b.touch(&b.items[i]) }
[ "func", "(", "b", "*", "Filter", ")", "Touch", "(", "d", "[", "]", "byte", ")", "bool", "{", "n", ":=", "len", "(", "b", ".", "items", ")", "\n", "h", ":=", "hash", "(", "b", ".", "key0", ",", "b", ".", "key1", ",", "d", ")", "\n", "i", ":=", "h", "%", "uint64", "(", "n", ")", "\n", "return", "b", ".", "touch", "(", "&", "b", ".", "items", "[", "i", "]", ")", "\n", "}" ]
// Touch finds the token bucket for d, takes a token out of it and reports if // there are still tokens left in the bucket.
[ "Touch", "finds", "the", "token", "bucket", "for", "d", "takes", "a", "token", "out", "of", "it", "and", "reports", "if", "there", "are", "still", "tokens", "left", "in", "the", "bucket", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/tokenbucket/bucket.go#L63-L68
2,070
cloudflare/golibs
lrucache/lrucache.go
expiredEntry
func (b *LRUCache) expiredEntry(now time.Time) *entry { if len(b.priorityQueue) == 0 { return nil } if now.IsZero() { // Fill it only when actually used. now = time.Now() } if e := b.priorityQueue[0]; e.expire.Before(now) { return e } return nil }
go
func (b *LRUCache) expiredEntry(now time.Time) *entry { if len(b.priorityQueue) == 0 { return nil } if now.IsZero() { // Fill it only when actually used. now = time.Now() } if e := b.priorityQueue[0]; e.expire.Before(now) { return e } return nil }
[ "func", "(", "b", "*", "LRUCache", ")", "expiredEntry", "(", "now", "time", ".", "Time", ")", "*", "entry", "{", "if", "len", "(", "b", ".", "priorityQueue", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "if", "now", ".", "IsZero", "(", ")", "{", "// Fill it only when actually used.", "now", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "if", "e", ":=", "b", ".", "priorityQueue", "[", "0", "]", ";", "e", ".", "expire", ".", "Before", "(", "now", ")", "{", "return", "e", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Give me the entry with lowest expiry field if it's before now.
[ "Give", "me", "the", "entry", "with", "lowest", "expiry", "field", "if", "it", "s", "before", "now", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/lrucache.go#L60-L74
2,071
cloudflare/golibs
lrucache/lrucache.go
Len
func (b *LRUCache) Len() int { // yes. this stupid thing requires locking b.lock.Lock() defer b.lock.Unlock() return b.lruList.Len() }
go
func (b *LRUCache) Len() int { // yes. this stupid thing requires locking b.lock.Lock() defer b.lock.Unlock() return b.lruList.Len() }
[ "func", "(", "b", "*", "LRUCache", ")", "Len", "(", ")", "int", "{", "// yes. this stupid thing requires locking", "b", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "return", "b", ".", "lruList", ".", "Len", "(", ")", "\n", "}" ]
// Number of entries used in the LRU
[ "Number", "of", "entries", "used", "in", "the", "LRU" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/lrucache.go#L301-L307
2,072
cloudflare/golibs
spacesaving/rate.go
Init
func (ss *Rate) Init(size uint32, halfLife time.Duration) *Rate { *ss = Rate{ keytobucketno: make(map[string]uint32, size), buckets: make([]bucket, size), weightHelper: -math.Ln2 / float64(halfLife.Nanoseconds()), halfLife: halfLife, } ss.sh.h = make([]uint32, size) ss.sh.ss = ss heap.Init(&ss.sh) for i := uint32(0); i < uint32(size); i++ { ss.sh.h[i] = i ss.buckets[i].idx = i } return ss }
go
func (ss *Rate) Init(size uint32, halfLife time.Duration) *Rate { *ss = Rate{ keytobucketno: make(map[string]uint32, size), buckets: make([]bucket, size), weightHelper: -math.Ln2 / float64(halfLife.Nanoseconds()), halfLife: halfLife, } ss.sh.h = make([]uint32, size) ss.sh.ss = ss heap.Init(&ss.sh) for i := uint32(0); i < uint32(size); i++ { ss.sh.h[i] = i ss.buckets[i].idx = i } return ss }
[ "func", "(", "ss", "*", "Rate", ")", "Init", "(", "size", "uint32", ",", "halfLife", "time", ".", "Duration", ")", "*", "Rate", "{", "*", "ss", "=", "Rate", "{", "keytobucketno", ":", "make", "(", "map", "[", "string", "]", "uint32", ",", "size", ")", ",", "buckets", ":", "make", "(", "[", "]", "bucket", ",", "size", ")", ",", "weightHelper", ":", "-", "math", ".", "Ln2", "/", "float64", "(", "halfLife", ".", "Nanoseconds", "(", ")", ")", ",", "halfLife", ":", "halfLife", ",", "}", "\n", "ss", ".", "sh", ".", "h", "=", "make", "(", "[", "]", "uint32", ",", "size", ")", "\n", "ss", ".", "sh", ".", "ss", "=", "ss", "\n", "heap", ".", "Init", "(", "&", "ss", ".", "sh", ")", "\n", "for", "i", ":=", "uint32", "(", "0", ")", ";", "i", "<", "uint32", "(", "size", ")", ";", "i", "++", "{", "ss", ".", "sh", ".", "h", "[", "i", "]", "=", "i", "\n", "ss", ".", "buckets", "[", "i", "]", ".", "idx", "=", "i", "\n", "}", "\n", "return", "ss", "\n", "}" ]
// Initialize already allocated Rate structure. // // Size stands for number of items to track in the stream. HalfLife determines // the time required half-charge or half-discharge a rate counter.
[ "Initialize", "already", "allocated", "Rate", "structure", ".", "Size", "stands", "for", "number", "of", "items", "to", "track", "in", "the", "stream", ".", "HalfLife", "determines", "the", "time", "required", "half", "-", "charge", "or", "half", "-", "discharge", "a", "rate", "counter", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/spacesaving/rate.go#L97-L112
2,073
cloudflare/golibs
spacesaving/rate.go
Touch
func (ss *Rate) Touch(key string, nowTs time.Time) { now := nowTs.UnixNano() var bucket *bucket if bucketno, found := ss.keytobucketno[key]; found { bucket = &ss.buckets[bucketno] } else { bucketno = uint32(ss.sh.h[0]) bucket = &ss.buckets[bucketno] delete(ss.keytobucketno, bucket.key) ss.keytobucketno[key] = bucketno bucket.key, bucket.errLastTs, bucket.errRate = key, bucket.lastTs, bucket.rate } if bucket.lastTs != 0 { bucket.rate = ss.count(bucket.rate, bucket.lastTs, now) } bucket.lastTs = now // Even lastTs change may change ordering. heap.Fix(&ss.sh, int(bucket.idx)) }
go
func (ss *Rate) Touch(key string, nowTs time.Time) { now := nowTs.UnixNano() var bucket *bucket if bucketno, found := ss.keytobucketno[key]; found { bucket = &ss.buckets[bucketno] } else { bucketno = uint32(ss.sh.h[0]) bucket = &ss.buckets[bucketno] delete(ss.keytobucketno, bucket.key) ss.keytobucketno[key] = bucketno bucket.key, bucket.errLastTs, bucket.errRate = key, bucket.lastTs, bucket.rate } if bucket.lastTs != 0 { bucket.rate = ss.count(bucket.rate, bucket.lastTs, now) } bucket.lastTs = now // Even lastTs change may change ordering. heap.Fix(&ss.sh, int(bucket.idx)) }
[ "func", "(", "ss", "*", "Rate", ")", "Touch", "(", "key", "string", ",", "nowTs", "time", ".", "Time", ")", "{", "now", ":=", "nowTs", ".", "UnixNano", "(", ")", "\n\n", "var", "bucket", "*", "bucket", "\n", "if", "bucketno", ",", "found", ":=", "ss", ".", "keytobucketno", "[", "key", "]", ";", "found", "{", "bucket", "=", "&", "ss", ".", "buckets", "[", "bucketno", "]", "\n", "}", "else", "{", "bucketno", "=", "uint32", "(", "ss", ".", "sh", ".", "h", "[", "0", "]", ")", "\n\n", "bucket", "=", "&", "ss", ".", "buckets", "[", "bucketno", "]", "\n", "delete", "(", "ss", ".", "keytobucketno", ",", "bucket", ".", "key", ")", "\n", "ss", ".", "keytobucketno", "[", "key", "]", "=", "bucketno", "\n\n", "bucket", ".", "key", ",", "bucket", ".", "errLastTs", ",", "bucket", ".", "errRate", "=", "key", ",", "bucket", ".", "lastTs", ",", "bucket", ".", "rate", "\n", "}", "\n\n", "if", "bucket", ".", "lastTs", "!=", "0", "{", "bucket", ".", "rate", "=", "ss", ".", "count", "(", "bucket", ".", "rate", ",", "bucket", ".", "lastTs", ",", "now", ")", "\n", "}", "\n", "bucket", ".", "lastTs", "=", "now", "\n\n", "// Even lastTs change may change ordering.", "heap", ".", "Fix", "(", "&", "ss", ".", "sh", ",", "int", "(", "bucket", ".", "idx", ")", ")", "\n", "}" ]
// Mark an event happening, using given timestamp. // // The implementation assumes time is monotonic, the behaviour is undefined in // the case of time going back. This operation has logarithmic complexity.
[ "Mark", "an", "event", "happening", "using", "given", "timestamp", ".", "The", "implementation", "assumes", "time", "is", "monotonic", "the", "behaviour", "is", "undefined", "in", "the", "case", "of", "time", "going", "back", ".", "This", "operation", "has", "logarithmic", "complexity", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/spacesaving/rate.go#L118-L142
2,074
cloudflare/golibs
spacesaving/rate.go
GetSingle
func (ss *Rate) GetSingle(key string, nowTs time.Time) (float64, float64) { now := nowTs.UnixNano() var bucket *bucket if bucketno, found := ss.keytobucketno[key]; found { bucket = &ss.buckets[bucketno] rate := ss.recount(bucket.rate, bucket.lastTs, now) errRate := ss.recount(bucket.errRate, bucket.errLastTs, now) return rate - errRate, rate } else { bucketno = uint32(ss.sh.h[0]) bucket = &ss.buckets[bucketno] errRate := ss.recount(bucket.rate, bucket.lastTs, now) return 0, errRate } }
go
func (ss *Rate) GetSingle(key string, nowTs time.Time) (float64, float64) { now := nowTs.UnixNano() var bucket *bucket if bucketno, found := ss.keytobucketno[key]; found { bucket = &ss.buckets[bucketno] rate := ss.recount(bucket.rate, bucket.lastTs, now) errRate := ss.recount(bucket.errRate, bucket.errLastTs, now) return rate - errRate, rate } else { bucketno = uint32(ss.sh.h[0]) bucket = &ss.buckets[bucketno] errRate := ss.recount(bucket.rate, bucket.lastTs, now) return 0, errRate } }
[ "func", "(", "ss", "*", "Rate", ")", "GetSingle", "(", "key", "string", ",", "nowTs", "time", ".", "Time", ")", "(", "float64", ",", "float64", ")", "{", "now", ":=", "nowTs", ".", "UnixNano", "(", ")", "\n", "var", "bucket", "*", "bucket", "\n", "if", "bucketno", ",", "found", ":=", "ss", ".", "keytobucketno", "[", "key", "]", ";", "found", "{", "bucket", "=", "&", "ss", ".", "buckets", "[", "bucketno", "]", "\n", "rate", ":=", "ss", ".", "recount", "(", "bucket", ".", "rate", ",", "bucket", ".", "lastTs", ",", "now", ")", "\n", "errRate", ":=", "ss", ".", "recount", "(", "bucket", ".", "errRate", ",", "bucket", ".", "errLastTs", ",", "now", ")", "\n", "return", "rate", "-", "errRate", ",", "rate", "\n", "}", "else", "{", "bucketno", "=", "uint32", "(", "ss", ".", "sh", ".", "h", "[", "0", "]", ")", "\n", "bucket", "=", "&", "ss", ".", "buckets", "[", "bucketno", "]", "\n", "errRate", ":=", "ss", ".", "recount", "(", "bucket", ".", "rate", ",", "bucket", ".", "lastTs", ",", "now", ")", "\n", "return", "0", ",", "errRate", "\n", "}", "\n\n", "}" ]
// GetSingle gets the lower and upper bounds of a range for a single element. If the // element isn't tracked lower bound will be zero and upper bound will be the // lowest bound of all the tracked items.
[ "GetSingle", "gets", "the", "lower", "and", "upper", "bounds", "of", "a", "range", "for", "a", "single", "element", ".", "If", "the", "element", "isn", "t", "tracked", "lower", "bound", "will", "be", "zero", "and", "upper", "bound", "will", "be", "the", "lowest", "bound", "of", "all", "the", "tracked", "items", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/spacesaving/rate.go#L196-L211
2,075
cloudflare/golibs
ewma/ewma.go
Init
func (e *Ewma) Init(halfLife time.Duration) *Ewma { *e = Ewma{ weightHelper: -math.Ln2 / float64(halfLife.Nanoseconds()), } return e }
go
func (e *Ewma) Init(halfLife time.Duration) *Ewma { *e = Ewma{ weightHelper: -math.Ln2 / float64(halfLife.Nanoseconds()), } return e }
[ "func", "(", "e", "*", "Ewma", ")", "Init", "(", "halfLife", "time", ".", "Duration", ")", "*", "Ewma", "{", "*", "e", "=", "Ewma", "{", "weightHelper", ":", "-", "math", ".", "Ln2", "/", "float64", "(", "halfLife", ".", "Nanoseconds", "(", ")", ")", ",", "}", "\n", "return", "e", "\n", "}" ]
// Initialize already allocated NewEwma structure // // halfLife it the time takes for a half charge or half discharge
[ "Initialize", "already", "allocated", "NewEwma", "structure", "halfLife", "it", "the", "time", "takes", "for", "a", "half", "charge", "or", "half", "discharge" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/ewma/ewma.go#L37-L42
2,076
cloudflare/golibs
ewma/ewma.go
UpdateNow
func (e *Ewma) UpdateNow(value float64) float64 { return e.Update(value, time.Now()) }
go
func (e *Ewma) UpdateNow(value float64) float64 { return e.Update(value, time.Now()) }
[ "func", "(", "e", "*", "Ewma", ")", "UpdateNow", "(", "value", "float64", ")", "float64", "{", "return", "e", ".", "Update", "(", "value", ",", "time", ".", "Now", "(", ")", ")", "\n", "}" ]
// Update moving average with the value. // // Uses system clock to determine current time to count wight. Returns // updated moving avarage.
[ "Update", "moving", "average", "with", "the", "value", ".", "Uses", "system", "clock", "to", "determine", "current", "time", "to", "count", "wight", ".", "Returns", "updated", "moving", "avarage", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/ewma/ewma.go#L54-L56
2,077
cloudflare/golibs
ewma/ewma.go
Update
func (e *Ewma) Update(next float64, timestamp time.Time) float64 { if timestamp.Before(e.lastTimestamp) || timestamp == e.lastTimestamp { return e.Current } if e.lastTimestamp.IsZero() { // Ignore the first sample e.lastTimestamp = timestamp return e.Current } timeDelta := timestamp.Sub(e.lastTimestamp) e.lastTimestamp = timestamp e.Current = e.count(next, timeDelta) return e.Current }
go
func (e *Ewma) Update(next float64, timestamp time.Time) float64 { if timestamp.Before(e.lastTimestamp) || timestamp == e.lastTimestamp { return e.Current } if e.lastTimestamp.IsZero() { // Ignore the first sample e.lastTimestamp = timestamp return e.Current } timeDelta := timestamp.Sub(e.lastTimestamp) e.lastTimestamp = timestamp e.Current = e.count(next, timeDelta) return e.Current }
[ "func", "(", "e", "*", "Ewma", ")", "Update", "(", "next", "float64", ",", "timestamp", "time", ".", "Time", ")", "float64", "{", "if", "timestamp", ".", "Before", "(", "e", ".", "lastTimestamp", ")", "||", "timestamp", "==", "e", ".", "lastTimestamp", "{", "return", "e", ".", "Current", "\n", "}", "\n\n", "if", "e", ".", "lastTimestamp", ".", "IsZero", "(", ")", "{", "// Ignore the first sample", "e", ".", "lastTimestamp", "=", "timestamp", "\n", "return", "e", ".", "Current", "\n", "}", "\n\n", "timeDelta", ":=", "timestamp", ".", "Sub", "(", "e", ".", "lastTimestamp", ")", "\n", "e", ".", "lastTimestamp", "=", "timestamp", "\n\n", "e", ".", "Current", "=", "e", ".", "count", "(", "next", ",", "timeDelta", ")", "\n", "return", "e", ".", "Current", "\n", "}" ]
// Update moving average with the value, using given time as weight // // Returns updated moving avarage.
[ "Update", "moving", "average", "with", "the", "value", "using", "given", "time", "as", "weight", "Returns", "updated", "moving", "avarage", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/ewma/ewma.go#L61-L77
2,078
cloudflare/golibs
lrucache/multilru.go
Init
func (m *MultiLRUCache) Init(buckets, bucket_capacity uint) { m.buckets = buckets m.cache = make([]*LRUCache, buckets) for i := uint(0); i < buckets; i++ { m.cache[i] = NewLRUCache(bucket_capacity) } }
go
func (m *MultiLRUCache) Init(buckets, bucket_capacity uint) { m.buckets = buckets m.cache = make([]*LRUCache, buckets) for i := uint(0); i < buckets; i++ { m.cache[i] = NewLRUCache(bucket_capacity) } }
[ "func", "(", "m", "*", "MultiLRUCache", ")", "Init", "(", "buckets", ",", "bucket_capacity", "uint", ")", "{", "m", ".", "buckets", "=", "buckets", "\n", "m", ".", "cache", "=", "make", "(", "[", "]", "*", "LRUCache", ",", "buckets", ")", "\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", "buckets", ";", "i", "++", "{", "m", ".", "cache", "[", "i", "]", "=", "NewLRUCache", "(", "bucket_capacity", ")", "\n", "}", "\n", "}" ]
// Using this constructor is almost always wrong. Use NewMultiLRUCache instead.
[ "Using", "this", "constructor", "is", "almost", "always", "wrong", ".", "Use", "NewMultiLRUCache", "instead", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/multilru.go#L18-L24
2,079
cloudflare/golibs
lrucache/multilru.go
SetExpireGracePeriod
func (m *MultiLRUCache) SetExpireGracePeriod(p time.Duration) { for _, c := range m.cache { c.ExpireGracePeriod = p } }
go
func (m *MultiLRUCache) SetExpireGracePeriod(p time.Duration) { for _, c := range m.cache { c.ExpireGracePeriod = p } }
[ "func", "(", "m", "*", "MultiLRUCache", ")", "SetExpireGracePeriod", "(", "p", "time", ".", "Duration", ")", "{", "for", "_", ",", "c", ":=", "range", "m", ".", "cache", "{", "c", ".", "ExpireGracePeriod", "=", "p", "\n", "}", "\n", "}" ]
// Set the stale expiry grace period for each cache in the multicache instance.
[ "Set", "the", "stale", "expiry", "grace", "period", "for", "each", "cache", "in", "the", "multicache", "instance", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/multilru.go#L27-L31
2,080
cloudflare/golibs
ewma/rate.go
Init
func (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate { r.Ewma.Init(halfLife) return r }
go
func (r *EwmaRate) Init(halfLife time.Duration) *EwmaRate { r.Ewma.Init(halfLife) return r }
[ "func", "(", "r", "*", "EwmaRate", ")", "Init", "(", "halfLife", "time", ".", "Duration", ")", "*", "EwmaRate", "{", "r", ".", "Ewma", ".", "Init", "(", "halfLife", ")", "\n", "return", "r", "\n", "}" ]
// Initialize already allocated NewEwmaRate structure // // halfLife it the time takes for a half charge or half discharge
[ "Initialize", "already", "allocated", "NewEwmaRate", "structure", "halfLife", "it", "the", "time", "takes", "for", "a", "half", "charge", "or", "half", "discharge" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/ewma/rate.go#L30-L33
2,081
cloudflare/golibs
ewma/rate.go
Update
func (r *EwmaRate) Update(now time.Time) float64 { timeDelta := now.Sub(r.lastTimestamp) return r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now) }
go
func (r *EwmaRate) Update(now time.Time) float64 { timeDelta := now.Sub(r.lastTimestamp) return r.Ewma.Update(nanosec/float64(timeDelta.Nanoseconds()), now) }
[ "func", "(", "r", "*", "EwmaRate", ")", "Update", "(", "now", "time", ".", "Time", ")", "float64", "{", "timeDelta", ":=", "now", ".", "Sub", "(", "r", ".", "lastTimestamp", ")", "\n", "return", "r", ".", "Ewma", ".", "Update", "(", "nanosec", "/", "float64", "(", "timeDelta", ".", "Nanoseconds", "(", ")", ")", ",", "now", ")", "\n", "}" ]
// Notify of an event happening, with specified current time. // // Returns current rate.
[ "Notify", "of", "an", "event", "happening", "with", "specified", "current", "time", ".", "Returns", "current", "rate", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/ewma/rate.go#L45-L48
2,082
cloudflare/golibs
ewma/rate.go
Current
func (r *EwmaRate) Current(now time.Time) float64 { if r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) { return r.Ewma.Current } timeDelta := now.Sub(r.lastTimestamp) // Count as if nothing was received since last update and // don't save anything. return r.count(0, timeDelta) }
go
func (r *EwmaRate) Current(now time.Time) float64 { if r.lastTimestamp.IsZero() || r.lastTimestamp == now || now.Before(r.lastTimestamp) { return r.Ewma.Current } timeDelta := now.Sub(r.lastTimestamp) // Count as if nothing was received since last update and // don't save anything. return r.count(0, timeDelta) }
[ "func", "(", "r", "*", "EwmaRate", ")", "Current", "(", "now", "time", ".", "Time", ")", "float64", "{", "if", "r", ".", "lastTimestamp", ".", "IsZero", "(", ")", "||", "r", ".", "lastTimestamp", "==", "now", "||", "now", ".", "Before", "(", "r", ".", "lastTimestamp", ")", "{", "return", "r", ".", "Ewma", ".", "Current", "\n", "}", "\n\n", "timeDelta", ":=", "now", ".", "Sub", "(", "r", ".", "lastTimestamp", ")", "\n\n", "// Count as if nothing was received since last update and", "// don't save anything.", "return", "r", ".", "count", "(", "0", ",", "timeDelta", ")", "\n", "}" ]
// Current reads the rate of events per second, with specified current time.
[ "Current", "reads", "the", "rate", "of", "events", "per", "second", "with", "specified", "current", "time", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/ewma/rate.go#L58-L68
2,083
cloudflare/golibs
circularbuffer/circularbuffer.go
NewCircularBuffer
func NewCircularBuffer(size uint) *CircularBuffer { return &CircularBuffer{ buffer: make([]interface{}, size), size: size, avail: make(chan bool, size), } }
go
func NewCircularBuffer(size uint) *CircularBuffer { return &CircularBuffer{ buffer: make([]interface{}, size), size: size, avail: make(chan bool, size), } }
[ "func", "NewCircularBuffer", "(", "size", "uint", ")", "*", "CircularBuffer", "{", "return", "&", "CircularBuffer", "{", "buffer", ":", "make", "(", "[", "]", "interface", "{", "}", ",", "size", ")", ",", "size", ":", "size", ",", "avail", ":", "make", "(", "chan", "bool", ",", "size", ")", ",", "}", "\n", "}" ]
// Create CircularBuffer object with a prealocated buffer of a given size.
[ "Create", "CircularBuffer", "object", "with", "a", "prealocated", "buffer", "of", "a", "given", "size", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/circularbuffer/circularbuffer.go#L60-L66
2,084
cloudflare/golibs
kt/kt_metrics.go
NewTrackedConn
func NewTrackedConn(host string, port int, poolsize int, timeout time.Duration, opTimer *prometheus.SummaryVec) (*TrackedConn, error) { conn, err := NewConn(host, port, poolsize, timeout) if err != nil { return nil, err } return &TrackedConn{ kt: conn, opTimer: opTimer}, nil }
go
func NewTrackedConn(host string, port int, poolsize int, timeout time.Duration, opTimer *prometheus.SummaryVec) (*TrackedConn, error) { conn, err := NewConn(host, port, poolsize, timeout) if err != nil { return nil, err } return &TrackedConn{ kt: conn, opTimer: opTimer}, nil }
[ "func", "NewTrackedConn", "(", "host", "string", ",", "port", "int", ",", "poolsize", "int", ",", "timeout", "time", ".", "Duration", ",", "opTimer", "*", "prometheus", ".", "SummaryVec", ")", "(", "*", "TrackedConn", ",", "error", ")", "{", "conn", ",", "err", ":=", "NewConn", "(", "host", ",", "port", ",", "poolsize", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "TrackedConn", "{", "kt", ":", "conn", ",", "opTimer", ":", "opTimer", "}", ",", "nil", "\n", "}" ]
// NewTrackedConn creates a new connection to a Kyoto Tycoon endpoint, and tracks // operations made to it using prometheus metrics. // All supported operations are tracked, opTimer times the number of seconds // each type of operation took, generating a summary.
[ "NewTrackedConn", "creates", "a", "new", "connection", "to", "a", "Kyoto", "Tycoon", "endpoint", "and", "tracks", "operations", "made", "to", "it", "using", "prometheus", "metrics", ".", "All", "supported", "operations", "are", "tracked", "opTimer", "times", "the", "number", "of", "seconds", "each", "type", "of", "operation", "took", "generating", "a", "summary", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt_metrics.go#L33-L43
2,085
cloudflare/golibs
kt/kt_metrics.go
NewTrackedConnFromConn
func NewTrackedConnFromConn(conn *Conn, opTimer *prometheus.SummaryVec) (*TrackedConn, error) { return &TrackedConn{ kt: conn, opTimer: opTimer}, nil }
go
func NewTrackedConnFromConn(conn *Conn, opTimer *prometheus.SummaryVec) (*TrackedConn, error) { return &TrackedConn{ kt: conn, opTimer: opTimer}, nil }
[ "func", "NewTrackedConnFromConn", "(", "conn", "*", "Conn", ",", "opTimer", "*", "prometheus", ".", "SummaryVec", ")", "(", "*", "TrackedConn", ",", "error", ")", "{", "return", "&", "TrackedConn", "{", "kt", ":", "conn", ",", "opTimer", ":", "opTimer", "}", ",", "nil", "\n", "}" ]
// NewTrackedConnFromConn returns a tracked connection that simply wraps the given // database connection.
[ "NewTrackedConnFromConn", "returns", "a", "tracked", "connection", "that", "simply", "wraps", "the", "given", "database", "connection", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt_metrics.go#L47-L51
2,086
cloudflare/golibs
lrucache/list.go
Front
func (l *list) Front() *element { if l.len == 0 { return nil } return l.root.next }
go
func (l *list) Front() *element { if l.len == 0 { return nil } return l.root.next }
[ "func", "(", "l", "*", "list", ")", "Front", "(", ")", "*", "element", "{", "if", "l", ".", "len", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "l", ".", "root", ".", "next", "\n", "}" ]
// Front returns the first element of list l or nil
[ "Front", "returns", "the", "first", "element", "of", "list", "l", "or", "nil" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L102-L107
2,087
cloudflare/golibs
lrucache/list.go
Back
func (l *list) Back() *element { if l.len == 0 { return nil } return l.root.prev }
go
func (l *list) Back() *element { if l.len == 0 { return nil } return l.root.prev }
[ "func", "(", "l", "*", "list", ")", "Back", "(", ")", "*", "element", "{", "if", "l", ".", "len", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "l", ".", "root", ".", "prev", "\n", "}" ]
// Back returns the last element of list l or nil.
[ "Back", "returns", "the", "last", "element", "of", "list", "l", "or", "nil", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L110-L115
2,088
cloudflare/golibs
lrucache/list.go
InsertBefore
func (l *list) InsertBefore(v interface{}, mark *element) *element { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark.prev) }
go
func (l *list) InsertBefore(v interface{}, mark *element) *element { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark.prev) }
[ "func", "(", "l", "*", "list", ")", "InsertBefore", "(", "v", "interface", "{", "}", ",", "mark", "*", "element", ")", "*", "element", "{", "if", "mark", ".", "list", "!=", "l", "{", "return", "nil", "\n", "}", "\n", "// see comment in List.Remove about initialization of l", "return", "l", ".", "insertValue", "(", "v", ",", "mark", ".", "prev", ")", "\n", "}" ]
// InsertBefore inserts a new element e with value v immediately before mark and returns e. // If mark is not an element of l, the list is not modified.
[ "InsertBefore", "inserts", "a", "new", "element", "e", "with", "value", "v", "immediately", "before", "mark", "and", "returns", "e", ".", "If", "mark", "is", "not", "an", "element", "of", "l", "the", "list", "is", "not", "modified", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L168-L174
2,089
cloudflare/golibs
lrucache/list.go
InsertAfter
func (l *list) InsertAfter(v interface{}, mark *element) *element { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark) }
go
func (l *list) InsertAfter(v interface{}, mark *element) *element { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark) }
[ "func", "(", "l", "*", "list", ")", "InsertAfter", "(", "v", "interface", "{", "}", ",", "mark", "*", "element", ")", "*", "element", "{", "if", "mark", ".", "list", "!=", "l", "{", "return", "nil", "\n", "}", "\n", "// see comment in List.Remove about initialization of l", "return", "l", ".", "insertValue", "(", "v", ",", "mark", ")", "\n", "}" ]
// InsertAfter inserts a new element e with value v immediately after mark and returns e. // If mark is not an element of l, the list is not modified.
[ "InsertAfter", "inserts", "a", "new", "element", "e", "with", "value", "v", "immediately", "after", "mark", "and", "returns", "e", ".", "If", "mark", "is", "not", "an", "element", "of", "l", "the", "list", "is", "not", "modified", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L178-L184
2,090
cloudflare/golibs
lrucache/list.go
MoveToFront
func (l *list) MoveToFront(e *element) { if e.list != l || l.root.next == e { return } // see comment in List.Remove about initialization of l l.insert(l.remove(e), &l.root) }
go
func (l *list) MoveToFront(e *element) { if e.list != l || l.root.next == e { return } // see comment in List.Remove about initialization of l l.insert(l.remove(e), &l.root) }
[ "func", "(", "l", "*", "list", ")", "MoveToFront", "(", "e", "*", "element", ")", "{", "if", "e", ".", "list", "!=", "l", "||", "l", ".", "root", ".", "next", "==", "e", "{", "return", "\n", "}", "\n", "// see comment in List.Remove about initialization of l", "l", ".", "insert", "(", "l", ".", "remove", "(", "e", ")", ",", "&", "l", ".", "root", ")", "\n", "}" ]
// MoveToFront moves element e to the front of list l. // If e is not an element of l, the list is not modified.
[ "MoveToFront", "moves", "element", "e", "to", "the", "front", "of", "list", "l", ".", "If", "e", "is", "not", "an", "element", "of", "l", "the", "list", "is", "not", "modified", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L188-L194
2,091
cloudflare/golibs
lrucache/list.go
MoveToBack
func (l *list) MoveToBack(e *element) { if e.list != l || l.root.prev == e { return } // see comment in List.Remove about initialization of l l.insert(l.remove(e), l.root.prev) }
go
func (l *list) MoveToBack(e *element) { if e.list != l || l.root.prev == e { return } // see comment in List.Remove about initialization of l l.insert(l.remove(e), l.root.prev) }
[ "func", "(", "l", "*", "list", ")", "MoveToBack", "(", "e", "*", "element", ")", "{", "if", "e", ".", "list", "!=", "l", "||", "l", ".", "root", ".", "prev", "==", "e", "{", "return", "\n", "}", "\n", "// see comment in List.Remove about initialization of l", "l", ".", "insert", "(", "l", ".", "remove", "(", "e", ")", ",", "l", ".", "root", ".", "prev", ")", "\n", "}" ]
// MoveToBack moves element e to the back of list l. // If e is not an element of l, the list is not modified.
[ "MoveToBack", "moves", "element", "e", "to", "the", "back", "of", "list", "l", ".", "If", "e", "is", "not", "an", "element", "of", "l", "the", "list", "is", "not", "modified", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L198-L204
2,092
cloudflare/golibs
lrucache/list.go
MoveBefore
func (l *list) MoveBefore(e, mark *element) { if e.list != l || e == mark { return } l.insert(l.remove(e), mark.prev) }
go
func (l *list) MoveBefore(e, mark *element) { if e.list != l || e == mark { return } l.insert(l.remove(e), mark.prev) }
[ "func", "(", "l", "*", "list", ")", "MoveBefore", "(", "e", ",", "mark", "*", "element", ")", "{", "if", "e", ".", "list", "!=", "l", "||", "e", "==", "mark", "{", "return", "\n", "}", "\n", "l", ".", "insert", "(", "l", ".", "remove", "(", "e", ")", ",", "mark", ".", "prev", ")", "\n", "}" ]
// MoveBefore moves element e to its new position before mark. // If e is not an element of l, or e == mark, the list is not modified.
[ "MoveBefore", "moves", "element", "e", "to", "its", "new", "position", "before", "mark", ".", "If", "e", "is", "not", "an", "element", "of", "l", "or", "e", "==", "mark", "the", "list", "is", "not", "modified", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L208-L213
2,093
cloudflare/golibs
lrucache/list.go
MoveAfter
func (l *list) MoveAfter(e, mark *element) { if e.list != l || e == mark { return } l.insert(l.remove(e), mark) }
go
func (l *list) MoveAfter(e, mark *element) { if e.list != l || e == mark { return } l.insert(l.remove(e), mark) }
[ "func", "(", "l", "*", "list", ")", "MoveAfter", "(", "e", ",", "mark", "*", "element", ")", "{", "if", "e", ".", "list", "!=", "l", "||", "e", "==", "mark", "{", "return", "\n", "}", "\n", "l", ".", "insert", "(", "l", ".", "remove", "(", "e", ")", ",", "mark", ")", "\n", "}" ]
// MoveAfter moves element e to its new position after mark. // If e is not an element of l, or e == mark, the list is not modified.
[ "MoveAfter", "moves", "element", "e", "to", "its", "new", "position", "after", "mark", ".", "If", "e", "is", "not", "an", "element", "of", "l", "or", "e", "==", "mark", "the", "list", "is", "not", "modified", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/lrucache/list.go#L217-L222
2,094
cloudflare/golibs
kt/kt.go
newConn
func newConn(host string, port int, poolsize int, timeout time.Duration, creds string) (*Conn, error) { var tlsConfig *tls.Config var err error scheme := "http" if creds != "" { tlsConfig, err = newTLSClientConfig(creds) if err != nil { return nil, err } scheme = "https" } portstr := strconv.Itoa(port) c := &Conn{ scheme: scheme, timeout: timeout, host: net.JoinHostPort(host, portstr), transport: &http.Transport{ TLSClientConfig: tlsConfig, ResponseHeaderTimeout: timeout, MaxIdleConnsPerHost: poolsize, }, } // connectivity check so that we can bail out // early instead of when we do the first operation. _, _, err = c.doRPC("/rpc/void", nil) if err != nil { return nil, err } return c, nil }
go
func newConn(host string, port int, poolsize int, timeout time.Duration, creds string) (*Conn, error) { var tlsConfig *tls.Config var err error scheme := "http" if creds != "" { tlsConfig, err = newTLSClientConfig(creds) if err != nil { return nil, err } scheme = "https" } portstr := strconv.Itoa(port) c := &Conn{ scheme: scheme, timeout: timeout, host: net.JoinHostPort(host, portstr), transport: &http.Transport{ TLSClientConfig: tlsConfig, ResponseHeaderTimeout: timeout, MaxIdleConnsPerHost: poolsize, }, } // connectivity check so that we can bail out // early instead of when we do the first operation. _, _, err = c.doRPC("/rpc/void", nil) if err != nil { return nil, err } return c, nil }
[ "func", "newConn", "(", "host", "string", ",", "port", "int", ",", "poolsize", "int", ",", "timeout", "time", ".", "Duration", ",", "creds", "string", ")", "(", "*", "Conn", ",", "error", ")", "{", "var", "tlsConfig", "*", "tls", ".", "Config", "\n", "var", "err", "error", "\n\n", "scheme", ":=", "\"", "\"", "\n\n", "if", "creds", "!=", "\"", "\"", "{", "tlsConfig", ",", "err", "=", "newTLSClientConfig", "(", "creds", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "scheme", "=", "\"", "\"", "\n", "}", "\n\n", "portstr", ":=", "strconv", ".", "Itoa", "(", "port", ")", "\n", "c", ":=", "&", "Conn", "{", "scheme", ":", "scheme", ",", "timeout", ":", "timeout", ",", "host", ":", "net", ".", "JoinHostPort", "(", "host", ",", "portstr", ")", ",", "transport", ":", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "tlsConfig", ",", "ResponseHeaderTimeout", ":", "timeout", ",", "MaxIdleConnsPerHost", ":", "poolsize", ",", "}", ",", "}", "\n\n", "// connectivity check so that we can bail out", "// early instead of when we do the first operation.", "_", ",", "_", ",", "err", "=", "c", ".", "doRPC", "(", "\"", "\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// KT has 2 interfaces, A restful one and an RPC one. // The RESTful interface is usually much faster than // the RPC one, but not all methods are implemented. // Use the RESTFUL interfaces when we can and fallback // to the RPC one when needed. // // The RPC format uses tab separated values with a choice of encoding // for each of the fields. We use base64 since it is always safe. // // REST format is just the body of the HTTP request being the value.
[ "KT", "has", "2", "interfaces", "A", "restful", "one", "and", "an", "RPC", "one", ".", "The", "RESTful", "interface", "is", "usually", "much", "faster", "than", "the", "RPC", "one", "but", "not", "all", "methods", "are", "implemented", ".", "Use", "the", "RESTFUL", "interfaces", "when", "we", "can", "and", "fallback", "to", "the", "RPC", "one", "when", "needed", ".", "The", "RPC", "format", "uses", "tab", "separated", "values", "with", "a", "choice", "of", "encoding", "for", "each", "of", "the", "fields", ".", "We", "use", "base64", "since", "it", "is", "always", "safe", ".", "REST", "format", "is", "just", "the", "body", "of", "the", "HTTP", "request", "being", "the", "value", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L160-L195
2,095
cloudflare/golibs
kt/kt.go
NewConnTLS
func NewConnTLS(host string, port int, poolsize int, timeout time.Duration, creds string) (*Conn, error) { return newConn(host, port, poolsize, timeout, creds) }
go
func NewConnTLS(host string, port int, poolsize int, timeout time.Duration, creds string) (*Conn, error) { return newConn(host, port, poolsize, timeout, creds) }
[ "func", "NewConnTLS", "(", "host", "string", ",", "port", "int", ",", "poolsize", "int", ",", "timeout", "time", ".", "Duration", ",", "creds", "string", ")", "(", "*", "Conn", ",", "error", ")", "{", "return", "newConn", "(", "host", ",", "port", ",", "poolsize", ",", "timeout", ",", "creds", ")", "\n", "}" ]
// NewConnTLS creates a TLS enabled connection to a Kyoto Tycoon endpoing
[ "NewConnTLS", "creates", "a", "TLS", "enabled", "connection", "to", "a", "Kyoto", "Tycoon", "endpoing" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L198-L200
2,096
cloudflare/golibs
kt/kt.go
NewConn
func NewConn(host string, port int, poolsize int, timeout time.Duration) (*Conn, error) { return newConn(host, port, poolsize, timeout, "") }
go
func NewConn(host string, port int, poolsize int, timeout time.Duration) (*Conn, error) { return newConn(host, port, poolsize, timeout, "") }
[ "func", "NewConn", "(", "host", "string", ",", "port", "int", ",", "poolsize", "int", ",", "timeout", "time", ".", "Duration", ")", "(", "*", "Conn", ",", "error", ")", "{", "return", "newConn", "(", "host", ",", "port", ",", "poolsize", ",", "timeout", ",", "\"", "\"", ")", "\n", "}" ]
// NewConn creates a connection to an Kyoto Tycoon endpoint.
[ "NewConn", "creates", "a", "connection", "to", "an", "Kyoto", "Tycoon", "endpoint", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L203-L205
2,097
cloudflare/golibs
kt/kt.go
Count
func (c *Conn) Count() (int, error) { code, m, err := c.doRPC("/rpc/status", nil) if err != nil { return 0, err } if code != 200 { return 0, makeError(m) } return strconv.Atoi(string(findRec(m, "count").Value)) }
go
func (c *Conn) Count() (int, error) { code, m, err := c.doRPC("/rpc/status", nil) if err != nil { return 0, err } if code != 200 { return 0, makeError(m) } return strconv.Atoi(string(findRec(m, "count").Value)) }
[ "func", "(", "c", "*", "Conn", ")", "Count", "(", ")", "(", "int", ",", "error", ")", "{", "code", ",", "m", ",", "err", ":=", "c", ".", "doRPC", "(", "\"", "\"", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "code", "!=", "200", "{", "return", "0", ",", "makeError", "(", "m", ")", "\n", "}", "\n", "return", "strconv", ".", "Atoi", "(", "string", "(", "findRec", "(", "m", ",", "\"", "\"", ")", ".", "Value", ")", ")", "\n", "}" ]
// Count returns the number of records in the database
[ "Count", "returns", "the", "number", "of", "records", "in", "the", "database" ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L227-L236
2,098
cloudflare/golibs
kt/kt.go
Remove
func (c *Conn) Remove(key string) error { code, body, err := c.doREST("DELETE", key, nil) if err != nil { return err } if code == 404 { return ErrNotFound } if code != 204 { return &Error{string(body), code} } return nil }
go
func (c *Conn) Remove(key string) error { code, body, err := c.doREST("DELETE", key, nil) if err != nil { return err } if code == 404 { return ErrNotFound } if code != 204 { return &Error{string(body), code} } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Remove", "(", "key", "string", ")", "error", "{", "code", ",", "body", ",", "err", ":=", "c", ".", "doREST", "(", "\"", "\"", ",", "key", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "code", "==", "404", "{", "return", "ErrNotFound", "\n", "}", "\n", "if", "code", "!=", "204", "{", "return", "&", "Error", "{", "string", "(", "body", ")", ",", "code", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Remove deletes the data at key in the database.
[ "Remove", "deletes", "the", "data", "at", "key", "in", "the", "database", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L239-L251
2,099
cloudflare/golibs
kt/kt.go
GetBulk
func (c *Conn) GetBulk(keysAndVals map[string]string) error { m := make(map[string][]byte) for k := range keysAndVals { m[k] = zeroslice } err := c.GetBulkBytes(m) if err != nil { return err } for k := range keysAndVals { b, ok := m[k] if ok { keysAndVals[k] = string(b) } else { delete(keysAndVals, k) } } return nil }
go
func (c *Conn) GetBulk(keysAndVals map[string]string) error { m := make(map[string][]byte) for k := range keysAndVals { m[k] = zeroslice } err := c.GetBulkBytes(m) if err != nil { return err } for k := range keysAndVals { b, ok := m[k] if ok { keysAndVals[k] = string(b) } else { delete(keysAndVals, k) } } return nil }
[ "func", "(", "c", "*", "Conn", ")", "GetBulk", "(", "keysAndVals", "map", "[", "string", "]", "string", ")", "error", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "byte", ")", "\n", "for", "k", ":=", "range", "keysAndVals", "{", "m", "[", "k", "]", "=", "zeroslice", "\n", "}", "\n", "err", ":=", "c", ".", "GetBulkBytes", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "k", ":=", "range", "keysAndVals", "{", "b", ",", "ok", ":=", "m", "[", "k", "]", "\n", "if", "ok", "{", "keysAndVals", "[", "k", "]", "=", "string", "(", "b", ")", "\n", "}", "else", "{", "delete", "(", "keysAndVals", ",", "k", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetBulk retrieves the keys in the map. The results will be filled in on function return. // If a key was not found in the database, it will be removed from the map.
[ "GetBulk", "retrieves", "the", "keys", "in", "the", "map", ".", "The", "results", "will", "be", "filled", "in", "on", "function", "return", ".", "If", "a", "key", "was", "not", "found", "in", "the", "database", "it", "will", "be", "removed", "from", "the", "map", "." ]
4efefffc6d5c2168e1c209e44dad549e0674e7a3
https://github.com/cloudflare/golibs/blob/4efefffc6d5c2168e1c209e44dad549e0674e7a3/kt/kt.go#L255-L273